GBATEK
Gameboy Advance / Nintendo DS / DSi / 3DS - Technical Info - Extracted from no$gba version 3.06
About this Document

 GBA Reference

Overview
GBA Technical Data
GBA Memory Map
GBA I/O Map

Hardware Programming
GBA LCD Video Controller
GBA Sound Controller
GBA Timers
GBA DMA Transfers
GBA Communication Ports
GBA Keypad Input
GBA Interrupt Control
GBA System Control
GBA Cartridges
GBA Unpredictable Things

Other
ARM CPU Reference
BIOS Functions
External Connectors
 NDS Reference

Overview
DS Technical Data
DS I/O Maps
DS Memory Maps

Hardware Programming
DS Memory Control
DS Video
DS 3D Video
DS Sound
DS System and Built-in Peripherals
DS Cartridges, Encryption, Firmware
DS Xboo
DS Wireless Communications

Other
BIOS Functions
ARM CPU Reference
External Connectors

 3DS Reference

3DS Reference (under construction)
 DSi Reference

DSi Basic Differences to NDS

New Hardware Features
DSi I/O Map
DSi Control Registers (SCFG)
DSi XpertTeak (DSP)
DSi New Shared WRAM
DSi New DMA (NDMA)
DSi Microphone and SoundExt
DSi Advanced Encryption Standard (AES)
DSi Cartridge Header
DSi Touchscreen/Sound Controller
DSi I2C Bus
DSi Cameras
DSi SD/MMC Protocol and I/O Ports
DSi SD/MMC Filesystem
DSi Atheros Wifi SDIO Interface
DSi Atheros Wifi Internal Hardware
DSi GPIO Registers
DSi Console IDs
DSi Unknown Registers
DSi Notes
DSi Exploits
DSi Regions


 CPU Reference

General ARM7TDMI Information
ARM CPU Overview
ARM CPU Register Set
ARM CPU Flags & Condition Field (cond)
ARM CPU 26bit Memory Interface
ARM CPU Exceptions
ARM CPU Memory Alignments

Further Information
ARM Pseudo Instructions and Directives
ARM CP15 System Control Coprocessor
ARM CPU Instruction Cycle Times
ARM CPU Versions
ARM CPU Data Sheet

 CPU 32bit ARM Mode

ARM 32bit Opcodes (ARM Code)
ARM Instruction Summary
ARM Branch and Branch with Link (B, BL, BX, BLX, SWI, BKPT)
ARM Data Processing (ALU)
ARM Multiply and Multiply-Accumulate (MUL, MLA)
ARM Special ARM9 Instructions (CLZ, QADD/QSUB)
ARM PSR Transfer (MRS, MSR)
ARM Memory: Single Data Transfer (LDR, STR, PLD)
ARM Memory: Halfword, Doubleword, and Signed Data Transfer
ARM Memory: Block Data Transfer (LDM, STM)
ARM Memory: Single Data Swap (SWP)
ARM Coprocessor (MRC/MCR, LDC/STC, CDP, MCRR/MRRC)

 CPU 16bit THUMB Mode

ARM 16bit Opcodes (THUMB Code)
When operating in THUMB state, cut-down 16bit opcodes are used.
THUMB is supported on T-variants of ARMv4 and up, ie. ARMv4T, ARMv5T, etc.
THUMB Instruction Summary
THUMB Register Operations (ALU, BX)
THUMB Memory Load/Store (LDR/STR)
THUMB Memory Addressing (ADD PC/SP)
THUMB Memory Multiple Load/Store (PUSH/POP and LDM/STM)
THUMB Jumps and Calls
GBA Reference

Overview
GBA Technical Data
GBA Memory Map
GBA I/O Map

Hardware Programming
GBA LCD Video Controller
GBA Sound Controller
GBA Timers
GBA DMA Transfers
GBA Communication Ports
GBA Keypad Input
GBA Interrupt Control
GBA System Control
GBA Cartridges
GBA Backwards Compatibility CGB Mode
GBA Unpredictable Things

Other
ARM CPU Reference
BIOS Functions
External Connectors


GBA Technical Data

CPU Modes
  ARM Mode     ARM7TDMI 32bit RISC CPU, 16.78MHz, 32bit opcodes (GBA)
  THUMB Mode   ARM7TDMI 32bit RISC CPU, 16.78MHz, 16bit opcodes (GBA)
  CGB Mode     Z80/8080-style 8bit CPU, 4.2MHz or 8.4MHz  (CGB compatibility)
  DMG Mode     Z80/8080-style 8bit CPU, 4.2MHz (monochrome gameboy compatib.)
Internal Memory
  BIOS ROM     16 KBytes
  Work RAM     288 KBytes (Fast 32K on-chip, plus Slow 256K on-board)
  VRAM         96 KBytes
  OAM          1 KByte (128 OBJs 3x16bit, 32 OBJ-Rotation/Scalings 4x16bit)
  Palette RAM  1 KByte (256 BG colors, 256 OBJ colors)
Video
  Display      240x160 pixels (2.9 inch TFT color LCD display)
  BG layers    4 background layers
  BG types     Tile/map based, or Bitmap based
  BG colors    256 colors, or 16 colors/16 palettes, or 32768 colors
  OBJ colors   256 colors, or 16 colors/16 palettes
  OBJ size     12 types (in range 8x8 up to 64x64 dots)
  OBJs/Screen  max. 128 OBJs of any size (up to 64x64 dots each)
  OBJs/Line    max. 128 OBJs of 8x8 dots size (under best circumstances)
  Priorities   OBJ/OBJ: 0-127, OBJ/BG: 0-3, BG/BG: 0-3
  Effects      Rotation/Scaling, alpha blending, fade-in/out, mosaic, window
  Backlight    GBA SP only (optionally by light on/off toggle button)
Sound
  Analogue     4 channel CGB compatible (3x square wave, 1x noise)
  Digital      2 DMA sound channels
  Output       Built-in speaker (mono), or headphones socket (stereo)
Controls
  Gamepad      4 Direction Keys, 6 Buttons
Communication Ports
  Serial Port  Various transfer modes, 4-Player Link, Single Game Pak play
External Memory
  GBA Game Pak max. 32MB ROM or flash ROM + max 64K SRAM
  CGB Game Pak max. 32KB ROM + 8KB SRAM (more memory requires banking)
Case Dimensions
  Size (mm)    GBA: 145x81x25 - GBA SP: 82x82x24 (closed), 155x82x24 (stretch)
Power Supply
  Battery GBA  GBA: 2x1.5V DC (AA), Life-time approx. 15 hours
  Battery SP   GBA SP: Built-in rechargeable Lithium ion battery, 3.7V 600mAh
  External     GBA: 3.3V DC 350mA - GBA SP: 5.2V DC 320mA

 ----------------------------------------------------------------------------

Original Gameboy Advance (GBA)
        ____._____________...___.____
   ____/    :  CARTRIDGE  SIO   :    \____
  | L       _____________________  LED  R |
  |        |                     |        |
  |  _||_  |   2.9" TFT SCREEN   |    (A) |
  | |_  _| | 240x160pix  61x40mm | (B)    |
  |   ||   |    NO BACKLIGHT     |  ::::  |
  |        |                     | SPEAKR |
  | STRT() |_____________________|  ::::  |
  | SLCT()     GAME BOY ADVANCE    VOLUME |
  |____  OFF-ON  BATTERY 2xAA PHONES  _==_|
       \__.##.__________________,,___/

GBA SP (GBA SP)
   _______________________                                 _
  | _____________________ |                               / /
  ||                     ||                              / /
  ||   2.9" TFT SCREEN   ||                             / /
  || 240x160pix  61x40mm ||                            / /
  ||   WITH BACKLIGHT    ||                           / /
  ||                     ||     GBA SP SIDE VIEWS    / /
  ||_____________________||                         / /
  |  GAME BOY ADVANCE SP  |   _____________________(_)
  |_______________________|  |. . . . . . . .'.'.   _|
  |_|________|________|_|_|  |_CARTRIDGE_:_BATT._:_|_| <-- EXT1/EXT2
  |L    EXT1     EXT2    R|
  |          (*)      LEDSo   _____________________ _
  (VOL_||_           (A)  o  |_____________________(_)
  |  |_  _| ,,,,,(B)      |  |. . . . . . . .'.'.   _|
  |    ||   ;SPK;         |  |_CARTRIDGE_:_BATT._:_|_| <-- EXT1/EXT2
  |         '''''      ON #                         _ _____________________
  |       SLCT STRT    OFF#   _____________________(_)_____________________|
  | CART.  ()   ()        |  |. . . . . . . .'.'.   _|
  |_:___________________:_|  |_CARTRIDGE_:_BATT._:_|_| <-- EXT1/EXT2

Gameboy Micro (GBA Micro)
      ________________SIO_______________
     | L      __________________      R |
     |       |     GBA-MICRO    |       |
     | _||_  |  2.0" TFT SCREEN |    (A)| +
     ||_  _| |240x160pix 42x28mm| (B)   |VOL
     |  ||   |     BACKLIGHT    |       | -
     |       |__________________|  ...  |
     |___________SELECT__START__________|
       PWR   <--- CARTRIDGE SLOT ---> PHONES

Nintendo DS (NDS)
     _____________________________________
    |        _____________________        |
    |       |                     |       |
    |       |    3" TFT SCREEN    |       |
    |       | 256x192pix  61x46mm |       |
    |       |      BACKLIGHT      |       |
    | ::::: |    Original NDS     | ::::: |
    | ::::: |_____________________| ::::: |
   _|        _          ______   _        |_  <-- gap between screens: 22mm
  |L|_______| |________|      |_| |_______|R|     (equivalent to 90 pixels)
  |_______   _____________________   _______|
  |  PWR  | |                     | |SEL STA|
  |   _   | |    3" TFT SCREEN    | |       |
  | _| |_ | | 256x192pix  61x46mm | |   X   |
  ||_   _|| |      BACKLIGHT      | | Y   A |
  |  |_|  | |    TOUCH SCREEN     | |   B   |
  |       | |_____________________| |       |
  |_______|             NintendoDS  |_______|
  |         MIC                LEDS         |
  |_________________________________________|
       VOL        SLOT2(GBA)     MIC/PHONES

Nintendo DS Lite (NDS-Lite)
     _____________________________________
    |        _____________________        |
    |       |                     |       |
    |       |    3" TFT SCREEN    |       |
    |  ...  | 256x192pix  61x46mm |  ...  |
    |  ...  |      BACKLIGHT      |  ...  |
    |       |      NDS-LITE       |       |
    |       |_____________________|       |
    |___  _ _ _ _ _ _ _ _ _ _ _ _ _ _ ____|   <-- gap between screens: 23mm
   L| _ |_____________MIC____________|LEDS|R
    |   _    _____________________        |
    | _| |_ |                     |   X   |
    ||_   _||    3" TFT SCREEN    | Y   A |PWR
    |  |_|  | 256x192pix  61x46mm |   B   |
    |       |      BACKLIGHT      |       |
    |       |    TOUCH SCREEN     |oSTART |
    |       |_____________________|oSELECT|
    |_____________________________________|
       VOL        SLOT2(GBA)     MIC/PHONES

Nintendo DSi (DSi)
     _____________________________________
    |        _____________________        |
    |       |                     |   O o | <-- CAM (O) and LED (o)
    |       |   3.25" TFT SCREEN  |       |     (on backside)
    |       | 256x192pix  66x50mm |       |
    |       |      BACKLIGHT      |       |
    |  __   |         DSi         |   __  |
    | (__)  |_____________________|  (__) |
    |___  _ _ _ _ _ _ _ _ _ _ _ _ _ _ ____|  <-- gap between screens: 23mm
   L|LEDS|__________CAM__MIC_________| __ |R                   (88 pixels)
  + |   _    _____________________        |
 VOL| _| |_ |                     |   X   | <-- SD Card Slot
  - ||_   _||   3.25" TFT SCREEN  | Y   A |
    |  |_|  | 256x192pix  66x50mm |   B   |
    |       |      BACKLIGHT      |       |
    |       |    TOUCH SCREEN     |oSTART |
    | POWERo|_____________________|oSELECT|
    |_____________________________________|
                                 MIC/PHONES

Nintendo DSi XL
  As DSi, but bigger case, and bigger 4.2" screens

Nintendo 3DS (Old3DS)
     _____________________________________
    |      __________CAM____________      | <-- internal camera
    |  .  |                         |  .  |     (and two back cameras and LED
    |. . .|     x.xx" TFT SCREEN    |. . .|     on backside)
    |  .  |   800x240pix  XXxXXmm   |  .  |
    |     |        BACKLIGHT        |    .|
    |     |     STEREOSCOPIC 3D     |    || <-- 3D slider
    |     |_________________________|    '|
    |___  _ _ _ _ _ _ _ _ _ _ _ _ _ _ ____|  <-- gap between screens: XXmm
   L| __ |___________________________| __o|R   <-- Notify RGB LED    (XX pix)
    |  .-.   _____________________        |
 VOL| (   ) |                     |   X   |  <-- wifi LED
    |  '-'  |   x.xx" TFT SCREEN  | Y   A |  <-- wifi Button
    |   _   | 320x240pix  XXxXXmm |   B   |
    | _| |_ |      BACKLIGHT      |       |
  SD||_   _||    TOUCH SCREEN     |       |
    |  |_|  |_____________________|       |
    |         SELECT  HOME  START  oPOWER |
    |_____________________________________|
                     PHONES       LEDs (power/charge)

Gameboy Player (Gamecube Joypad) (GBA Player)
                   _________
       L____-------         -------____R
       /   ___   \           /   (Y)   \Z
      /   / O \   | (START) |        (X)\   Z      = Gameboy Player Menu
     |    \___/    \_______/      (A)    |  X or Y = Select button
     |\         _   \     /    (B)      /|
     | \___   _| |_  \   /   ___    ___/ |  optionally X/Y can be
     |    |\ |_   _| /   \  / C \  /|    |  swapped with L/R (?)
     |    | \  |_|  /     \ \___/ / |    |
     |    |  \_____/       \_____/  |    |  analogue sticks = ?
      \__/                           \__/

Gameboy Player (Gamecube Bongos) (GBA Player)
       _______     _______
      /   Y   \   /   X   \   Y/B = left bongo rear/front side
     | . . . . |_| . . . . |  X/A = right bongo rear/front side
     |    B    |R|    A    |  S   = start/pause button
     |\_______/|_|\_______/|  R   = microphone (triggers R button)
     |\_______/|S|\_______/|
     |         |_|         |  (the X/Y inputs can be assigned to
     |\_______/| |\_______/|  GBA R/L inputs in GBA player setup)
      \_______/   \_______/

The GBA's separate 8bit/32bit CPU modes cannot be operated simultaneously. Switching is allowed between ARM and THUMB modes only (that are the two GBA modes).
This manual does not describe CGB and DMG modes, both are completely different than GBA modes, and both cannot be accessed from inside of GBA modes anyways.

Gameboy Player
An GBA Adapter for the Gamecube console; allowing to play GBA games on a television set.
GBA Gameboy Player

GBA SP Notes
Deluxe version of the original GBA. With backlight, new folded laptop-style case, and built-in rechargeable battery. Appears to be 100% compatible with GBA, there seems to be no way to detect SPs by software.

Gameboy Micro (GBA Micro)
Minituarized GBA. Supports 32bit GBA games only (no 8bit DMG/CGB games). The 256K Main RAM is a bit slower than usually (cannot be "overclocked via port 4000800h).

Nintendo DS (Dual Screen) Notes
New handheld with two screens, backwards compatible with GBA games, it is NOT backwards compatible with older 8bit games (mono/color gameboys) though..
Also, the DS has no link port, so that GBA games will thus work only in single player mode, link-port accessoires like printers cannot be used, and most unfortunately multiboot won't work (trying to press Select+Start at powerup will just lock up the DS).

iQue Notes
iQue is a brand name used by Nintendo in China, iQue GBA and iQue DS are essentially same as Nintendo GBA and Nintendo DS.
The iQue DS contains a larger firmware chip (the charset additionally contains about 6700 simplified chinese characters), the bootmenu still allows to select (only) six languages (japanese has been replaced by chinese). The iQue DS can play normal international NDS games, plus chinese dedicated games. The latter ones won't work on normal NDS consoles (that, reportedly simply due to a firmware-version check contained in chinese dedicated games, aside from that check, the games should be fully compatible with NDS consoles).


GBA Memory Map

General Internal Memory
  00000000-00003FFF   BIOS - System ROM         (16 KBytes)
  00004000-01FFFFFF   Not used
  02000000-0203FFFF   WRAM - On-board Work RAM  (256 KBytes) 2 Wait
  02040000-02FFFFFF   Not used
  03000000-03007FFF   WRAM - On-chip Work RAM   (32 KBytes)
  03008000-03FFFFFF   Not used
  04000000-040003FE   I/O Registers
  04000400-04FFFFFF   Not used
Internal Display Memory
  05000000-050003FF   BG/OBJ Palette RAM        (1 Kbyte)
  05000400-05FFFFFF   Not used
  06000000-06017FFF   VRAM - Video RAM          (96 KBytes)
  06018000-06FFFFFF   Not used
  07000000-070003FF   OAM - OBJ Attributes      (1 Kbyte)
  07000400-07FFFFFF   Not used
External Memory (Game Pak)
  08000000-09FFFFFF   Game Pak ROM/FlashROM (max 32MB) - Wait State 0
  0A000000-0BFFFFFF   Game Pak ROM/FlashROM (max 32MB) - Wait State 1
  0C000000-0DFFFFFF   Game Pak ROM/FlashROM (max 32MB) - Wait State 2
  0E000000-0E00FFFF   Game Pak SRAM    (max 64 KBytes) - 8bit Bus width
  0E010000-0FFFFFFF   Not used
Unused Memory Area
  10000000-FFFFFFFF   Not used (upper 4bits of address bus unused)

Default WRAM Usage
By default, the 256 bytes at 03007F00h-03007FFFh in Work RAM are reserved for Interrupt vector, Interrupt Stack, and BIOS Call Stack. The remaining WRAM is free for whatever use (including User Stack, which is initially located at 03007F00h).

Address Bus Width and CPU Read/Write Access Widths
Shows the Bus-Width, supported read and write widths, and the clock cycles for 8/16/32bit accesses.
  Region        Bus   Read      Write     Cycles
  BIOS ROM      32    8/16/32   -         1/1/1
  Work RAM 32K  32    8/16/32   8/16/32   1/1/1
  I/O           32    8/16/32   8/16/32   1/1/1
  OAM           32    8/16/32   16/32     1/1/1 *
  Work RAM 256K 16    8/16/32   8/16/32   3/3/6 **
  Palette RAM   16    8/16/32   16/32     1/1/2 *
  VRAM          16    8/16/32   16/32     1/1/2 *
  GamePak ROM   16    8/16/32   -         5/5/8 **/***
  GamePak Flash 16    8/16/32   16/32     5/5/8 **/***
  GamePak SRAM  8     8         8         5     **
Timing Notes:
  *   Plus 1 cycle if GBA accesses video memory at the same time.
  **  Default waitstate settings, see System Control chapter.
  *** Separate timings for sequential, and non-sequential accesses.
  One cycle equals approx. 59.59ns (ie. 16.78MHz clock).
All memory (except GamePak SRAM) can be accessed by 16bit and 32bit DMA.

GamePak Memory
Only DMA3 (and the CPU of course) may access GamePak ROM. GamePak SRAM can be accessed by the CPU only - restricted to bytewise 8bit transfers. The SRAM region is supposed for as external FLASH backup memory, or for battery-backed SRAM.
For details about configuration of GamePak Waitstates, see:
GBA System Control

VRAM, OAM, and Palette RAM Access
These memory regions can be accessed during H-Blank or V-Blank only (unless display is disabled by Forced Blank bit in DISPCNT register).
There is an additional restriction for OAM memory: Accesses during H-Blank are allowed only if 'H-Blank Interval Free' in DISPCNT is set (which'd reduce number of display-able OBJs though).
The CPU appears to be able to access VRAM/OAM/Palette at any time, a waitstate (one clock cycle) being inserted automatically in case that the display controller was accessing memory simultaneously. (Ie. unlike as in old 8bit gameboy, the data will not get lost.)

CPU Mode Performance
Note that the GamePak ROM bus is limited to 16bits, thus executing ARM instructions (32bit opcodes) from inside of GamePak ROM would result in a not so good performance. So, it'd be more recommended to use THUMB instruction (16bit opcodes) which'd allow each opcode to be read at once.
(ARM instructions can be used at best performance by copying code from GamePak ROM into internal Work RAM)

Data Format
Even though the ARM CPU itself would allow to select between Little-Endian and Big-Endian format by using an external circuit, in the GBA no such circuit exists, and the data format is always Little-Endian. That is, when accessing 16bit or 32bit data in memory, the least significant bits are stored in the first byte (smallest address), and the most significant bits in the last byte. (Ie. same as for 80x86 and Z80 CPUs.)


GBA I/O Map

LCD I/O Registers
  4000000h  2    R/W  DISPCNT   LCD Control
  4000002h  2    R/W  -         Undocumented - Green Swap
  4000004h  2    R/W  DISPSTAT  General LCD Status (STAT,LYC)
  4000006h  2    R    VCOUNT    Vertical Counter (LY)
  4000008h  2    R/W  BG0CNT    BG0 Control
  400000Ah  2    R/W  BG1CNT    BG1 Control
  400000Ch  2    R/W  BG2CNT    BG2 Control
  400000Eh  2    R/W  BG3CNT    BG3 Control
  4000010h  2    W    BG0HOFS   BG0 X-Offset
  4000012h  2    W    BG0VOFS   BG0 Y-Offset
  4000014h  2    W    BG1HOFS   BG1 X-Offset
  4000016h  2    W    BG1VOFS   BG1 Y-Offset
  4000018h  2    W    BG2HOFS   BG2 X-Offset
  400001Ah  2    W    BG2VOFS   BG2 Y-Offset
  400001Ch  2    W    BG3HOFS   BG3 X-Offset
  400001Eh  2    W    BG3VOFS   BG3 Y-Offset
  4000020h  2    W    BG2PA     BG2 Rotation/Scaling Parameter A (dx)
  4000022h  2    W    BG2PB     BG2 Rotation/Scaling Parameter B (dmx)
  4000024h  2    W    BG2PC     BG2 Rotation/Scaling Parameter C (dy)
  4000026h  2    W    BG2PD     BG2 Rotation/Scaling Parameter D (dmy)
  4000028h  4    W    BG2X      BG2 Reference Point X-Coordinate
  400002Ch  4    W    BG2Y      BG2 Reference Point Y-Coordinate
  4000030h  2    W    BG3PA     BG3 Rotation/Scaling Parameter A (dx)
  4000032h  2    W    BG3PB     BG3 Rotation/Scaling Parameter B (dmx)
  4000034h  2    W    BG3PC     BG3 Rotation/Scaling Parameter C (dy)
  4000036h  2    W    BG3PD     BG3 Rotation/Scaling Parameter D (dmy)
  4000038h  4    W    BG3X      BG3 Reference Point X-Coordinate
  400003Ch  4    W    BG3Y      BG3 Reference Point Y-Coordinate
  4000040h  2    W    WIN0H     Window 0 Horizontal Dimensions
  4000042h  2    W    WIN1H     Window 1 Horizontal Dimensions
  4000044h  2    W    WIN0V     Window 0 Vertical Dimensions
  4000046h  2    W    WIN1V     Window 1 Vertical Dimensions
  4000048h  2    R/W  WININ     Inside of Window 0 and 1
  400004Ah  2    R/W  WINOUT    Inside of OBJ Window & Outside of Windows
  400004Ch  2    W    MOSAIC    Mosaic Size
  400004Eh       -    -         Not used
  4000050h  2    R/W  BLDCNT    Color Special Effects Selection
  4000052h  2    R/W  BLDALPHA  Alpha Blending Coefficients
  4000054h  2    W    BLDY      Brightness (Fade-In/Out) Coefficient
  4000056h       -    -         Not used
Sound Registers
  4000060h  2  R/W  SOUND1CNT_L Channel 1 Sweep register       (NR10)
  4000062h  2  R/W  SOUND1CNT_H Channel 1 Duty/Length/Envelope (NR11, NR12)
  4000064h  2  R/W  SOUND1CNT_X Channel 1 Frequency/Control    (NR13, NR14)
  4000066h     -    -           Not used
  4000068h  2  R/W  SOUND2CNT_L Channel 2 Duty/Length/Envelope (NR21, NR22)
  400006Ah     -    -           Not used
  400006Ch  2  R/W  SOUND2CNT_H Channel 2 Frequency/Control    (NR23, NR24)
  400006Eh     -    -           Not used
  4000070h  2  R/W  SOUND3CNT_L Channel 3 Stop/Wave RAM select (NR30)
  4000072h  2  R/W  SOUND3CNT_H Channel 3 Length/Volume        (NR31, NR32)
  4000074h  2  R/W  SOUND3CNT_X Channel 3 Frequency/Control    (NR33, NR34)
  4000076h     -    -           Not used
  4000078h  2  R/W  SOUND4CNT_L Channel 4 Length/Envelope      (NR41, NR42)
  400007Ah     -    -           Not used
  400007Ch  2  R/W  SOUND4CNT_H Channel 4 Frequency/Control    (NR43, NR44)
  400007Eh     -    -           Not used
  4000080h  2  R/W  SOUNDCNT_L  Control Stereo/Volume/Enable   (NR50, NR51)
  4000082h  2  R/W  SOUNDCNT_H  Control Mixing/DMA Control
  4000084h  2  R/W  SOUNDCNT_X  Control Sound on/off           (NR52)
  4000086h     -    -           Not used
  4000088h  2  BIOS SOUNDBIAS   Sound PWM Control
  400008Ah  ..   -    -         Not used
  4000090h 2x10h R/W  WAVE_RAM  Channel 3 Wave Pattern RAM (2 banks!!)
  40000A0h  4    W    FIFO_A    Channel A FIFO, Data 0-3
  40000A4h  4    W    FIFO_B    Channel B FIFO, Data 0-3
  40000A8h       -    -         Not used
DMA Transfer Channels
  40000B0h  4    W    DMA0SAD   DMA 0 Source Address
  40000B4h  4    W    DMA0DAD   DMA 0 Destination Address
  40000B8h  2    W    DMA0CNT_L DMA 0 Word Count
  40000BAh  2    R/W  DMA0CNT_H DMA 0 Control
  40000BCh  4    W    DMA1SAD   DMA 1 Source Address
  40000C0h  4    W    DMA1DAD   DMA 1 Destination Address
  40000C4h  2    W    DMA1CNT_L DMA 1 Word Count
  40000C6h  2    R/W  DMA1CNT_H DMA 1 Control
  40000C8h  4    W    DMA2SAD   DMA 2 Source Address
  40000CCh  4    W    DMA2DAD   DMA 2 Destination Address
  40000D0h  2    W    DMA2CNT_L DMA 2 Word Count
  40000D2h  2    R/W  DMA2CNT_H DMA 2 Control
  40000D4h  4    W    DMA3SAD   DMA 3 Source Address
  40000D8h  4    W    DMA3DAD   DMA 3 Destination Address
  40000DCh  2    W    DMA3CNT_L DMA 3 Word Count
  40000DEh  2    R/W  DMA3CNT_H DMA 3 Control
  40000E0h       -    -         Not used
Timer Registers
  4000100h  2    R/W  TM0CNT_L  Timer 0 Counter/Reload
  4000102h  2    R/W  TM0CNT_H  Timer 0 Control
  4000104h  2    R/W  TM1CNT_L  Timer 1 Counter/Reload
  4000106h  2    R/W  TM1CNT_H  Timer 1 Control
  4000108h  2    R/W  TM2CNT_L  Timer 2 Counter/Reload
  400010Ah  2    R/W  TM2CNT_H  Timer 2 Control
  400010Ch  2    R/W  TM3CNT_L  Timer 3 Counter/Reload
  400010Eh  2    R/W  TM3CNT_H  Timer 3 Control
  4000110h       -    -         Not used
Serial Communication (1)
  4000120h  4    R/W  SIODATA32 SIO Data (Normal-32bit Mode; shared with below)
  4000120h  2    R/W  SIOMULTI0 SIO Data 0 (Parent)    (Multi-Player Mode)
  4000122h  2    R/W  SIOMULTI1 SIO Data 1 (1st Child) (Multi-Player Mode)
  4000124h  2    R/W  SIOMULTI2 SIO Data 2 (2nd Child) (Multi-Player Mode)
  4000126h  2    R/W  SIOMULTI3 SIO Data 3 (3rd Child) (Multi-Player Mode)
  4000128h  2    R/W  SIOCNT    SIO Control Register
  400012Ah  2    R/W  SIOMLT_SEND SIO Data (Local of MultiPlayer; shared below)
  400012Ah  2    R/W  SIODATA8  SIO Data (Normal-8bit and UART Mode)
  400012Ch       -    -         Not used
Keypad Input
  4000130h  2    R    KEYINPUT  Key Status
  4000132h  2    R/W  KEYCNT    Key Interrupt Control
Serial Communication (2)
  4000134h  2    R/W  RCNT      SIO Mode Select/General Purpose Data
  4000136h  -    -    IR        Ancient - Infrared Register (Prototypes only)
  4000138h       -    -         Not used
  4000140h  2    R/W  JOYCNT    SIO JOY Bus Control
  4000142h       -    -         Not used
  4000150h  4    R/W  JOY_RECV  SIO JOY Bus Receive Data
  4000154h  4    R/W  JOY_TRANS SIO JOY Bus Transmit Data
  4000158h  2    R/?  JOYSTAT   SIO JOY Bus Receive Status
  400015Ah       -    -         Not used
Interrupt, Waitstate, and Power-Down Control
  4000200h  2    R/W  IE        Interrupt Enable Register
  4000202h  2    R/W  IF        Interrupt Request Flags / IRQ Acknowledge
  4000204h  2    R/W  WAITCNT   Game Pak Waitstate Control
  4000206h       -    -         Not used
  4000208h  2    R/W  IME       Interrupt Master Enable Register
  400020Ah       -    -         Not used
  4000300h  1    R/W  POSTFLG   Undocumented - Post Boot Flag
  4000301h  1    W    HALTCNT   Undocumented - Power Down Control
  4000302h       -    -         Not used
  4000410h  ?    ?    ?         Undocumented - Purpose Unknown / Bug ??? 0FFh
  4000411h       -    -         Not used
  4000800h  4    R/W  ?         Undocumented - Internal Memory Control (R/W)
  4000804h       -    -         Not used
  4xx0800h  4    R/W  ?         Mirrors of 4000800h (repeated each 64K)
  4700000h  4    W    (3DS)     Disable ARM7 bootrom overlay (3DS only)

All further addresses at 4XXXXXXh are unused and do not contain mirrors of the I/O area, with the only exception that 4000800h is repeated each 64K (ie. mirrored at 4010800h, 4020800h, etc.)


GBA LCD Video Controller

Registers
LCD I/O Display Control
LCD I/O Interrupts and Status
LCD I/O BG Control
LCD I/O BG Scrolling
LCD I/O BG Rotation/Scaling
LCD I/O Window Feature
LCD I/O Mosaic Function
LCD I/O Color Special Effects

VRAM
LCD VRAM Overview
LCD VRAM Character Data
LCD VRAM BG Screen Data Format (BG Map)
LCD VRAM Bitmap BG Modes

Sprites
LCD OBJ - Overview
LCD OBJ - OAM Attributes
LCD OBJ - OAM Rotation/Scaling Parameters
LCD OBJ - VRAM Character (Tile) Mapping

Other
LCD Color Palettes
LCD Dimensions and Timings


LCD I/O Display Control

4000000h - DISPCNT - LCD Control (Read/Write)
  Bit   Expl.
  0-2   BG Mode                (0-5=Video Mode 0-5, 6-7=Prohibited)
  3     Reserved / CGB Mode    (0=GBA, 1=CGB; can be set only by BIOS opcodes)
  4     Display Frame Select   (0-1=Frame 0-1) (for BG Modes 4,5 only)
  5     H-Blank Interval Free  (1=Allow access to OAM during H-Blank)
  6     OBJ Character VRAM Mapping (0=Two dimensional, 1=One dimensional)
  7     Forced Blank           (1=Allow FAST access to VRAM,Palette,OAM)
  8     Screen Display BG0  (0=Off, 1=On)
  9     Screen Display BG1  (0=Off, 1=On)
  10    Screen Display BG2  (0=Off, 1=On)
  11    Screen Display BG3  (0=Off, 1=On)
  12    Screen Display OBJ  (0=Off, 1=On)
  13    Window 0 Display Flag   (0=Off, 1=On)
  14    Window 1 Display Flag   (0=Off, 1=On)
  15    OBJ Window Display Flag (0=Off, 1=On)

The table summarizes the facilities of the separate BG modes (video modes).
  Mode  Rot/Scal Layers Size               Tiles Colors       Features
  0     No       0123   256x256..512x515   1024  16/16..256/1 SFMABP
  1     Mixed    012-   (BG0,BG1 as above Mode 0, BG2 as below Mode 2)
  2     Yes      --23   128x128..1024x1024 256   256/1        S-MABP
  3     Yes      --2-   240x160            1     32768        --MABP
  4     Yes      --2-   240x160            2     256/1        --MABP
  5     Yes      --2-   160x128            2     32768        --MABP
Features: S)crolling, F)lip, M)osaic, A)lphaBlending, B)rightness, P)riority.

BG Modes 0-2 are Tile/Map-based. BG Modes 3-5 are Bitmap-based, in these modes 1 or 2 Frames (ie. bitmaps, or 'full screen tiles') exists, if two frames exist, either one can be displayed, and the other one can be redrawn in background.

Blanking Bits
Setting Forced Blank (Bit 7) causes the video controller to display white lines, and all VRAM, Palette RAM, and OAM may be accessed.
"When the internal HV synchronous counter cancels a forced blank during a display period, the display begins from the beginning, following the display of two vertical lines." What ?
Setting H-Blank Interval Free (Bit 5) allows to access OAM during H-Blank time - using this feature reduces the number of sprites that can be displayed per line.

Display Enable Bits
By default, BG0-3 and OBJ Display Flags (Bit 8-12) are used to enable/disable BGs and OBJ. When enabling Window 0 and/or 1 (Bit 13-14), color special effects may be used, and BG0-3 and OBJ are controlled by the window(s).

Frame Selection
In BG Modes 4 and 5 (Bitmap modes), either one of the two bitmaps/frames may be displayed (Bit 4), allowing the user to update the other (invisible) frame in background. In BG Mode 3, only one frame exists.
In BG Modes 0-2 (Tile/Map based modes), a similar effect may be gained by altering the base address(es) of BG Map and/or BG Character data.

4000002h - Undocumented - Green Swap (R/W)
Normally, red green blue intensities for a group of two pixels is output as BGRbgr (uppercase for left pixel at even xloc, lowercase for right pixel at odd xloc). When the Green Swap bit is set, each pixel group is output as BgRbGr (ie. green intensity of each two pixels exchanged).
  Bit   Expl.
  0     Green Swap  (0=Normal, 1=Swap)
  1-15  Not used
This feature appears to be applied to the final picture (ie. after mixing the separate BG and OBJ layers). Eventually intended for other display types (with other pin-outs). With normal GBA hardware it is just producing an interesting dirt effect.
The NDS DISPCNT registers are 32bit (4000000h..4000003h), so Green Swap doesn't exist in NDS mode, however, the NDS does support Green Swap in GBA mode.


LCD I/O Interrupts and Status

4000004h - DISPSTAT - General LCD Status (Read/Write)
Display status and Interrupt control. The H-Blank conditions are generated once per scanline, including for the 'hidden' scanlines during V-Blank.
  Bit   Expl.
  0     V-Blank flag   (Read only) (1=VBlank) (set in line 160..226; not 227)
  1     H-Blank flag   (Read only) (1=HBlank) (toggled in all lines, 0..227)
  2     V-Counter flag (Read only) (1=Match)  (set in selected line)     (R)
  3     V-Blank IRQ Enable         (1=Enable)                          (R/W)
  4     H-Blank IRQ Enable         (1=Enable)                          (R/W)
  5     V-Counter IRQ Enable       (1=Enable)                          (R/W)
  6     Not used (0) / DSi: LCD Initialization Ready (0=Busy, 1=Ready)   (R)
  7     Not used (0) / NDS: MSB of V-Vcount Setting (LYC.Bit8) (0..262)(R/W)
  8-15  V-Count Setting (LYC)      (0..227)                            (R/W)
The V-Count-Setting value is much the same as LYC of older gameboys, when its value is identical to the content of the VCOUNT register then the V-Counter flag is set (Bit 2), and (if enabled in Bit 5) an interrupt is requested.
Although the drawing time is only 960 cycles (240*4), the H-Blank flag is "0" for a total of 1006 cycles.

4000006h - VCOUNT - Vertical Counter (Read only)
Indicates the currently drawn scanline, values in range from 160..227 indicate 'hidden' scanlines within VBlank area.
  Bit   Expl.
  0-7   Current Scanline (LY)      (0..227)                              (R)
  8     Not used (0) / NDS: MSB of Current Scanline (LY.Bit8) (0..262)   (R)
  9-15  Not Used (0)
Note: This is much the same than the 'LY' register of older gameboys.


LCD I/O BG Control

4000008h - BG0CNT - BG0 Control (R/W) (BG Modes 0,1 only)
400000Ah - BG1CNT - BG1 Control (R/W) (BG Modes 0,1 only)
400000Ch - BG2CNT - BG2 Control (R/W) (BG Modes 0,1,2 only)
400000Eh - BG3CNT - BG3 Control (R/W) (BG Modes 0,2 only)
  Bit   Expl.
  0-1   BG Priority           (0-3, 0=Highest)
  2-3   Character Base Block  (0-3, in units of 16 KBytes) (=BG Tile Data)
  4-5   Not used (must be zero) (except in NDS mode: MSBs of char base)
  6     Mosaic                (0=Disable, 1=Enable)
  7     Colors/Palettes       (0=16/16, 1=256/1)
  8-12  Screen Base Block     (0-31, in units of 2 KBytes) (=BG Map Data)
  13    BG0/BG1: Not used (except in NDS mode: Ext Palette Slot for BG0/BG1)
  13    BG2/BG3: Display Area Overflow (0=Transparent, 1=Wraparound)
  14-15 Screen Size (0-3)
Internal Screen Size (dots) and size of BG Map (bytes):
  Value  Text Mode      Rotation/Scaling Mode
  0      256x256 (2K)   128x128   (256 bytes)
  1      512x256 (4K)   256x256   (1K)
  2      256x512 (4K)   512x512   (4K)
  3      512x512 (8K)   1024x1024 (16K)
In case that some or all BGs are set to same priority then BG0 is having the highest, and BG3 the lowest priority.

In 'Text Modes', the screen size is organized as follows: The screen consists of one or more 256x256 pixel (32x32 tiles) areas. When Size=0: only 1 area (SC0), when Size=1 or Size=2: two areas (SC0,SC1 either horizontally or vertically arranged next to each other), when Size=3: four areas (SC0,SC1 in upper row, SC2,SC3 in lower row). Whereas SC0 is defined by the normal BG Map base address (Bit 8-12 of BGxCNT), SC1 uses same address +2K, SC2 address +4K, SC3 address +6K. When the screen is scrolled it'll always wraparound.

In 'Rotation/Scaling Modes', the screen size is organized as follows, only one area (SC0) of variable size 128x128..1024x1024 pixels (16x16..128x128 tiles) exists. When the screen is rotated/scaled (or scrolled?) so that the LCD viewport reaches outside of the background/screen area, then BG may be either displayed as transparent or wraparound (Bit 13 of BGxCNT).


LCD I/O BG Scrolling

4000010h - BG0HOFS - BG0 X-Offset (W)
4000012h - BG0VOFS - BG0 Y-Offset (W)
  Bit   Expl.
  0-8   Offset (0-511)
  9-15  Not used
Specifies the coordinate of the upperleft first visible dot of BG0 background layer, ie. used to scroll the BG0 area.

4000014h - BG1HOFS - BG1 X-Offset (W)
4000016h - BG1VOFS - BG1 Y-Offset (W)
Same as above BG0HOFS and BG0VOFS for BG1 respectively.

4000018h - BG2HOFS - BG2 X-Offset (W)
400001Ah - BG2VOFS - BG2 Y-Offset (W)
Same as above BG0HOFS and BG0VOFS for BG2 respectively.

400001Ch - BG3HOFS - BG3 X-Offset (W)
400001Eh - BG3VOFS - BG3 Y-Offset (W)
Same as above BG0HOFS and BG0VOFS for BG3 respectively.

The above BG scrolling registers are exclusively used in Text modes, ie. for all layers in BG Mode 0, and for the first two layers in BG mode 1.
In other BG modes (Rotation/Scaling and Bitmap modes) above registers are ignored. Instead, the screen may be scrolled by modifying the BG Rotation/Scaling Reference Point registers.


LCD I/O BG Rotation/Scaling

4000028h - BG2X_L - BG2 Reference Point X-Coordinate, lower 16 bit (W)
400002Ah - BG2X_H - BG2 Reference Point X-Coordinate, upper 12 bit (W)
400002Ch - BG2Y_L - BG2 Reference Point Y-Coordinate, lower 16 bit (W)
400002Eh - BG2Y_H - BG2 Reference Point Y-Coordinate, upper 12 bit (W)
These registers are replacing the BG scrolling registers which are used for Text mode, ie. the X/Y coordinates specify the source position from inside of the BG Map/Bitmap of the pixel to be displayed at upper left of the GBA display. The normal BG scrolling registers are ignored in Rotation/Scaling and Bitmap modes.
  Bit   Expl.
  0-7   Fractional portion (8 bits)
  8-26  Integer portion    (19 bits)
  27    Sign               (1 bit)
  28-31 Not used
Because values are shifted left by eight, fractional portions may be specified in steps of 1/256 pixels (this would be relevant only if the screen is actually rotated or scaled). Normal signed 32bit values may be written to above registers (the most significant bits will be ignored and the value will be cut-down to 28bits, but this is no actual problem because signed values have set all MSBs to the same value).

Internal Reference Point Registers
The above reference points are automatically copied to internal registers during each vblank, specifying the origin for the first scanline. The internal registers are then incremented by dmx and dmy after each scanline.
Caution: Writing to a reference point register by software outside of the Vblank period does immediately copy the new value to the corresponding internal register, that means: in the current frame, the new value specifies the origin of the <current> scanline (instead of the topmost scanline).

4000020h - BG2PA - BG2 Rotation/Scaling Parameter A (alias dx) (W)
4000022h - BG2PB - BG2 Rotation/Scaling Parameter B (alias dmx) (W)
4000024h - BG2PC - BG2 Rotation/Scaling Parameter C (alias dy) (W)
4000026h - BG2PD - BG2 Rotation/Scaling Parameter D (alias dmy) (W)
  Bit   Expl.
  0-7   Fractional portion (8 bits)
  8-14  Integer portion    (7 bits)
  15    Sign               (1 bit)
See below for details.

400003Xh - BG3X_L/H, BG3Y_L/H, BG3PA-D - BG3 Rotation/Scaling Parameters
Same as above BG2 Reference Point, and Rotation/Scaling Parameters, for BG3 respectively.

dx (PA) and dy (PC)
When transforming a horizontal line, dx and dy specify the resulting gradient and magnification for that line. For example:
Horizontal line, length=100, dx=1, and dy=1. The resulting line would be drawn at 45 degrees, f(y)=1/1*x. Note that this would involve that line is magnified, the new length is SQR(100^2+100^2)=141.42. Yup, exactly - that's the old a^2 + b^2 = c^2 formula.

dmx (PB) and dmy (PD)
These values define the resulting gradient and magnification for transformation of vertical lines. However, when rotating a square area (which is surrounded by horizontal and vertical lines), then the desired result should be usually a rotated <square> area (ie. not a parallelogram, for example).
Thus, dmx and dmy must be defined in direct relationship to dx and dy, taking the example above, we'd have to set dmx=-1, and dmy=1, f(x)=-1/1*y.

Area Overflow
In result of rotation/scaling it may often happen that areas outside of the actual BG area become moved into the LCD viewport. Depending of the Area Overflow bit (BG2CNT and BG3CNT, Bit 13) these areas may be either displayed (by wrapping the BG area), or may be displayed transparent.
This works only in BG modes 1 and 2. The area overflow is ignored in Bitmap modes (BG modes 3-5), the outside of the Bitmaps is always transparent.

--- more details and confusing or helpful formulas ---

The following parameters are required for Rotation/Scaling
  Rotation Center X and Y Coordinates (x0,y0)
  Rotation Angle                      (alpha)
  Magnification X and Y Values        (xMag,yMag)
The display is rotated by 'alpha' degrees around the center.
The displayed picture is magnified by 'xMag' along x-Axis (Y=y0) and 'yMag' along y-Axis (X=x0).

Calculating Rotation/Scaling Parameters A-D
  A = Cos (alpha) / xMag    ;distance moved in direction x, same line
  B = Sin (alpha) / xMag    ;distance moved in direction x, next line
  C = Sin (alpha) / yMag    ;distance moved in direction y, same line
  D = Cos (alpha) / yMag    ;distance moved in direction y, next line

Calculating the position of a rotated/scaled dot
Using the following expressions,
  x0,y0    Rotation Center
  x1,y1    Old Position of a pixel (before rotation/scaling)
  x2,y2    New position of above pixel (after rotation scaling)
  A,B,C,D  BG2PA-BG2PD Parameters (as calculated above)
the following formula can be used to calculate x2,y2:
  x2 = A(x1-x0) + B(y1-y0) + x0
  y2 = C(x1-x0) + D(y1-y0) + y0


LCD I/O Window Feature

The Window Feature may be used to split the screen into four regions. The BG0-3,OBJ layers and Color Special Effects can be separately enabled or disabled in each of these regions.

The DISPCNT Register
DISPCNT Bits 13-15 are used to enable Window 0, Window 1, and/or OBJ Window regions, if any of these regions is enabled then the "Outside of Windows" region is automatically enabled, too.
DISPCNT Bits 8-12 are kept used as master enable bits for the BG0-3,OBJ layers, a layer is displayed only if both DISPCNT and WININ/OUT enable bits are set.

4000040h - WIN0H - Window 0 Horizontal Dimensions (W)
4000042h - WIN1H - Window 1 Horizontal Dimensions (W)
  Bit   Expl.
  0-7   X2, Rightmost coordinate of window, plus 1
  8-15  X1, Leftmost coordinate of window
Garbage values of X2>240 or X1>X2 are interpreted as X2=240.

4000044h - WIN0V - Window 0 Vertical Dimensions (W)
4000046h - WIN1V - Window 1 Vertical Dimensions (W)
  Bit   Expl.
  0-7   Y2, Bottom-most coordinate of window, plus 1
  8-15  Y1, Top-most coordinate of window
Garbage values of Y2>160 or Y1>Y2 are interpreted as Y2=160.

4000048h - WININ - Control of Inside of Window(s) (R/W)
  Bit   Expl.
  0-3   Window 0 BG0-BG3 Enable Bits     (0=No Display, 1=Display)
  4     Window 0 OBJ Enable Bit          (0=No Display, 1=Display)
  5     Window 0 Color Special Effect    (0=Disable, 1=Enable)
  6-7   Not used
  8-11  Window 1 BG0-BG3 Enable Bits     (0=No Display, 1=Display)
  12    Window 1 OBJ Enable Bit          (0=No Display, 1=Display)
  13    Window 1 Color Special Effect    (0=Disable, 1=Enable)
  14-15 Not used

400004Ah - WINOUT - Control of Outside of Windows & Inside of OBJ Window (R/W)
  Bit   Expl.
  0-3   Outside BG0-BG3 Enable Bits      (0=No Display, 1=Display)
  4     Outside OBJ Enable Bit           (0=No Display, 1=Display)
  5     Outside Color Special Effect     (0=Disable, 1=Enable)
  6-7   Not used
  8-11  OBJ Window BG0-BG3 Enable Bits   (0=No Display, 1=Display)
  12    OBJ Window OBJ Enable Bit        (0=No Display, 1=Display)
  13    OBJ Window Color Special Effect  (0=Disable, 1=Enable)
  14-15 Not used

The OBJ Window
The dimension of the OBJ Window is specified by OBJs which are having the "OBJ Mode" attribute being set to "OBJ Window". Any non-transparent dots of any such OBJs are marked as OBJ Window area. The OBJ itself is not displayed.
The color, palette, and display priority of these OBJs are ignored. Both DISPCNT Bits 12 and 15 must be set when defining OBJ Window region(s).

Window Priority
In case that more than one window is enabled, and that these windows do overlap, Window 0 is having highest priority, Window 1 medium, and Obj Window lowest priority. Outside of Window is having zero priority, it is used for all dots which are not inside of any window region.


LCD I/O Mosaic Function

400004Ch - MOSAIC - Mosaic Size (W)
The Mosaic function can be separately enabled/disabled for BG0-BG3 by BG0CNT-BG3CNT Registers, as well as for each OBJ0-127 by OBJ attributes in OAM memory. Also, setting all of the bits below to zero effectively disables the mosaic function.
  Bit   Expl.
  0-3   BG Mosaic H-Size  (minus 1)
  4-7   BG Mosaic V-Size  (minus 1)
  8-11  OBJ Mosaic H-Size (minus 1)
  12-15 OBJ Mosaic V-Size (minus 1)
  16-31 Not used
Example: When setting H-Size to 5, then pixels 0-5 of each display row are colorized as pixel 0, pixels 6-11 as pixel 6, pixels 12-17 as pixel 12, and so on.

Normally, a 'mosaic-pixel' is colorized by the color of the upperleft covered pixel. In many cases it might be more desireful to use the color of the pixel in the center of the covered area - this effect may be gained by scrolling the background (or by adjusting the OBJ position, as far as upper/left rows/columns of OBJ are transparent).


LCD I/O Color Special Effects

Two types of Special Effects are supported: Alpha Blending (Semi-Transparency) allows to combine colors of two selected surfaces. Brightness Increase/Decrease adjust the brightness of the selected surface.

4000050h - BLDCNT - Color Special Effects Selection (R/W)
  Bit   Expl.
  0     BG0 1st Target Pixel (Background 0)
  1     BG1 1st Target Pixel (Background 1)
  2     BG2 1st Target Pixel (Background 2)
  3     BG3 1st Target Pixel (Background 3)
  4     OBJ 1st Target Pixel (Top-most OBJ pixel)
  5     BD  1st Target Pixel (Backdrop)
  6-7   Color Special Effect (0-3, see below)
         0 = None                (Special effects disabled)
         1 = Alpha Blending      (1st+2nd Target mixed)
         2 = Brightness Increase (1st Target becomes whiter)
         3 = Brightness Decrease (1st Target becomes blacker)
  8     BG0 2nd Target Pixel (Background 0)
  9     BG1 2nd Target Pixel (Background 1)
  10    BG2 2nd Target Pixel (Background 2)
  11    BG3 2nd Target Pixel (Background 3)
  12    OBJ 2nd Target Pixel (Top-most OBJ pixel)
  13    BD  2nd Target Pixel (Backdrop)
  14-15 Not used
Selects the 1st Target layer(s) for special effects. For Alpha Blending/Semi-Transparency, it does also select the 2nd Target layer(s), which should have next lower display priority as the 1st Target.
However, any combinations are possible, including that all layers may be selected as both 1st+2nd target, in that case the top-most pixel will be used as 1st target, and the next lower pixel as 2nd target.

4000052h - BLDALPHA - Alpha Blending Coefficients (R/W) (not W)
Used for Color Special Effects Mode 1, and for Semi-Transparent OBJs.
  Bit   Expl.
  0-4   EVA Coefficient (1st Target) (0..16 = 0/16..16/16, 17..31=16/16)
  5-7   Not used
  8-12  EVB Coefficient (2nd Target) (0..16 = 0/16..16/16, 17..31=16/16)
  13-15 Not used
For this effect, the top-most non-transparent pixel must be selected as 1st Target, and the next-lower non-transparent pixel must be selected as 2nd Target, if so - and only if so, then color intensities of 1st and 2nd Target are mixed together by using the parameters in BLDALPHA register, for each pixel each R, G, B intensities are calculated separately:
  I = MIN ( 31, I1st*EVA + I2nd*EVB )
Otherwise - for example, if only one target exists, or if a non-transparent non-2nd-target pixel is moved between the two targets, or if 2nd target has higher display priority than 1st target - then only the top-most pixel is displayed (at normal intensity, regardless of BLDALPHA).

4000054h - BLDY - Brightness (Fade-In/Out) Coefficient (W) (not R/W)
Used for Color Special Effects Modes 2 and 3.
  Bit   Expl.
  0-4   EVY Coefficient (Brightness) (0..16 = 0/16..16/16, 17..31=16/16)
  5-31  Not used
For each pixel each R, G, B intensities are calculated separately:
  I = I1st + (31-I1st)*EVY   ;For Brightness Increase
  I = I1st - (I1st)*EVY      ;For Brightness Decrease
The color intensities of any selected 1st target surface(s) are increased or decreased by using the parameter in BLDY register.

Semi-Transparent OBJs
OBJs that are defined as 'Semi-Transparent' in OAM memory are always selected as 1st Target (regardless of BLDCNT Bit 4), and are always using Alpha Blending mode (regardless of BLDCNT Bit 6-7).
The BLDCNT register may be used to perform Brightness effects on the OBJ (and/or other BG/BD layers). However, if a semi-transparent OBJ pixel does overlap a 2nd target pixel, then semi-transparency becomes priority, and the brightness effect will not take place (neither on 1st, nor 2nd target).

The OBJ Layer
Before special effects are applied, the display controller computes the OBJ priority ordering, and isolates the top-most OBJ pixel. In result, only the top-most OBJ pixel is recursed at the time when processing special effects. Ie. alpha blending and semi-transparency can be used for OBJ-to-BG or BG-to-OBJ , but not for OBJ-to-OBJ.


LCD VRAM Overview

The GBA contains 96 Kbytes VRAM built-in, located at address 06000000-06017FFF, depending on the BG Mode used as follows:

BG Mode 0,1,2 (Tile/Map based Modes)
  06000000-0600FFFF  64 KBytes shared for BG Map and Tiles
  06010000-06017FFF  32 KBytes OBJ Tiles
The shared 64K area can be split into BG Map area(s), and BG Tiles area(s), the respective addresses for Map and Tile areas are set up by BG0CNT-BG3CNT registers. The Map address may be specified in units of 2K (steps of 800h), the Tile address in units of 16K (steps of 4000h).

BG Mode 0,1 (Tile/Map based Text mode)
The tiles may have 4bit or 8bit color depth, minimum map size is 32x32 tiles, maximum is 64x64 tiles, up to 1024 tiles can be used per map.
  Item        Depth     Required Memory
  One Tile    4bit      20h bytes
  One Tile    8bit      40h bytes
  1024 Tiles  4bit      8000h (32K)
  1024 Tiles  8bit      10000h (64K) - excluding some bytes for BG map
  BG Map      32x32     800h (2K)
  BG Map      64x64     2000h (8K)

BG Mode 1,2 (Tile/Map based Rotation/Scaling mode)
The tiles may have 8bit color depth only, minimum map size is 16x16 tiles, maximum is 128x128 tiles, up to 256 tiles can be used per map.
  Item        Depth     Required Memory
  One Tile    8bit      40h bytes
  256  Tiles  8bit      4000h (16K)
  BG Map      16x16     100h bytes
  BG Map      128x128   4000h (16K)

BG Mode 3 (Bitmap based Mode for still images)
  06000000-06013FFF  80 KBytes Frame 0 buffer (only 75K actually used)
  06014000-06017FFF  16 KBytes OBJ Tiles

BG Mode 4,5 (Bitmap based Modes)
  06000000-06009FFF  40 KBytes Frame 0 buffer (only 37.5K used in Mode 4)
  0600A000-06013FFF  40 KBytes Frame 1 buffer (only 37.5K used in Mode 4)
  06014000-06017FFF  16 KBytes OBJ Tiles

Note
Additionally to the above VRAM, the GBA also contains 1 KByte Palette RAM (at 05000000h) and 1 KByte OAM (at 07000000h) which are both used by the display controller as well.


LCD VRAM Character Data

Each character (tile) consists of 8x8 dots (64 dots in total). The color depth may be either 4bit or 8bit (see BG0CNT-BG3CNT).

4bit depth (16 colors, 16 palettes)
Each tile occupies 32 bytes of memory, the first 4 bytes for the topmost row of the tile, and so on. Each byte representing two dots, the lower 4 bits define the color for the left (!) dot, the upper 4 bits the color for the right dot.

8bit depth (256 colors, 1 palette)
Each tile occupies 64 bytes of memory, the first 8 bytes for the topmost row of the tile, and so on. Each byte selects the palette entry for each dot.


LCD VRAM BG Screen Data Format (BG Map)

The display background consists of 8x8 dot tiles, the arrangement of these tiles is specified by the BG Screen Data (BG Map). The separate entries in this map are as follows:

Text BG Screen (2 bytes per entry)
Specifies the tile number and attributes. Note that BG tile numbers are always specified in steps of 1 (unlike OBJ tile numbers which are using steps of two in 256 color/1 palette mode).
  Bit   Expl.
  0-9   Tile Number     (0-1023) (a bit less in 256 color mode, because
                           there'd be otherwise no room for the bg map)
  10    Horizontal Flip (0=Normal, 1=Mirrored)
  11    Vertical Flip   (0=Normal, 1=Mirrored)
  12-15 Palette Number  (0-15)    (Not used in 256 color/1 palette mode)
A Text BG Map always consists of 32x32 entries (256x256 pixels), 400h entries = 800h bytes. However, depending on the BG Size, one, two, or four of these Maps may be used together, allowing to create backgrounds of 256x256, 512x256, 256x512, or 512x512 pixels, if so, the first map (SC0) is located at base+0, the next map (SC1) at base+800h, and so on.

Rotation/Scaling BG Screen (1 byte per entry)
In this mode, only 256 tiles can be used. There are no x/y-flip attributes, the color depth is always 256 colors/1 palette.
  Bit   Expl.
  0-7   Tile Number     (0-255)
The dimensions of Rotation/Scaling BG Maps depend on the BG size. For size 0-3 that are: 16x16 tiles (128x128 pixels), 32x32 tiles (256x256 pixels), 64x64 tiles (512x512 pixels), or 128x128 tiles (1024x1024 pixels).

The size and VRAM base address of the separate BG maps for BG0-3 are set up by BG0CNT-BG3CNT registers.


LCD VRAM Bitmap BG Modes

In BG Modes 3-5 the background is defined in form of a bitmap (unlike as for Tile/Map based BG modes). Bitmaps are implemented as BG2, with Rotation/Scaling support. As bitmap modes are occupying 80KBytes of BG memory, only 16KBytes of VRAM can be used for OBJ tiles.

BG Mode 3 - 240x160 pixels, 32768 colors
Two bytes are associated to each pixel, directly defining one of the 32768 colors (without using palette data, and thus not supporting a 'transparent' BG color).
  Bit   Expl.
  0-4   Red Intensity   (0-31)
  5-9   Green Intensity (0-31)
  10-14 Blue Intensity  (0-31)
  15    Not used in GBA Mode (in NDS Mode: Alpha=0=Transparent, Alpha=1=Normal)
The first 480 bytes define the topmost line, the next 480 the next line, and so on. The background occupies 75 KBytes (06000000-06012BFF), most of the 80 Kbytes BG area, not allowing to redraw an invisible second frame in background, so this mode is mostly recommended for still images only.

BG Mode 4 - 240x160 pixels, 256 colors (out of 32768 colors)
One byte is associated to each pixel, selecting one of the 256 palette entries. Color 0 (backdrop) is transparent, and OBJs may be displayed behind the bitmap.
The first 240 bytes define the topmost line, the next 240 the next line, and so on. The background occupies 37.5 KBytes, allowing two frames to be used (06000000-060095FF for Frame 0, and 0600A000-060135FF for Frame 1).

BG Mode 5 - 160x128 pixels, 32768 colors
Colors are defined as for Mode 3 (see above), but horizontal and vertical size are cut down to 160x128 pixels only - smaller than the physical dimensions of the LCD screen.
The background occupies exactly 40 KBytes, so that BG VRAM may be split into two frames (06000000-06009FFF for Frame 0, and 0600A000-06013FFF for Frame 1).

In BG modes 4,5, one Frame may be displayed (selected by DISPCNT Bit 4), the other Frame is invisible and may be redrawn in background.


LCD OBJ - Overview

General
Objects (OBJs) are moveable sprites. Up to 128 OBJs (of any size, up to 64x64 dots each) can be displayed per screen, and under best circumstances up to 128 OBJs (of small 8x8 dots size) can be displayed per horizontal display line.

Maximum Number of Sprites per Line
The total available OBJ rendering cycles per line are
  1210  (=304*4-6)   If "H-Blank Interval Free" bit in DISPCNT register is 0
  954   (=240*4-6)   If "H-Blank Interval Free" bit in DISPCNT register is 1
The required rendering cycles are (depending on horizontal OBJ size)
  Cycles per <n> Pixels    OBJ Type              OBJ Type Screen Pixel Range
  n*1 cycles               Normal OBJs           8..64 pixels
  10+n*2 cycles            Rotation/Scaling OBJs 8..64 pixels   (area clipped)
  10+n*2 cycles            Rotation/Scaling OBJs 16..128 pixels (double size)
Caution:
The maximum number of OBJs per line is also affected by undisplayed (offscreen) OBJs which are having higher priority than displayed OBJs.
To avoid this, move displayed OBJs to the begin of OAM memory (ie. OBJ0 has highest priority, OBJ127 lowest).
Otherwise (in case that the program logic expects OBJs at fixed positions in OAM) at least take care to set the OBJ size of undisplayed OBJs to 8x8 with Rotation/Scaling disabled (this reduces the overload).
Does the above also apply for VERTICALLY OFFSCREEN (or VERTICALLY not on CURRENT LINE) sprites ?

VRAM - Character Data
OBJs are always combined of one or more 8x8 pixel Tiles (much like BG Tiles in BG Modes 0-2). However, OBJ Tiles are stored in a separate area in VRAM: 06010000-06017FFF (32 KBytes) in BG Mode 0-2, or 06014000-06017FFF (16 KBytes) in BG Mode 3-5.
Depending on the size of the above area (16K or 32K), and on the OBJ color depth (4bit or 8bit), 256-1024 8x8 dots OBJ Tiles can be defined.

OAM - Object Attribute Memory
This memory area contains Attributes which specify position, size, color depth, etc. appearance for each of the 128 OBJs. Additionally, it contains 32 OBJ Rotation/Scaling Parameter groups. OAM is located at 07000000-070003FF (sized 1 KByte).


LCD OBJ - OAM Attributes

OBJ Attributes
There are 128 entries in OAM for each OBJ0-OBJ127. Each entry consists of 6 bytes (three 16bit Attributes). Attributes for OBJ0 are located at 07000000, for OBJ1 at 07000008, OBJ2 at 07000010, and so on.

As you can see, there are blank spaces at 07000006, 0700000E, 07000016, etc. - these 16bit values are used for OBJ Rotation/Scaling (as described in the next chapter) - they are not directly related to the separate OBJs.

OBJ Attribute 0 (R/W)
  Bit   Expl.
  0-7   Y-Coordinate           (0-255)
  8     Rotation/Scaling Flag  (0=Off, 1=On)
  When Rotation/Scaling used (Attribute 0, bit 8 set):
    9     Double-Size Flag     (0=Normal, 1=Double)
  When Rotation/Scaling not used (Attribute 0, bit 8 cleared):
    9     OBJ Disable          (0=Normal, 1=Not displayed)
  10-11 OBJ Mode  (0=Normal, 1=Semi-Transparent, 2=OBJ Window, 3=Prohibited)
  12    OBJ Mosaic             (0=Off, 1=On)
  13    Colors/Palettes        (0=16/16, 1=256/1)
  14-15 OBJ Shape              (0=Square,1=Horizontal,2=Vertical,3=Prohibited)
Caution: A very large OBJ (of 128 pixels vertically, ie. a 64 pixels OBJ in a Double Size area) located at Y>128 will be treated as at Y>-128, the OBJ is then displayed parts offscreen at the TOP of the display, it is then NOT displayed at the bottom.

OBJ Attribute 1 (R/W)
  Bit   Expl.
  0-8   X-Coordinate           (0-511)
  When Rotation/Scaling used (Attribute 0, bit 8 set):
    9-13  Rotation/Scaling Parameter Selection (0-31)
          (Selects one of the 32 Rotation/Scaling Parameters that
          can be defined in OAM, for details read next chapter.)
  When Rotation/Scaling not used (Attribute 0, bit 8 cleared):
    9-11  Not used
    12    Horizontal Flip      (0=Normal, 1=Mirrored)
    13    Vertical Flip        (0=Normal, 1=Mirrored)
  14-15 OBJ Size               (0..3, depends on OBJ Shape, see Attr 0)
          Size  Square   Horizontal  Vertical
          0     8x8      16x8        8x16
          1     16x16    32x8        8x32
          2     32x32    32x16       16x32
          3     64x64    64x32       32x64

OBJ Attribute 2 (R/W)
  Bit   Expl.
  0-9   Character Name          (0-1023=Tile Number)
  10-11 Priority relative to BG (0-3; 0=Highest)
  12-15 Palette Number   (0-15) (Not used in 256 color/1 palette mode)

Notes:

OBJ Mode
The OBJ Mode may be Normal, Semi-Transparent, or OBJ Window.
Semi-Transparent means that the OBJ is used as 'Alpha Blending 1st Target' (regardless of BLDCNT register, for details see chapter about Color Special Effects).
OBJ Window means that the OBJ is not displayed, instead, dots with non-zero color are used as mask for the OBJ Window, see DISPCNT and WINOUT for details.

OBJ Tile Number
There are two situations which may divide the amount of available tiles by two (by four if both situations apply):

1. When using the 256 Colors/1 Palette mode, only each second tile may be used, the lower bit of the tile number should be zero (in 2-dimensional mapping mode, the bit is completely ignored).

2. When using BG Mode 3-5 (Bitmap Modes), only tile numbers 512-1023 may be used. That is because lower 16K of OBJ memory are used for BG. Attempts to use tiles 0-511 are ignored (not displayed).

Priority
In case that the 'Priority relative to BG' is the same than the priority of one of the background layers, then the OBJ becomes higher priority and is displayed on top of that BG layer.
Caution: Take care not to mess up BG Priority and OBJ priority. For example, the following would cause garbage to be displayed:
  OBJ No. 0 with Priority relative to BG=1   ;hi OBJ prio, lo BG prio
  OBJ No. 1 with Priority relative to BG=0   ;lo OBJ prio, hi BG prio
That is, OBJ0 is always having priority above OBJ1-127, so assigning a lower BG Priority to OBJ0 than for OBJ1-127 would be a bad idea.


LCD OBJ - OAM Rotation/Scaling Parameters

As described in the previous chapter, there are blank spaces between each of the 128 OBJ Attribute Fields in OAM memory. These 128 16bit gaps are used to store OBJ Rotation/Scaling Parameters.

Location of Rotation/Scaling Parameters in OAM
Four 16bit parameters (PA,PB,PC,PD) are required to define a complete group of Rotation/Scaling data. These are spread across OAM as such:
  1st Group - PA=07000006, PB=0700000E, PC=07000016, PD=0700001E
  2nd Group - PA=07000026, PB=0700002E, PC=07000036, PD=0700003E
  etc.
By using all blank space (128 x 16bit), up to 32 of these groups (4 x 16bit each) can be defined in OAM.

OBJ Rotation/Scaling PA,PB,PC,PD Parameters (R/W)
Each OBJ that uses Rotation/Scaling may select between any of the above 32 parameter groups. For details, refer to the previous chapter about OBJ Attributes.
The meaning of the separate PA,PB,PC,PD values is identical as for BG, for details read the chapter about BG Rotation/Scaling.

OBJ Reference Point & Rotation Center
The OBJ Reference Point is the upper left of the OBJ, ie. OBJ X/Y coordinates: X+0, Y+0.
The OBJ Rotation Center is always (or should be usually?) in the middle of the object, ie. for a 8x32 pixel OBJ, this would be at the OBJ X/Y coordinates: X+4, and Y+16.

OBJ Double-Size Bit (for OBJs that use Rotation/Scaling)
When Double-Size is zero: The sprite is rotated, and then display inside of the normal-sized (not rotated) rectangular area - the edges of the rotated sprite will become invisible if they reach outside of that area.
When Double-Size is set: The sprite is rotated, and then display inside of the double-sized (not rotated) rectangular area - this ensures that the edges of the rotated sprite remain visible even if they would reach outside of the normal-sized area. (Except that, for example, rotating a 8x32 pixel sprite by 90 degrees would still cut off parts of the sprite as the double-size area isn't large enough.)


LCD OBJ - VRAM Character (Tile) Mapping

Each OBJ tile consists of 8x8 dots, however, bigger OBJs can be displayed by combining several 8x8 tiles. The horizontal and vertical size for each OBJ may be separately defined in OAM, possible H/V sizes are 8,16,32,64 dots - allowing 'square' OBJs to be used (such like 8x8, 16x16, etc) as well as 'rectangular' OBJs (such like 8x32, 64x16, etc.)

When displaying an OBJ that contains of more than one 8x8 tile, one of the following two mapping modes can be used. In either case, the tile number of the upperleft tile must be specified in OAM memory.

Two Dimensional Character Mapping (DISPCNT Bit 6 cleared)
This mapping mode assumes that the 1024 OBJ tiles are arranged as a matrix of 32x32 tiles / 256x256 pixels (In 256 color mode: 16x32 tiles / 128x256 pixels). Ie. the upper row of this matrix contains tiles 00h-1Fh, the next row tiles 20h-3Fh, and so on.
For example, when displaying a 16x16 pixel OBJ, with tile number set to 04h; The upper row of the OBJ will consist of tile 04h and 05h, the next row of 24h and 25h. (In 256 color mode: 04h and 06h, 24h and 26h.)

One Dimensional Character Mapping (DISPCNT Bit 6 set)
In this mode, tiles are mapped each after each other from 00h-3FFh.
Using the same example as above, the upper row of the OBJ will consist of tile 04h and 05h, the next row of tile 06h and 07h. (In 256 color mode: 04h and 06h, 08h and 0Ah.)


LCD Color Palettes

Color Palette RAM
BG and OBJ palettes are using separate memory regions:
  05000000-050001FF - BG Palette RAM (512 bytes, 256 colors)
  05000200-050003FF - OBJ Palette RAM (512 bytes, 256 colors)
Each BG and OBJ palette RAM may be either split into 16 palettes with 16 colors each, or may be used as a single palette with 256 colors.
Note that some OBJs may access palette RAM in 16 color mode, while other OBJs may use 256 color mode at the same time. Same for BG0-BG3 layers.

Transparent Colors
Color 0 of all BG and OBJ palettes is transparent. Even though palettes are described as 16 (256) color palettes, only 15 (255) colors are actually visible.

Backdrop Color
Color 0 of BG Palette 0 is used as backdrop color. This color is displayed if an area of the screen is not covered by any non-transparent BG or OBJ dots.

Color Definitions
Each color occupies two bytes (same as for 32768 color BG modes):
  Bit   Expl.
  0-4   Red Intensity   (0-31)
  5-9   Green Intensity (0-31)
  10-14 Blue Intensity  (0-31)
  15    Not used

Intensities
Under normal circumstances (light source/viewing angle), the intensities 0-14 are practically all black, and only intensities 15-31 are resulting in visible medium..bright colors.

Note: The intensity problem appears in the 8bit CGB "compatibility" mode either. The original CGB display produced the opposite effect: Intensities 0-14 resulted in dark..medium colors, and intensities 15-31 resulted in bright colors. Any "medium" colors of CGB games will appear invisible/black on GBA hardware, and only very bright colors will be visible.


LCD Dimensions and Timings

Horizontal Dimensions
The drawing time for each dot is 4 CPU cycles.
  Visible     240 dots,  57.221 us,    960 cycles - 78% of h-time
  H-Blanking   68 dots,  16.212 us,    272 cycles - 22% of h-time
  Total       308 dots,  73.433 us,   1232 cycles - ca. 13.620 kHz
VRAM and Palette RAM may be accessed during H-Blanking. OAM can accessed only if "H-Blank Interval Free" bit in DISPCNT register is set.

Vertical Dimensions
  Visible (*) 160 lines, 11.749 ms, 197120 cycles - 70% of v-time
  V-Blanking   68 lines,  4.994 ms,  83776 cycles - 30% of v-time
  Total       228 lines, 16.743 ms, 280896 cycles - ca. 59.737 Hz
All VRAM, OAM, and Palette RAM may be accessed during V-Blanking.
Note that no H-Blank interrupts are generated within V-Blank period.

System Clock
The system clock is 16.78MHz (16*1024*1024 Hz), one cycle is thus approx. 59.59ns.

(*) Even though vertical screen size is 160 lines, the upper 8 lines are not <really> visible, these lines are covered by a shadow when holding the GBA orientated towards a light source, the lines are effectively black - and should not be used to display important information.

Interlace
The LCD display is using some sort of interlace in which even scanlines are dimmed in each second frame, and odd scanlines are dimmed in each other frame (it does always render ALL lines in ALL frames, but half of them are dimmed).
The effect can be seen when displaying some horizontal lines in each second frame, and hiding them in each other frame: the hardware will randomly show the lines in dimmed or non-dimmed form (depending on whether the test was started in an even or odd frame).
Unknown if it's possible to determine the even/off frame state by software (or possibly to reset the hardware to this or that state by software).
Note: The NDS is applying some sort of frameskip to GBA games, about every 3 seconds there will by a missing (or maybe: inserted) frame, ie. a GBA game that is updating the display in sync with GBA interlace will get offsync on NDS consoles.


GBA Sound Controller

The GBA supplies four 'analogue' sound channels for Tone and Noise (mostly compatible to CGB sound), as well as two 'digital' sound channels (which can be used to replay 8bit DMA sample data).

GBA Sound Channel 1 - Tone & Sweep
GBA Sound Channel 2 - Tone
GBA Sound Channel 3 - Wave Output
GBA Sound Channel 4 - Noise
GBA Sound Channel A and B - DMA Sound

GBA Sound Control Registers
GBA Comparison of CGB and GBA Sound

The GBA includes only a single (mono) speaker built-in, each channel may be output to either left and/or right channels by using the external line-out connector (for stereo headphones, etc).


GBA Sound Channel 1 - Tone & Sweep

4000060h - SOUND1CNT_L (NR10) - Channel 1 Sweep register (R/W)
  Bit        Expl.
  0-2   R/W  Number of sweep shift      (n=0-7)
  3     R/W  Sweep Frequency Direction  (0=Increase, 1=Decrease)
  4-6   R/W  Sweep Time; units of 7.8ms (0-7, min=7.8ms, max=54.7ms)
  7-15  -    Not used
Sweep is disabled by setting Sweep Time to zero, if so, the direction bit should be set.
The change of frequency (NR13,NR14) at each shift is calculated by the following formula where X(0) is initial freq & X(t-1) is last freq:
  X(t) = X(t-1) +/- X(t-1)/2^n

4000062h - SOUND1CNT_H (NR11, NR12) - Channel 1 Duty/Len/Envelope (R/W)
  Bit        Expl.
  0-5   W    Sound length; units of (64-n)/256s  (0-63)
  6-7   R/W  Wave Pattern Duty                   (0-3, see below)
  8-10  R/W  Envelope Step-Time; units of n/64s  (1-7, 0=No Envelope)
  11    R/W  Envelope Direction                  (0=Decrease, 1=Increase)
  12-15 R/W  Initial Volume of envelope          (1-15, 0=No Sound)
Wave Duty:
  0: 12.5% ( -_______-_______-_______ )
  1: 25%   ( --______--______--______ )
  2: 50%   ( ----____----____----____ ) (normal)
  3: 75%   ( ------__------__------__ )
The Length value is used only if Bit 6 in NR14 is set.

4000064h - SOUND1CNT_X (NR13, NR14) - Channel 1 Frequency/Control (R/W)
  Bit        Expl.
  0-10  W    Frequency; 131072/(2048-n)Hz  (0-2047)
  11-13 -    Not used
  14    R/W  Length Flag  (1=Stop output when length in NR11 expires)
  15    W    Initial      (1=Restart Sound)
  16-31 -    Not used


GBA Sound Channel 2 - Tone

This sound channel works exactly as channel 1, except that it doesn't have a Tone Envelope/Sweep Register.

4000068h - SOUND2CNT_L (NR21, NR22) - Channel 2 Duty/Length/Envelope (R/W)
400006Ah - Not used
400006Ch - SOUND2CNT_H (NR23, NR24) - Channel 2 Frequency/Control (R/W)
For details, refer to channel 1 description.


GBA Sound Channel 3 - Wave Output

This channel can be used to output digital sound, the length of the sample buffer (Wave RAM) can be either 32 or 64 digits (4bit samples). This sound channel can be also used to output normal tones when initializing the Wave RAM by a square wave. This channel doesn't have a volume envelope register.

4000070h - SOUND3CNT_L (NR30) - Channel 3 Stop/Wave RAM select (R/W)
  Bit        Expl.
  0-4   -    Not used
  5     R/W  Wave RAM Dimension   (0=One bank/32 digits, 1=Two banks/64 digits)
  6     R/W  Wave RAM Bank Number (0-1, see below)
  7     R/W  Sound Channel 3 Off  (0=Stop, 1=Playback)
  8-15  -    Not used
The currently selected Bank Number (Bit 6) will be played back, while reading/writing to/from wave RAM will address the other (not selected) bank. When dimension is set to two banks, output will start by replaying the currently selected bank.

4000072h - SOUND3CNT_H (NR31, NR32) - Channel 3 Length/Volume (R/W)
  Bit        Expl.
  0-7   W    Sound length; units of (256-n)/256s  (0-255)
  8-12  -    Not used.
  13-14 R/W  Sound Volume  (0=Mute/Zero, 1=100%, 2=50%, 3=25%)
  15    R/W  Force Volume  (0=Use above, 1=Force 75% regardless of above)
The Length value is used only if Bit 6 in NR34 is set.

4000074h - SOUND3CNT_X (NR33, NR34) - Channel 3 Frequency/Control (R/W)
  Bit        Expl.
  0-10  W    Sample Rate; 2097152/(2048-n) Hz   (0-2047)
  11-13 -    Not used
  14    R/W  Length Flag  (1=Stop output when length in NR31 expires)
  15    W    Initial      (1=Restart Sound)
  16-31 -    Not used
The above sample rate specifies the number of wave RAM digits per second, the actual tone frequency depends on the wave RAM content, for example:
  Wave RAM, single bank 32 digits   Tone Frequency
  FFFFFFFFFFFFFFFF0000000000000000  65536/(2048-n) Hz
  FFFFFFFF00000000FFFFFFFF00000000  131072/(2048-n) Hz
  FFFF0000FFFF0000FFFF0000FFFF0000  262144/(2048-n) Hz
  FF00FF00FF00FF00FF00FF00FF00FF00  524288/(2048-n) Hz
  F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0  1048576/(2048-n) Hz

4000090h - WAVE_RAM0_L - Channel 3 Wave Pattern RAM (W/R)
4000092h - WAVE_RAM0_H - Channel 3 Wave Pattern RAM (W/R)
4000094h - WAVE_RAM1_L - Channel 3 Wave Pattern RAM (W/R)
4000096h - WAVE_RAM1_H - Channel 3 Wave Pattern RAM (W/R)
4000098h - WAVE_RAM2_L - Channel 3 Wave Pattern RAM (W/R)
400009Ah - WAVE_RAM2_H - Channel 3 Wave Pattern RAM (W/R)
400009Ch - WAVE_RAM3_L - Channel 3 Wave Pattern RAM (W/R)
400009Eh - WAVE_RAM3_H - Channel 3 Wave Pattern RAM (W/R)
This area contains 16 bytes (32 x 4bits) Wave Pattern data which is output by channel 3. Data is played back ordered as follows: MSBs of 1st byte, followed by LSBs of 1st byte, followed by MSBs of 2nd byte, and so on - this results in a confusing ordering when filling Wave RAM in units of 16bit data - ie. samples would be then located in Bits 4-7, 0-3, 12-15, 8-11.

In the GBA, two Wave Patterns exists (each 32 x 4bits), either one may be played (as selected in NR30 register), the other bank may be accessed by the users. After all 32 samples have been played, output of the same bank (or other bank, as specified in NR30) will be automatically restarted.

Internally, Wave RAM is a giant shift-register, there is no pointer which is addressing the currently played digit. Instead, the entire 128 bits are shifted, and the 4 least significant bits are output.
Thus, when reading from Wave RAM, data might have changed its position. And, when writing to Wave RAM all data should be updated (it'd be no good idea to assume that old data is still located at the same position where it has been written to previously).


GBA Sound Channel 4 - Noise

This channel is used to output white noise. This is done by randomly switching the amplitude between high and low at a given frequency. Depending on the frequency the noise will appear 'harder' or 'softer'.

It is also possible to influence the function of the random generator, so the that the output becomes more regular, resulting in a limited ability to output Tone instead of Noise.

4000078h - SOUND4CNT_L (NR41, NR42) - Channel 4 Length/Envelope (R/W)
  Bit        Expl.
  0-5   W    Sound length; units of (64-n)/256s  (0-63)
  6-7   -    Not used
  8-10  R/W  Envelope Step-Time; units of n/64s  (1-7, 0=No Envelope)
  11    R/W  Envelope Direction                  (0=Decrease, 1=Increase)
  12-15 R/W  Initial Volume of envelope          (1-15, 0=No Sound)
  16-31 -    Not used
The Length value is used only if Bit 6 in NR44 is set.

400007Ch - SOUND4CNT_H (NR43, NR44) - Channel 4 Frequency/Control (R/W)
The amplitude is randomly switched between high and low at the given frequency. A higher frequency will make the noise to appear 'softer'.
When Bit 3 is set, the output will become more regular, and some frequencies will sound more like Tone than Noise.
  Bit        Expl.
  0-2   R/W  Dividing Ratio of Frequencies (r)
  3     R/W  Counter Step/Width (0=15 bits, 1=7 bits)
  4-7   R/W  Shift Clock Frequency (s)
  8-13  -    Not used
  14    R/W  Length Flag  (1=Stop output when length in NR41 expires)
  15    W    Initial      (1=Restart Sound)
  16-31 -    Not used
Frequency = 524288 Hz / r / 2^(s+1) ;For r=0 assume r=0.5 instead

Noise Random Generator (aka Polynomial Counter)
Noise randomly switches between HIGH and LOW levels, the output levels are calculated by a shift register (X), at the selected frequency, as such:
  7bit:  X=X SHR 1, IF carry THEN Out=HIGH, X=X XOR 60h ELSE Out=LOW
  15bit: X=X SHR 1, IF carry THEN Out=HIGH, X=X XOR 6000h ELSE Out=LOW
The initial value when (re-)starting the sound is X=40h (7bit) or X=4000h (15bit). The data stream repeats after 7Fh (7bit) or 7FFFh (15bit) steps.


GBA Sound Channel A and B - DMA Sound

The GBA contains two DMA sound channels (A and B), each allowing to replay digital sound (signed 8bit data, ie. -128..+127). Data can be transferred from INTERNAL memory (not sure if EXTERNAL memory works also ?) to FIFO by using DMA channel 1 or 2, the sample rate is generated by using one of the Timers.

40000A0h - FIFO_A_L - Sound A FIFO, Data 0 and Data 1 (W)
40000A2h - FIFO_A_H - Sound A FIFO, Data 2 and Data 3 (W)
These two registers may receive 32bit (4 bytes) of audio data (Data 0-3, Data 0 being located in least significant byte which is replayed first).
Internally, the capacity of the FIFO is 8 x 32bit (32 bytes), allowing to buffer a small amount of samples. As the name says (First In First Out), oldest data is replayed first.

40000A4h - FIFO_B_L - Sound B FIFO, Data 0 and Data 1 (W)
40000A6h - FIFO_B_H - Sound B FIFO, Data 2 and Data 3 (W)
Same as above, for Sound B.

Initializing DMA-Sound Playback
- Select Timer 0 or 1 in SOUNDCNT_H control register.
- Clear the FIFO.
- Manually write a sample byte to the FIFO.
- Initialize transfer mode for DMA 1 or 2.
- Initialize DMA Sound settings in sound control register.
- Start the timer.

DMA-Sound Playback Procedure
The pseudo-procedure below is automatically repeated.
  If Timer overflows then
    Move 8bit data from FIFO to sound circuit.
    If FIFO contains only 4 x 32bits (16 bytes) then
      Request more data per DMA
      Receive 4 x 32bit (16 bytes) per DMA
    Endif
  Endif
This playback mechanism will be repeated forever, regardless of the actual length of the sample buffer.

Synchronizing Sample Buffers
The buffer-end may be determined by counting sound Timer IRQs (each sample byte), or sound DMA IRQs (each 16th sample byte). Both methods would require a lot of CPU time (IRQ processing), and both would fail if interrupts are disabled for a longer period.
Better solutions would be to synchronize the sample rate/buffer length with V-blanks, or to use a second timer (in count up/slave mode) which produces an IRQ after the desired number of samples.

The Sample Rate
The GBA hardware does internally re-sample all sound output to 32.768kHz (default SOUNDBIAS setting). It'd thus do not make much sense to use higher DMA/Timer rates. Best re-sampling accuracy can be gained by using DMA/Timer rates of 32.768kHz, 16.384kHz, or 8.192kHz (ie. fragments of the physical output rate).


GBA Sound Control Registers

4000080h - SOUNDCNT_L (NR50, NR51) - Channel L/R Volume/Enable (R/W)
  Bit        Expl.
  0-2   R/W  Sound 1-4 Master Volume RIGHT (0-7)
  3     -    Not used
  4-6   R/W  Sound 1-4 Master Volume LEFT (0-7)
  7     -    Not used
  8-11  R/W  Sound 1-4 Enable Flags RIGHT (each Bit 8-11, 0=Disable, 1=Enable)
  12-15 R/W  Sound 1-4 Enable Flags LEFT (each Bit 12-15, 0=Disable, 1=Enable)

4000082h - SOUNDCNT_H (GBA only) - DMA Sound Control/Mixing (R/W)
  Bit        Expl.
  0-1   R/W  Sound # 1-4 Volume   (0=25%, 1=50%, 2=100%, 3=Prohibited)
  2     R/W  DMA Sound A Volume   (0=50%, 1=100%)
  3     R/W  DMA Sound B Volume   (0=50%, 1=100%)
  4-7   -    Not used
  8     R/W  DMA Sound A Enable RIGHT (0=Disable, 1=Enable)
  9     R/W  DMA Sound A Enable LEFT  (0=Disable, 1=Enable)
  10    R/W  DMA Sound A Timer Select (0=Timer 0, 1=Timer 1)
  11    W?   DMA Sound A Reset FIFO   (1=Reset)
  12    R/W  DMA Sound B Enable RIGHT (0=Disable, 1=Enable)
  13    R/W  DMA Sound B Enable LEFT  (0=Disable, 1=Enable)
  14    R/W  DMA Sound B Timer Select (0=Timer 0, 1=Timer 1)
  15    W?   DMA Sound B Reset FIFO   (1=Reset)

4000084h - SOUNDCNT_X (NR52) - Sound on/off (R/W)
Bits 0-3 are automatically set when starting sound output, and are automatically cleared when a sound ends. (Ie. when the length expires, as far as length is enabled. The bits are NOT reset when an volume envelope ends.)
  Bit        Expl.
  0     R    Sound 1 ON flag (Read Only)
  1     R    Sound 2 ON flag (Read Only)
  2     R    Sound 3 ON flag (Read Only)
  3     R    Sound 4 ON flag (Read Only)
  4-6   -    Not used
  7     R/W  PSG/FIFO Master Enable (0=Disable, 1=Enable) (Read/Write)
  8-31  -    Not used
While Bit 7 is cleared, both PSG and FIFO sounds are disabled, and all PSG registers at 4000060h..4000081h are reset to zero (and must be re-initialized after re-enabling sound). However, registers 4000082h and 4000088h are kept read/write-able (of which, 4000082h has no function when sound is off, whilst 4000088h does work even when sound is off).

4000088h - SOUNDBIAS - Sound PWM Control (R/W, see below)
This register controls the final sound output. The default setting is 0200h, it is normally not required to change this value.
  Bit        Expl.
  0     -    Not used
  1-9   R/W  Bias Level (Default=100h, converting signed samples into unsigned)
  10-13 -    Not used
  14-15 R/W  Amplitude Resolution/Sampling Cycle (Default=0, see below)
  16-31 -    Not used
Amplitude Resolution/Sampling Cycle (0-3):
  0  9bit / 32.768kHz   (Default, best for DMA channels A,B)
  1  8bit / 65.536kHz
  2  7bit / 131.072kHz
  3  6bit / 262.144kHz  (Best for PSG channels 1-4)
The Bias Level has no audible effect on 3DS in GBA mode.
For more information on this register, read the descriptions below.

400008Ch - Not used
400008Eh - Not used

Max Output Levels (with max volume settings)
Each of the two FIFOs can span the FULL output range (+/-200h).
Each of the four PSGs can span one QUARTER of the output range (+/-80h).
The current output levels of all six channels are added together by hardware.
So together, the FIFOs and PSGs, could reach THRICE the range (+/-600h).
The BIAS value is added to that signed value. With default BIAS (200h), the possible range becomes -400h..+800h, however, values that exceed the unsigned 10bit output range of 0..3FFh are clipped to MinMax(0,3FFh).

Resampling to 32.768kHz / 9bit (default)
The PSG channels 1-4 are internally generated at 262.144kHz, and DMA sound A-B could be theoretically generated at timer rates up to 16.78MHz. However, the final sound output is resampled to a rate of 32.768kHz, at 9bit depth (the above 10bit value, divided by two). If necessary, rates higher than 32.768kHz can be selected in the SOUNDBIAS register, that would result in a depth smaller than 9bit though.

PWM (Pulse Width Modulation) Output 16.78MHz / 1bit
Okay, now comes the actual output. The GBA can output only two voltages (low and high), these 'bits' are output at system clock speed (16.78MHz). If using the default 32.768kHz sampling rate, then 512 bits are output per sample (512*32K=16M). Each sample value (9bit range, N=0..511), would be then output as N low bits, followed by 512-N high bits. The resulting 'noise' is smoothed down by capacitors, by the speaker, and by human hearing, so that it will effectively sound like clean D/A converted 9bit voltages at 32kHz sampling rate.

Changing the BIAS Level
Normally use 200h for clean sound output. A value of 000h might make sense during periods when no sound is output (causing the PWM circuit to output low-bits only, which is eventually reducing the power consumption, and/or preventing 32KHz noise). Note: Using the SoundBias function (SWI 19h) allows to change the level by slowly incrementing or decrementing it (without hard scratch noise).

Low Power Mode
When not using sound output, power consumption can be reduced by setting both 4000084h (PSG/FIFO) and 4000088h (BIAS) to zero.


GBA Comparison of CGB and GBA Sound

The GBA sound controller is mostly the same than that of older monochrome gameboy and CGB. The following changes have been done:

New Sound Channels
Two new sound channels have been added that may be used to replay 8bit digital sound. Sample rate and sample data must be supplied by using a Timer and a DMA channel.

New Control Registers
The SOUNDCNT_H register controls the new DMA channels - as well as mixing with the four old channels. The SOUNDBIAS register controls the final sound output.

Sound Channel 3 Changes
The length of the Wave RAM is doubled by dividing it into two banks of 32 digits each, either one or both banks may be replayed (one after each other), for details check NR30 Bit 5-6. Optionally, the sound may be output at 75% volume, for details check NR32 Bit 7.

Changed Control Registers
NR50 is not supporting Vin signals (that's been an external sound input from cartridge).

Changed I/O Addresses
The GBAs sound register are located at 04000060-040000AE instead of at FF10-FF3F as in CGB and monochrome gameboy. However, note that there have been new blank spaces inserted between some of the separate registers - therefore it is NOT possible to port CGB software to GBA just by changing the sound base address.

Accessing I/O Registers
In some cases two of the old 8bit registers are packed into a 16bit register and may be accessed as such.


GBA Timers

The GBA includes four incrementing 16bit timers.
Timer 0 and 1 can be used to supply the sample rate for DMA sound channel A and/or B.

4000100h - TM0CNT_L - Timer 0 Counter/Reload (R/W)
4000104h - TM1CNT_L - Timer 1 Counter/Reload (R/W)
4000108h - TM2CNT_L - Timer 2 Counter/Reload (R/W)
400010Ch - TM3CNT_L - Timer 3 Counter/Reload (R/W)
Writing to these registers initializes the <reload> value (but does not directly affect the current counter value). Reading returns the current <counter> value (or the recent/frozen counter value if the timer has been stopped).
The reload value is copied into the counter only upon following two situations: Automatically upon timer overflows, or when the timer start bit becomes changed from 0 to 1.
Note: When simultaneously changing the start bit from 0 to 1, and setting the reload value at the same time (by a single 32bit I/O operation), then the newly written reload value is recognized as new counter value.

4000102h - TM0CNT_H - Timer 0 Control (R/W)
4000106h - TM1CNT_H - Timer 1 Control (R/W)
400010Ah - TM2CNT_H - Timer 2 Control (R/W)
400010Eh - TM3CNT_H - Timer 3 Control (R/W)
  Bit   Expl.
  0-1   Prescaler Selection (0=F/1, 1=F/64, 2=F/256, 3=F/1024)
  2     Count-up Timing   (0=Normal, 1=See below)  ;Not used in TM0CNT_H
  3-5   Not used
  6     Timer IRQ Enable  (0=Disable, 1=IRQ on Timer overflow)
  7     Timer Start/Stop  (0=Stop, 1=Operate)
  8-15  Not used
When Count-up Timing is enabled, the prescaler value is ignored, instead the time is incremented each time when the previous counter overflows. This function cannot be used for Timer 0 (as it is the first timer).
F = System Clock (16.78MHz).


GBA DMA Transfers

Overview
The GBA includes four DMA channels, the highest priority is assigned to DMA0, followed by DMA1, DMA2, and DMA3. DMA Channels with lower priority are paused until channels with higher priority have completed.
The CPU is paused when DMA transfers are active, however, the CPU is operating during the periods when Sound/Blanking DMA transfers are paused.

Special features of the separate DMA channels
DMA0 - highest priority, best for timing critical transfers (eg. HBlank DMA).
DMA1 and DMA2 - can be used to feed digital sample data to the Sound FIFOs.
DMA3 - can be used to write to Game Pak ROM/FlashROM (but not GamePak SRAM).
Aside from that, each DMA 0-3 may be used for whatever general purposes.

40000B0h,0B2h - DMA0SAD - DMA 0 Source Address (W) (internal memory)
40000BCh,0BEh - DMA1SAD - DMA 1 Source Address (W) (any memory)
40000C8h,0CAh - DMA2SAD - DMA 2 Source Address (W) (any memory)
40000D4h,0D6h - DMA3SAD - DMA 3 Source Address (W) (any memory)
The most significant address bits are ignored, only the least significant 27 or 28 bits are used (max 07FFFFFFh internal memory, or max 0FFFFFFFh any memory - except SRAM ?!).

40000B4h,0B6h - DMA0DAD - DMA 0 Destination Address (W) (internal memory)
40000C0h,0C2h - DMA1DAD - DMA 1 Destination Address (W) (internal memory)
40000CCh,0CEh - DMA2DAD - DMA 2 Destination Address (W) (internal memory)
40000D8h,0DAh - DMA3DAD - DMA 3 Destination Address (W) (any memory)
The most significant address bits are ignored, only the least significant 27 or 28 bits are used (max. 07FFFFFFh internal memory or 0FFFFFFFh any memory - except SRAM ?!).

40000B8h - DMA0CNT_L - DMA 0 Word Count (W) (14 bit, 1..4000h)
40000C4h - DMA1CNT_L - DMA 1 Word Count (W) (14 bit, 1..4000h)
40000D0h - DMA2CNT_L - DMA 2 Word Count (W) (14 bit, 1..4000h)
40000DCh - DMA3CNT_L - DMA 3 Word Count (W) (16 bit, 1..10000h)
Specifies the number of data units to be transferred, each unit is 16bit or 32bit depending on the transfer type, a value of zero is treated as max length (ie. 4000h, or 10000h for DMA3).

40000BAh - DMA0CNT_H - DMA 0 Control (R/W)
40000C6h - DMA1CNT_H - DMA 1 Control (R/W)
40000D2h - DMA2CNT_H - DMA 2 Control (R/W)
40000DEh - DMA3CNT_H - DMA 3 Control (R/W)
  Bit   Expl.
  0-4   Not used
  5-6   Dest Addr Control  (0=Increment,1=Decrement,2=Fixed,3=Increment/Reload)
  7-8   Source Adr Control (0=Increment,1=Decrement,2=Fixed,3=Prohibited)
  9     DMA Repeat                   (0=Off, 1=On) (Must be zero if Bit 11 set)
  10    DMA Transfer Type            (0=16bit, 1=32bit)
  11    Game Pak DRQ  - DMA3 only -  (0=Normal, 1=DRQ <from> Game Pak, DMA3)
  12-13 DMA Start Timing  (0=Immediately, 1=VBlank, 2=HBlank, 3=Special)
          The 'Special' setting (Start Timing=3) depends on the DMA channel:
          DMA0=Prohibited, DMA1/DMA2=Sound FIFO, DMA3=Video Capture
  14    IRQ upon end of Word Count   (0=Disable, 1=Enable)
  15    DMA Enable                   (0=Off, 1=On)
After changing the Enable bit from 0 to 1, wait 2 clock cycles before accessing any DMA related registers.

When accessing OAM (7000000h) or OBJ VRAM (6010000h) by HBlank Timing, then the "H-Blank Interval Free" bit in DISPCNT register must be set.

Source and Destination Address and Word Count Registers
The SAD, DAD, and CNT_L registers are holding the initial start addresses, and initial length. The hardware does NOT change the content of these registers during or after the transfer.
The actual transfer takes place by using internal pointer/counter registers. The initial values are copied into internal regs under the following circumstances:
Upon DMA Enable (Bit 15) changing from 0 to 1: Reloads SAD, DAD, CNT_L.
Upon Repeat: Reloads CNT_L, and optionally DAD (Increment+Reload).

DMA Repeat bit
If the Repeat bit is cleared: The Enable bit is automatically cleared after the specified number of data units has been transferred.
If the Repeat bit is set: The Enable bit remains set after the transfer, and the transfer will be restarted each time when the Start condition (eg. HBlank, Fifo) becomes true. The specified number of data units is transferred <each> time when the transfer is (re-)started. The transfer will be repeated forever, until it gets stopped by software.

Sound DMA (FIFO Timing Mode) (DMA1 and DMA2 only)
In this mode, the DMA Repeat bit must be set, and the destination address must be FIFO_A (040000A0h) or FIFO_B (040000A4h).
Upon DMA request from sound controller, 4 units of 32bits (16 bytes) are transferred (both Word Count register and DMA Transfer Type bit are ignored). The destination address will not be incremented in FIFO mode.
Keep in mind that DMA channels of higher priority may offhold sound DMA. For example, when using a 64 kHz sample rate, 16 bytes of sound DMA data are requested each 0.25ms (4 kHz), at this time another 16 bytes are still in the FIFO so that there's still 0.25ms time to satisfy the DMA request. Thus DMAs with higher priority should not be operated for longer than 0.25ms. (This problem does not arise for HBlank transfers as HBlank time is limited to 16.212us.)

Game Pak DMA
Only DMA 3 may be used to transfer data to/from Game Pak ROM or Flash ROM - it cannot access Game Pak SRAM though (as SRAM data bus is limited to 8bit units). In normal mode, DMA is requested as long until Word Count becomes zero. When setting the 'Game Pack DRQ' bit, then the cartridge must contain an external circuit which outputs a /DREQ signal. Note that there is only one pin for /DREQ and /IREQ, thus the cartridge may not supply /IREQs while using DRQ mode.

Video Capture Mode (DMA3 only)
Intended to copy a bitmap from memory (or from external hardware/camera) to VRAM. When using this transfer mode, set the repeat bit, and write the number of data units (per scanline) to the word count register. Capture works similar like HBlank DMA, however, the transfer is started when VCOUNT=2, it is then repeated each scanline, and it gets stopped when VCOUNT=162.

Transfer End
The DMA Enable flag (Bit 15) is automatically cleared upon completion of the transfer. The user may also clear this bit manually in order to stop the transfer (obviously this is possible for Sound/Blanking DMAs only, in all other cases the CPU is stopped until the transfer completes by itself).

Transfer Rate/Timing
Except for the first data unit, all units are transferred by sequential reads and writes. For n data units, the DMA transfer time is:
  2N+2(n-1)S+xI
Of which, 1N+(n-1)S are read cycles, and the other 1N+(n-1)S are write cycles, actual number of cycles depends on the waitstates and bus-width of the source and destination areas (as described in CPU Instruction Cycle Times chapter). Internal time for DMA processing is 2I (normally), or 4I (if both source and destination are in gamepak memory area).

DMA lockup when stopping while starting ???
Capture delayed, Capture Enable=AutoCleared ???


GBA Communication Ports

The GBAs Serial Port may be used in various different communication modes. Normal mode may exchange data between two GBAs (or to transfer data from master GBA to several slave GBAs in one-way direction).
Multi-player mode may exchange data between up to four GBAs. UART mode works much like a RS232 interface. JOY Bus mode uses a standardized Nintendo protocol. And General Purpose mode allows to mis-use the 'serial' port as bi-directional 4bit parallel port.
Note: The Nintendo DS does not include a Serial Port.

SIO Normal Mode
SIO Multi-Player Mode
SIO UART Mode
SIO JOY BUS Mode
SIO General-Purpose Mode
SIO Control Registers Summary

Wireless Adapter
GBA Wireless Adapter

Infrared Communication Adapters
Even though early GBA prototypes have been intended to support IR communication, this feature has been removed.
However, Nintendo is apparently considering to provide an external IR adapter (to be connected to the SIO connector, being accessed in General Purpose mode).
Also, it'd be theoretically possible to include IR ports built-in in game cartridges (as done for some older 8bit/monochrome Hudson games).


SIO Normal Mode

This mode is used to communicate between two units.
Transfer rates of 256Kbit/s or 2Mbit/s can be selected, however, the fast 2Mbit/s is intended ONLY for special hardware expansions that are DIRECTLY connected to the GBA link port (ie. without a cable being located between the GBA and expansion hardware). In normal cases, always use 256Kbit/s transfer rate which provides stable results.
Transfer lengths of 8bit or 32bit may be used, the 8bit mode is the same as for older DMG/CGB gameboys, however, the voltages for "GBA cartridges in GBAs" are different as for "DMG/CGB cartridges in DMG/CGB/GBAs", ie. it is not possible to communicate between DMG/CGB games and GBA games.

4000134h - RCNT (R) - Mode Selection, in Normal/Multiplayer/UART modes (R/W)
  Bit   Expl.
  0-3   Undocumented (current SC,SD,SI,SO state, as for General Purpose mode)
  4-8   Not used     (Should be 0, bits are read/write-able though)
  9-13  Not used     (Always 0, read only)
  14    Not used     (Should be 0, bit is read/write-able though)
  15    Must be zero (0) for Normal/Multiplayer/UART modes

4000128h - SIOCNT - SIO Control, usage in NORMAL Mode (R/W)
  Bit   Expl.
  0     Shift Clock (SC)        (0=External, 1=Internal)
  1     Internal Shift Clock    (0=256KHz, 1=2MHz)
  2     SI State (opponents SO) (0=Low, 1=High/None) --- (Read Only)
  3     SO during inactivity    (0=Low, 1=High) (applied ONLY when Bit7=0)
  4-6   Not used                (Read only, always 0 ?)
  7     Start Bit               (0=Inactive/Ready, 1=Start/Active)
  8-11  Not used                (R/W, should be 0)
  12    Transfer Length         (0=8bit, 1=32bit)
  13    Must be "0" for Normal Mode
  14    IRQ Enable              (0=Disable, 1=Want IRQ upon completion)
  15    Not used                (Read only, always 0)
The Start bit is automatically reset when the transfer completes, ie. when all 8 or 32 bits are transferred, at that time an IRQ may be generated.

400012Ah - SIODATA8 - SIO Normal Communication 8bit Data (R/W)
For 8bit normal mode. Contains 8bit data (only lower 8bit are used). Outgoing data should be written to this register before starting the transfer. During transfer, transmitted bits are shifted-out (MSB first), and received bits are shifted-in simultaneously. Upon transfer completion, the register contains the received 8bit value.

4000120h - SIODATA32_L - SIO Normal Communication lower 16bit data (R/W)
4000122h - SIODATA32_H - SIO Normal Communication upper 16bit data (R/W)
Same as above SIODATA8, for 32bit normal transfer mode respectively.
SIOCNT/RCNT must be set to 32bit normal mode <before> writing to SIODATA32.

Initialization
First, initialize RCNT register. Second, set mode/clock bits in SIOCNT with startbit cleared. For master: select internal clock, and (in most cases) specify 256KHz as transfer rate. For slave: select external clock, the local transfer rate selection is then ignored, as the transfer rate is supplied by the remote GBA (or other computer, which might supply custom transfer rates).
Third, set the startbit in SIOCNT with mode/clock bits unchanged.

Recommended Communication Procedure for SLAVE unit (external clock)
- Initialize data which is to be sent to master.
- Set Start flag.
- Set SO to LOW to indicate that master may start now.
- Wait for IRQ (or for Start bit to become zero). (Check timeout here!)
- Set SO to HIGH to indicate that we are not ready.
- Process received data.
- Repeat procedure if more data is to be transferred.
(or is so=high done automatically? would be fine - more stable - otherwise master may still need delay)

Recommended Communication Procedure for SLAVE unit (external clock)
- Initialize data which is to be sent to master.
- Set Start=0 and SO=0 (SO=LOW indicates that slave is (almost) ready).
- Set Start=1 and SO=1 (SO=HIGH indicates not ready, applied after transfer).
  (Expl. Old SO=LOW kept output until 1st clock bit received).
  (Expl. New SO=HIGH is automatically output at transfer completion).
- Set SO to LOW to indicate that master may start now.
- Wait for IRQ (or for Start bit to become zero). (Check timeout here!)
- Process received data.
- Repeat procedure if more data is to be transferred.

Recommended Communication Procedure for MASTER unit (internal clock)
- Initialize data which is to be sent to slave.
- Wait for SI to become LOW (slave ready). (Check timeout here!)
- Set Start flag.
- Wait for IRQ (or for Start bit to become zero).
- Process received data.
- Repeat procedure if more data is to be transferred.

Cable Protocol
During inactive transfer, the shift clock (SC) is high. The transmit (SO) and receive (SI) data lines may be manually controlled as described above.
When master sends SC=LOW, each master and slave must output the next outgoing data bit to SO. When master sends SC=HIGH, each master and slave must read out the opponents data bit from SI. This is repeated for each of the 8 or 32 bits, and when completed SC will be kept high again.

Transfer Rates
Either 256KHz or 2MHz rates can be selected for SC, so max 32KBytes (256Kbit) or 128KBytes (2Mbit) can be transferred per second. However, the software must process each 8bit or 32bit of transmitted data separately, so the actual transfer rate will be reduced by the time spent on handling each data unit.
Only 256KHz provides stable results in most cases (such like when linking between two GBAs). The 2MHz rate is intended for special expansion hardware (with very short wires) only.

Using Normal mode for One-Way Multiplayer communication
When using normal mode with multiplay-cables, data isn't exchanged between first and second GBA as usually. Instead, data is shifted from first to last GBA (the first GBA receives zero, because master SI is shortcut to GND).
This behaviour may be used for fast ONE-WAY data transfer from master to all other GBAs. For example (3 GBAs linked):
  Step         Sender      1st Recipient   2nd Recipient
  Transfer 1:  DATA #0 --> UNDEF      -->  UNDEF     -->
  Transfer 2:  DATA #1 --> DATA #0    -->  UNDEF     -->
  Transfer 3:  DATA #2 --> DATA #1    -->  DATA #0   -->
  Transfer 4:  DATA #3 --> DATA #2    -->  DATA #1   -->
The recipients should not output any own data, instead they should forward the previously received data to the next recipient during next transfer (just keep the incoming data unmodified in the data register).
Due to the delayed forwarding, 2nd recipient should ignore the first incoming data. After the last transfer, the sender must send one (or more) dummy data unit(s), so that the last data is forwarded to the 2nd (or further) recipient(s).


SIO Multi-Player Mode

Multi-Player mode can be used to communicate between up to 4 units.

4000134h - RCNT (R) - Mode Selection, in Normal/Multiplayer/UART modes (R/W)
  Bit   Expl.
  0-3   Undocumented (current SC,SD,SI,SO state, as for General Purpose mode)
  4-8   Not used     (Should be 0, bits are read/write-able though)
  9-13  Not used     (Always 0, read only)
  14    Not used     (Should be 0, bit is read/write-able though)
  15    Must be zero (0) for Normal/Multiplayer/UART modes
Note: Even though undocumented, many Nintendo games are using Bit 0 to test current SC state in multiplay mode.

4000128h - SIOCNT - SIO Control, usage in MULTI-PLAYER Mode (R/W)
  Bit   Expl.
  0-1   Baud Rate     (0-3: 9600,38400,57600,115200 bps)
  2     SI-Terminal   (0=Parent, 1=Child)                  (Read Only)
  3     SD-Terminal   (0=Bad connection, 1=All GBAs Ready) (Read Only)
  4-5   Multi-Player ID     (0=Parent, 1-3=1st-3rd child)  (Read Only)
  6     Multi-Player Error  (0=Normal, 1=Error)            (Read Only)
  7     Start/Busy Bit      (0=Inactive, 1=Start/Busy) (Read Only for Slaves)
  8-11  Not used            (R/W, should be 0)
  12    Must be "0" for Multi-Player mode
  13    Must be "1" for Multi-Player mode
  14    IRQ Enable          (0=Disable, 1=Want IRQ upon completion)
  15    Not used            (Read only, always 0)
The ID Bits are undefined until the first transfer has completed.

400012Ah - SIOMLT_SEND - Data Send Register (R/W)
Outgoing data (16 bit) which is to be sent to the other GBAs.

4000120h - SIOMULTI0 - SIO Multi-Player Data 0 (Parent) (R/W)
4000122h - SIOMULTI1 - SIO Multi-Player Data 1 (1st child) (R/W)
4000124h - SIOMULTI2 - SIO Multi-Player Data 2 (2nd child) (R/W)
4000126h - SIOMULTI3 - SIO Multi-Player Data 3 (3rd child) (R/W)
These registers are automatically reset to FFFFh upon transfer start.
After transfer, these registers contain incoming data (16bit each) from all remote GBAs (if any / otherwise still FFFFh), as well as the local outgoing SIOMLT_SEND data.
Ie. after the transfer, all connected GBAs will contain the same values in their SIOMULTI0-3 registers.

Initialization
- Initialize RCNT Bit 14-15 and SIOCNT Bit 12-13 to select Multi-Player mode.
- Read SIOCNT Bit 3 to verify that all GBAs are in Multi-Player mode.
- Read SIOCNT Bit 2 to detect whether this is the Parent/Master unit.

Recommended Transmission Procedure
- Write outgoing data to SIODATA_SEND.
- Master must set Start bit.
- All units must process received data in SIOMULTI0-3 when transfer completed.
- After the first successful transfer, ID Bits in SIOCNT are valid.
- If more data is to be transferred, repeat procedure.
The parent unit blindly sends data regardless of whether childs have already processed old data/supplied new data. So, parent unit might be required to insert delays between each transfer, and/or perform error checking.
Also, slave units may signalize that they are not ready by temporarily switching into another communication mode (which does not output SD High, as Multi-Player mode does during inactivity).

Transfer Protocol
Beginning
- The masters SI pin is always LOW.
- When all GBAs are in Multiplayer mode (ready) SD is HIGH.
- When master starts the transfer, it sets SC=LOW, slaves receive Busy bit.
Step A
- ID Bits in master unit are set to 0.
- Master outputs Startbit (LOW), 16bit Data, Stopbit (HIGH) through SD.
- This data is written to SIOMULTI0 of all GBAs (including master).
- Master forwards LOW from its SO to 1st childs SI.
- Transfer ends if next child does not output data after certain time.
Step B
- ID Bits in 1st child unit are set to 1.
- 1st Child outputs Startbit (LOW), 16bit Data, Stopbit (HIGH) through SD.
- This data is written to SIOMULTI1 of all GBAs (including 1st child).
- 1st child forwards LOW from its SO to 2nd childs SI.
- Transfer ends if next child does not output data after certain time.
Step C
- ID Bits in 2nd child unit are set to 2.
- 2nd Child outputs Startbit (LOW), 16bit Data, Stopbit (HIGH) through SD.
- This data is written to SIOMULTI2 of all GBAs (including 2nd child).
- 2nd child forwards LOW from its SO to 3rd childs SI.
- Transfer ends if next child does not output data after certain time.
Step D
- ID Bits in 3rd child unit are set to 3.
- 3rd Child outputs Startbit (LOW), 16bit Data, Stopbit (HIGH) through SD.
- This data is written to SIOMULTI3 of all GBAs (including 3rd child).
- Transfer ends (this was the last child).
Transfer end
- Master sets SC=HIGH, all GBAs set SO=HIGH.
- The Start/Busy bits of all GBAs are automatically cleared.
- Interrupts are requested in all GBAs (as far as enabled).

Error Bit
This bit is set when a slave did not receive SI=LOW even though SC=LOW signalized a transfer (this might happen when connecting more than 4 GBAs, or when the previous child is not connected). Also, the bit is set when a Stopbit wasn't HIGH.
The error bit may be undefined during active transfer - read only after transfer completion (the transfer continues and completes as normal even if errors have occurred for some or all GBAs).
Don't know: The bit is automatically reset/initialized with each transfer, or must be manually reset?

Transmission Time
The transmission time depends on the selected Baud rate. And on the amount of Bits (16 data bits plus start/stop bits for each GBA), delays between data for each GBA, plus final timeout (if less than 4 GBAs). That is, depending on the number of connected GBAs:
  GBAs    Bits    Delays   Timeout
  1       18      None     Yes
  2       36      1        Yes
  3       54      2        Yes
  4       72      3        None
(The average Delay and Timeout periods are unknown?)
Above is not counting the additional CPU time that must be spent on initiating and processing each transfer.

Fast One-Way Transmission
Beside for the actual SIO Multiplayer mode, you can also use SIO Normal mode for fast one-way data transfer from Master unit to all Child unit(s). See chapter about SIO Normal mode for details.


SIO UART Mode

This mode works much like a RS232 port, however, the voltages are unknown, probably 0/3V rather than +/-12V ?. SI and SO are data lines (with crossed wires), SC and SD signalize Clear to Send (with crossed wires also, which requires special cable when linking between two GBAs ?)

4000134h - RCNT (R) - Mode Selection, in Normal/Multiplayer/UART modes (R/W)
  Bit   Expl.
  0-3   Undocumented (current SC,SD,SI,SO state, as for General Purpose mode)
  4-8   Not used     (Should be 0, bits are read/write-able though)
  9-13  Not used     (Always 0, read only)
  14    Not used     (Should be 0, bit is read/write-able though)
  15    Must be zero (0) for Normal/Multiplayer/UART modes

4000128h - SCCNT_L - SIO Control, usage in UART Mode (R/W)
  Bit   Expl.
  0-1   Baud Rate  (0-3: 9600,38400,57600,115200 bps)
  2     CTS Flag   (0=Send always/blindly, 1=Send only when SC=LOW)
  3     Parity Control (0=Even, 1=Odd)
  4     Send Data Flag      (0=Not Full,  1=Full)    (Read Only)
  5     Receive Data Flag   (0=Not Empty, 1=Empty)   (Read Only)
  6     Error Flag          (0=No Error,  1=Error)   (Read Only)
  7     Data Length         (0=7bits,   1=8bits)
  8     FIFO Enable Flag    (0=Disable, 1=Enable)
  9     Parity Enable Flag  (0=Disable, 1=Enable)
  10    Send Enable Flag    (0=Disable, 1=Enable)
  11    Receive Enable Flag (0=Disable, 1=Enable)
  12    Must be "1" for UART mode
  13    Must be "1" for UART mode
  14    IRQ Enable          (0=Disable, 1=IRQ when any Bit 4/5/6 become set)
  15    Not used            (Read only, always 0)

400012Ah - SIODATA8 - usage in UART Mode (R/W)
Addresses the send/receive shift register, or (when FIFO is used) the send/receive FIFO. In either case only the lower 8bit of SIODATA8 are used, the upper 8bit are not used.
The send/receive FIFO may store up to four 8bit data units each. For example, while 1 unit is still transferred from the send shift register, it is possible to deposit another 4 units in the send FIFO, which are then automatically moved to the send shift register one after each other.

Send/Receive Enable, CTS Feedback
The receiver outputs SD=LOW (which is input as SC=LOW at the remote side) when it is ready to receive data (that is, when Receive Enable is set, and the Receive shift register (or receive FIFO) isn't full.
When CTS flag is set to always/blindly, then the sender transmits data immediately when Send Enable is set, otherwise data is transmitted only when Send Enable is set and SC is LOW.

Error Flag
The error flag is set when a bad stop bit has been received (stop bit must be 0), when a parity error has occurred (if enabled), or when new data has been completely received while the receive data register (or receive FIFO) is already full.
The error flag is automatically reset when reading from SIOCNT register.

Init & Initback
The content of the FIFO is reset when FIFO is disabled in UART mode, thus, when entering UART mode initially set FIFO=disabled.
The Send/Receive enable bits must be reset before switching from UART mode into another SIO mode!


SIO JOY BUS Mode

This communication mode uses Nintendo's standardized JOY Bus protocol. When using this communication mode, the GBA is always operated as SLAVE!

The JOY BUS mode is intended for communicating with Nintendo Gamecube (DOL) consoles, where the GBA would somehow act as peripheral for the Gamecube (unknown if/which Gamecube games are supporting that feature).

In this mode, SI and SO pins are data lines (apparently synchronized by Start/Stop bits?), SC and SD are set to low (including during active transfer?), the transfer rate is unknown?

4000134h - RCNT (R) - Mode Selection, in JOY BUS mode (R/W)
  Bit   Expl.
  0-3   Undocumented (current SC,SD,SI,SO state, as for General Purpose mode)
  4-8   Not used     (Should be 0, bits are read/write-able though)
  9-13  Not used     (Always 0, read only)
  14    Must be "1" for JOY BUS Mode
  15    Must be "1" for JOY BUS Mode

4000128h - SIOCNT - SIO Control, not used in JOY BUS Mode
This register is not used in JOY BUS mode.

4000140h - JOYCNT - JOY BUS Control Register (R/W)
  Bit   Expl.
  0     Device Reset Flag     (Command FFh)          (Read/Acknowledge)
  1     Receive Complete Flag (Command 14h or 15h?)  (Read/Acknowledge)
  2     Send Complete Flag    (Command 15h or 14h?)  (Read/Acknowledge)
  3-5   Not used
  6     IRQ when receiving a Device Reset Command  (0=Disable, 1=Enable)
  7-31  Not used
Bit 0-2 are working much like the bits in the IF register: Write a "1" bit to reset (acknowledge) the respective bit.
UNCLEAR: Interrupts can be requested for Send/Receive commands also?

4000150h - JOY_RECV_L - Receive Data Register low (R/W)
4000152h - JOY_RECV_H - Receive Data Register high (R/W)
4000154h - JOY_TRANS_L - Send Data Register low (R/W)
4000156h - JOY_TRANS_H - Send Data Register high (R/W)
Send/receive data registers.

4000158h - JOYSTAT - Receive Status Register (R/W)
  Bit   Expl.
  0     Not used
  1     Receive Status Flag   (0=Remote Side is/was receiving) (Read Only?)
  2     Not used
  3     Send Status Flag      (1=Remote Side is/was sending)   (Read Only?)
  4-5   General Purpose Flag  (Not assigned, may be used for whatever purpose)
  6-31  Not used
Bit 1 is automatically set when writing to local JOY_TRANS.
Bit 3 is automatically reset when reading from local JOY_RECV.

Below are the four possible commands which can be received by the GBA. Note that the GBA (slave) cannot send any commands itself, all it can do is to read incoming data, and to provide 'reply' data which may (or may not) be read out by the master unit.

Command FFh - Device Reset
  Receive FFh (Command)
  Send    00h (GBA Type number LSB)
  Send    04h (GBA Type number MSB)
  Send    XXh (lower 8bits of JOYSTAT register)

Command 00h - Type/Status Data Request
  Receive 00h (Command)
  Send    00h (GBA Type number LSB)
  Send    04h (GBA Type number MSB)
  Send    XXh (lower 8bits of JOYSTAT register)

Command 15h - GBA Data Write (to GBA)
  Receive 15h (Command)
  Receive XXh (Lower 8bits of JOY_RECV_L)
  Receive XXh (Upper 8bits of JOY_RECV_L)
  Receive XXh (Lower 8bits of JOY_RECV_H)
  Receive XXh (Upper 8bits of JOY_RECV_H)
  Send    XXh (lower 8bits of JOYSTAT register)

Command 14h - GBA Data Read (from GBA)
  Receive 14h (Command)
  Send    XXh (Lower 8bits of JOY_TRANS_L)
  Send    XXh (Upper 8bits of JOY_TRANS_L)
  Send    XXh (Lower 8bits of JOY_TRANS_H)
  Send    XXh (Upper 8bits of JOY_TRANS_H)
  Send    XXh (lower 8bits of JOYSTAT register)

See also
https://hitmen.c02.at/files/yagcd/yagcd/chap9.html


SIO General-Purpose Mode

In this mode, the SIO is 'misused' as a 4bit bi-directional parallel port, each of the SI,SO,SC,SD pins may be directly controlled, each can be separately declared as input (with internal pull-up) or as output signal.

4000134h - RCNT (R) - SIO Mode, usage in GENERAL-PURPOSE Mode (R/W)
Interrupts can be requested when SI changes from HIGH to LOW, as General Purpose mode does not require a serial shift clock, this interrupt may be produced even when the GBA is in Stop (low power standby) state.
  Bit   Expl.
  0     SC Data Bit         (0=Low, 1=High)
  1     SD Data Bit         (0=Low, 1=High)
  2     SI Data Bit         (0=Low, 1=High)
  3     SO Data Bit         (0=Low, 1=High)
  4     SC Direction        (0=Input, 1=Output)
  5     SD Direction        (0=Input, 1=Output)
  6     SI Direction        (0=Input, 1=Output, but see below)
  7     SO Direction        (0=Input, 1=Output)
  8     SI Interrupt Enable (0=Disable, 1=Enable)
  9-13  Not used
  14    Must be "0" for General-Purpose Mode
  15    Must be "1" for General-Purpose or JOYBUS Mode
SI should be always used as Input to avoid problems with other hardware which does not expect data to be output there.

4000128h - SIOCNT - SIO Control, not used in GENERAL-PURPOSE Mode
This register is not used in general purpose mode. That is, the separate bits of SIOCNT still exist and are read- and/or write-able in the same manner as for Normal, Multiplay, or UART mode (depending on SIOCNT Bit 12,13), but are having no effect on data being output to the link port.


SIO Control Registers Summary

Mode Selection (by RCNT.15-14 and SIOCNT.13-12)
  R.15 R.14 S.13 S.12 Mode
  0    x    0    0    Normal 8bit
  0    x    0    1    Normal 32bit
  0    x    1    0    Multiplay 16bit
  0    x    1    1    UART (RS232)
  1    0    x    x    General Purpose
  1    1    x    x    JOY BUS

SIOCNT
  Bit    0      1    2     3      4 5 6   7     8    9      10   11
  Normal Master Rate SI/In SO/Out - - -   Start -    -      -    -
  Multi  Baud   Baud SI/In SD/In  ID# Err Start -    -      -    -
  UART   Baud   Baud CTS   Parity S R Err Bits  FIFO Parity Send Recv


GBA Wireless Adapter

GBA Wireless Adapter (AGB-015 or OXY-004)
GBA Wireless Adapter Games
GBA Wireless Adapter Login
GBA Wireless Adapter Commands
GBA Wireless Adapter Component Lists


GBA Wireless Adapter Games

GBA Wireless Adapter compatible Games
  bit Generations series (Japan only)
  Boktai 2: Solar Boy Django (Konami)
  Boktai 3: Sabata's Counterattack
  Classic NES Series: Donkey Kong
  Classic NES Series: Dr. Mario
  Classic NES Series: Ice Climber
  Classic NES Series: Pac-Man
  Classic NES Series: Super Mario Bros.
  Classic NES Series: Xevious
  Digimon Racing (Bandai) (No Wireless Adapter support in European release)
  Dragon Ball Z: Buu's Fury (Atari)
  Famicom Mini Series: #13 Balloon Fight
  Famicom Mini Series: #12 Clu Clu Land
  Famicom Mini Series: #16 Dig Dug
  Famicom Mini Series: #02 Donkey Kong
  Famicom Mini Series: #15 Dr. Mario
  Famicom Mini Series: #03 Ice Climber
  Famicom Mini Series: #18 Makaimura
  Famicom Mini Series: #08 Mappy
  Famicom Mini Series: #11 Mario Bros.
  Famicom Mini Series: #06 Pac-Man
  Famicom Mini Series: #30 SD Gundam World Scramble Wars
  Famicom Mini Series: #01 Super Mario Bros.
  Famicom Mini Series: #21 Super Mario Bros.
  Famicom Mini Series: #19 Twin Bee
  Famicom Mini Series: #14 Wrecking Crew
  Famicom Mini Series: #07 Xevious
  Hamtaro: Ham-Ham Games (Nintendo)
  Lord of the Rings: The Third Age, The (EA Games)
  Mario Golf: Advance Tour (Nintendo)
  Mario Tennis: Power Tour (Nintendo)
  Mega Man Battle Network 5: Team Protoman (Capcom)
  Mega Man Battle Network 5: Team Colonel (Capcom)
  Mega Man Battle Network 6: Cybeast Falzar
  Mega Man Battle Network 6: Cybeast Gregar
  Momotaro Dentetsu G: Make a Gold Deck! (Japan only)
  Pokemon Emerald (Nintendo)
  Pokemon FireRed (Nintendo)
  Pokemon LeafGreen (Nintendo)
  Sennen Kazoku (Japan only)
  Shrek SuperSlam
  Sonic Advance 3


GBA Wireless Adapter Login

GBA Wireless Adapter Login
  rcnt=8000h    ;\
  rcnt=80A0h    ;
  rcnt=80A2h    ; reset adapter or so
  wait          ;
  rcnt=80A0h    ;/
  siocnt=5003h  ;\set 32bit normal mode, 2MHz internal clock
  rcnt=0000h    ;/
  passes=0, index=0
 @@lop:
  passes=passes+1, if passes>32 then ERROR  ;give up (usually only 10 passses)
  recv.lo=siodata AND FFFFh    ;response from adapter
  recv.hi=siodata/10000h       ;adapter's own "NI" data
  if send.hi<>recv.lo then index=0, goto @@stuck  ;<-- fallback to index=0
  if (send.lo XOR FFFFh)<>recv.lo then goto @@stuck
  if (send.hi XOR FFFFh)<>recv.hi then goto @@stuck
  index=index+1
 @@stuck:
  send.lo=halfword[@@key_string+index*2]
  send.hi=recv.hi XOR FFFFh
  siodata=send.lo+(send.hi*10000h)
  siocnt.bit7=1                        ;<-- start transmission
  if index<4 then goto @@lop
  ret
 @@key_string db 'NINTENDO',01h,80h    ;10 bytes (5 halfwords; index=0..4)

Data exchanged during Login
               GBA                         ADAPTER
               xxxx494E ;\     <-->        xxxxxxxx
               xxxx494E ; "NI" <--> "NI"/; 494EB6B1 ;\
  NOT("NI") /; B6B1494E ;/     <-->     \; 494EB6B1 ; NOT("NI")
            \; B6B1544E ;\"NT" <--> "NT"/; 544EB6B1 ;/
  NOT("NT") /; ABB1544E ;/     <-->     \; 544EABB1 ;\NOT("NT")
            \; ABB14E45 ;\"EN" <--> "EN"/; 4E45ABB1 ;/
  NOT("EN") /; B1BA4E45 ;/     <-->     \; 4E45B1BA ;\NOT("EN")
            \; B1BA4F44 ;\"DO" <--> "DO"/; 4F44B1BA ;/
  NOT("DO") /; B0BB4F44 ;/     <-->     \; 4F44B0BB ;\NOT("DO")
            \; B0BB8001 ;-fin  <-->  fin-; 8001B0BB ;/
                 \   \                      \   \
                  \   LSBs=Own               \   LSBs=Inverse of
                   \   Data.From.Gba          \   Prev.Data.From.Gba
                    \                          \
                     MSBs=Inverse of            MSBs=Own
                      Prev.Data.From.Adapter     Data.From.Adapter


GBA Wireless Adapter Commands

Wireless Command/Parameter Transmission
  GBA       Adapter
  9966ppcch 80000000h   ;-send command (cc), and num param_words (pp)
  <param01> 80000000h   ;\
  <param02> 80000000h   ; send "pp" parameter word(s), if any
  ...       ...         ;/
  80000000h 9966rraah   ;-recv ack (aa=cc+80h), and num response_words (rr)
  80000000? <reply01>   ;\
  80000000? <reply02>   ; recv "rr" response word(s), if any
  ...       ...         ;/
Wireless 32bit Transfers
  wait until [4000128h].Bit2=0  ;want SI=0
  set [4000128h].Bit3=1         ;set SO=1
  wait until [4000128h].Bit2=1  ;want SI=1
  set [4000128h].Bit3=0,Bit7=1  ;set SO=0 and start 32bit transfer
All command/param/reply transfers should be done at Internal Clock (except, Response Words for command 25h,27h,35h,37h should use External Clock).

Wireless Commands
  Cmd Para Reply Name
  10h -    -     Hello (send immediately after login)
  11h -    1     Good/Bad response to cmd 16h ?
  12h
  13h -    1
  14h
  15h
  16h 6    -     Introduce (send game/user name)
  17h 1    -     Config (send after Hello) (eg. param=003C0420h or 003C043Ch)
  18h
  19h
  1Ah
  1Bh
  1Ch -    -
  1Dh -    NN    Get Directory? (receive list of game/user names?)
  1Eh -    NN    Get Directory? (receive list of game/user names?)
  1Fh 1    -     Select Game for Download (send 16bit Game_ID)

  20h -    1
  21h -    1     Good/Bad response to cmd 1Fh ?
  22h
  23h
  24h -    -
  25h                                       ;use EXT clock!
  26h -    -
  27h -    -     Begin Download ?           ;use EXT clock!
  28h
  29h
  2Ah
  2Bh
  2Ch
  2Dh
  2Eh
  2Fh

  30h 1    -
  31h
  32h
  33h
  34h
  35h                                       ;use EXT clock!
  36h
  37h                                       ;use EXT clock!
  38h
  39h
  3Ah
  3Bh
  3Ch
  3Dh -    -     Bye (return to language select)
  3Eh
  3Fh
Special Response 996601EEh for error or so? (only at software side?)


GBA Wireless Adapter Component Lists

Main Chipset
  U1 32pin Freescale MC13190 (2.4 GHz ISM band transceiver)
  U2 48pin Freescale CT3000 or CT3001 (depending on adapter version)
  X3  2pin 9.5MHz crystal
The MC13190 is a Short-Range, Low-Power 2.4 GHz ISM band transceiver.
The processor is Motorola's 32-bit M-Core RISC engine. (?) MCT3000 (?)
See also: http://www.eetimes.com/document.asp?doc_id=1271943

Version with GERMAN Postal Code on sticker:
  Sticker on Case:
    "GAME BOY advance, WIRELESS ADAPTER"
    "Pat.Pend.Made in Philipines, CE0125(!)B"
    "MODEL NO./MODELE NO.AGB-015 D-63760 Grossosteim P/AGB-A-WA-EUR-2 E3"
  PCB: "19-C046-04, A-7" (top side) and "B-7" and Microchip ",\\" (bottom side)
  PCB: white stamp "3104, 94V-0, RU, TW-15"
  PCB: black stamp "22FDE"
  U1 32pin "Freescale 13190, 4WFQ" (MC13190) (2.4 GHz ISM band transceiver)
  U2 48pin "Freescale CT3001, XAC0445"  (bottom side)
  X3  2pin "D959L4I" (9.5MHz)           (top side) (ca. 19 clks per 2us)
Further components... top side (A-7)
  D1   5pin "D6F, 44"   (top side, below X3)
  U71  6pin ".., () 2"  (top side, right of X3, tiny black chip)
  B71  6pin "[]"        (top side, right of X3, small white chip)
  ANT  2pin on-board copper wings
  Q?   3pin             (top side, above CN1)
  Q?   3pin             (top side, above CN1)
  D?   2pin "72"        (top side, above CN1)
  D3   2pin "F2"        (top side, above CN1)
  U200 4pin "MSV"       (top side, above CN1)
  U202 5pin "LXKA"      (top side, right of CN1)
  U203 4pin "M6H"       (top side, right of CN1)
  CN1  6pin connector to GBA link port (top side)
Further components... bottom side (B-7)
  U201 5pin "LXVB"      (bottom side, near CN1)
  U72  4pin "BMs"       (bottom side, near ANT, tiny black chip)
  FL70 ?pin "[] o26"    (bottom side, near ANT, bigger white chip)
  B70  6pin "[]"        (bottom side, near ANT, small white chip)
Plus, resistors and capacitors (without any markings).

Version WITHOUT sticker:
  Sticker on Case: N/A
  PCB: "19-C046-03, A-1" (top side) and "B-1" and Microchip ",\\" (bottom side)
  PCB: white stamp "3204, TW-15, RU, 94V-0"
  PCB: black stamp "23MN" or "23NH" or so (smeared)
  U1 32pin "Freescale 13190, 4FGD"      (top side)
  U2 48pin "Freescale CT3000, XAB0425"  (bottom side) ;CT3000 (not CT3001)
  X3  2pin "9.5SKSS4GT"                 (top side)
Further components... top side (A-1)
  D1   5pin "D6F, 31"   (top side, below X3)
  U71  6pin "P3, () 2"  (top side, right of X3, tiny black chip)
  B71  6pin "[]"        (top side, right of X3, small white chip)
  ANT  2pin on-board copper wings
  Q70  3pin             (top side, above CN1)
  D?   2pin "72"        (top side, above CN1)
  D3   2pin "F2"        (top side, above CN1)
  U200 4pin "MSV"       (top side, above CN1)
  U202 5pin "LXKH"      (top side, right of CN1)
  U203 4pin "M6H"       (top side, right of CN1)
  CN1  6pin connector to GBA link port (top side)
Further components... bottom side (B-1)
  U201 5pin "LXV2"      (bottom side, near CN1)
  U70  6pin "AAG"       (bottom side, near ANT, tiny black chip)
  FL70 ?pin "[] o26"    (bottom side, near ANT, bigger white chip)
  B70  6pin "[]"        (bottom side, near ANT, small white chip)
Plus, resistors and capacitors (without any markings).

Major Differences
  Sticker      "N/A"                     vs "Grossosteim P/AGB-A-WA-EUR-2 E3"
  PCB-markings "19-C046-03, A-1, 3204"   vs "19-C046-04, A-7, 3104"
  U1           "CT3000, XAB0425"         vs "CT3001, XAC0445"
  Transistors  One transistor (Q70)      vs Two transistors (both nameless)
  U70/U72      U70 "AAG" (6pin)          vs U72 "BMs" (4pin)
Purpose of the changes is unknown (either older/newer revisions, or different regions with different FCC regulations).


GBA Infrared Communication

Early GBA prototypes have been intended to include a built-in IR port for sending and receiving IR signals. Among others, this port could have been used to communicate with other GBAs, or older CGB models, or TV Remote Controls, etc.

[ THE INFRARED COMMUNICATION FEATURE IS -NOT- SUPPORTED ANYMORE ]
Anyways, the prototype specifications have been as shown below...

Keep in mind that the IR signal may be interrupted by whatever objects moved between sender and receiver - the IR port isn't recommended for programs that require realtime data exchange (such like action games).

4000136h - IR - Infrared Register (R/W)
  Bit   Expl.
  0     Transmission Data  (0=LED Off, 1=LED On)
  1     READ Enable        (0=Disable, 1=Enable)
  2     Reception Data     (0=None, 1=Signal received) (Read only)
  3     AMP Operation      (0=Off, 1=On)
  4     IRQ Enable Flag    (0=Disable, 1=Enable)
  5-15  Not used
When IRQ is enabled, an interrupt is requested if the incoming signal was 0.119us Off (2 cycles), followed by 0.536us On (9 cycles) - minimum timing periods each.

Transmission Notes
When transmitting an IR signal, note that it'd be not a good idea to keep the LED turned On for a very long period (such like sending a 1 second synchronization pulse). The recipient's circuit would treat such a long signal as "normal IR pollution which is in the air" after a while, and thus ignore the signal.

Reception Notes
Received data is internally latched. Latched data may be read out by setting both READ and AMP bits.
Note: Provided that you don't want to receive your own IR signal, be sure to set Bit 0 to zero before attempting to receive data.

Power-consumption
After using the IR port, be sure to reset the register to zero in order to reduce battery power consumption.


GBA Keypad Input

The built-in GBA gamepad has 4 direction keys, and 6 buttons.

4000130h - KEYINPUT - Key Status (R)
  Bit   Expl.
  0     Button A        (0=Pressed, 1=Released)
  1     Button B        (etc.)
  2     Select          (etc.)
  3     Start           (etc.)
  4     Right           (etc.)
  5     Left            (etc.)
  6     Up              (etc.)
  7     Down            (etc.)
  8     Button R        (etc.)
  9     Button L        (etc.)
  10-15 Not used
It'd be usually recommended to read-out this register only once per frame, and to store the current state in memory. As a side effect, this method avoids problems caused by switch bounce when a key is newly released or pressed.

4000132h - KEYCNT - Key Interrupt Control (R/W)
The keypad IRQ function is intended to terminate the very-low-power Stop mode, it is not suitable for processing normal user input, to do this, most programs are invoking their keypad handlers from within VBlank IRQ.
  Bit   Expl.
  0     Button A        (0=Ignore, 1=Select)
  1     Button B        (etc.)
  2     Select          (etc.)
  3     Start           (etc.)
  4     Right           (etc.)
  5     Left            (etc.)
  6     Up              (etc.)
  7     Down            (etc.)
  8     Button R        (etc.)
  9     Button L        (etc.)
  10-13 Not used
  14    Button IRQ Enable      (0=Disable, 1=Enable)
  15    Button IRQ Condition   (0=Logical OR, 1=Logical AND)
In logical OR mode, an interrupt is requested when at least one of the selected buttons is pressed.
In logical AND mode, an interrupt is requested when ALL of the selected buttons are pressed.

Notes
In 8bit gameboy compatibility mode, L and R Buttons are used to toggle the screen size between normal 160x144 pixels and stretched 240x144 pixels.
The GBA SP is additionally having a * Button used to toggle the backlight on and off (controlled by separate hardware logic, there's no way to detect or change the current backlight state by software).


GBA Interrupt Control

4000208h - IME - Interrupt Master Enable Register (R/W)
  Bit   Expl.
  0     Disable all interrupts         (0=Disable All, 1=See IE register)
  1-31  Not used

4000200h - IE - Interrupt Enable Register (R/W)
  Bit   Expl.
  0     LCD V-Blank                    (0=Disable)
  1     LCD H-Blank                    (etc.)
  2     LCD V-Counter Match            (etc.)
  3     Timer 0 Overflow               (etc.)
  4     Timer 1 Overflow               (etc.)
  5     Timer 2 Overflow               (etc.)
  6     Timer 3 Overflow               (etc.)
  7     Serial Communication           (etc.)
  8     DMA 0                          (etc.)
  9     DMA 1                          (etc.)
  10    DMA 2                          (etc.)
  11    DMA 3                          (etc.)
  12    Keypad                         (etc.)
  13    Game Pak (external IRQ source) (etc.)
  14-15 Not used
Note that there is another 'master enable flag' directly in the CPUs Status Register (CPSR) accessible in privileged modes, see CPU reference for details.

4000202h - IF - Interrupt Request Flags / IRQ Acknowledge (R/W, see below)
  Bit   Expl.
  0     LCD V-Blank                    (1=Request Interrupt)
  1     LCD H-Blank                    (etc.)
  2     LCD V-Counter Match            (etc.)
  3     Timer 0 Overflow               (etc.)
  4     Timer 1 Overflow               (etc.)
  5     Timer 2 Overflow               (etc.)
  6     Timer 3 Overflow               (etc.)
  7     Serial Communication           (etc.)
  8     DMA 0                          (etc.)
  9     DMA 1                          (etc.)
  10    DMA 2                          (etc.)
  11    DMA 3                          (etc.)
  12    Keypad                         (etc.)
  13    Game Pak (external IRQ source) (etc.)
  14-15 Not used
Interrupts must be manually acknowledged by writing a "1" to one of the IRQ bits, the IRQ bit will then be cleared.

"[Cautions regarding clearing IME and IE]
A corresponding interrupt could occur even while a command to clear IME or each flag of the IE register is being executed. When clearing a flag of IE, you need to clear IME in advance so that mismatching of interrupt checks will not occur." ?

"[When multiple interrupts are used]
When the timing of clearing of IME and the timing of an interrupt agree, multiple interrupts will not occur during that interrupt. Therefore, set (enable) IME after saving IME during the interrupt routine." ?

BIOS Interrupt handling
Upon interrupt execution, the CPU is switched into IRQ mode, and the physical interrupt vector is called - as this address is located in BIOS ROM, the BIOS will always execute the following code before it forwards control to the user handler:
  00000018  b      128h                ;IRQ vector: jump to actual BIOS handler
  00000128  stmfd  r13!,r0-r3,r12,r14  ;save registers to SP_irq
  0000012C  mov    r0,4000000h         ;ptr+4 to 03FFFFFC (mirror of 03007FFC)
  00000130  add    r14,r15,0h          ;retadr for USER handler $+8=138h
  00000134  ldr    r15,[r0,-4h]        ;jump to [03FFFFFC] USER handler
  00000138  ldmfd  r13!,r0-r3,r12,r14  ;restore registers from SP_irq
  0000013C  subs   r15,r14,4h          ;return from IRQ (PC=LR-4, CPSR=SPSR)
As shown above, a pointer to the 32bit/ARM-code user handler must be setup in [03007FFCh]. By default, 160 bytes of memory are reserved for interrupt stack at 03007F00h-03007F9Fh.

Recommended User Interrupt handling
- If necessary switch to THUMB state manually (handler is called in ARM state)
- Determine reason(s) of interrupt by examining IF register
- User program may freely assign priority to each reason by own logic
- Process the most important reason of your choice
- User MUST manually acknowledge by writing to IF register
- If user wants to allow nested interrupts, save SPSR_irq, then enable IRQs.
- If using other registers than BIOS-pushed R0-R3, manually save R4-R11 also.
- Note that Interrupt Stack is used (which may have limited size)
- So, for memory consuming stack operations use system mode (=user stack).
- When calling subroutines in system mode, save LSR_usr also.
- Restore SPSR_irq and/or R4-R11 if you've saved them above.
- Finally, return to BIOS handler by BX LR (R14_irq) instruction.

Default memory usage at 03007FXX (and mirrored to 03FFFFXX)
  Addr.    Size Expl.
  3007FFCh 4    Pointer to user IRQ handler (32bit ARM code)
  3007FF8h 2    Interrupt Check Flag (for IntrWait/VBlankIntrWait functions)
  3007FF4h 4    Allocated Area
  3007FF0h 4    Pointer to Sound Buffer
  3007FE0h 16   Allocated Area
  3007FA0h 64   Default area for SP_svc Supervisor Stack (4 words/time)
  3007F00h 160  Default area for SP_irq Interrupt Stack (6 words/time)
Memory below 7F00h is free for User Stack and user data. The three stack pointers are initially initialized at the TOP of the respective areas:
  SP_svc=03007FE0h
  SP_irq=03007FA0h
  SP_usr=03007F00h
The user may redefine these addresses and move stacks into other locations, however, the addresses for system data at 7FE0h-7FFFh are fixed.

Not sure, is following free for user ?
Registers R8-R12_fiq, R13_fiq, R14_fiq, SPSR_fiq
Registers R13-R14_abt, SPSR_abt
Registers R13-R14_und, SPSR_und

Fast Interrupt (FIQ)
The ARM CPU provides two interrupt sources, IRQ and FIQ. In the GBA only IRQ is used. In normal GBAs, the FIQ signal is shortcut to VDD35, ie. the signal is always high, and there is no way to generate a FIQ by hardware. The registers R8..12_fiq could be used by software (when switching into FIQ mode by writing to CPSR) - however, this might make the game incompatible with hardware debuggers (which are reportedly using FIQs for debugging purposes).


GBA System Control

4000204h - WAITCNT - Waitstate Control (R/W)
This register is used to configure game pak access timings. The game pak ROM is mirrored to three address regions at 08000000h, 0A000000h, and 0C000000h, these areas are called Wait State 0-2. Different access timings may be assigned to each area (this might be useful in case that a game pak contains several ROM chips with different access times each).
  Bit   Expl.
  0-1   SRAM Wait Control          (0..3 = 4,3,2,8 cycles)
  2-3   Wait State 0 First Access  (0..3 = 4,3,2,8 cycles)
  4     Wait State 0 Second Access (0..1 = 2,1 cycles)
  5-6   Wait State 1 First Access  (0..3 = 4,3,2,8 cycles)
  7     Wait State 1 Second Access (0..1 = 4,1 cycles; unlike above WS0)
  8-9   Wait State 2 First Access  (0..3 = 4,3,2,8 cycles)
  10    Wait State 2 Second Access (0..1 = 8,1 cycles; unlike above WS0,WS1)
  11-12 PHI Terminal Output        (0..3 = Disable, 4.19MHz, 8.38MHz, 16.78MHz)
  13    Not used
  14    Game Pak Prefetch Buffer (Pipe) (0=Disable, 1=Enable)
  15    Game Pak Type Flag  (Read Only) (0=GBA, 1=CGB) (IN35 signal)
  16-31 Not used
At startup, the default setting is 0000h. Currently manufactured cartridges are using the following settings: WS0/ROM=3,1 clks; SRAM=8 clks; WS2/EEPROM: 8,8 clks; prefetch enabled; that is, WAITCNT=4317h, for more info see "GBA Cartridges" chapter.

First Access (Non-sequential) and Second Access (Sequential) define the waitstates for N and S cycles, the actual access time is 1 clock cycle PLUS the number of waitstates.
GamePak uses 16bit data bus, so that a 32bit access is split into TWO 16bit accesses (of which, the second fragment is always sequential, even if the first fragment was non-sequential).

GBA GamePak Prefetch

NOTES:
The GBA forcefully uses non-sequential timing at the beginning of each 128K-block of gamepak ROM, eg. "LDMIA [801fff8h],r0-r7" will have non-sequential timing at 8020000h.
The PHI Terminal output (PHI Pin of Gamepak Bus) should be disabled.

4000300h - POSTFLG - BYTE - Undocumented - Post Boot / Debug Control (R/W)
After initial reset, the GBA BIOS initializes the register to 01h, and any further execution of the Reset vector (00000000h) will pass control to the Debug vector (0000001Ch) when sensing the register to be still set to 01h.
  Bit   Expl.
  0     Undocumented. First Boot Flag  (0=First, 1=Further)
  1-7   Undocumented. Not used.
Normally the debug handler rejects control unless it detects Debug flags in cartridge header, in that case it may redirect to a cut-down boot procedure (bypassing Nintendo logo and boot delays, much like nocash burst boot for multiboot software). I am not sure if it is possible to reset the GBA externally without automatically resetting register 300h though.

4000301h - HALTCNT - BYTE - Undocumented - Low Power Mode Control (W)
Writing to this register switches the GBA into battery saving mode.
In Halt mode, the CPU is paused as long as (IE AND IF)=0, this should be used to reduce power-consumption during periods when the CPU is waiting for interrupt events.
In Stop mode, most of the hardware including sound and video are paused, this very-low-power mode could be used much like a screensaver.
  Bit   Expl.
  0-6   Undocumented. Not used.
  7     Undocumented. Power Down Mode  (0=Halt, 1=Stop)
The current GBA BIOS addresses only the upper eight bits of this register (by writing 00h or 80h to address 04000301h), however, as the register isn't officially documented, some or all of the bits might have different meanings in future GBA models.
For best forwards compatibility, it'd generally be more recommended to use the BIOS Functions SWI 2 (Halt) or SWI 3 (Stop) rather than writing to this register directly.

4000410h - Undocumented - Purpose Unknown ? 8bit (W)
The BIOS writes the 8bit value 0FFh to this address. Purpose Unknown.
Probably just another bug in the BIOS.

4000800h - 32bit - Undocumented - Internal Memory Control (R/W)
Supported by GBA and GBA SP only - NOT supported by DS (even in GBA mode).
Also supported by GBA Micro - but crashes on "overclocked" WRAM setting.
Initialized to 0D000020h (by hardware). Unlike all other I/O registers, this register is mirrored across the whole I/O area (in increments of 64K, ie. at 4000800h, 4010800h, 4020800h, ..., 4FF0800h)
  Bit   Expl.
  0     Disable 32K+256K WRAM (0=Normal, 1=Disable) (when off: empty/prefetch)
         From endrift: bit0 swaps 00000000h-01FFFFFFh and 02000000h-03FFFFFFh
         in GBA mode (but keeps BIOS protection)
  1     Unknown          (Read/Write-able)
  2     Unknown          (Read/Write-able)
  3     Disable CGB Bootrom (0=Normal, 1=Disable, start cart at 0000h)
  4     Unused (0)
  5     Enable 256K WRAM (0=Disable, 1=Normal) (when off: mirror of 32K WRAM)
  6-23  Unused (0)
  24-27 Wait Control WRAM 256K (0-14 = 15..1 Waitstates, 15=Lockup)
  28-31 Unknown          (Read/Write-able)
The default value 0Dh in Bits 24-27 selects 2 waitstates for 256K WRAM (ie. 3/3/6 cycles 8/16/32bit accesses). The fastest possible setting would be 0Eh (1 waitstate, 2/2/4 cycles for 8/16/32bit), that works on GBA and GBA SP only, the GBA Micro locks up with that setting (it's on-chip RAM is too slow, and works only with 2 or more waitstates).

Note: One cycle equals approx. 59.59ns (ie. 16.78MHz clock).


GBA GamePak Prefetch

GamePak Prefetch can be enabled in WAITCNT register. When prefetch buffer is enabled, the GBA attempts to read opcodes from Game Pak ROM during periods when the CPU is not using the bus (if any). Memory access is then performed with 0 Waits if the CPU requests data which is already stored in the buffer. The prefetch buffer stores up to eight 16bit values.

GamePak ROM Opcodes
The prefetch feature works only with <opcodes> fetched from GamePak ROM. Opcodes executed in RAM or BIOS are not affected by the prefetch feature (even if that opcodes read <data> from GamePak ROM).

Prefetch Enable
For GamePak ROM opcodes, prefetch may occur in two situations:
  1) opcodes with internal cycles (I) which do not change R15, shift/rotate
     register-by-register, load opcodes (ldr,ldm,pop,swp), multiply opcodes
  2) opcodes that load/store memory (ldr,str,ldm,stm,etc.)

Prefetch Disable Bug
When Prefetch is disabled, the Prefetch Disable Bug will occur for all
  "Opcodes in GamePak ROM with Internal Cycles which do not change R15"
for those opcodes, the bug changes the opcode fetch time from 1S to 1N.
Note: Affected opcodes (with I cycles) are: Shift/rotate register-by-register opcodes, multiply opcodes, and load opcodes (ldr,ldm,pop,swp).


GBA Cartridges

ROM
GBA Cartridge Header
GBA Cartridge ROM

Backup Media
Aside from ROM, cartridges may also include one of the following backup medias, used to store game positions, highscore tables, options, or other data.
GBA Cart Backup IDs
GBA Cart Backup SRAM/FRAM
GBA Cart Backup EEPROM
GBA Cart Backup Flash ROM
GBA Cart Backup DACS

Add-Ons
GBA Cart I/O Port (GPIO)
GBA Cart Real-Time Clock (RTC)
GBA Cart Solar Sensor
GBA Cart Tilt Sensor
GBA Cart Gyro Sensor
GBA Cart Rumble
GBA Cart e-Reader
GBA Cart Unknown Devices
GBA Cart Protections

Other Accessoires
GBA Flashcards
GBA Cheat Devices


GBA Cartridge Header

The first 192 bytes at 8000000h-80000BFh in ROM are used as cartridge header. The same header is also used for Multiboot images at 2000000h-20000BFh (plus some additional multiboot entries at 20000C0h and up).

Header Overview
  Address Bytes Expl.
  000h    4     ROM Entry Point  (32bit ARM branch opcode, eg. "B rom_start")
  004h    156   Nintendo Logo    (compressed bitmap, required!)
  0A0h    12    Game Title       (uppercase ascii, max 12 characters)
  0ACh    4     Game Code        (uppercase ascii, 4 characters)
  0B0h    2     Maker Code       (uppercase ascii, 2 characters)
  0B2h    1     Fixed value      (must be 96h, required!)
  0B3h    1     Main unit code   (00h for current GBA models)
  0B4h    1     Device type      (usually 00h) (bit7=DACS/debug related)
  0B5h    7     Reserved Area    (should be zero filled)
  0BCh    1     Software version (usually 00h)
  0BDh    1     Complement check (header checksum, required!)
  0BEh    2     Reserved Area    (should be zero filled)
  --- Additional Multiboot Header Entries ---
  0C0h    4     RAM Entry Point  (32bit ARM branch opcode, eg. "B ram_start")
  0C4h    1     Boot mode        (init as 00h - BIOS overwrites this value!)
  0C5h    1     Slave ID Number  (init as 00h - BIOS overwrites this value!)
  0C6h    26    Not used         (seems to be unused)
  0E0h    4     JOYBUS Entry Pt. (32bit ARM branch opcode, eg. "B joy_start")
Note: With all entry points, the CPU is initially set into system mode.

000h - Entry Point, 4 Bytes
Space for a single 32bit ARM opcode that redirects to the actual startaddress of the cartridge, this should be usually a "B <start>" instruction.
Note: This entry is ignored by Multiboot slave GBAs (in fact, the entry is then overwritten and redirected to a separate Multiboot Entry Point, as described below).

004h..09Fh - Nintendo Logo, 156 Bytes
Contains the Nintendo logo which is displayed during the boot procedure. Cartridge won't work if this data is missing or modified.
In detail: This area contains Huffman compression data (but excluding the compression header which is hardcoded in the BIOS, so that it'd be probably not possible to hack the GBA by producing de-compression buffer overflows).
A copy of the compression data is stored in the BIOS, the GBA will compare this data and lock-up itself if the BIOS data isn't exactly the same as in the cartridge (or multiboot header). The only exception are the two entries below which are allowed to have variable settings in some bits.

09Ch Bit 2,7 - Debugging Enable
This is part of the above Nintendo Logo area, and must be commonly set to 21h, however, Bit 2 and Bit 7 may be set to other values.
When both bits are set (ie. A5h), the FIQ/Undefined Instruction handler in the BIOS becomes unlocked, the handler then forwards these exceptions to the user handler in cartridge ROM (entry point defined in 80000B4h, see below).
Other bit combinations currently do not seem to have special functions.

09Eh Bit 0,1 - Cartridge Key Number MSBs
This is part of the above Nintendo Logo area, and must be commonly set to F8h, however, Bit 0-1 may be set to other values.
During startup, the BIOS performs some dummy-reads from a stream of pre-defined addresses, even though these reads seem to be meaningless, they might be intended to unlock a read-protection inside of commercial cartridge. There are 16 pre-defined address streams - selected by a 4bit key number - of which the upper two bits are gained from 800009Eh Bit 0-1, and the lower two bits from a checksum across header bytes 09Dh..0B7h (bytewise XORed, divided by 40h).

0A0h - Game Title, Uppercase Ascii, max 12 characters
Space for the game title, padded with 00h (if less than 12 chars).

0ACh - Game Code, Uppercase Ascii, 4 characters
This is the same code as the AGB-UTTD code which is printed on the package and sticker on (commercial) cartridges (excluding the leading "AGB-" part).
  U  Unique Code          (usually "A" or "B" or special meaning)
  TT Short Title          (eg. "PM" for Pac Man)
  D  Destination/Language (usually "J" or "E" or "P" or specific language)
The first character (U) is usually "A" or "B", in detail:
  A  Normal game; Older titles (mainly 2001..2003)
  B  Normal game; Newer titles (2003..)
  C  Normal game; Not used yet, but might be used for even newer titles
  F  Famicom/Classic NES Series (software emulated NES games)
  K  Yoshi and Koro Koro Puzzle (acceleration sensor)
  P  e-Reader (dot-code scanner) (or NDS PassMe image when gamecode="PASS")
  R  Warioware Twisted (cartridge with rumble and z-axis gyro sensor)
  U  Boktai 1 and 2 (cartridge with RTC and solar sensor)
  V  Drill Dozer (cartridge with rumble)
The second/third characters (TT) are:
  Usually an abbreviation of the game title (eg. "PM" for "Pac Man") (unless
  that gamecode was already used for another game, then TT is just random)
The fourth character (D) indicates Destination/Language:
  J  Japan             P  Europe/Elsewhere   F  French          S  Spanish
  E  USA/English       D  German             I  Italian

0B0h - Maker code, Uppercase Ascii, 2 characters
Identifies the (commercial) developer. For example, "01"=Nintendo.

0B2h - Fixed value, 1 Byte
Must be 96h.

0B3h - Main unit code, 1 Byte
Identifies the required hardware. Should be 00h for current GBA models.

0B4h - Device type, 1 Byte
Normally, this entry should be zero. With Nintendo's hardware debugger Bit 7 identifies the debugging handlers entry point and size of DACS (Debugging And Communication System) memory: Bit7=0: 9FFC000h/8MBIT DACS, Bit7=1: 9FE2000h/1MBIT DACS. The debugging handler can be enabled in 800009Ch (see above), normal cartridges do not have any memory (nor any mirrors) at these addresses though.

0B5h - Reserved Area, 7 Bytes
Reserved, zero filled.

0BCh - Software version number
Version number of the game. Usually zero.

0BDh - Complement check, 1 Byte
Header checksum, cartridge won't work if incorrect. Calculate as such:
chk=0:for i=0A0h to 0BCh:chk=chk-[i]:next:chk=(chk-19h) and 0FFh

0BEh - Reserved Area, 2 Bytes
Reserved, zero filled.

Below required for Multiboot/slave programs only. For Multiboot, the above 192 bytes are required to be transferred as header-block (loaded to 2000000h-20000BFh), and some additional header-information must be located at the beginning of the actual program/data-block (loaded to 20000C0h and up). This extended header consists of Multiboot Entry point(s) which must be set up correctly, and of two reserved bytes which are overwritten by the boot procedure:

0C0h - Normal/Multiplay mode Entry Point
This entry is used only if the GBA has been booted by using Normal or Multiplay transfer mode (but not by Joybus mode).
Typically deposit a ARM-32bit "B <start>" branch opcode at this location, which is pointing to your actual initialization procedure.

0C4h (BYTE) - Boot mode
The slave GBA download procedure overwrites this byte by a value which is indicating the used multiboot transfer mode.
  Value  Expl.
  01h    Joybus mode
  02h    Normal mode
  03h    Multiplay mode
Typically set this byte to zero by inserting DCB 00h in your source.
Be sure that your uploaded program does not contain important program code or data at this location, or at the ID-byte location below.

0C5h (BYTE) - Slave ID Number
If the GBA has been booted in Normal or Multiplay mode, this byte becomes overwritten by the slave ID number of the local GBA (that'd be always 01h for normal mode).
  Value  Expl.
  01h    Slave #1
  02h    Slave #2
  03h    Slave #3
Typically set this byte to zero by inserting DCB 00h in your source.
When booted in Joybus mode, the value is NOT changed and remains the same as uploaded from the master GBA.

0C6h..0DFh - Not used
Appears to be unused.

0E0h - Joybus mode Entry Point
If the GBA has been booted by using Joybus transfer mode, then the entry point is located at this address rather than at 20000C0h. Either put your initialization procedure directly at this address, or redirect to the actual boot procedure by depositing a "B <start>" opcode here (either one using 32bit ARM code). Or, if you are not intending to support joybus mode (which is probably rarely used), ignore this entry.


GBA Cartridge ROM

ROM Size
The games F-ZERO and Super Mario Advance use ROMs of 4 MBytes each. Zelda uses 8 MBytes. Not sure if other sizes are manufactured.

ROM Waitstates
The GBA starts the cartridge with 4,2 waitstates (N,S) and prefetch disabled. The program may change these settings by writing to WAITCNT, the games F-ZERO and Super Mario Advance use 3,1 waitstates (N,S) each, with prefetch enabled.
Third-party flashcards are reportedly running unstable with these settings. Also, prefetch and shorter waitstates are allowing to read more data and opcodes from ROM is less time, the downside is that it increases the power consumption.

ROM Chip
Because of how 24bit addresses are squeezed through the Gampak bus, the cartridge must include a circuit that latches the lower 16 address bits on non-sequential access, and that increments these bits on sequential access. Nintendo includes this circuit directly in the ROM chip.
Also, the ROM must have 16bit data bus (or a circuit which converts two 8bit data units into one 16bit unit - by not exceeding the waitstate timings).


GBA Cart Backup IDs

Nintendo didn't include a backup-type entry in the ROM header, however, the required type can be detected by ID strings in the ROM-image. Nintendo's tools are automatically inserting these strings (as part of their library headers). When using other tools, you may insert ID strings by hand.

ID Strings
The ID string must be located at a word-aligned memory location, the string length should be a multiple of 4 bytes (padded with zero's).
  EEPROM_Vnnn    EEPROM 512 bytes or 8 Kbytes (4Kbit or 64Kbit)
  SRAM_Vnnn      SRAM 32 Kbytes (256Kbit)
  FLASH_Vnnn     FLASH 64 Kbytes (512Kbit) (ID used in older files)
  FLASH512_Vnnn  FLASH 64 Kbytes (512Kbit) (ID used in newer files)
  FLASH1M_Vnnn   FLASH 128 Kbytes (1Mbit)
For Nintendo's tools, "nnn" is a 3-digit library version number. When using other tools, best keep it set to "nnn" rather than inserting numeric digits.

Notes
No$gba does auto-detect most backup types, even without ID strings, except for 128K FLASH (without ID "FLASH1M_Vnnn", the FLASH size defaults to 64K). Ideally, for faster detection, the ID should be put into the first some bytes of the ROM-image (ie. somewhere right after the ROM header).


GBA Cart Backup SRAM/FRAM

SRAM - 32 KBytes (256Kbit) Lifetime: Depends on back-up battery
FRAM - 32 KBytes (256Kbit) Lifetime: 10,000,000,000 read/write per bit

Hyundai GM76V256CLLFW10 SRAM (Static RAM) (eg. F-Zero)
Fujitsu MB85R256 FRAM (Ferroelectric RAM) (eg. Warioware Twisted)

Addressing and Waitstates
SRAM/FRAM is mapped to E000000h-E007FFFh, it should be accessed with 8 waitstates (write a value of 3 into Bit0-1 of WAITCNT).

Databus Width
The SRAM/FRAM databus is restricted to 8 bits, it should be accessed by LDRB, LDRSB, and STRB opcodes only.

Reading and Writing
Reading from SRAM/FRAM should be performed by code executed in WRAM only (but not by code executed in ROM). There is no such restriction for writing.

Preventing Data Loss
The GBA SRAM/FRAM carts do not include a write-protect function (unlike older 8bit gameboy carts). This seems to be a problem and may cause data loss when a cartridge is removed or inserted while the GBA is still turned on. As far as I understand, this is not so much a hardware problem, but rather a software problem, ie. theoretically you could remove/insert the cartridge as many times as you want, but you should take care that your program does not crash (and write blindly into memory).

Recommended Workaround
Enable the Gamepak Interrupt (it'll most likely get triggered when removing the cartridge), and hang-up the GBA in an endless loop when your interrupt handler senses a Gamepak IRQ. For obvious reason, your interrupt handler should be located in WRAM, ie. not in the (removed) ROM cartridge. The handler should process Gamepak IRQs at highest priority. Periods during which interrupts are disabled should be kept as short as possible, if necessary allow nested interrupts.

When to use the above Workaround
A program that relies wholly on code and data in WRAM, and that does not crash even when ROM is removed, may keep operating without having to use the above mechanism.
Do NOT use the workaround for programs that run without a cartridge inserted (ie. single gamepak/multiboot slaves), or for programs that use Gamepak IRQ/DMA for other purposes.
All other programs should use it. It'd be eventually a good idea to include it even in programs that do not use SRAM/FRAM themselves (eg. otherwise removing a SRAM/FRAM-less cartridge may lock up the GBA, and may cause it to destroy backup data when inserting a SRAM/FRAM cartridge).

SRAM vs FRAM
FRAM (Ferroelectric RAM) is a newer technology, used in newer GBA carts, unlike SRAM (Static RAM), it doesn't require a battery to hold the data. At software side, it is accessed exactly like SRAM, ie. unlike EEPROM/FLASH, it doesn't require any Write/Erase commands/delays.

Note
In SRAM/FRAM cartridges, the /REQ pin (Pin 31 of Gamepak bus) should be a little bit shorter as than the other pins; when removing the cartridge, this causes the gamepak IRQ signal to get triggered before the other pins are disconnected.


GBA Cart Backup EEPROM

9853 - EEPROM 512 Bytes (0200h) (4Kbit) (eg. used by Super Mario Advance)
9854 - EEPROM 8 KBytes (2000h) (64Kbit) (eg. used by Boktai)
Lifetime: 100,000 writes per address

Addressing and Waitstates
The eeprom is connected to Bit0 of the data bus, and to the upper 1 bit (or upper 17 bits in case of large 32MB ROM) of the cartridge ROM address bus, communication with the chip takes place serially.
The eeprom must be used with 8 waitstates (set WAITCNT=X3XXh; 8,8 clks in WS2 area), the eeprom can be then addressed at DFFFF00h..DFFFFFFh.
Respectively, with eeprom, ROM is restricted to 8000000h-9FFFeFFh (max. 1FFFF00h bytes = 32MB minus 256 bytes). On carts with 16MB or smaller ROM, eeprom can be alternately accessed anywhere at D000000h-DFFFFFFh.

Data and Address Width
Data can be read from (or written to) the EEPROM in units of 64bits (8 bytes). Writing automatically erases the old 64bits of data. Addressing works in units of 64bits respectively, that is, for 512 Bytes EEPROMS: an address range of 0-3Fh, 6bit bus width; and for 8KByte EEPROMs: a range of 0-3FFh, 14bit bus width (only the lower 10 address bits are used, upper 4 bits should be zero).

Set Address (For Reading)
Prepare the following bitstream in memory:
  2 bits "11" (Read Request)
  n bits eeprom address (MSB first, 6 or 14 bits, depending on EEPROM)
  1 bit "0"
Then transfer the stream to eeprom by using DMA.

Read Data
Read a stream of 68 bits from EEPROM by using DMA,
then decipher the received data as follows:
  4 bits - ignore these
 64 bits - data (conventionally MSB first)

Write Data to Address
Prepare the following bitstream in memory, then transfer the stream to eeprom by using DMA, it'll take ca. 108368 clock cycles (ca. 6.5ms) until the old data is erased and new data is programmed.
  2 bits "10" (Write Request)
  n bits eeprom address (MSB first, 6 or 14 bits, depending on EEPROM)
 64 bits data (conventionally MSB first)
  1 bit "0"
After the DMA, keep reading from the chip, by normal LDRH [DFFFF00h], until Bit 0 of the returned data becomes "1" (Ready). To prevent your program from locking up in case of malfunction, generate a timeout if the chip does not reply after 10ms or longer.

Using DMA
Transferring a bitstreams to/from the EEPROM must be done via DMA3 (manual transfers via LDRH/STRH won't work; probably because they don't keep /CS=LOW and A23=HIGH throughout the transfer).
For using DMA, a buffer in memory must be used (that buffer would be typically allocated temporarily on stack, one halfword for each bit, bit1-15 of the halfwords are don't care, only bit0 is used).
The buffer must be transfered as a whole to/from EEPROM by using DMA3 (DMA0-2 can't access external memory), use 16bit transfer mode, both source and destination address incrementing (ie. DMA3CNT=80000000h+length).
DMA channels of higher priority should be disabled during the transfer (ie. H/V-Blank or Sound FIFO DMAs). And, of course any interrupts that might mess with DMA registers should be disabled.

Pin-Outs
The EEPROM chips are having only 8 pins, these are connected, Pin 1..8, to ROMCS, RD, WR, AD0, GND, GND, A23, VDD of the GamePak bus. Carts with 32MB ROM must have A7..A22 logically ANDed with A23.
The chips seem to be some custom design, the pinout, transfer protocol and 8-byte pages don't resemble any standard serial EEPROMs.
The chips have no other markings than 9853 or 9854 (plus some datecode), without any manufacturer info (https://gbhwdb.gekkio.fi/ declares them as Rohm chips).

Notes
There seems to be no autodection mechanism, so that a hardcoded bus width must be used.


GBA Cart Backup Flash ROM

64 KBytes - 512Kbits Flash ROM - Lifetime: 10,000 writes per sector
128 KBytes - 1Mbit Flash ROM - Lifetime: ??? writes per sector

Chip Identification (all device types)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=90h  (enter ID mode)
  dev=[E000001h], man=[E000000h]                  (get device & manufacturer)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=F0h  (terminate ID mode)
Used to detect the type (and presence) of FLASH chips. See Device Types below.

Reading Data Bytes (all device types)
  dat=[E00xxxxh]                                  (read byte from address xxxx)

Erase Entire Chip (all device types)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=80h  (erase command)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=10h  (erase entire chip)
  wait until [E000000h]=FFh (or timeout)
Erases all memory in chip, erased memory is FFh-filled.

Erase 4Kbyte Sector (all device types, except Atmel)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=80h  (erase command)
  [E005555h]=AAh, [E002AAAh]=55h, [E00n000h]=30h  (erase sector n)
  wait until [E00n000h]=FFh (or timeout)
Erases memory at E00n000h..E00nFFFh, erased memory is FFh-filled.

Erase-and-Write 128 Bytes Sector (only Atmel devices)
  old=IME, IME=0                                  (disable interrupts)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=A0h  (erase/write sector command)
  [E00xxxxh+00h..7Fh]=dat[00h..7Fh]               (write 128 bytes)
  IME=old                                         (restore old IME state)
  wait until [E00xxxxh+7Fh]=dat[7Fh] (or timeout)
Interrupts (and DMAs) should be disabled during command/write phase. Target address must be a multiple of 80h.

Write Single Data Byte (all device types, except Atmel)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=A0h  (write byte command)
  [E00xxxxh]=dat                                  (write byte to address xxxx)
  wait until [E00xxxxh]=dat (or timeout)
The target memory location must have been previously erased.

Terminate Command after Timeout (only Macronix devices, ID=1CC2h)
  [E005555h]=F0h                            (force end of write/erase command)
Use if timeout occurred during "wait until" periods, for Macronix devices only.

Bank Switching (devices bigger than 64K only)
  [E005555h]=AAh, [E002AAAh]=55h, [E005555h]=B0h  (select bank command)
  [E000000h]=bnk                                  (write bank number 0..1)
Specifies 64K bank number for read/write/erase operations.
Required because gamepak flash/sram addressbus is limited to 16bit width.

Device Types
Nintendo puts different FLASH chips in commercial game cartridges. Developers should thus detect & support all chip types. For Atmel chips it'd be recommended to simulate 4K sectors by software, though reportedly Nintendo doesn't use Atmel chips in newer games anymore. Also mind that different timings should not disturb compatibility and performance.
  ID     Name       Size  Sectors  AverageTimings  Timeouts/ms   Waits
  D4BFh  SST        64K   16x4K    20us?,?,?       10,  40, 200  3,2
  1CC2h  Macronix   64K   16x4K    ?,?,?           10,2000,2000  8,3
  1B32h  Panasonic  64K   16x4K    ?,?,?           10, 500, 500  4,2
  3D1Fh  Atmel      64K   512x128  ?,?,?           ...40..,  40  8,8
  1362h  Sanyo      128K  ?        ?,?,?           ?    ?    ?    ?
  09C2h  Macronix   128K  ?        ?,?,?           ?    ?    ?    ?
Identification Codes MSB=Device Type, LSB=Manufacturer.
Size in bytes, and numbers of sectors * sector size in bytes.
Average medium Write, Erase Sector, Erase Chips timings are unknown?
Timeouts in milliseconds for Write, Erase Sector, Erase Chips.
Waitstates for Writes, and Reads in clock cycles.

Accessing FLASH Memory
FLASH memory is located in the "SRAM" area at E000000h..E00FFFFh, which is restricted to 16bit address and 8bit data buswidths. Respectively, the memory can be accessed <only> by 8bit read/write LDRB/STRB opcodes.
Also, reading anything (data or status/busy information) can be done <only> by opcodes executed in WRAM (not from opcodes in ROM) (there's no such restriction for writing).

FLASH Waitstates
Use 8 clk waitstates for initial detection (WAITCNT Bits 0,1 both set). After detection of certain device types smaller wait values may be used for write/erase, and even smaller wait values for raw reading, see Device Types table.
In practice, games seem to use smaller values only for write/erase (even though those operations are slow anyways), whilst raw reads are always done at 8 clk waits (even though reads could actually benefit slightly from smaller wait values).

Verify Write/Erase and Retry
Even though device signalizes the completion of write/erase operations, it'd be recommended to read/confirm the content of the changed memory area by software. In practice, Nintendo's "erase-write-verify-retry" function typically repeats the operation up to three times in case of errors.
Also, for SST devices only, the "erase-write" and "erase-write-verify-retry" functions repeat the erase command up to 80 times, additionally followed by one further erase command if no retries were needed, otherwise followed by six further erase commands.

Note
FLASH (64Kbytes) is used by the game Sonic Advance, and possibly others.


GBA Cart Backup DACS

128 KBytes - 1Mbit DACS - Lifetime: 100,000 writes.
1024 KBytes - 8Mbit DACS - Lifetime: 100,000 writes.

DACS (Debugging And Communication System) is used in Nintendo's hardware debugger only, DACS is NOT used in normal game cartridges.

Parts of DACS memory is used to store the debugging exception handlers (entry point/size defined in cartridge header), the remaining memory could be used to store game positions or other data. The address space is the upper end of the 32MB ROM area, the memory can be read directly by the CPU, including for ability to execute program code in this area.


GBA Cart I/O Port (GPIO)

4bit General Purpose I/O Port (GPIO) - contained in the ROM-chip

Used by Boktai for RTC and Solar Sensor:
GBA Cart Real-Time Clock (RTC)
GBA Cart Solar Sensor
And by Warioware Twisted for Rumble and Z-Axis Sensor:
GBA Cart Rumble
GBA Cart Gyro Sensor
Might be also used by other games for other purposes, such like other sensors, or SRAM bank switching, etc.

The I/O registers are mapped to a 6-byte region in the ROM-area at 80000C4h, the 6-byte region should be zero-filled in the ROM-image. In Boktai, the size of the zero-filled region is 0E0h bytes - that probably due to an incorrect definition (the additional bytes do not contain any extra ports, nor mirrors of the ports in the 6-byte region). Observe that ROM-bus writes are limited to 16bit/32bit access (STRB opcodes are ignored; that, only in DS mode?).

80000C4h - I/O Port Data (selectable W or R/W)
  bit0-3  Data Bits 0..3 (0=Low, 1=High)
  bit4-15 not used (0)

80000C6h - I/O Port Direction (for above Data Port) (selectable W or R/W)
  bit0-3  Direction for Data Port Bits 0..3 (0=In, 1=Out)
  bit4-15 not used (0)

80000C8h - I/O Port Control (selectable W or R/W)
  bit0    Register 80000C4h..80000C8h Control (0=Write-Only, 1=Read/Write)
  bit1-15 not used (0)
In write-only mode, reads return 00h (or possible other data, if the rom contains non-zero data at that location).

Connection Examples
  GPIO       | Boktai  | Wario
  Bit Pin    | RTC SOL | GYR RBL
  -----------+---------+---------
  0   ROM.1  | SCK CLK | RES -
  1   ROM.2  | SIO RST | CLK -
  2   ROM.21 | CS  -   | DTA -
  3   ROM.22 | -   FLG | -   MOT
  -----------+---------+---------
  IRQ ROM.43 | IRQ -   | -   -

Aside from the I/O Port, the ROM-chip also includes an inverter (used for inverting the RTC /IRQ signal), and some sort of an (unused) address decoder output (which appears to be equal or related to A23 signal) (ie. reacting on ROM A23, or SRAM D7, which share the same pin on GBA slot).


GBA Cart Real-Time Clock (RTC)

S3511 - 8pin RTC with 3-wire serial bus (used in Boktai)

The RTC chip is (almost) the same as used in NDS consoles:
DS Real-Time Clock (RTC)
The chip is accessed via 4bit I/O port (only 3bits are used for RTC):
GBA Cart I/O Port (GPIO)

Comparision of RTC Registers
  NDS_________GBA_________GBA/Params___
  stat2       control     (1-byte)
  datetime    datetime    (7-byte)
  time        time        (3-byte)
  stat1       force reset (0-byte)
  clkadjust   force irq   (0-byte)
  alarm1/int1 always FFh  (boktai contains code for writing 1-byte to it)
  alarm2      always FFh  (unused)
  free        always FFh  (unused)

Control Register
  Bit Dir Expl.
  0   -   Not used
  1   R/W IRQ duty/hold related?
  2   -   Not used
  3   R/W Per Minute IRQ (30s duty)        (0=Disable, 1=Enable)
  4   -   Not used
  5   R/W Unknown?
  6   R/W 12/24-hour Mode                  (0=12h, 1=24h) (usually 1)
  7   R   Power-Off (auto cleared on read) (0=Normal, 1=Failure, time lost)
Setting after Battery-Shortcut is 82h. Setting after Force-Reset is 00h.
Unused bits seem to be always zero, but might be read-only or write-only?

Datetime and Time Registers
Same as NDS, except AM/PM flag moved from hour.bit6 (NDS) to hour.bit7 (GBA).

Force Reset/Irq Registers
Used to reset all RTC registers (all used registers become 00h, except day/month which become 01h), or to drag the IRQ output LOW for a short moment. These registers are strobed by ANY access to them, ie. by both writing to, as well as reading from these registers.

RTC Games
  Boktai series     ;which/how many titles?
  P-Letter series   ;which/how many titles?
  Rockman EXE 4.5 Real Operation

Pin-Outs / IRQ Signal
The package has identical pin-outs as in NDS, although it is slightly larger than the miniature chip in the DS.
For whatever reason, the RTC's /IRQ output is passed through an inverter (contained in the ROM-chip), the inverted signal is then passed to the /IRQ pin on the cartridge slot. So, IRQ's will be triggered on the "wrong" edge - possible somehow in relation with detecting cartridge-removal IRQs?


GBA Cart Solar Sensor

Uses a Photo Diode as Solar Sensor (used in Boktai, allowing to defeat vampires when the cartridge is exposed to sunlight). The cartridge comes in transparent case, and it's slightly longer than normal carts, so the sensor reaches out of the cartridge slot. According to the manual, the sensor works only with sunlight, but actually it works with any strong light source (eg. a 100 Watt bulb at 1-2 centimeters distance). The sensor is accessed via 4bit I/O port (only 3bits used), which is contained in the ROM-chip.
GBA Cart I/O Port (GPIO)

A/D Conversion
The cartridge uses a self-made digital-ramp converter A/D converter, which is (maybe) better than measuring a capacitor charge-up time, and/or less expensive than a real ADC-chip:
It contains a 74LV4040 12bit binary counter (clocked by CPU via the I/O port), of which only the lower 8bit are used, which are passed to a resistor ladder-type D/A converter, which is generating a linear increasing voltage, which is passed to a TLV272 voltage comparator, which is passing a signal to the I/O port when the counter voltage becomes greater than the sensor voltage.

Example Code
  strh  0001h,[80000c8h] ;-enable R/W mode
  strh  0007h,[80000c6h] ;-init I/O direction
  strh  0002h,[80000c4h] ;-reset counter to zero (high=reset) (I/O bit0)
  strh  0000h,[80000c4h] ;-clear reset (low=normal)
  mov   r0,0             ;-initial level
 @@lop:
  strh  0001h,[80000c4h] ;-clock high ;\increase counter      (I/O bit1)
  strh  0000h,[80000c4h] ;-clock low  ;/
  ldrh  r1,[80000c4h]    ;-read port                          (I/O bit3)
  tst   r1,08h           ;\
  addeq r0,1             ; loop until voltage match (exit with r0=00h..FFh),
  tsteq r0,100h          ; or until failure/timeout (exit with r0=100h)
  beq   @@lop            ;/
The results vary depending on the clock rate used. In above example, ensure that IRQs or DMAs do not interrupt the function. Alternately, use a super-slow clock rate (eg. like 666Hz used in Boktai) so that additional small IRQ/DMA delays have little effect on the overall timing. Results should be somewhat:
  E8h  total darkness (including LED light, or daylight on rainy days)
  Dxh  close to a 100 Watt Bulb
  5xh  reaches max level in boktai's solar gauge
  00h  close to a tactical nuclear bomb dropped on your city
The exact values may change from cartridge to cartridge, so it'd be recommened to include a darkness calibration function, prompting the user to cover the sensor for a moment (in Boktai, access Options by pressing left/right in title screen) (alternately, auto-calibration could theoretically memorize the darkest in-game level ever seen).


GBA Cart Tilt Sensor

Yoshi's Universal Gravitation / Yoshi Topsy Turvy (X/Y-Axis)
Koro Koro Puzzle (probably same as Yoshi, X/Y-Axis, too) (?)

Yoshi-Type (X/Y-Axis)
All of the registers are one byte wide, mapped into the top "half" of the SRAM memory range.
  E008000h (W) Write 55h to start sampling
  E008100h (W) Write AAh to start sampling
  E008200h (R) Lower 8 bits of X axis
  E008300h (R) Upper 4 bits of X axis, and Bit7: ADC Status (0=Busy, 1=Ready)
  E008400h (R) Lower 8 bits of Y axis
  E008500h (R) Upper 4 bits of Y axis
You must set SRAM wait control to 8 clocks to access it correctly.
You must also set the cartridge PHI terminal to 4 MHz to make it work.
Sampling routine (typically executed once a frame during VBlank):
  wait until [E008300h].Bit7=1 or until timeout ;wait ready
  x = ([E008300h] AND 0Fh)*100h + [E008200h]    ;get x
  y = ([E008500h] AND 0Fh)*100h + [E008400h]    ;get y
  [E008000h]=55h, [E008100h]=AAh                ;start next conversion
Example values (may vary on different carts and on temperature, etc):
  X ranged between 0x2AF to 0x477, center at 0x392.    Huh?
  Y ranged between 0x2C3 to 0x480, center at 0x3A0.    Huh?
Thanks to Flubba for Yoshi-Type information.
Unknown if the Yoshi-Type sensors are sensing rotation, or orientation, or motion, or something else? In case of rotation, rotation around X-axis would result in motion in Y-direction, so not too sure whether X and Y have which meaning?
Most probably, the sensors are measuring (both) static acceleration (gravity), and dynamic acceleration (eg. shaking the device left/right).
The X/Y values are likely to be mirrored depending on using a back-loading cartridge slot (original GBA), or front-loading cartridge slot (newer GBA SP, and NDS, and NDS-Lite).


GBA Cart Gyro Sensor

Warioware Twisted (Z-Axis Gyro Sensor, plus Rumble)

Wario-Type (Z-Axis)
Uses a single-axis sensor, which senses rotation around the Z-axis. The sensor is connected to an analogue-in, serial-out ADC chip, which is accessed via lower 3 bits of the GPIO,
GBA Cart I/O Port (GPIO)
The four I/O Lines are connected like so,
  GPIO.Bit0 (W) Start Conversion
  GPIO.Bit1 (W) Serial Clock
  GPIO.Bit2 (R) Serial Data
  GPIO.Bit3 (W) Used for Rumble (not gyro related)
There should be at least <three sequential 32bit ARM opcodes executed in WS0 region> between the STRH opcodes which toggle the CLK signal. Wario uses WAITCNT=45B7h (SRAM=8clks, WS0/WS1/WS2=3,1clks, Prefetch=On, PHI=Off).
The data stream consists of: 4 dummy bits (usually zero), followed by 12 data bits, followed by endless unused bits (usually zero).
 read_gyro:
  mov  r1,8000000h      ;-cartridge base address
  mov  r0,01h           ;\enable R/W access
  strh r0,[r1,0c8h]     ;/
  mov  r0,0bh           ;\init direction (gpio2=input, others=output)
  strh r0,[r1,0c6h]     ;/
  ldrh r2,[r1,0c4h]     ;-get current state (for keeping gpio3=rumble)
  orr  r2,3                     ;\
  strh r2,[r1,0c4h] ;gpio0=1    ; start ADC conversion
  bic  r2,1                     ;
  strh r2,[r1,0c4h] ;gpio0=0    ;/
  mov  r0,00010000h ;stop-bit           ;\
  bic  r2,2                             ;
 @@lop:                                 ;
  ldrh r3,[r1,0c4h] ;get gpio2=data     ; read 16 bits
  strh r2,[r1,0c4h] ;gpio1=0=clk=low    ; (4 dummy bits, plus 12 data bits)
  movs r3,r3,lsr 3  ;gpio2 to cy=data   ;
  adcs r0,r0,r0     ;merge data, cy=done;
  orr  r3,r2,2      ;set bit1 and delay ;
  strh r3,[r1,0c4h] ;gpio1=1=clk=high   ;
  bcc  @@lop                            ;/
  bic  r0,0f000h                 ;-strip upper 4 dummy bits (isolate 12bit adc)
  bx   lr
Example values (may vary on different carts, battery charge, temperature, etc):
  354h  rotated in anti-clockwise direction (shock-speed)
  64Dh  rotated in anti-clockwise direction (normal fast)
  6A3h  rotated in anti-clockwise direction (slow)
  6C0h  no rotation                         (stopped)
  6DAh  rotation in clockwise direction     (slow)
  73Ah  rotation in clockwise direction     (normal fast)
  9E3h  rotation in clockwise direction     (shock-speed)
For detection, values 000h and FFFh would indicate that there's no sensor.
The Z-axis always points into same direction; no matter of frontloading or backloading cartridge slots.
Thanks to Momo Vampire for contributing a Wario cartridge.

X/Y/Z-Axes
X-Axis and Y-Axis are meant to be following the screens X and Y coordinates, so the Z-Axis would point into the screens depth direction.

DSi Cameras
DSi consoles can mis-use the built-in cameras as Gyro sensor (as done by the System Flaw DSi game).


GBA Cart Rumble

Warioware Twisted (Rumble, plus Z-Axis Gyro Sensor)
Drill Dozer (Rumble only) <-- and ALSO supports Gameboy Player rumble?

GBA Rumble Carts are containing a small motor, which is causing some vibration when/while it is switched on (that, unlike DS Rumble, which must be repeatedly toggled on/off).

In Warioware Twisted, rumble is controlled via GPIO.Bit3 (Data 0=Low=Off, 1=High=On) (and Direction 1=Output), the other GPIO Bits are used for the gyro sensor.
GBA Cart I/O Port (GPIO)
Note: GPIO3 is connected to an external pulldown resistor (so the HighZ level gets dragged to Low=Off when direction is set to Input).

Unknown if Drill Dozer is controlled via GPIO.Bit3, too?

DS Rumble Pak
Additionally, there's a Rumble Pak for the NDS, which connects to the GBA slot, so it can be used also for GBA games (provided that the game doesn't require the GBA slot, eg. GBA multiboot games).
DS Cart Rumble Pak

Gamecube Rumble
Moreover, GBA games that are running on a Gameboy Player are having access to the Rumble function of Gamecube joypads.
GBA Gameboy Player


GBA Cart e-Reader

GBA Cart e-Reader Overview
GBA Cart e-Reader I/O Ports
GBA Cart e-Reader Dotcode Format
GBA Cart e-Reader Data Format
GBA Cart e-Reader Program Code
GBA Cart e-Reader API Functions
GBA Cart e-Reader VPK Decompression
GBA Cart e-Reader Error Correction
GBA Cart e-Reader File Formats

   ________________
  |   ShortStrip   |
  |L              L|
  |o    Center    o|
  |n    Region    n|
  |g              g|
  |  may contain   |
  |S   pictures,  S|
  |t instructions t|
  |r     etc.     r|
  |i              i|
  |p              p|
  |___ShortStrip___|


GBA Cart e-Reader Overview

The e-Reader is a large GBA cartridge (about as big as the GBA console), with built-in dotcode scanning hardware. Dotcodes are tiny strips of black and white pixels printed on the edges of cardboard cards. The cards have to be pulled through a slot on the e-Reader, which is giving it a feeling like using a magnet card reader. The binary data on the dotcodes contains small games, either in native GBA code (ARM/THUMB), or in software emulated 8bit Z80 or NES/Famicom (6502) code.

The e-Reader Hardware
The hardware consists of regular 8MByte ROM and 128KByte FLASH chips, two link ports, a custom PGA chip, the camera module (with two red LEDs, used as light source), and some analogue components for generating the LED voltages, etc. The camera supports 402x302 pixels with 7bit monochrome color depth, but the PGA clips it to max 320 pixels per scanline with 1bit color depth.

Link Port Plug/Socket
The e-Reader's two link ports are simply interconnected with each other; without connection to the rest of the e-Reader hardware. These ports are used only on the original GBA (where the large e-Reader cartridge would be covering the GBA's link socket). When trying to insert the e-Reader into an original NDS (or GBA-Micro), then the e-Reader's link plug will hit against the case of the NDS, so it works only with some minor modification to the hardware. There's no such problem with GBA-SP and NDS-Lite.

Region/Version
There are 3 different e-Reader's: Japanese/Original, Japanese/Plus, and Non-Japanese. The Original version has only 64K FLASH, no Link Port, and reportedly supports only Z80 code, but no NES/GBA code. The Plus and Non-Japanese versions should be almost identical, except that they reject cards from the wrong region, and that the title strings aren't ASCII in Japan, the Plus version should be backwards compatible to the Original one.

The Problem
Nintendo's current programmers are definetly unable to squeeze a Pac-Man style game into less than 4MBytes. Their solution has been: MORE memory. That is, they've put a whopping 8MByte BIOS ROM into the e-Reader, which contains the User Interface, and software emulation for running some of their 20 years old 8bit NES and Game&Watch titles, which do fit on a few dotcode strips.


GBA Cart e-Reader I/O Ports

DF80000h Useless Register (R/W)
  0     Output to PGA.Pin93 (which seems to be not connected to anything)
  1-3   Unknown, read/write-able (not used by e-Reader BIOS)
  4-15  Always zero (0)

DFA0000h Reset Register (R/W)
  0    Always zero              (0)
  1    Reset Something?         (0=Normal, 1=Reset)
  2    Unknown, always set      (1)
  3    Unknown, read/write-able (not used by e-Reader BIOS)
  4-7  Always zero              (0)
  8    Unknown, read/write-able (not used by e-Reader BIOS)
  9-15 Always zero              (0)

DFC0000h..DFC0027h Scanline Data (R)
Scanline data (40 bytes, for 320 pixels, 1bit per pixel, 0=black, 1=white).
The first (leftmost) pixel is located in the LSB of the LAST byte.
Port E00FFB1h.Bit1 (and [4000202h].Bit13) indicates when a new scanline is present, the data should be then transferred to RAM via DMA3 (SAD=DFC0000h, DAD=buf+y*28h, CNT=80000014h; a slower non-DMA transfer method would result in missed scanlines). After the DMA, software must reset E00FFB1h.Bit1.
Note: The scanning resolution is 1000 DPI.

DFC0028h+(0..2Fh*2) Brightest Pixels of 8x6 Blocks (R)
  0-6  Max Brightness (00h..7Fh; 00h=All black, 7Fh=One or more white)
  7-15 Always zero
Can be used to adjust the Port E00FF80h..E00FFAFh settings.

DFC0088h Darkest Pixel of whole Image (R)
  0-7  Max Darkness   (00h..7Fh; 00h=One or more black, 7Fh=All white)
  8-15 Always zero
Can be used to adjust the Port E00FF80h..E00FFAFh settings.

E00FF80h..E00FFAFh Intensity Boundaries for 8x6 Blocks (R/W)
The 320x246 pixel camera input is split into 8x6 blocks (40x41 pixels each), with Block00h=Upper-right, Block07h=Upper-left, ..., Block27h=Lower-left. The boundary values for the separate blocks are used for 128-grayscale to 2-color conversion, probably done like "IF Pixel>Boundary THEN white ELSE black".
  0-6  Block Intensity Boundaries (0..7Fh; 7Fh=Whole block gets black)
  7    Always zero
The default boundary values are stored in FLASH memory, the values are typically ranging from 28h (outer edges) to 34h (center image), that in respect to the light source (the two LEDs are emitting more light to the center region).

E00FFB0h Control Register 0 (R/W)
  0    Serial Data       (Low/High)
  1    Serial Clock      (Low/High)
  2    Serial Direction  (0=Input, 1=Output)
  3    Led/Irq Enable    (0=Off, 1=On; Enable LED and Gamepak IRQ)
  4    Start Scan        (0=Off, 1=Start) (0-to-1 --> Resync line 0)
  5    Phi 16MHz Output  (0=Off, 1=On; Enable Clock for Camera, and for LED)
  6    Power 3V Enable   (0=Off, 1=On; Enable 3V Supply for Camera)
  7    Not used          (always 0) (sometimes 1) (Read only)

E00FFB1h Control Register 1 (R/W)
  0    Not used          (always 0)
  1    Scanline Flag     (1=Scanline Received, 0=Acknowledge)
  2-3  Not used          (always 0)
  4    Strange Bit       (0=Normal, 1=Force Resync/Line0 on certain interval?)
  5    LED Anode Voltage (0=3.0V, 1=5.1V; requires E00FFB0h.Bit3+5 to be set)
  6    Not used          (always 0)
  7    Input from PGA.Pin22, always high (not used by e-Reader) (Read Only)
Bit1 can be SET by hardware only, software can only RESET that bit, the Gamepak IRQ flag (Port 4000202h.Bit13) becomes set on 0-to-1 transitions.

E00FFB2h Light Source LED Kathode Duration (LSB) (R/W)
E00FFB3h Light Source LED Kathode Duration (MSB) (R/W)
Selects the LED Kathode=LOW Duration, aka the LED=ON Duration. That does act as pulse width modulated LED brightness selection (the camera seems to react slowly enough to view the light as being dimmed to medium, rather than seeing the actual light ON and OFF states). The PWM timer seems to be clocked at 8MHz. The hardware clips timer values 2000h..FFFFh to max 2000h (=1ms). Additionally, the e-Reader BIOS clips values to max 11B3h. Default setting is found in FLASH calibration data. A value of 0000h disables the LED.

Serial Port Registers (Camera Type 1) (DV488800) (calib_data[3Ch]=1)
All 16bit values are ordered MSB,LSB. All registers are whole 8bit Read/Write-able, except 00h,57h-5Ah (read only), and 53h-55h (2bit only).
  Port     Expl.               (e-Reader Setting)
  00h      Maybe Chip ID (12h) (not used by e-Reader BIOS) (Read Only)
  01h                          (05h)    ;-Bit0: 1=auto-repeat scanning?
  02h                          (0Eh)
  10h-11h  Vertical Scroll     (calib_data[30h]+7)
  12h-13h  Horizontal Scroll   (0030h)
  14h-15h  Vertical Size       (00F6h=246)
  16h-17h  Horizontal Size     (0140h=320)
  20h-21h  H-Blank Duration    (00C4h)
  22h-23h                      (0400h)  ;-Upper-Blanking in dot-clock units?
  25h                          (var)    ;-bit1: 0=enable [57h..5Ah] ?
  26h                          (var)    ;\maybe a 16bit value
  27h                          (var)    ;/
  28h                          (00h)
  30h      Brightness/contrast (calib_data[31h]+/-nn)
  31h-33h                      (014h,014h,014h)
  34h      Brightness/contrast (02h)
  50h-52h  8bit Read/Write     (not used by e-Reader BIOS)
  53h-55h  2bit Read/Write     (not used by e-Reader BIOS)
  56h      8bit Read/Write     (not used by e-Reader BIOS)
  57h-58h  16bit value, used to autodetect/adjust register[30h] (Read Only)
  59h-5Ah  16bit value, used to autodetect/adjust register[30h] (Read Only)
  80h-FFh  Mirrors of 00h..7Fh (not used by e-Reader BIOS)
All other ports are unused, writes to those ports are ignored, and reads are returning data mirrored from other ports; that is typically data from 2 or more ports, ORed together.

Serial Port Registers (Camera Type 2) (calib_data[3Ch]=2)
All 16bit values are using more conventional LSB,MSB ordering, and port numbers are arranged in a more reasonable way. The e-Reader BIOS doesn't support (or doesn't require) brightness adjustment for this camera module.
  Port     Expl.             (e-Reader Setting)
  00h                        (22h)
  01h                        (50h)
  02h-03h  Vertical Scroll   (calib_data[30h]+28h)
  04h-05h  Horizontal Scroll (001Eh)
  06h-07h  Vertical Size     (00F6h)    ;=246
  08h-09h  Horizontal Size   (0140h)    ;=320
  0Ah-0Ch                    (not used by e-Reader BIOS)
  0Dh                        (01h)
  0Eh-0Fh                    (01EAh)    ;=245*2
  10h-11h                    (00F5h)    ;=245
  12h-13h                    (20h,F0h)  ;maybe min/max values?
  14h-15h                    (31h,C0h)  ;maybe min/max values?
  16h                        (00h)
  17h-18h                    (77h,77h)
  19h-1Ch                    (30h,30h,30h,30h)
  1Dh-20h                    (80h,80h,80h,80h)
  21h-FFh                    (not used by e-Reader BIOS)
This appears to be a Micron (aka Aptina) camera (resembling the DSi cameras).
My own e-Reader uses a Type 1 camera module. Not sure if Nintendo has ever manufactured any e-Readers with Type 2 cameras?

Calibration Data in FLASH Memory (Bank 0, Sector 0Dh)
  E00D000 14h  ID String ('Card-E Reader 2001',0,0)
  E00D014 2    Sector Checksum (NOT(x+x/10000h); x=sum of all other halfwords)
Begin of actual data (40h bytes)
  E00D016 8x6  [00h] Intensity Boundaries for 8x6 blocks ;see E00FF80h..AFh
  E00D046 1    [30h] Vertical scroll (0..36h)  ;see type1.reg10h/type2.reg02h
  E00D047 1    [31h] Brightness or contrast    ;see type1.reg30h
  E00D048 2    [32h] LED Duration              ;see E00FFB2h..B3h
  E00D04A 2    [34h] Not used?   (0000h)
  E00D04C 2    [36h] Signed value, related to adjusting the 8x6 blocks
  E00D04E 4    [38h] Not used?   (00000077h)
  E00D052 4    [3Ch] Camera Type (0=none,1=DV488800,2=Whatever?)
Remaining bytes in this Sector...
  E00D056 FAAh Not used (zerofilled) (included in above checksum)

Flowchart for Overall Camera Access
ereader_scan_camera:
 call ereader_power_on
 call ereader_initialize
 for z=1 to number_of_frames
  for y=0 to 245
   Wait until E00FFB1h.Bit1 gets set by hardware (can be handled by IRQ)
   Copy 14h halfwords from DFC0000h to buf+y*28h via DMA3
   Reset E00FFB1h.Bit1 by software
  next y
  ;(could now check DFC0028h..DFC0086h/DFC0088h for adjusting E00FF00h..2Fh)
  ;(could now show image on screen, that may require to stop/pause scanning)
 next z
 call ereader_power_off
 Ret
ereader_power_on:
 [4000204h]=5803h   ;Init waitstates, and enable Phi 16MHz
 [DFA0000h].Bit1=1
 Wait(10ms)
 [E00FFB0h]=40h     ;Enable Power3V and reset other bits
 [DFA0000h].Bit1=0
 [E00FFB1h]=20h     ;Enable Power5V and reset other bits
 Wait(40ms)
 [E00FFB1h].Bit4=0  ;...should be already 0 ?
 [E00FFB0h]=40h+27h ;Phi16MHz=On, SioDtaClkDir=HighHighOut
 Ret
ereader_power_off:
 [E00FFB0h]=04h    ;Power3V=Off, Disable Everything, SioDtaClkDir=LowLowOut
 [DFA0000h].Bit1=0 ;...should be already 0
 [E00FFB1h].Bit5=0 ;Power5V=Off
 Ret
ereader_initialize:
 IF calib_data[3Ch] AND 03h = 1 THEN init_camera_type1
 [E00FFB0h].Bit4=1 ;ScanStart
 IF calib_data[3Ch] AND 03h = 2 THEN init_camera_type2
 Copy calib_data[00h..2Fh] to [E00FF80h+00h..2Fh]  ;Intensity Boundaries
 Copy calib_data[32h..33h] to [E00FFB2h+00h..01h]  ;LED Duration LSB,MSB
 [E00FFB0h].Bit3=1                                 ;LedIrqOn
 Ret
init_camera_type1:
 x=MIN(0,calib_data[31h]-0Bh)
 Set Sio Registers (as shown for Camera Type 1, except below values...)
 Set Sio Registers [30h]=x [25h]=04h, [26h]=58h, [27h]=6Ch
 ;(could now detect/adjust <x> based on Sio Registers [57h..5Ah])
 Set Sio Registers [30h]=x [25h]=06h, [26h]=E8h, [27h]=6Ch
 Ret
init_camera_type2:
 Wait(0.5ms)
 Set Sio Registers (as shown for Camera Type 2)
 Ret

Accessing Serial Registers via E00FFB0h
      Begin   Write(A) Write(B) Read(C) Read(D) End     Idle    PwrOff
  Dir ooooooo ooooooo  ooooooo  iiiiiii iiiiiii ooooooo ooooooo ooooooo
  Dta ---____ AAAAAAA  BBBBBBB  xxxxxCx xxxxxDx ______- ------- _______
  Clk ------_ ___---_  ___---_  ___---_ ___---_ ___---- ------- _______

Flowchart for accessing Serial Registers via E00FFB0h (looks like I2C bus)
 Delay:
  Wait circa 2.5us, Ret
 SioBegin:
  SioDta=1, SioDir=Out, SioClk=1, Delay, SioDta=0, Delay, SioClk=0, Ret
 SioEnd:
  SioDta=0, SioDir=Out, Delay, SioClk=1, Delay, SioDta=1, Ret
 SioRead1bit:   ;out: databit
  SioDir=In, Delay, SioClk=1, Delay, databit=SioDta, SioClk=0, Ret
 SioWrite1bit:  ;in: databit
  SioDta=databit, SioDir=Out, Delay, SioClk=1, Delay, SioClk=0, Ret
 SioReadByte:   ;in: endflag - out: data
  for i=7 to 0, data.bit<i>=SioRead1bit, next i, SioWrite1bit(endflag), Ret
 SioWriteByte:  ;in: data - out: errorflag
  for i=7 to 0, Delay(huh/why?), SioWrite1bit(data.bit<i>), next i
  errorflag=SioRead1bit, SioDir=Out(huh/why?), Ret
 SioWriteRegisters:  ;in: index, len, buffer
  SioBegin
  SioWriteByte(22h)        ;command (set_index) (and write_data)
  SioWriteByte(index)      ;index
  for i=0 to len-1
   SioWriteByte(buffer[i]) ;write data (and auto-increment index)
  next
  SioEnd
  ret
 SioReadRegisters:   ;in: index, len - out: buffer
  SioBegin
  SioWriteByte(22h)        ;command (set_index) (without any write_data here)
  SioWriteByte(index)      ;index
  SioBegin
  SioWriteByte(23h)        ;command (read_data) (using above index)
  for i=0 to len-1
   if i=len-1 then endflag=1 else endflag=0
   buffer[i]=SioReadByte(endflag)  ;read data (and auto-increment index)
  next
  SioEnd
  Ret
Caution: Accessing the SIO registers appears highly unstable, and seems to require error handling with retries. Not sure what is causing that problem, possibly the registers cannot be accessed during camera-data-scans...?

WAITCNT
The e-Reader BIOS uses WAITCNT [4000204h]=5803h when accessing the PGA, that is, gamepak 16.78MHz phi output (bit11-12=3), 8 waits for SRAM region (bit0-1=3), gamepak prefetch enabled (bit14=1), also sets WS0 to 4,2 waits (bit2-4=0), and sets WS2 to odd 4,8 waits (bit8-10=0). The WS2 (probably WS0 too) settings are nonsense, and should work with faster timings (the e-Reader can be accessed in NDS mode, which doesn't support that slow timings).

e-Reader Memory and I/O Map (with all used/unused/mirrored regions)
  C000000h-C7FFFFFh  ROM (8MB)
  C800000h-DF7FFFFh  Open Bus
  DF80000h-DF80001h  Useless Register (R/W)
  DF80002h-DF9FFFFh  Mirrors of DF80000h-DF80001h
  DFA0000h-DFA0001h  Reset Register (R/W)
  DFA0002h-DFBFFFFh  Mirrors of DFA0000h-DFA0001h
  DFC0000h-DFC0027h  Scanline Data (320 Pixels) (R)
  DFC0028h-DFC0087h  Brightest Pixels of 8x6 Blocks (R)
  DFC0088h           Darkest Pixel of whole Image (R)
  DFC0089h-DFC00FFh  Always zero
  DFC0100h-DFDFFFFh  Mirrors of DFC0000h-DFC00FFh
  DFE0000h-DFFFFFFh  Open Bus
  E000000h-E00CFFFh  FLASH Bank 0 - Data
  E00D000h-E00DFFFh  FLASH Bank 0 - Calibration Data
  E00E000h-E00EFFFh  FLASH Bank 0 - Copy of Calibration Data
  E00F000h-E00FF7Fh  FLASH Bank 0 - Unused region
  E000000h-E00EFFFh  FLASH Bank 1 - Data
  E00F000h-E00FF7Fh  FLASH Bank 1 - Unused region
  E00FF80h-E00FFAFh  Intensity Boundaries for 8x6 Blocks (R/W)
  E00FFB0h           Control Register 0 (R/W)
  E00FFB1h           Control Register 1 (R/W)
  E00FFB2h-E00FFB3h  LED Duration (16bit) (R/W)
  E00FFB4h-E00FFBFh  Always zero
  E00FFC0h-E00FFFFh  Mirror of E00FF80h-E00FFBFh
Mind that WS2 should be accessed by LDRH/STRH, and SRAM region by LDRB/STRB.
Additionally about 32 serial bus registers are contained in the camera module.

Camera Module Notes
The Type 1 initial setting on power-on is 402x302 pixels, the e-Reader uses only 320x246 pixels. The full vertical resolution could be probably used without problems. Port DFC0000h-DFC0027h are restricted to 320 pixels, so larger horizontal resolutions could be probably obtained only by changing the horizontal scroll offset on each 2nd scan.
The camera output is 128 grayscales (via parallel 7bit databus), but the PGA converts it to 2 colors (1bit depth). For still images, it might be possible to get 4 grayshades via 3 scans with different block intensity boundary settings.
No idea if the camera supports serial commands other than 22h and 23h. Namely, it <would> be a quite obvious and basic feature to allow to receive the bitmap via the 2-wire serial bus (alternately to the 7bit databus), if supported, it'd allow to get 7bit images, bypassing 1bit PGA conversion.
When used as actual camera (by cutting an opening in the case), the main problem is the 1bit color depth, which allows only black and white schemes, when/if solving that problem, focusing might be also a problem.

Either the camera or the PGA seem to have a problem on white-to-black transitions in vertical direction, the upper some black pixels are sorts of getting striped or dithered. For example, scanning the large sync marks appears as:
  Actual Shape    Scanned Shape
     XXXXX            X  X
    XXXXXXX           X  X X
   XXXXXXXXX        X X  X XX
   XXXXXXXXX        X X  X XX
    XXXXXXX          XXXXXXX
     XXXXX            XXXXX
That appears only on large black shapes (the smaller data dots look better). Probably the image is scanned from bottom upwards (and the camera senses only the initial transition at the bottom, and then looses track of what it is doing).


GBA Cart e-Reader Dotcode Format

Resolution is 342.39 DPI (almost 10 blocks per inch).
Resolution is 134.8 dots/cm (almost 4 blocks per centimeter).
The width and height of each block, and the spacing to the bottom edge of the card is ca. 1/10 inch, or ca. 4 millimeters.

   XXX            BLOCK 1             XXX            BLOCK 2             XXX
  XXXXX                              XXXXX                              XXXXX
  XXXXX   X X X X X X  X X X X X X   XXXXX   X X X X X X  X X X X X X   XXXXX
  XXXXX                              XXXXX                              XXXXX
   XXX   HHHHHHHHHHHHHHHHHHHH......   XXX   HHHHHHHHHHHHHHHHHHHH......   XXX
         ..........................         ..........................
         ...... 3 short lines .....         ..........................
    A..................................A..................................A..
    A....      26 long lines       ....A........ X = Sync Marks   ........A..
    A....  (each 34 data dots)     ....A........ H = Block Header ........A..
    A....(not all lines shown here)....A........ . = Data Bits    ........A..
    A..................................A........ A = Address Bits ........A..
         ...... 3 short lines .....         ..........................
         ...(each 26 data dots)....         ..........................
   XXX   ..........................   XXX   ..........................   XXX
  XXXXX                              XXXXX                              XXXXX
  XXXXX   X X X X X X  X X X X X X   XXXXX   X X X X X X  X X X X X X   XXXXX
  XXXXX                              XXXXX                              XXXXX
   XXX                                XXX                                XXX
             <ca. 35 blank lines>
  ___Snip____________________________________________________________________

Address Columns
Each Column consists of 26 dots. From top to bottom: 1 black dot, 8 blank dots, 16 address dots (MSB topmost), and 1 blank dot. The 16bit address values can be calculated as:
  addr[0] = 03FFh
  for i = 1 to 53
    addr[i] = addr[i-1] xor ((i and (-i)) * 769h)
    if (i and 07h)=0 then addr[i] = addr[i] xor (769h)
    if (i and 0Fh)=0 then addr[i] = addr[i] xor (769h*2)
    if (i and 1Fh)=0 then addr[i] = addr[i] xor (769h*4) xor (769h)
  next i
Short strips use addr[1..19], long strips use addr[25..53], left to right.

Block Header
The 18h-byte Block Header is taken from the 1st two bytes (20 dots) of the 1st 0Ch blocks (and is then repeated in the 1st two bytes of further blocks).
  00h      Unknown              (00h)
  01h      Dotcode type         (02h=Short, 03h=Long)
  02h      Unknown              (00h)
  03h      Address of 1st Block (01h=Short, 19h=Long)
  04h      Total Fragment Size  (40h) ;64 bytes per fragment, of which,
                                      ;48 bytes are actual data, the remaining
  05h      Error-Info Size      (10h) ;16 bytes are error-info
  06h      Unknown              (00h)
  07h      Interleave Value     (1Ch=Short, 2Ch=Long)
  08h..17h 16 bytes Reed-solomon error correction info for Block Header

Data 4-Bit to 5-bit Conversion
In the Block Header (HHHHH), and Data Region (.....), each 4bit are expanded to 5bit, so one byte occupies 10 dots, and each block (1040 data dots) contains 104 bytes.
  4bit  00h 01h 02h 03h 04h 05h 06h 07h 08h 09h 0Ah 0Bh 0Ch 0Dh 0Eh 0Fh
  5bit  00h 01h 02h 12h 04h 05h 06h 16h 08h 09h 0Ah 14h 0Ch 0Dh 11h 10h
That formatting ensures that there are no more than two continous black dots (in horizontal direction), neither inside of a 5bit value, nor between two 5bit values, however, the address bars are violating that rule, and up to 5 continous black dots can appear at the (..A..) block boundaries.

Data Order
Data starts with the upper bit of the 5bit value for the upper 4bit of the first byte, which is located at the leftmost dot of the upper line of the leftmost block, it does then extend towards rightmost dot of that block, and does then continue in the next line, until reaching the bottom of the block, and does then continue in the next block. The 1st two bytes of each block contain a portion of the Block Header, the remaining 102 bytes in each block contain data.

Data Size
A long strip consists of 28 blocks (28*104 = 2912 bytes), a short strip of 18 blocks (18*104 = 1872 bytes). Of which, less than 75% can be actually used for program code, the remaining data contains error correction info, and various headers. See Data Format for more info.

Interleaved Fragments
The Interleave Value (I) specifies the number of fragments, and does also specify the step to the next byte inside of a fragment; except that, at the block boundaries (every 104 bytes), the step is 2 bigger (for skipping the next two Block Header bytes).
  RAW Offset  Content
  000h..001h  1st 2 bytes of RAW Header
  002h        1st byte of 1st fragment
  003h        1st byte of 2nd fragment
  ...         ...
  002h+I-1    1st byte of last fragment
  002h+I      2nd byte of 1st fragment
  003h+I      2nd byte of 2nd fragment
  ...         ...
  002h+I*2-1  2nd byte of last fragment
  ...         ...
Each fragment consists of 48 actual data bytes, followed by 16 error correction bytes, followed by 0..2 unused bytes (since I*40h doesn't exactly match num_blocks*102).


GBA Cart e-Reader Data Format

Data Strip Format
The size of the data region is I*48 bytes (I=Interleave Value, see Dotcode Format), the first 48-byte fragment contains the Data Header, the remaining (I-1) fragments are Data Fragments (which contain title(s), and VPK compressed program code).

First Strip
  Data Header  (48 bytes)
  Main-Title   (17 bytes, or 33 bytes)
  Sub-Title(s) (3+18 bytes, or 33 bytes) (for each strip) (optional)
  VPK Size     (2 byte value, total length of VPK Data in ALL strips)
  NULL Value   (4 bytes, contained ONLY in 1st strip of GBA strips)
  VPK Data     (length as defined in VPK Size entry, see above)

Further Strip(s)
  Data Header  (48 bytes)
  Main-Title   (17 bytes, or 33 bytes)
  Sub-Title(s) (3+18 bytes, or 33 bytes) (for each strip) (optional)
  VPK Data     (continued from previous strip)

Data Header (30h bytes) (1st fragment)
  00h-01h  Fixed         (00h,30h)
  02h      Fixed         (01h)     ;01h="Do not calculate Global Checksum" ?
  03h      Primary Type  (see below)
  04h-05h  Fixed         (00h,01h) (don't care)
  06h-07h  Strip Size    (0510h=Short, 0810h=Long Strip) ((I-1)*30h) (MSB,LSB)
  08h-0Bh  Fixed         (00h,00h,10h,12h)
  0Ch-0Dh  Region/Type   (see below)
  0Eh      Strip Type    (02h=Short Strip, 01h=Long Strip) (don't care)
  0Fh      Fixed         (00h) (don't care)
  10h-11h  Unknown       (whatever) (don't care)
  12h      Fixed         (10h)     ;10h="Do calculate Data Checksum" ?
  13h-14h  Data Checksum (see below) (MSB,LSB)
  15h-19h  Fixed         (19h,00h,00h,00h,08h)
  1Ah-21h  ID String     ('NINTENDO')
  22h-25h  Fixed         (00h,22h,00h,09h)
  26h-29h  Size Info     (see below)
  2Ah-2Dh  Flags         (see below)
  2Eh      Header Checksum (entries [0Ch-0Dh,10h-11h,26h-2Dh] XORed together)
  2Fh      Global Checksum (see below)
Primary Type [03h] is 8bit,
  0      Card Type (upper bit) (see below)
  1      Unknown (usually opposite of Bit0) (don't care)
  2-7    Unknown (usually zero)
Region/Type [0Ch..0Dh] is 16bit,
  0-3    Unknown (don't care)
  4-7    Card Type (lower bits) (see below)
  8-11   Region/Version (0=Japan/Original, 1=Non-japan, 2=Japan/Plus)
  12-15  Unknown (don't care)
Size Info [26h-29h] is 32bit,
  0      Unknown            (don't care)
  1-4    Strip Number       (01h..Number of strips)
  5-8    Number of Strips   (01h..0Ch) (01h..08h for Japan/Original version)
  9-23   Size of all Strips (excluding Headers and Main/Sub-Titles)
         (same as "VPK Size", but also including the 2-byte "VPK Size" value,
         plus the 4-byte NULL value; if it is present)
  24-31  Fixed              (02h) (don't care)
Flags [2Ah-2Dh] is 32bit,
  0      Permission to save (0=Start Immediately, 1=Prompt for FLASH Saving)
  1      Sub-Title Flag     (0=Yes, 1=None)    (Japan/Original: always 0=Yes)
  2      Application Type   (0=GBA/Z80, 1=NES) (Japan/Original: always 0=Z80)
  3-31   Zero (0) (don't care)
Data Checksum [13h-14h] is the complement (NOT) of the sum of all halfwords in all Data Fragments, however, it's all done in reversed byte order: checksum is calculated with halfwords that are read in MSB,LSB order, and the resulting checksum is stored in MSB,LSB order in the Header Fragment.
Global Checksum [2Fh] is the complement (NOT) of the sum of the first 2Fh bytes in the Data Header plus the sum of all Data Fragment checksums; the Data Fragment checksums are all 30h bytes in a fragment XORed with each other.

Titles (3+N bytes, or N bytes)
Titles can be 33 bytes for both Main and Sub (Format 0Eh), or Main=17 bytes and Sub=3+18 bytes (Formats 02h..05h). In the 3+N bytes form, the first 3 bytes (24bit) are are used to display "stats" information in form of "HP: h1 ID: i1-i2-i3", defined as:
  Bit    Expl.
  0-3    h1, values 1..15 shown as "10..150", value 0 is not displayed
  4-6    i3, values 0..7 shown as "A..G,#"
  7-13   i2, values 0..98 shown as "01..99" values 99..127 as "A0..C8"
  14-18  i1, values 0..31 shown as "A..Z,-,_,{HP},.,{ID?},:"
  19-22  Unknown
  23     Disable stats (0=Show as "HP: h1 ID: i1-i2-i3", 1=Don't show it)
The N bytes portion contains the actual title, which must be terminated by 00h (so the max length is N-1 characters, if it is shorter than N-1, then the unused bytes are padded by further 00h's). The character set is normal ASCII for non-Japan (see Region/Version entry in header), and 2-byte SHIFT-JIS for Japanese long-titles (=max 16 2-byte chars) with values as so:
  00h          --> end-byte
  81h,40h      --> SPC
  81h,43h..97h --> punctuation marks
  82h,4Fh..58h --> "0..9"
  82h,60h..79h --> "A..Z"
  82h,81h..9Ah --> "a..z"
And 1-byte chars for Japanese short-titles,
  00     = end-byte
  01     = spc
  02..0B = 0..9
  0C..AF = japanese
  B0..B4 = dash, male, female, comma, round-dot
  B5..C0 = !"%&~?/+-:.'
  C1..DA = A..Z
  DB..DF = unused (blank)
  E0..E5 = japanese
  E6..FF = a..z
  N/A    = #$()*;<=>@[\]^_`{|}
Additionally to the Main-Title, optional Sub-Titles for each strip can be included (see Sub-Title Flag in header). If enabled, then ALL strip titles are included in each strip (allowing to show a preview of which strips have/haven't been scanned yet).
The e-Reader can display maximum of 8 sub-titles, if the data consists of more than 8 strips, then sub-titles aren't displayed (so it'd be waste of space to include them in the dotcodes).
The Main Title gets clipped to 128 pixels width (that are, circa 22 characters), and, the e-Reader BIOS acts confused on multi-strip games with Main Titles longer than 26 characters (so the full 33 bytes may be used only in Japan; with 16bit charset).
If the title is empty (00h-filled), and there is only one card in the application, then the application is started immediately. That, without allowing the user to save it in FLASH memory.
Caution: Although shorter Titles do save memory, they do act unpleasant: the text "(C) P-Letter" will be displayed at the bottom of the loading screen.
On Japanese/Original, 8bit sub-titles can be up to 18 characters (without any end-byte) (or less when stats are enabled, due to limited screen width).

Card Types (Primary Type.Bit0 and Region/Type.Bit12-15)
  00h..01h  Blank Screen (?)
  02h..03h  Dotcode Application with 17byte-title, with stats, load music A
  04h..05h  Dotcode Application with 17byte-title, with stats, load music B
  06h..07h  P-Letter Attacks
  08h..09h  Construction Escape
  0Ah..0Bh  Construction Action
  0Ch..0Dh  Construction Melody Box
  0Eh       Dotcode Application with 33byte-title, without stats, load music A
  0Fh       Game specific cards
  10h..1Dh  P-Letter Viewer
  1Eh..1Fh  Same as 0Eh and 0Fh (see above)
The 'Application' types are meant to be executable GBA/Z80/NES programs.


GBA Cart e-Reader Program Code

The GBA/Z80/NES program code is stored in the VPK compressed area.
NES-type is indicated by header [2Ah].Bit2, GBA-type is indicated by the NULL value inserted between VPK Size and VPK Data, otherwise Z80-type is used.

GBA Format
Load Address and Entrypoint are at 2000000h (in ARM state). The 32bit word at 2000008h is eventually destroyed by the e-Reader. Namely,
  IF e-Reader is Non-Japanese,
  AND [2000008h] is outside of range of 2000000h..20000E3h,
  AND only if booted from camera (not when booted from FLASH?),
  THEN [2000008h]=[2000008h]-0001610Ch ELSE [2000008h] kept intact
Existing multiboot-able GBA binaries can be converted to e-Reader format by,
  Store "B 20000C0h" at 2000000h   ;redirect to RAM-entrypoint
  Zerofill 2000004h..20000BFh      ;erase header (for better compression rate)
  Store 01h,01h at 20000C4h        ;indicate RAM boot
The GBA code has full access to the GBA hardware, and may additionally use whatever API functions contained in the e-Reader BIOS. With the incoming LR register value, "mov r0,N, bx lr" returns to the e-Reader BIOS (with N being 0=Restart, or 2=To_Menu). No idea if it's necessary to preserve portions of RAM when returning to the e-Reader BIOS?
Caution: Unlike for normal GBA cartridges/multiboot files, the hardware is left uninitialized when booting dotcodes (among others: sound DMA is active, and brightness is set to zero), use "mov r0,0feh, swi 010000h" to get the normal settings.

NES Format
Emulates a NES (Nintendo Entertainment System) console (aka Family Computer).
The visible 240x224 pixel NES/NTSC screen resolution is resampled to 240x160 to match the smaller vertical resolution of the GBA hardware. So, writing e-Reader games in NES format will result in blurred screen output. The screen/sound/joypad is accessed via emulated NES I/O ports, program code is running on an emulated 6502 8bit CPU, for more info on the NES hardware, see no$nes debugger specifications, or
  http://problemkaputt.de/everynes.htm
The e-Reader's NES emulator supports only 16K PRG ROM, followed by 8K VROM. The emulation accuracy is very low, barely working with some of Nintendo's own NES titles; running the no$nes diagnostics program on it has successfully failed on ALL hardware tests ;-)
The load address for the 16K PRG-ROM is C000h, the 16bit NMI vector at [FFFAh] is encrypted like so:
  for i=17h to 0
   for j=07h to 0, nmi = nmi shr 1, if carry then nmi = nmi xor 8646h, next j
   nmi = nmi xor (byte[dmca_data+i] shl 8)
  next i
  dmca_data: db 0,0,'DMCA NINTENDO E-READER'
The 16bit reset vector at [FFFCh] contains:
  Bit0-14  Lower bits of Entrypoint (0..7FFFh = Address 8000h..FFFFh)
  Bit15    Nametable Mode (0=Vertical Mirroring, 1=Horizontal Mirroring)
reportedly,
   (NES limitations, 1 16K program rom + 1-2 8K CHR rom, mapper 0 and 1)
   ines mapper 1 would be MMC1, rather than CNROM (ines mapper 3)?
   but, there are more or less NONE games that have 16K PRG ROM + 16K VROM?
The L+R Button key-combination allows to reset the NES, however, there seems to be no way to return to the e-Reader BIOS.

Z80/8080 Format
The e-Reader doesn't support the following Z80 opcodes:
  CB [Prefix]     E0 RET PO   E2 JP PO,nn   E4 CALL PO,nn   27 DAA    76 HALT
  ED [Prefix]     E8 RET PE   EA JP PE,nn   EC CALL PE,nn   D3 OUT (n),A
  DD [IX Prefix]  F3 DI       08 EX AF,AF'  F4 CALL P,nn    DB IN A,(n)
  FD [IY Prefix]  FB EI       D9 EXX        FC CALL M,nn    xx RST 00h..38h
That is leaving not more than six supported Z80 opcodes (DJNZ, JR, JR c/nc/z/nz), everything else are 8080 opcodes. Custom opcodes are:
  76 WAIT A frames, D3 WAIT n frames, and C7/CF RST 0/8 used for API calls.
The load address and entrypoint are at 0100h in the emulated Z80 address space. The Z80 doesn't have direct access to the GBA hardware, instead video/sound/joypad are accessed via API functions, invoked via RST 0 and RST 8 opcodes, followed by an 8bit data byte, and with parameters in the Z80 CPU registers. For example, "ld a,02h, rst 8, db 00h" does return to the e-Reader BIOS.
The Z80/8080 emulation is incredibly inefficient, written in HLL code, developed by somebody whom knew nothing about emulation nor about ARM nor about Z80/8080 processors.

Running GBA-code on Japanese/Original e-Reader
Original e-Reader supports Z80 code only, but can be tweaked to run GBA-code:
  retry:
   ld bc,data // ld hl,00c8h      ;src/dst
  lop:
   ld a,[bc] // inc bc // ld e,a  ;lsb
   ld a,[bc] // inc bc // ld d,a  ;msb
   dw 0bcfh ;aka rst 8 // db 0bh  ;[4000000h+hl]=de (DMA registers)
   inc hl // inc  hl // ld a,l
   cp a,0dch // jr nz,lop
  mod1 equ $+1
   dw 37cfh ;aka rst 8 // db 37h  ;bx 3E700F0h
  ;below executed only on jap/plus... on jap/plus, above 37cfh is hl=[400010Ch]
   ld a,3Ah // ld [mod1],a                  ;bx 3E700F0h (3Ah instead 37h)
   ld hl,1 // ld [mod2],hl // ld [mod3],hl  ;base (0200010Ch instead 0201610Ch)
   jr retry
  data:
  mod2 equ $+1
   dd loader         ;40000C8h dma2sad (loader)            ;\
   dd 030000F0h      ;40000CCh dma2dad (mirrored 3E700F0h) ; relocate loader
   dd 8000000ah      ;40000D0h dma2cnt (copy 0Ah x 16bit)  ;/
  mod3 equ $+1
   dd main           ;40000D4h dma3sad (main)              ;\prepare main reloc
   dd 02000000h      ;40000D8h dma3dad (2000000h)          ;/dma3cnt see loader
   .align 2          ;alignment for 16bit-halfword
  org $+201600ch     ;jap/plus: adjusted to org $+200000ch
  loader:
   mov r0,80000000h  ;(dma3cnt, copy 10000h x 16bit)
   mov r1,04000000h  ;i/o base
   strb r1,[r1,208h] ;ime=0 (better disable ime before moving ram)
   str r0,[r1,0DCh]  ;dma3cnt (relocate to 2000000h)
   mov r15,2000000h  ;start relocated code at 2000000h in ARM state
  main:
   ;...insert/append whatever ARM code here...
   end


GBA Cart e-Reader API Functions

Z80 Interface (Special Opcodes)
  db 76h       ;Wait8bit A
  db D3h,xxh   ;Wait8bit xxh
  db C7h,xxh   ;RST0_xxh
  db CFh,xxh   ;RST8_xxh
  ld r,[00xxh]       ;get system values (addresses differ on jap/ori)
  ld r,[00C2h..C3h]  ;GetKeyStateSticky (jap/ori: 9F02h..9F03h)
  ld r,[00C4h..C5h]  ;GetKeyStateRaw    (jap/ori: 9F04h..9F05h)
  ld r,[00C0h..C1h]  ;see Exit and ExitRestart
  ld r,[00D0h..D3h]  ;see Mul16bit
For jap/ori, 9Fxxh isn't forwards compatible with jap/plus, so it'd be better to check joypad via IoRead.

GBA Interface
  bx [30075FCh] ;ApiVector ;in: r0=func_no,r1,r2,r3,[sp+0],[sp+4],[sp+8]=params
  bx lr         ;Exit      ;in: r0 (0=Restart, 2=To_Menu)

Wait8bit/Wait16bit
The various Wait opcodes and functions are waiting as many frames as specified. Many API functions have no effect until the next Wait occurs.

Z80 RST0_xxh Functions / GBA Functions 02xxh
  RST0_00h FadeIn, A speed, number of frames (0..x)
  RST0_01h FadeOut
  RST0_02h BlinkWhite
  RST0_03h  (?)
  RST0_04h  (?) blend_func_unk1
  RST0_05h  (?)
  RST0_06h  (?)
  RST0_07h  (?)
  RST0_08h  (?)
  RST0_09h  (?) _020264CC_check
  RST0_0Ah  (?) _020264CC_free
  RST0_0Bh N/A (bx 0)
  RST0_0Ch N/A (bx 0)
  RST0_0Dh N/A (bx 0)
  RST0_0Eh N/A (bx 0)
  RST0_0Fh N/A (bx 0)
  RST0_10h LoadSystemBackground, A number of background (1..101), E bg# (0..3)
  RST0_11h SetBackgroundOffset, A=bg# (0..3), DE=X, BC=Y
  RST0_12h SetBackgroundAutoScroll
  RST0_13h SetBackgroundMirrorToggle
  RST0_14h  (?)
  RST0_15h  (?)
  RST0_16h  (?) write_000000FF_to_02029494_
  RST0_17h  (?)
  RST0_18h  (?)
  RST0_19h SetBackgroundMode, A=mode (0..2)
  RST0_1Ah  (?)
  RST0_1Bh  (?)
  RST0_1Ch  (?)
  RST0_1Dh  (?)
  RST0_1Eh  (?)
  RST0_1Fh  (?)
  RST0_20h LayerShow
  RST0_21h LayerHide
  RST0_22h  (?)
  RST0_23h  (?)
  RST0_24h ... [20264DCh+A*20h+1Ah]=DE, [20264DCh+A*20h+1Ch]=BC
  RST0_25h  (?)
  RST0_26h  (?)
  RST0_27h  (?)
  RST0_28h  (?)
  RST0_29h  (?)
  RST0_2Ah  (?)
  RST0_2Bh  (?)
  RST0_2Ch  (?)
  RST0_2Dh LoadCustomBackground, A bg# (0..3), DE pointer to struct_background,
           max. tile data size = 3000h bytes, max. map data size = 1000h bytes
  RST0_2Eh GBA: N/A - Z80: (?)
  RST0_2Fh  (?)
  RST0_30h CreateSystemSprite, - -   (what "- -" ???)
  RST0_31h SpriteFree, HL sprite handle
  RST0_32h SetSpritePos, HL=sprite handle, DE=X, BC=Y
  RST0_33h  (?) sprite_unk2
  RST0_34h SpriteFrameNext
  RST0_35h SpriteFramePrev
  RST0_36h SetSpriteFrame, HL=sprite handle, E=frame number (0..x)
  RST0_37h  (?) sprite_unk3
  RST0_38h  (?) sprite_unk4
  RST0_39h SetSpriteAutoMove, HL=sprite handle, DE=X, BC=Y
  RST0_3Ah  (?) sprite_unk5
  RST0_3Bh  (?) sprite_unk6
  RST0_3Ch SpriteAutoAnimate
  RST0_3Dh  (?) sprite_unk7
  RST0_3Eh SpriteAutoRotateUntilAngle
  RST0_3Fh SpriteAutoRotateByAngle
  RST0_40h SpriteAutoRotateByTime
  RST0_41h  (?) sprite_unk8
  RST0_42h SetSpriteAutoMoveHorizontal
  RST0_43h SetSpriteAutoMoveVertical
  RST0_44h  (?) sprite_unk9
  RST0_45h SpriteDrawOnBackground
  RST0_46h SpriteShow, HL=sprite handle
  RST0_47h SpriteHide, HL=sprite handle
  RST0_48h SpriteMirrorToggle
  RST0_49h  (?) sprite_unk10
  RST0_4Ah  (?) sprite_unk11
  RST0_4Bh  (?) sprite_unk12
  RST0_4Ch GetSpritePos
  RST0_4Dh CreateCustomSprite
  RST0_4Eh  (?)
  RST0_4Fh  (?) sprite_unk14
  RST0_50h  (?) sprite_unk15
  RST0_51h  (?) sprite_unk16
  RST0_52h  (?) sprite_unk17
  RST0_53h  (?) sprite_unk18
  RST0_54h  (?)
  RST0_55h  (?) sprite_unk20
  RST0_56h  (?)
  RST0_57h SpriteMove
  RST0_58h  (?) sprite_unk22
  RST0_59h  (?) sprite_unk23
  RST0_5Ah  (?) sprite_unk24
  RST0_5Bh SpriteAutoScaleUntilSize, C=speed (higher value is slower),
           HL=sprite handle, DE=size (0100h = normal size,
           lower value = larger, higher value = smaller)
  RST0_5Ch SpriteAutoScaleBySize
  RST0_5Dh SpriteAutoScaleWidthUntilSize
  RST0_5Eh SpriteAutoScaleHeightBySize
  RST0_5Fh  (?)
  RST0_60h  (?)
  RST0_61h  (?)
  RST0_62h  (?)
  RST0_63h  (?)
  RST0_64h hl=[[2024D28h+a*4]+12h]
  RST0_65h  (?) sprite_unk25
  RST0_66h SetSpriteVisible, HL=sprite handle, E=(0=not visible, 1=visible)
  RST0_67h  (?) sprite_unk26
  RST0_68h  (?) set_sprite_unk27
  RST0_69h  (?) get_sprite_unk27
  RST0_6Ah  (?)
  RST0_6Bh  (?)
  RST0_6Ch  (?)
  RST0_6Dh  (?)
  RST0_6Eh hl=[hl+000Ah]  ;r0=[r1+0Ah]
  RST0_6Fh  (?)
  RST0_70h  (?)
  RST0_71h  (?)
  RST0_72h  (?)
  RST0_73h  (?)
  RST0_74h  (?)
  RST0_75h  (?)
  RST0_76h  (?)
  RST0_77h  (?)
  RST0_78h  (?)
  RST0_79h  (?)
  RST0_7Ah  (?)
  RST0_7Bh  (?)
  RST0_7Ch  (?) _0202FD2C_unk12
  RST0_7Dh Wait16bit ;HL=num_frames (16bit variant of Wait8bit opcode/function)
  RST0_7Eh SetBackgroundPalette, HL=src_addr, DE=offset, C=num_colors (1..x)
  RST0_7Fh GetBackgroundPalette(a,b,c)
  RST0_80h SetSpritePalette, HL=src_addr, DE=offset, C=num_colors (1..x)
  RST0_81h GetSpritePalette(a,b,c)
  RST0_82h ClearPalette
  RST0_83h  (?) _0202FD2C_unk11
  RST0_84h  (?)
  RST0_85h  (?)
  RST0_86h  (?)
  RST0_87h  (?) _0202FD2C_unk8
  RST0_88h  (?) _0202FD2C_unk7
  RST0_89h  (?)
  RST0_8Ah  (?) _0202FD2C_unk6
  RST0_8Bh  (?) _0202FD2C_unk5
  RST0_8Ch GBA: N/A - Z80: (?)
  RST0_8Dh GBA: N/A - Z80: (?)
  RST0_8Eh  (?)
  RST0_8Fh WindowHide
  RST0_90h CreateRegion, H=bg# (0..3), L=palbank# (0..15),
           D,E,B,C=x1,y1,cx,cy (in tiles), return: n/a (no$note: n/a ???)
  RST0_91h SetRegionColor
  RST0_92h ClearRegion
  RST0_93h SetPixel
  RST0_94h GetPixel
  RST0_95h DrawLine
  RST0_96h DrawRect
  RST0_97h  (?) _0202FD2C_unk4
  RST0_98h SetTextColor, A=region handle, D=color foreground (0..15),
           E=color background (0..15)
  RST0_99h DrawText, A=region handle, BC=pointer to text, D=X, E=Y
           (non-japan uses ASCII text, but japanese e-reader's use STH ELSE?)
  RST0_9Ah SetTextSize
  RST0_9Bh  (?) RegionUnk7
  RST0_9Ch  (?) _0202FD2C_unk3
  RST0_9Dh  (?) _0202FD2C_unk2
  RST0_9Eh  (?) _0202FD2C_unk1
  RST0_9Fh Z80: (?) - GBA: SetBackgroundModeRaw
  RST0_A0h  (?)
  RST0_A1h  (?)
  RST0_A2h  (?) RegionUnk6
  RST0_A3h GBA: N/A - Z80: (?)
  RST0_A4h GBA: N/A - Z80: (?)
  RST0_A5h  (?)
  RST0_A6h  (?)
  RST0_A7h  (?)
  RST0_A8h  (?)
  RST0_A9h  (?)
  RST0_AAh  (?)
  RST0_ABh  (?)
  RST0_ACh  (?)
  RST0_ADh  (?) RegionUnk5
  RST0_AEh [202FD2Ch+122h]=A
  RST0_AFh [202FD2Ch+123h]=A
  RST0_B0h [202FD2Ch+124h]=A
  RST0_B1h  (?)
  RST0_B2h  (?)
  RST0_B3h GBA: N/A - Z80: Sqrt   ;hl=sqrt(hl)
  RST0_B4h GBA: N/A - Z80: ArcTan ;hl=ArcTan2(hl,de)
  RST0_B5h Sine                   ;hl=sin(a)*de
  RST0_B6h Cosine                 ;hl=cos(a)*de
  RST0_B7h  (?)
  RST0_B8h  (?)
  RST0_B9h N/A (bx 0)
  RST0_BAh N/A (bx 0)
  RST0_BBh N/A (bx 0)
  RST0_BCh N/A (bx 0)
  RST0_BDh N/A (bx 0)
  RST0_BEh N/A (bx 0)
  RST0_BFh N/A (bx 0)
  Below Non-Japan and Japan/Plus only (not Japan/Ori)
  RST0_C0h GetTextWidth(a,b)
  RST0_C1h GetTextWidthEx(a,b,c)
  RST0_C2h  (?)
  RST0_C3h Z80: N/A (bx 0) - GBA: (?)
  RST0_C4h  (?)
  RST0_C5h  (?)
  RST0_C6h  (?)
  RST0_C7h  (?)
  RST0_C8h  (?)
  RST0_C9h  (?)
  RST0_CAh  (?)
  RST0_CBh  (?)
  RST0_CCh  (?)
  RST0_CDh N/A (bx lr)
  RST0_CEh ;same as RST0_3Bh, but with 16bit mask
  RST0_CFh ;same as RST0_3Eh, but with 16bit de
  RST0_D0h ;same as RST0_3Fh, but with 16bit de
  RST0_D1h ;same as RST0_5Bh, but with 16bit de
  RST0_D2h ;same as RST0_5Ch, but with 16bit de
  RST0_D3h ;same as RST0_5Dh, but with 16bit de
  RST0_D4h ;same as RST0_5Eh, but with 16bit de
  RST0_D5h  (?)
  RST0_D6h  (?)
  RST0_D7h ;[202FD2Ch+125h]=A
  RST0_D8h  (?)
  RST0_D9h  (?)
  RST0_DAh  (?)
  RST0_DBh ;A=[3003E51h]
  RST0_DCh ;[3004658h]=01h
  RST0_DDh DecompressVPKorNonVPK
  RST0_DEh FlashWriteSectorSingle(a,b)
  RST0_DFh FlashReadSectorSingle(a,b)
  RST0_E0h SoftReset
  RST0_E1h GetCartridgeHeader     ;[hl+0..BFh]=[8000000h..80000BFh]
  RST0_E2h GBA: N/A - Z80: bx hl  ;in: hl=addr, af,bc,de,sp=param, out: a
  RST0_E3h Z80: N/A (bx 0) - GBA: (?)
  RST0_E4h  (?)
  RST0_E5h  (?)
  RST0_E6h  (?)
  RST0_E7h  (?)
  RST0_E8h  (?)
  RST0_E9h ;[2029498h]=0000h
  RST0_EAh Z80: N/A (bx 0) - GBA: InitMemory(a)
  RST0_EBh  (?) BL_irq_sio_dma3
  RST0_ECh ;hl = [3003E30h]*100h + [3003E34h]
  RST0_EDh FlashWriteSectorMulti(a,b,c)
  RST0_EEh FlashReadPart(a,b,c)
  RST0_EFh ;A=((-([2029416h] xor 1)) OR (+([2029416h] xor 1))) SHR 31
  RST0_F0h  (?) _unk1
  RST0_F1h RandomInit     ;in: hl=random_seed
  RST0_F2h                         (?)
  Below Japan/Plus only
  RST0_F3h  (?)
  RST0_F4h  (?)
  RST0_F5h  (?)
  RST0_F6h  (?)
  RST0_F7h GBA: N/A - Z80: (?)
  Below is undefined/garbage (values as so in Z80 mode)
  Jap/Ori: RST0_C0h      N/A (bx 0)
  Jap/Ori: RST0_C1h..FFh Overlaps RST8 jump list
  Non-Jap: RST0_F3h..FFh Overlaps RST8 jump list
  Jap/Pls: RST0_F8h..FFh Overlaps RST8 jump list

Z80 RST8_xxh Functions / GBA Functions 01xxh
  RST8_00h GBA: N/A - Z80: Exit       ;[00C0h]=a ;(1=restart, 2=exit)
  RST8_01h GBA: N/A - Z80: Mul8bit    ;hl=a*e
  RST8_02h GBA: N/A - Z80: Mul16bit   ;hl=hl*de, s32[00D0h]=hl*de
  RST8_03h Div                        ;hl=hl/de
  RST8_04h DivRem                     ;hl=hl mod de
  RST8_05h PlaySystemSound            ;in: hl=sound_number
  RST8_06h  (?) sound_unk1
  RST8_07h Random8bit                 ;a=random(0..FFh)
  RST8_08h SetSoundVolume
  RST8_09h BcdTime                    ;[de+0..5]=hhmmss(hl*bc)
  RST8_0Ah BcdNumber                  ;[de+0..4]=BCD(hl), [de+5]=00h
  RST8_0Bh IoWrite                    ;[4000000h+hl]=de
  RST8_0Ch IoRead                     ;de=[4000000h+hl]
  RST8_0Dh GBA: N/A - Z80:  (?)
  RST8_0Eh GBA: N/A - Z80:  (?)
  RST8_0Fh GBA: N/A - Z80:  (?)
  RST8_10h GBA: N/A - Z80:  (?)
  RST8_11h DivSigned                  ;hl=hl/de, signed
  RST8_12h RandomMax                  ;a=random(0..a-1)
  RST8_13h SetSoundSpeed
  RST8_14h  hl=[202FD20h]=[2024CACh]
  RST8_15h  hl=[2024CACh]-[202FD20h]
  RST8_16h SoundPause
  RST8_17h SoundResume
  RST8_18h PlaySystemSoundEx
  RST8_19h IsSoundPlaying
  RST8_1Ah  (?)
  RST8_1Bh  (?)
  RST8_1Ch  (?)
  RST8_1Dh GetExitCount               ;a=[2032D34h]
  RST8_1Eh Permille                   ;hl=de*1000/hl
  RST8_1Fh GBA: N/A - Z80: ExitRestart;[2032D38h]=a, [00C0h]=0001h  ;a=?
  RST8_20h GBA: N/A - Z80: WaitJoypad ;wait until joypad<>0, set hl=joypad
  RST8_21h GBA: N/A - Z80:  (?)
  RST8_22h  (?) _sound_unk7
  RST8_23h  (?) _sound_unk8
  RST8_24h  (?) _sound_unk9
  RST8_25h  (?) _sound_unk10
  RST8_26h Mosaic     ;bg<n>cnt.bit6=a.bit<n>, [400004Ch]=de
  RST8_27h  (?)
  RST8_28h  (?)
  RST8_29h  (?)
  RST8_2Ah  (?) get_8bit_from_2030110h
  RST8_2Bh  (?)
  RST8_2Ch  (?) get_16bit_from_2030112h ;jap/ori: hl=[20077B2h]
  RST8_2Dh  (?) get_16bit_from_2030114h ;jap/ori: hl=[20077B4h]
  RST8_2Eh  (?)
  RST8_2Fh PlayCustomSound(a,b)
  Below not for Japanese/Original
  (the renumbered functions can be theoretically used on japanese/original)
  (but, doing so would blow forwards compatibility with japanese/plus)
  RST8_30h (ori: none)      GBA: N/A - Z80: (?)
  RST8_31h (ori: none)      PlayCustomSoundEx(a,b,c)
  RST8_32h (ori: RST8_30h)  BrightnessHalf   ;[4000050h]=00FFh,[4000054h]=0008h
  RST8_33h (ori: RST8_31h)  BrightnessNormal ;[4000050h]=0000h
  RST8_34h (ori: RST8_32h)  N/A (bx lr)
  RST8_35h (ori: RST8_33h)   (?)
  RST8_36h (ori: RST8_34h)  ResetTimer ;[400010Ch]=00000000h, [400010Eh]=A+80h
  RST8_37h (ori: RST8_35h)  GetTimer   ;hl=[400010Ch]
  RST8_38h (ori: none)      GBA: N/A - Z80:  (?)
  Below is undefined/reserved/garbage (values as so in Z80 mode)
  (can be used to tweak jap/ori to start GBA-code from inside of Z80-code)
  (that, after relocating code to 3000xxxh via DMA via IoWrite function)
  RST8_39h (ori: RST8_36h)  bx 0140014h
  RST8_3Ah (ori: RST8_37h)  bx 3E700F0h
  RST8_3Bh (ori: RST8_38h)  bx 3E70000h+1
  RST8_3Ch (ori: RST8_39h)  bx 3E703E6h+1
  RST8_3Dh (ori: RST8_3Ah)  bx 3E703E6h+1
  RST8_3Eh (ori: RST8_3Bh)  bx 3E703E6h+1
  RST8_3Fh (ori: RST8_3Ch)  bx 3E703E6h+1
  40h-FFh  (ori: 3Dh-FFh)   bx ...

GBA Functions 03xxh (none such in Z80 mode)
  RSTX_00h Wait8bit  ;for 16bit: RST0_7Dh
  RSTX_01h GetKeyStateSticky()
  RSTX_02h GetKeyStateRaw()
  RSTX_03h  (?)
  RSTX_04h  (?)


GBA Cart e-Reader VPK Decompression

vpk_decompress(src,dest)
  collected32bit=80000000h  ;initially empty (endflag in bit31)
  for i=0 to 3, id[i]=read_bits(8), next i, if id[0..3]<>'vpk0' then error
  dest_end=dest+read_bits(32)     ;size of decompressed data (of all strips)
  method=read_bits(8), if method>1 then error
  tree_index=0, load_huffman_tree, disproot=tree_index
  tree_index=tree_index+1, load_huffman_tree, lenroot=tree_index
  ;above stuff is contained only in the first strip. below loop starts at
  ;current location in first strip, and does then continue in further strips.
 decompress_loop:
  if read_bits(1)=0 then                   ;copy one uncompressed data byte,
    [dest]=read_bits(8), dest=dest+1       ;does work without huffman trees
  else
    if disproot=-1 or lenroot=-1 then error  ;compression does require trees
    disp=read_tree(disproot)
    if method=1   ;disp*4 is good for 32bit ARM opcodes
      if disp>2 then disp=disp*4-8 else disp=disp+4*read_tree(disproot)-7
    len=read_tree(lenroot)
    if len=0 or disp<=0 or dest+len-1>dest_end then error ;whoops
    for j=1 to len, [dest]=[dest-disp], dest=dest+1, next j
  if dest<dest_end then decompress_loop
  ret

read_bits(num)
  mov  data=0
  for i=1 to num
    shl collected32bit,1   ;move next bit to carry, or set zeroflag if empty
    if zeroflag
      collected32bit=[src+0]*1000000h+[src+1]*10000h+[src+2]*100h+[src+3]
      src=src+4            ;read data in 32bit units, in reversed byte-order
      carryflag=1          ;endbit
      rcl collected32bit,1 ;move bit31 to carry (and endbit to bit0)
    rcl data,1             ;move carry to data
  next i
  ret(data)

read_tree(root_index)
  i=root_index
  while node[i].right<>-1  ;loop until reaching data node
    if read_bits(1)=1 then i=node[i].right else i=node[i].left
  i=node[i].left           ;get number of bits
  i=read_bits(i)           ;read that number of bits
  ret(i)                   ;return that value

load_huffman_tree
  stacktop=sp
  if read_bits(1)=1 then tree_index=-1, ret  ;exit (empty)
  node[tree_index].right=-1                  ;indicate data node
  node[tree_index].left=read_bits(8)         ;store data value
  if read_bits(1)=1 then ret                 ;exit (only 1 data node at root)
  push tree_index                     ;save previous (child) node
  tree_index=tree_index+1
  jmp data_injump
 load_loop:
  push tree_index                     ;save previous (child) node
  tree_index=tree_index+1
  if read_bits(1)=1 then parent_node
 data_injump:
  node[tree_index].right=-1           ;indicate data node
  node[tree_index].left=read_bits(8)  ;store data value
  jmp load_loop
 parent_node:
  pop node[tree_index].right          ;store 1st child
  pop node[tree_index].left           ;store 2nd child
  if sp<>stacktop then jmp load_loop
  if read_bits(1)=0 then error        ;end bit (must be 1)
  ret
The best values for the huffman trees that I've found are 6,9,12-bit displacements for method 0 (best for NES/Z80 code), and two less for method 1, ie. 4,7,10-bit (best for GBA code). And 2,4,10-bit for the length values. The smallest value in node 0, and the other values in node 10 and 11.

Notes
The decompression works similar to the GBA BIOS'es LZ77 decompression function, but without using fixed bit-widths of length=4bit and displacement=12bit, instead, the bit-widths are read from huffman trees (which can also define fixed bit-widths; if data is located directly in the root node).
Unlike the GBA BIOS'es Huffman decompression function, the trees are starting with data entries, end are ending with the root entry. The above load function deciphers the data, and returns the root index.
With the variable bit-widths, the VPK compression rate is quite good, only, it's a pity that the length/disp values are zero-based, eg. for 2bit and 4bit lengths, it'd be much better to assign 2bit as 2..5, and 4bit as 6..21.

Non-VPK
The e-Reader additionally supports an alternate decompression function, indicated by the absence of the "vpk0" ID, which supports compression of increasing byte-values, which isn't useful for program code.
Bit15 of the VPK Size value seems to disable (de-)compression, the VPK Data field is then containing plain uncompressed data.


GBA Cart e-Reader Error Correction

The Error Correction Information that is appended at the end of the Block Header & Data Fragments consists of standard Reed-Solomon codes, which are also used for CD/DVD disks, DSL modems, and digital DVB television signals. That info allows to locate and repair a number of invalid data bytes.

Below code shows how to create and verify error-info (but not how to do the actual error correction). The dtalen,errlen values should be 18h,10h for the Block Header, and 40h,10h for Data Fragments; the latter settings might be possible to get changed to other values though?

append_error_info(data,dtalen,errlen)
  reverse_byte_order(data,dtalen)
  zerofill_error_bytes(data,errlen)
  for i=dtalen-1 to errlen  ;loop across data portion
    z = rev[ data[i] xor data[errlen-1] ] ;
    for j=errlen-1 to 0     ;loop across error-info portion
    if j=0 then x=00h else x=data[j-1]
      if z<>FFh then
        y=gg[j], if y<>FFh then
          y=y+z, if y>=FFh then y=y-FFh
          x=x xor pow[y]
      data[j]=x
    next j
  next i
  invert_error_bytes(data,errlen)
  reverse_byte_order(data,dtalen)

verify_error_info(data,dtalen,errlen)
  reverse_byte_order(data,dtalen)
  invert_error_bytes(data,errlen)
  make_rev(data,dtalen)
  for i=78h to 78h+errlen-1
    x=0, z=0
    for j=0 to dtalen-1
      y=data[j]
      if y<>FFh then
        y=y+z, if y>=FFh then y=y-FFh
        x=x xor pow[y]
      z=z+i, if z>=FFh then z=z-FFh
    next j
    if x<>0 then error
  next i
  ;(if errors occured, could correct them now)
  make_pow(data,dtalen)
  invert_error_bytes(data,errlen)
  reverse_byte_order(data,dtalen)

make_rev(data,len)
  for i=0 to len-1, data[i]=rev[data[i]], next i

make_pow(data,len)
  for i=0 to len-1, data[i]=pow[data[i]], next i

invert_error_bytes(data,len)
  for i=0 to len-1, data[i]=data[i] xor FFh, next i

zerofill_error_bytes(data,len)
  for i=0 to len-1, data[i]=00h, next i

reverse_byte_order(data,len)
  for i=0 to (len-1)/2, x=data[i], data[i]=data[len-i], data[len-i]=x, next i

create_pow_and_rev_tables
  x=01h, pow[FFh]=00h, rev[00h]=FFh
  for i=00h to FEh
    pow[i]=x, rev[x]=i, x=x*2, if x>=100h then x=x xor 187h
  next i

create_gg_table
  gg[0]=pow[78h]
  for i=1 to errlen-1
    gg[i]=01h
    for j=i downto 0
      if j=0 then y=00h else y=gg[j-1]
      x=gg[j], if x<>00h then
        x=rev[x]+78h+i, if x>=FFh then x=x-FFh
        y=y xor pow[x]
      gg[j]=y
    next j
  next i
  make_rev(gg,errlen)
With above value of 78h, and errlen=10h, gg[00h..0Fh] will be always:
  00h,4Bh,EBh,D5h,EFh,4Ch,71h,00h,F4h,00h,71h,4Ch,EFh,D5h,EBh,4Bh
So using a hardcoded table should take up less memory than calculating it.

Notes
The actual error correction should be able to fix up to "errlen" errors at known locations (eg. data from blocks that haven't been scanned, or whose 5bit-to-4bit conversion had failed due to an invalid 5bit value), or up to "errlen/2" errors at unknown locations. The corrected data isn't guaranteed to be correct (even if it looks okay to the "verify" function), so the Data Header checksums should be checked, too.

More Info
For more info, I've found Reed-Solomon source code from Simon Rockliff, and an updated version from Robert Morelos-Zaragoza and Hari Thirumoorthy to be useful. For getting started with that source, some important relationships & differences are:
  pow = alpha_to, but generated as shown above
  rev = index_of, dito
  b0  = 78h
  nn  = dtalen
  kk  = dtalen-errlen
  %nn = MOD FFh (for the ereader that isn't MOD dtalen)
  -1  = FFh
And, the ereader processes data/errinfo backwards, starting at the last byte.


GBA Cart e-Reader File Formats

.BMP Files (homebrew 300 DPI strips)
Contains a picture of the whole dotcode strip with address bars and sync marks (see Dotcode chapter) in Microsoft's Bitmap format. The image is conventionally surrounded by a blank 2-pixel border, resulting in a size of 989x44 pixels for long strips. The file should should have 1bit color depth. The pixels per meter entry should match the desired printing resolution, either 300 DPI or 360 DPI. But, resolution of printer hardware is typically specified in inch rather than in meters, so an exact match isn't supported by Microsoft. Most homebrew .BMP files contain nonsense resolutions like 200 DPI, or 300 dots per meter (ca. 8 DPI).

.JPG Files (scanned 1200 DPI strips)
Same as BMP, but should contain a dotcode scanned at 1200 DPI, with correct orientation (the card-edge side at the bottom of the image), and containing only the dotcode (not the whole card), so the JPG size should be about 3450x155 pixels for long strips.
No$gba currently doesn't work with progressive JPGs. Scans with white background can be saved as monochrome JPG. Scans with red/yellow background should contain a correct RED layer (due to the red LED light source) (the brightness of the green/blue layers can be set to zero for better compression).

.RAW Files
Contains the "raw" information from the BMP format, that is, 2-byte block header, 102-byte data, 2-byte block header, 102-byte data, etc. The data portion is interleaved, and includes the full 48-byte data header, titles, vpk compressed data, error-info, and unused bytes. RAW files are excluding Address Bars, Sync Marks, and 4bit-to-5bit encoding.
Each RAW file contains one or more strip(s), so the RAW filesize is either 18*104 bytes (short strip), or 28*104 bytes (long strip), or a multiple thereof (if it contains more than one strip) (although multi-strip games are often stored in separate files for each strip; named file1.raw, file2.raw, etc).

.BIN Files
Filesize should be I*30h, with I=1Ch for short strips, and I=2Ch for long strips, or a multiple thereof (if it contains more than one strip). Each strip consists of the 48-byte Data Header, followed by title(s), and vpk compressed data. Unlike .RAW files, .BIN files aren't interleaved, and do not contain Block Headers, nor error-info, nor unused bytes (in last block). The files do contain padding bytes to match a full strip-size of I*30h.
Caution: Older .BIN files have been using a size-reduced 12-byte header (taken from entries 0Dh, 0Ch, 10h-11h, 26h-2Dh of the 48-byte Data Header; in that order), that files have never contained more than one strip per file, so the filesize should be exactly I*30h-36, the size-reduced header doesn't contain a Primary Type entry, so it's everyone's bet which Card Type is to be used (hint: the 12-byte headers were based on the assumption that Primary Type would be always 01h on Short Strips, and 02h on Long Strips).

.SAV Files
Contains a copy of the e-Reader's 128Kbyte FLASH memory. With the saved e-Reader application being located in the 2nd 64K-bank, the data consists of a header with title and gba/nes/z80 format info, followed by the vpk compressed data. The FLASH memory does also contain e-Reader calibration settings, the remaining 100Kbytes are typically FFh-filled.


GBA Cart Unknown Devices

GBA Infra-Red Port (AGB-006)
No info?


GBA Cart Protections

Classic NES Series
These are some NES/Famicom games ported or emulated to work on GBA. The games are doing some uncommon stuff that can cause compatibility problems when not using original GBA consoles or cartridges.
- CPU pipeline (selfmodifying code that shall NOT affect prefetched opcodes)
- STMDA write to I/O ports (writes in INCREASING order, not DECREASING order)
- SRAM detection (refuses to run if SRAM exists; the games do contain EEPROM)
- ROM mirrors (instead of the usual increasing numbers in unused ROM area)
- RAM mirrors (eg. main RAM accessed at 2F00000h instead of 2000000h)
Note: These games can be detected by checking [80000ACh]="F" (ie. game code="Fxxx").


GBA Flashcards

Flashcards are re-writable cartridges using FLASH memory, allowing to test even multiboot-incompatible GBA software on real hardware, providing a good development environment when used in combination with a reasonable software debugger.

The carts can be written to from external tools, or directly from GBA programs.
Below are pseudo code flowcharts for detect, erase, and write operations.
All flash reads/writes are meant to be 16bit (ldrh/strh) memory accesses.

detect_flashcard:
 configure_flashcard(9E2468Ah,9413h)    ;unlock flash advance cards
 turbo=1, send_command(8000000h,90h)    ;enter ID mode (both chips, if any)
 maker=[8000000h], device=[8000000h+2]
 IF maker=device THEN device=[8000000h+4] ELSE turbo=0
 flashcard_read_mode                    ;exit ID mode
 search (maker+device*10000h) in device_list
 total/erase/write_block_size = list_entry SHL turbo

flashcard_erase(dest,len):
 FOR x=1 to len/erase_block_size
  send_command(dest,20h)        ;erase sector command
  send_command(dest,D0h)        ;confirm erase sector
  dest=dest+erase_block_size
 IF wait_busy=okay THEN NEXT x
 enter_read_mode                ;exit erase/status mode

flashcard_write(src,dest,len):
 siz=write_block_size
 FOR x=1 to len/siz
  IF siz=2 THEN send_command(dest,10h)  ;write halfword command
  IF siz>2 THEN send_command(dest,E8h)  ;write to buffer command
  IF siz>2 THEN send_command(dest,16-1) ;buffer size 16 halfwords (per chip)
  FOR y=1 TO siz/2
   [dest]=[src], dest=dest+2, src=src+2 ;write data to buffer
  NEXT y
  IF siz>2 THEN send_command(dest,D0h)  ;confirm write to buffer
 IF wait_busy=okay THEN NEXT x
 enter_read_mode                        ;exit write/status mode

send_command(adr,val):
 [adr]=val
 IF turbo THEN [adr+2]=val

enter_read_mode:
 send_command(8000000h,FFh)     ;exit status mode
 send_command(8000000h,FFh)     ;again maybe more stable (as in jeff's source)

flashcard_wait_busy:
 start=time
 REPEAT
  stat=[8000000h] XOR 80h
  IF turbo THEN stat=stat OR ([8000000h+2] XOR 80h)
  IF (stat AND 7Fh)>0 THEN error
  IF (stat AND 80h)=0 THEN ready
  IF time-start>5secs THEN timeout
 UNTIL ready OR error OR timeout
 IF error OR timeout THEN send_command(8000000h,50h)    ;clear status

configure_flashcard(adr,val): ;required for Flash Advance cards only
 [930ECA8h]=5354h
 [802468Ah]=1234h, repeated 500 times
 [800ECA8h]=5354h
 [802468Ah]=5354h
 [802468Ah]=5678h, repeated 500 times
 [930ECA8h]=5354h
 [802468Ah]=5354h
 [8ECA800h]=5678h
 [80268A0h]=1234h
 [802468Ah]=ABCDh, repeated 500 times
 [930ECA8h]=5354h
 [adr]=val

init_backup: ;no info how to use that exactly
 configure_flashcard(942468Ah,???)

device_list: (id code, total/erase/write sizes in bytes)
  ID Code    Total   Erase  Write  Name
  -??-00DCh      ?       ?      ?  Hudson Cart (???)
  00160089h     4M    128K     32  Intel i28F320J3A (Flash Advance)
  00170089h     8M    128K     32  Intel i28F640J3A (Flash Advance)
  00180089h    16M    128K     32  Intel i28F128J3A (Flash Advance)
  00E200B0h      ?     64K      2  Sharp LH28F320BJE ? (Nintendo)

Notes
All flashcards should work at 4,2 waitstates (power on default), most commercial games change waits to 3,1 which may work unstable with some/older FA flashcards. Intel FLASH specified to have a lifetime of 100,000 erases, and average block erase time 1 second (up to 5 second in worst cases).
Aside from the main FLASH memory, Flash Advance (FA) (aka Visoly) cards additionally contain battery buffered SRAM backup, and FLASH backup, and in some cases also EEPROM backup.
Turbo FA cards are containing two chips interlaced (at odd/even halfword addresses), allowing to write/erase both chips simultaneously, resulting in twice as fast programming time.
Standard Nintendo flash carts have to be modified before you can actually write to them. This is done by removing resistor R7 and putting it at empty location R8.
Mind that write/erase/detect modes output status information in ROM area, so that in that modes all GBA program code (and any interrupt handlers) must be executed in WRAM, not in ROM.

Thanks to Jeff Frohwein for his FAQ and CARTLIB sample in FLGBA at devrs.com


GBA Cheat Devices

Codebreaker (US) aka Xploder (EUR).
Gameshark (US) aka Action Replay (EUR).

GBA Cheat Codes - General Info
GBA Cheat Codes - Codebreaker/Xploder
GBA Cheat Codes - Gameshark/Action Replay V1/V2
GBA Cheat Codes - Pro Action Replay V3


GBA Cheat Codes - General Info

Cheat devices are external adapters, connected between the GBA and the game cartridge. The devices include a BIOS ROM which is, among others, used to prompt the user to enter cheat codes.
These codes are used to patch specified memory locations for a certain GBA game, allowing the user to gain goodies such like Infinite sex, 255 Cigarettes, etc.

ROM and RAM Patches
For ROM Patches, the device watches the address bus, if it matches a specified address then it outputs a patched value to the data bus, that mechanism is implemented by hardware, aside from the Hook Enable Code some devices also allow a limited number of cheats to use ROM patches.
Most cheat codes are RAM patches, each time when the hook procedure is executed it will process all codes and overwrite the specified addresses in RAM (or VRAM or I/O area) by the desired values.

Enable Codes (Must Be On)
Enable codes usually consist of the Game ID, Hook Address, and eventually a third code used to encrypt all following codes. The Game ID is used to confirm that the correct cartridge is inserted, just a verification, though the device may insist on the ID code.
The Hook Address specifies an address in cartridge ROM, and should point to an opcode which is executed several times per second (eg. once per frame, many codes place the hook in the joypad handler). At the hook address, the device redirects to its own BIOS, processes the RAM patches, and does then return control to the game cartridge.
Note: The hook address should not point to opcodes with relative addressing (eg. B, BL, LDR Rd,=Imm, ADD Rd,=Imm opcodes - which are all relative to PC program counter register).

Alignment
Addresses for 16bit or 32bit values should be properly aligned.


GBA Cheat Codes - Codebreaker/Xploder

Codebreaker Codes
  0000xxxx 000y  Enable Code 1 - Game ID
  1aaaaaaa 000z  Enable Code 2 - Hook Address
  2aaaaaaa yyyy  [aaaaaaa]=[aaaaaaa] OR yyyy
  3aaaaaaa 00yy  [aaaaaaa]=yy
  4aaaaaaa yyyy  [aaaaaaa+0..(cccc-1)*ssss]=yyyy+0..(cccc-1)*ssss
  iiiicccc ssss  parameters for above code
  5aaaaaaa cccc  [aaaaaaa+0..(cccc-1)]=11,22,33,44,etc.
  11223344 5566  parameter bytes 1..6 for above code (example)
  77880000 0000  parameter bytes 7..8 for above code (padded with zero)
  6aaaaaaa yyyy  [aaaaaaa]=[aaaaaaa] AND yyyy
  7aaaaaaa yyyy  IF [aaaaaaa]=yyyy THEN (next code)
  8aaaaaaa yyyy  [aaaaaaa]=yyyy
  9xyyxxxx xxxx  Enable Code 0 - Encrypt all following codes (optional)
  Aaaaaaaa yyyy  IF [aaaaaaa]<>yyyy THEN (next code)
  Baaaaaaa yyyy  IF [aaaaaaa]>yyyy THEN (next code) (signed comparison)
  Caaaaaaa yyyy  IF [aaaaaaa]<yyyy THEN (next code) (signed comparison)
  D0000020 yyyy  IF [joypad] AND yyyy = 0 THEN (next code)
  Eaaaaaaa yyyy  [aaaaaaa]=[aaaaaaa]+yyyy
  Faaaaaaa yyyy  IF [aaaaaaa] AND yyyy THEN (next code)

Codebreaker Enable Codes
Hook Address 'aaaaaaa' is a 25bit offset in ROM-image (0-1FFFFFFh).
Flag byte 'y' (usually 0Ah), Bit1=Disable IRQs, Bit3=CRC Exists.
Code Handler Store Address 'z' (0-7, usually 7) (8000100h+z*400000h).
Checksum 'xxxx' for first 64Kbytes of cartridge (no$gba pads by FFh if ROM is smaller than 64K). Calculated, by using unsigned 16bit values, as such:
  crc=FFFFh
  for i=0 to FFFFh
   x=byte[i] xor (crc/100h)
   x=x xor (x/10h)
   crc=(crc*100h) xor (x*1001h) xor (x*20h)
  next i

Codebreaker Encryption
codebreaker_change_encryption:
Encryption can be (optionally) activated by code "9xyyxxxx xxxx",
  for i=0 to 2Fh, swaplist[i]=i, next i
  randomizer = 1111h xor byte[code+4]                              ;LSB value
  for i=0 to 4Fh
    exchange swaplist[random MOD 30h] with swaplist[random MOD 30h]
  next i
  halfword[seedlist+0] = halfword[code+0]                          ;LSW address
  randomizer = 4EFAD1C3h
  for i=0 to byte[code+3]-91h, randomizer=random, next i           ;MSB address
  word[seedlist+2]=random, halfword[seedlist+6]=random
  randomizer = F254h xor byte[code+5]                              ;MSB value
  for i=0 to byte[code+5]-01h, randomizer=random, next i           ;MSB value
  word[seedlist+8]=random, halfword[seedlist+12]=random
  ;note: byte[code+2] = don't care
  ret
The above random function works like so:
  randomizer=randomizer*41C64E6Dh+3039h, x=(randomizer SHL 14 AND C0000000h)
  randomizer=randomizer*41C64E6Dh+3039h, x=(randomizer SHR 1  AND 3FFF8000h)+x
  randomizer=randomizer*41C64E6Dh+3039h, x=(randomizer SHR 16 AND 00007FFFh)+x
  return(x)
Once when encryption is activated, all following codes are decrypted like so:
  for i=2Fh to 0
    j=swaplist[i]
    bitno1=(i AND 7), index1=xlatlist[i/8]
    bitno2=(j AND 7), index2=xlatlist[j/8]
    exchange [code+index1].bitno1 with [code+index2].bitno2
  next i
  word[code+0] = word[code+0] xor word[seedlist+8]
  i = (byte[code+3]*1010000h + byte[code+0]*100h + byte[code+5])
  i = (halfword[code+1]*10001h) xor (word[seedlist+2]) xor i
  i = (byte[seedlist+0]*1010101h) xor (byte[seedlist+1]*1000000h) xor i
  j = (byte[code+5] + (byte[code+0] xor byte[code+4])*100h)
  j = (byte[seedlist+0]*101h) xor halfword[seedlist+6] xor j
  word[code+0] = i, halfword[code+4] = j
The above xlatlist is fixed: xlatlist[0..5] = 3,2,1,0,5,4


GBA Cheat Codes - Gameshark/Action Replay V1/V2

Gameshark RAW Codes (These codes must be encrypted before using them)
  0aaaaaaa 000000xx  [aaaaaaa]=xx
  1aaaaaaa 0000xxxx  [aaaaaaa]=xxxx
  2aaaaaaa xxxxxxxx  [aaaaaaa]=xxxxxxxx
  3000cccc xxxxxxxx  write xxxxxxxx to (cccc-1) addresses (list in next codes)
  aaaaaaaa aaaaaaaa  parameter for above code, containing two addresses each
  aaaaaaaa 00000000  last parameter for above, zero-padded if only one address
  60aaaaaa y000xxxx  [8000000h+aaaaaa*2]=xxxx (ROM Patch)
  8a1aaaaa 000000xx  IF GS_Button_Down THEN [a0aaaaa]=xx
  8a2aaaaa 0000xxxx  IF GS_Button_Down THEN [a0aaaaa]=xxxx
  80F00000 0000xxxx  IF GS_Button_Down THEN slowdown xxxx * ? cycles per hook
  Daaaaaaa 0000xxxx  IF [aaaaaaa]=xxxx THEN (next code)
  E0zzxxxx 0aaaaaaa  IF [aaaaaaa]=xxxx THEN (next 'zz' codes)
  Faaaaaaa 00000x0y  Enable Code - Hook Routine
  xxxxxxxx 001DC0DE  Enable Code - Game Code ID (value at [0ACh] in cartridge)
  DEADFACE 0000xxyy  Change Encryption Seeds

Enable Code - Hook Routine
Hook Address 'aaaaaaa' is a 28bit ROM address (8FFFFFFh-9FFFFFFh).
Used to insert the GS code handler routine where it will be executed at
least 20 times per second. Without this code, GSA can not write to RAM.
 y=1 - Executes code handler without backing up the LR register.
 y=2 - Executes code handler and backs up the LR register.
 y=3 - Replaces a 32-bit pointer used for long-branches.
 x=0 - Must turn GSA off before loading game.
 x=1 - Must not do that.

ROM Patch
This type allows GSA to intercept ROM reads and returns the value xxxx.
 y=0 wait for the code handler to enable the patch
 y=1 patch is enabled before the game starts
 y=2 unknown ?
Note: V1/V2 hardware can only have up to 1 user-defined rom patch max. V3 can have up to 4. Some enable code types can shorten the amount of user-defined rom patches available.

Gameshark Encryption
A=Left half, and V=Right half of code.
  FOR I=1 TO 32
    A=A + (V*16+S0) XOR (V+I*9E3779B9h) XOR (V/32+S1)
    V=V + (A*16+S2) XOR (A+I*9E3779B9h) XOR (A/32+S3)
  NEXT I
Upon startup, the initial encryption seeds are:
  S0=09F4FBBDh S1=9681884Ah S2=352027E9h S3=F3DEE5A7h
Upon DEADFACE 0000xxyy, the S0..S3 seeds are changed like so:
  FOR y=0 TO 3
   FOR x=0 TO 3
    z = T1[(xx+x) AND FFh] + T2[(yy+y) AND FFh]
    Sy = Sy*100h + (z AND FFh)
   NEXT x
  NEXT y
All calculations truncated to unsigned 32bit integer values.
T1 and T2 are translation tables contained in the gameshark cartridge.


GBA Cheat Codes - Pro Action Replay V3

Pro Action Replay V3 - RAW Codes
  C4aaaaaa 0000yyyy  Enable Code - Hook Routine at [8aaaaaa]
  xxxxxxxx 001DC0DE  Enable Code - ID Code [080000AC]
  DEADFACE 0000xxxx  Enable Code - Change Encryption Seeds
  00aaaaaa xxxxxxyy  [a0aaaaa..a0aaaaa+xxxxxx]=yy
  02aaaaaa xxxxyyyy  [a0aaaaa..a0aaaaa+xxxx*2]=yyyy
  04aaaaaa yyyyyyyy  [a0aaaaa]=yyyyyyyy
  40aaaaaa xxxxxxyy  [ [a0aaaaa] + xxxxxx ]=yy   (Indirect)
  42aaaaaa xxxxyyyy  [ [a0aaaaa] + xxxx*2 ]=yyyy (Indirect)
  44aaaaaa yyyyyyyy  [ [a0aaaaa] ]=yyyyyyyy      (Indirect)
  80aaaaaa 000000yy  [a0aaaaa]=[a0aaaaa]+yy
  82aaaaaa 0000yyyy  [a0aaaaa]=[a0aaaaa]+yyyy
  84aaaaaa yyyyyyyy  [a0aaaaa]=[a0aaaaa]+yyyyyyyy
  C6aaaaaa 0000yyyy  [4aaaaaa]=yyyy              (I/O Area)
  C7aaaaaa yyyyyyyy  [4aaaaaa]=yyyyyyyy          (I/O Area)
  iiaaaaaa yyyyyyyy  IF [a0aaaaa] <cond> <value> THEN <action>
  00000000 60000000  ELSE (?)
  00000000 40000000  ENDIF (?)
  00000000 0800xx00  AR Slowdown : loops the AR xx times
  00000000 00000000  End of the code list
  00000000 10aaaaaa 000000zz 00000000  IF AR_BUTTON THEN [a0aaaaa]=zz
  00000000 12aaaaaa 0000zzzz 00000000  IF AR_BUTTON THEN [a0aaaaa]=zzzz
  00000000 14aaaaaa zzzzzzzz 00000000  IF AR_BUTTON THEN [a0aaaaa]=zzzzzzzz
  00000000 18aaaaaa 0000zzzz 00000000  [8000000+aaaaaa*2]=zzzz  (ROM Patch 1)
  00000000 1Aaaaaaa 0000zzzz 00000000  [8000000+aaaaaa*2]=zzzz  (ROM Patch 2)
  00000000 1Caaaaaa 0000zzzz 00000000  [8000000+aaaaaa*2]=zzzz  (ROM Patch 3)
  00000000 1Eaaaaaa 0000zzzz 00000000  [8000000+aaaaaa*2]=zzzz  (ROM Patch 4)

  00000000 80aaaaaa 000000yy ssccssss  repeat cc times [a0aaaaa]=yy
   (with yy=yy+ss, a0aaaaa=a0aaaaa+ssss after each step)

  00000000 82aaaaaa 0000yyyy ssccssss  repeat cc times [a0aaaaa]=yyyy
   (with yyyy=yyyy+ss, a0aaaaa=a0aaaaa+ssss*2 after each step)

  00000000 84aaaaaa yyyyyyyy ssccssss  repeat cc times [a0aaaaa]=yyyyyyyy
   (with yyyy=yyyy+ss, a0aaaaa=a0aaaaa+ssss*4 after each step)

Warning: There is a bug on the real AR (v2 upgraded to v3, and maybe on real v3) with the 32bit Increment Slide code. You HAVE to add a code (best choice is 80000000 00000000 : add 0 to value at address 0) right after it, else the AR will erase the 2 last 8 digits lines of the 32 Bits Inc. Slide code when you enter it !!!

Final Notes
The 'turn off all codes' makes an infinite loop (that can't be broken, unless the condition becomes True). - How? By Interrupt? Huh?
ROM Patch1 works on real V3 and, on V1/V2 upgraded to V3.
ROM Patch2,3,4 work on real V3 hardware only.

Pro Action Replay V3 Conditional Codes - iiaaaaaa yyyyyyyy
The 'ii' is composed of <cond> + <value> + <action>.
  <cond>           <value>            <action>
  08 Equal =       00 8bit zz         00 execute next code
  10 Not equal <>  02 16bit zzzz      40 execute next two codes
  18 Signed <      04 32bit zzzzzzzz  80 execute all following
  20 Signed >      06 (always false)     codes until ELSE or ENDIF
  28 Unsigned <                       C0 normal ELSE turn off all codes
  30 Unsigned >
  38 Logical AND
For example, ii=18h+02h+40h=5Ah, produces IF [a0aaaaa]<zzzz THEN next 2 codes.

Always... Codes
  For the "Always..." codes:
  - XXXXXXXX can be any authorised address except 00000000 (eg. use 02000000).
  - ZZZZZZZZ can be anything.
  - The "y" in the code data must be in the [1-7] range (which means not 0).
  typ=y,sub=0,siz=3   Always skip next line.
  typ=y,sub=1,siz=3   Always skip next 2 lines.
  typ=y,sub=2,siz=3   Always Stops executing all the codes below.
  typ=y,sub=3,siz=3   Always turn off all codes.

Code Format (ttaaaaaa xxxxyyzz)
 adr mask = 003FFFFF
 n/a mask = 00C00000 ;not used
 xtr mask = 01000000 ;used only by I/O write, and MSB of Hook
 siz mask = 06000000
 typ mask = 38000000 ;0=normal, other=conditional
 sub mask = C0000000

Pro Action Replay V3 Encryption
Works exactly as for Gameshark Encryption, but with different initial seeds,
  S0=7AA9648Fh S1=7FAE6994h S2=C0EFAAD5h S3=42712C57h
And, the T1 and T2 translation tables are different, too.


GBA Gameboy Player

The Gameboy Player is an "adapter" for the Gamecube console. It's basicly is a GBA in a black box without LCD screen and without buttons, connected to an expansion port at the bottom of the Gamecube. The Gamecube is then capturing the GBA video output (and passing it to the television set), and in the other direction, passing the Gamecube joypad input to the GBA inputs.

Unlocking and Detecting Gameboy Player Functions
Both unlocking and detection requires to display the 240x160 pixel Gameboy Player logo (44 colors) for a number of frames... maybe at least 3-4 frames? not sure if it checks the color of the logo... so maybe it can be hidden by using dark gray on black background?
While displaying this logo, the joypad data will switch between values 03FFh (2 frames duration) and 030Fh (1 frame duration). The latter value (left, right, up, down all pressed) indicates that it's a Gameboy Player.

Palette
Knowing Nintendo, they've probably not reproduced the blurred GBA colors (?), so the games won't look as desired on the TV screen. Unless the game does detect the Gameboy Player, and adjust the colors accordingly by software.

Rumble
The only known existing special function is the joypad rumble function, controlled by sending data through the serial port (the normal GBA port, even though it also has the connectors).

The Game Boy Player added a rumble feature to certain Game Boy Advance games when played with a GameCube controller. Those games included:
 Drill Dozer (supports BOTH handheld-rumble and GBP-rumble?)
 Mario & Luigi: Superstar Saga
 Pokemon Pinball: Ruby & Sapphire
 Shikakui Atama wo Marukusuru Advance: Kokugo Sansu Rika Shakai
 Shikakui Atama wo Marukusuru Advance: Kanji Keisan
 Summon Night Craft Sword Monogatari: Hajimari no Ishi
 Super Mario Advance 4: Super Mario Bros. 3

Fredrik Olsson (aka Flubba) has implemented rumble in 3 applications now RumblePong (FluBBA) (homebrew)
  Remudvance (FluBBA) (homebrew)
  Goomba (FluBBA) (8bit Gameboy Color Emulator for 32bit GBA) (homebrew)
  and, supposedly in "Tetanus on Drugs" (Tepples) (homebrew)

The GBP can also use some of the extra controllers for the GC like the Bongas
from Donkey Konga.

The logo requires at least 256 colors, it doesn't matter if you use a tiled
screen mode or a bitmapped one, the logo can be ripped from either
"Pokemon Pinball" or "Super Mario Advance 4".

Rumble
After detecting/unlocking the Gameboy Player, init RCNT and SIOCNT to 32bit normal mode, external clock, SO=high, with IRQ enabled, and set the transfer start bit. You should then receive the following sequence (about once per frame), and your serial IRQ handler should send responses accordingly:
  Receive  Response
  0000494E 494EB6B1
  xxxx494E 494EB6B1
  B6B1494E 544EB6B1
  B6B1544E 544EABB1
  ABB1544E 4E45ABB1
  ABB14E45 4E45B1BA
  B1BA4E45 4F44B1BA
  B1BA4F44 4F44B0BB
  B0BB4F44 8000B0BB
  B0BB8002 10000010
  10000010 20000013
  20000013 40000004
  30000003 40000004
  30000003 40000004
  30000003 40000004
  30000003 400000yy
  30000003 40000004
The first part of the transfer just contains the string "NINTENDO" split into 16bit fragments, and bitwise inversions thereof (eg. 494Eh="NI", and B6B1h=NOT 494Eh). In the second part, <yy> should be 04h=RumbleOff, or 26h=RumbleOn.

Note
If it's having a similar range of functions as the 8bit Super Gameboy, then the Gameboy Player might be also able to access analogue joypad input, and to access other features of the Gamecube hardware, up to possibly executing code on the Gamecube CPU...?


GBA Backwards Compatibility CGB Mode

Related GBA Registers
  4000000h.bit14 (DISPCNT) - enable BG2 aka CGB screen
  4000000h.bit3  (DISPCNT) - prepare switch to CGB mode
  4000301h       (HALTCNT) - apply switch to CGB mode (and stop ARM forever?)
  4000204h.bit15 (WAITCNT) - detect GBA/CGB cart type (and supply voltage)
  4000800h.bit3  (UNDOC)   - disable CGB bootrom
  5000000h.bit0-15         - Palette Backdrop (screen border color)
  BG2X/BG2Y registers      - CGB screen position within GBA screen
  BLDCNT/BLDY              - can be used to tweak better CGB brightness
  sound BIAS and vol?      - sound

Normal CGB Boot
The GBA does always boot in GBA mode, but the GBA BIOS does almost immediately switch to CGB mode when detecting gameboy cart via Port 4000204h; that detection relies on a mechanical switch in the cartridge slot, which does also toggle the system voltage from 3.3V (GBA) to 5V (CGB).

GBA, GBA SP, and GBA micro
CGB mode is supported on GBA and GBA SP. The GBA micro does lack the cartridge switch (and thus cannot detect 8bit carts, and cannot switch the system voltage, nethertheless it does contain semi-functional CGB hardware: it can be manually switched to CGB mode and execute the CGB intro).

CGB Bootrom Disable
The CGB Bootrom can be disabled via 4000800h, that allows to skip the CGB intro (but requires booting custom GBA code with GBA intro and then hot plugging a gameboy cartridge, which must contain a valid entrypoint at address 0000h, and which must select CGB or DMG mode and initialize the DMG color scheme).
The Bootrom Disable works same as ROMDIS pin on real CGBs (and also includes unlocking port FF60h, FF61h, FF63h, see no$gmb/pandocs for details).
Unknown if it's possible to keep the ARM CPU running after entering CGB mode (so one could re-disable ROMDIS some cycles after booting).

Palette Issues
The GBA vs CGB palettes have different intensities ramps (CGB colors with medium brightness will appear black on GBA), that's making CGB games mostly unplayable on GBA (and only monochrome DMG games are actually working on GBA). As a workaroud, one could tweak BLDCNT/BLDY to increase the brightness.

GBA Memory Usage in CGB Mode
  2000000h-200FFFFh.bit0-15  unused                    ;\
  2010000h-2011FFEh.bit0-7   mapped to C000h-CFFFh     ;
  2012000h-2013FFEh.bit0-7   mapped to 1:D000h-DFFFh   ; GBA Main RAM halfwords
  2014000h-2015FFEh.bit0-7   mapped to 2:D000h-DFFFh   ; used as 32K CGB WRAM
  2016000h-2017FFEh.bit0-7   mapped to 3:D000h-DFFFh   ;
  2018000h-2019FFEh.bit0-7   mapped to 4:D000h-DFFFh   ;
  201A000h-201BFFEh.bit0-7   mapped to 5:D000h-DFFFh   ;
  201C000h-201DFFEh.bit0-7   mapped to 6:D000h-DFFFh   ;
  201E000h-201FFFEh.bit0-7   mapped to 7:D000h-DFFFh   ;
  2010001h-201FFFFh.bit8-15  unused (halfword.msbs)    ;
  2020000h-203FFFFh.bit0-15  unused                    ;/
  3000000h-3003FFFh.bit0-7   mapped to 0:8000h-8FFFh   ;\
  3000000h-3003FFFh.bit8-15  mapped to 0:9000h-9FFFh   ; GBA Fast WRAM words
  3000000h-3003FFFh.bit16-23 mapped to 1:8000h-8FFFh   ; used as 16K CGB VRAM
  3000000h-3003FFFh.bit24-31 mapped to 1:9000h-9FFFh   ;
  3004000h-3007FFFh.bit0-31  unused                    ;/


GBA Unpredictable Things

Forward
Most of the below is caused by 'traces' from previous operations which have used the databus. No promises that the results are stable on all current or future GBA models, and/or under all temperature and interference circumstances.
Also, below specifies 32bit data accesses only. When reading units less than 32bit, data is rotated depending on the alignment of the originally specified address, and 8bit or 16bit are then isolated from the 32bit value as usually.

Reading from BIOS Memory (00000000-00003FFF)
The BIOS memory is protected against reading, the GBA allows to read opcodes or data only if the program counter is located inside of the BIOS area. If the program counter is not in the BIOS area, reading will return the most recent successfully fetched BIOS opcode (eg. the opcode at [00DCh+8] after startup and SoftReset, the opcode at [0134h+8] during IRQ execution, and opcode at [013Ch+8] after IRQ execution, and opcode at [0188h+8] after SWI execution).

Reading from Unused Memory (00004000-01FFFFFF,10000000-FFFFFFFF)
Accessing unused memory at 00004000h-01FFFFFFh, and 10000000h-FFFFFFFFh (and 02000000h-03FFFFFFh when RAM is disabled via Port 4000800h) returns the recently pre-fetched opcode. For ARM code this is simply:
  WORD = [$+8]
For THUMB code the result consists of two 16bit fragments and depends on the address area and alignment where the opcode was stored.
For THUMB code in Main RAM, Palette Memory, VRAM, and Cartridge ROM this is:
  LSW = [$+4], MSW = [$+4]
For THUMB code in BIOS or OAM (and in 32K-WRAM on Original-NDS (in GBA mode)):
  LSW = [$+4], MSW = [$+6]   ;for opcodes at 4-byte aligned locations
  LSW = [$+2], MSW = [$+4]   ;for opcodes at non-4-byte aligned locations
For THUMB code in 32K-WRAM on GBA, GBA SP, GBA Micro, NDS-Lite (but not NDS):
  LSW = [$+4], MSW = OldHI   ;for opcodes at 4-byte aligned locations
  LSW = OldLO, MSW = [$+4]   ;for opcodes at non-4-byte aligned locations
Whereas OldLO/OldHI are usually:
  OldLO=[$+2], OldHI=[$+2]
Unless the previous opcode's prefetch was overwritten; that can happen if the previous opcode was itself an LDR opcode, ie. if it was itself reading data:
  OldLO=LSW(data), OldHI=MSW(data)
  Theoretically, this might also change if a DMA transfer occurs.
Note: Additionally, as usually, the 32bit data value will be rotated if the data address wasn't 4-byte aligned, and the upper bits of the 32bit value will be masked in case of LDRB/LDRH reads.
Note: The opcode prefetch is caused by the prefetch pipeline in the CPU itself, not by the external gamepak prefetch, ie. it works for code in ROM and RAM as well.

Reading from Unused or Write-Only I/O Ports
Works like above Unused Memory when the entire 32bit memory fragment is Unused (eg. 0E0h) and/or Write-Only (eg. DMA0SAD). And otherwise, returns zero if the lower 16bit fragment is readable (eg. 04Ch=MOSAIC, 04Eh=NOTUSED/ZERO).

Reading from GamePak ROM when no Cartridge is inserted
Because Gamepak uses the same signal-lines for both 16bit data and for lower 16bit halfword address, the entire gamepak ROM area is effectively filled by incrementing 16bit values (Address/2 AND FFFFh).

Memory Mirrors
Most internal memory is mirrored across the whole 24bit/16MB address space in which it is located: Slow On-board RAM at 2XXXXXX, Fast On-Chip RAM at 3XXXXXXh, Palette RAM at 5XXXXXXh, VRAM at 6XXXXXXh, and OAM at 7XXXXXXh. Even though VRAM is sized 96K (64K+32K), it is repeated in steps of 128K (64K+32K+32K, the two 32K blocks itself being mirrors of each other).
BIOS ROM, Normal ROM Cartridges, and I/O area are NOT mirrored, the only exception is the undocumented I/O port at 4000800h (repeated each 64K).
The 64K SRAM area is mirrored across the whole 32MB area at E000000h-FFFFFFFh, also, inside of the 64K SRAM field, 32K SRAM chips are repeated twice.

Writing 8bit Data to Video Memory
Video Memory (BG, OBJ, OAM, Palette) can be written to in 16bit and 32bit units only. Attempts to write 8bit data (by STRB opcode) won't work:
Writes to OBJ (6010000h-6017FFFh) (or 6014000h-6017FFFh in Bitmap mode) and to OAM (7000000h-70003FFh) are ignored, the memory content remains unchanged.
Writes to BG (6000000h-600FFFFh) (or 6000000h-6013FFFh in Bitmap mode) and to Palette (5000000h-50003FFh) are writing the new 8bit value to BOTH upper and lower 8bits of the addressed halfword, ie. "[addr AND NOT 1]=data*101h".

Using Invalid Tile Numbers
In Text mode, large tile numbers (combined with a non-zero character base setting in BGnCNT register) may exceed the available 64K of BG VRAM.
On GBA and GBA SP, such invalid tiles are displayed as if the character data is filled by the 16bit BG Map entry value (ie. as vertically striped tiles). Above applies only if there is only one BG layer enabled, with two or more layers, things are getting much more complicated: tile-data is then somehow derived from the other layers, depending on their priority order and scrolling offsets.
On NDS (in GBA mode), such invalid tiles are displayed as if the character data is zero-filled (ie. as invisible/transparent tiles).

Accessing SRAM Area by 16bit/32bit
Reading retrieves 8bit value from specified address, multiplied by 0101h (LDRH) or by 01010101h (LDR). Writing changes the 8bit value at the specified address only, being set to LSB of (source_data ROR (address*8)).


NDS Reference

Overview
DS Technical Data
DS I/O Maps
DS Memory Maps

Hardware Programming
DS Memory Control
DS Video
DS 3D Video
DS Sound
DS System and Built-in Peripherals
DS Cartridges, Encryption, Firmware
DS Xboo
DS Wireless Communications

Other
BIOS Functions
ARM CPU Reference
External Connectors


DS Technical Data

Processors
  1x ARM946E-S 32bit RISC CPU, 66MHz (NDS9 video) (not used in GBA mode)
  1x ARM7TDMI  32bit RISC CPU, 33MHz (NDS7 sound) (16MHz in GBA mode)
Internal Memory
  4096KB Main RAM (8192KB in debug version)
  96KB   WRAM (64K mapped to NDS7, plus 32K mappable to NDS7 or NDS9)
  60KB   TCM/Cache (TCM: 16K Data, 32K Code) (Cache: 4K Data, 8K Code)
  656KB  VRAM (allocateable as BG/OBJ/2D/3D/Palette/Texture/WRAM memory)
  4KB    OAM/PAL (2K OBJ Attribute Memory, 2K Standard Palette RAM)
  248KB  Internal 3D Memory (104K Polygon RAM, 144K Vertex RAM)
  ?KB    Matrix Stack, 48 scanline cache
  8KB    Wifi RAM
  256KB  Firmware FLASH (512KB in iQue variant, with chinese charset)
  36KB   BIOS ROM (4K NDS9, 16K NDS7, 16K GBA)
Video
  2x LCD screens (each 256x192 pixel, 3 inch, 18bit color depth, backlight)
  2x 2D video engines (extended variants of the GBA's video controller)
  1x 3D video engine (can be assigned to upper or lower screen)
  1x video capture (for effects, or for forwarding 3D to the 2nd 2D engine)
Sound
  16 sound channels (16x PCM8/PCM16/IMA-ADPCM, 6x PSG-Wave, 2x PSG-Noise)
  2 sound capture units (for echo effects, etc.)
  Output: Two built-in stereo speakers, and headphones socket
  Input:  One built-in microphone, and microphone socket
Controls
  Gamepad      4 Direction Keys, 8 Buttons
  Touchscreen  (on lower LCD screen)
Communication Ports
  Wifi IEEE802.11b
Specials
  Built-in Real Time Clock
  Power Managment Device
  Hardware divide and square root functions
  CP15 System Control Coprocessor (cache, tcm, pu, bist, etc.)
External Memory
  NDS Slot (for NDS games) (encrypted 8bit data bus, and serial 1bit bus)
  GBA Slot (for NDS expansions, or for GBA games) (but not for DMG/CGB games)
Manufactured Cartridges
  ROM: 16MB, 32MB, or 64MB
  EEPROM/FLASH/FRAM: 0.5KB, 8KB, 64KB, 256KB, or 512KB
Can be booted from
  NDS Cartridge (NDS mode)
  Firmware FLASH (NDS mode) (eg. by patching firmware via ds-xboo cable)
  Wifi (NDS mode)
  GBA Cartridge (GBA mode) (without DMG/CGB support) (without SIO support)
Power Supply
  Built-in rechargeable Lithium ion battery, 3.7V 1000mAh (DS-Lite)
  External Supply: 5.2V DC

NDS-Lite
Slightly smaller than the original NDS, coming in a more decently elegant case. The LCDs are much more colorful (and thus not backwards compatible with any older NDS or GBA games), and the LCDs support wider viewing angles. Slightly different power managment device (with selectable backlight brightness, new external power source flag, lost audio amplifier mute flag). Slightly different Wifi controller (different chip ID, different dirt effects when accessing invalid wifi ports and unused wifi memory regions, different behaviour on GAPDISP registers, RF/BB chips replaced by a single chip). Slightly different touch screen controller (with new unused input, and slightly different powerdown bits).

Notice
NDS9 means the ARM9 processor and its memory and I/O ports in NDS mode
NDS7 means the ARM7 processor and its memory and I/O ports in NDS mode
GBA means the ARM7 processor and its memory and I/O ports in GBA mode

The two Processors
Most game code is usually executed on the ARM9 processor (in fact, Nintendo reportedly doesn't allow developers use the ARM7 processor, except by predefined API functions, anyways, even with the most likely inefficient API code, most of the ARM7's 33MHz horsepower is left unused).
The ARM9's 66MHz "horsepower" is a different tale - it seems Nintendo thought that a 33MHz processor would be too "slow" for 3D games, and so they (tried to) badge an additional CPU to the original GBA hardware.
However, the real 66MHz can be used only with cache and tcm, all other memory and I/O accesses are delayed to the 33MHz bus clock, that'd be still quite fast, but, there seems to be a hardware glitch that adds 3 waitcycles to all nonsequential accesses at the NDS9 side, which effectively drops its bus clock to about 8MHz, making it ways slower than the 33MHz NDS7 processor, it's even slower than the original 16MHz GBA processor.
Altogether, with the bugged 66MHz, and the unused 33MHz, Nintendo could have reached almost the same power when staying with the GBA's 16MHz processor :-)
Although, when properly using cache/tcm, then the 66MHz processor <can> be very fast, still, the NDS should have worked as well with a single processor, though using only an ARM9 might cause a lot of compatibility problems with GBA games, so there's at least one reason for keeping the ARM7 included.


DS I/O Maps

ARM9 I/O Map
ARM9 Display Engine A
  4000000h  4    2D Engine A - DISPCNT - LCD Control (Read/Write)
  4000004h  2    2D Engine A+B - DISPSTAT - General LCD Status (Read/Write)
  4000006h  2    2D Engine A+B - VCOUNT - Vertical Counter (Read only)
  4000008h  50h  2D Engine A (same registers as GBA, some changed bits)
  4000060h  2    DISP3DCNT - 3D Display Control Register (R/W)
  4000064h  4    DISPCAPCNT - Display Capture Control Register (R/W)
  4000068h  4    DISP_MMEM_FIFO - Main Memory Display FIFO (R?/W)
  400006Ch  2    2D Engine A - MASTER_BRIGHT - Master Brightness Up/Down
GBA I/O Map
ARM9 DMA, Timers, and Keypad
  40000B0h  30h  DMA Channel 0..3
  40000E0h  10h  DMA FILL Registers for Channel 0..3
  4000100h  10h  Timers 0..3
  4000130h  2    KEYINPUT
  4000132h  2    KEYCNT
ARM9 IPC/ROM
  4000180h  2  IPCSYNC - IPC Synchronize Register (R/W)
  4000184h  2  IPCFIFOCNT - IPC Fifo Control Register (R/W)
  4000188h  4  IPCFIFOSEND - IPC Send Fifo (W)
  40001A0h  2  AUXSPICNT - Gamecard ROM and SPI Control
  40001A2h  2  AUXSPIDATA - Gamecard SPI Bus Data/Strobe
  40001A4h  4  Gamecard bus timing/control
  40001A8h  8  Gamecard bus 8-byte command out
  40001B0h  4  Gamecard Encryption Seed 0 Lower 32bit
  40001B4h  4  Gamecard Encryption Seed 1 Lower 32bit
  40001B8h  2  Gamecard Encryption Seed 0 Upper 7bit (bit7-15 unused)
  40001BAh  2  Gamecard Encryption Seed 1 Upper 7bit (bit7-15 unused)
ARM9 Memory and IRQ Control
  4000204h  2  EXMEMCNT - External Memory Control (R/W)
  4000208h  2  IME - Interrupt Master Enable (R/W)
  4000210h  4  IE  - Interrupt Enable (R/W)
  4000214h  4  IF  - Interrupt Request Flags (R/W)
  4000240h  1  VRAMCNT_A - VRAM-A (128K) Bank Control (W)
  4000241h  1  VRAMCNT_B - VRAM-B (128K) Bank Control (W)
  4000242h  1  VRAMCNT_C - VRAM-C (128K) Bank Control (W)
  4000243h  1  VRAMCNT_D - VRAM-D (128K) Bank Control (W)
  4000244h  1  VRAMCNT_E - VRAM-E (64K) Bank Control (W)
  4000245h  1  VRAMCNT_F - VRAM-F (16K) Bank Control (W)
  4000246h  1  VRAMCNT_G - VRAM-G (16K) Bank Control (W)
  4000247h  1  WRAMCNT   - WRAM Bank Control (W)
  4000248h  1  VRAMCNT_H - VRAM-H (32K) Bank Control (W)
  4000249h  1  VRAMCNT_I - VRAM-I (16K) Bank Control (W)
ARM9 Maths
  4000280h  2  DIVCNT - Division Control (R/W)
  4000290h  8  DIV_NUMER - Division Numerator (R/W)
  4000298h  8  DIV_DENOM - Division Denominator (R/W)
  40002A0h  8  DIV_RESULT - Division Quotient (=Numer/Denom) (R)
  40002A8h  8  DIVREM_RESULT - Division Remainder (=Numer MOD Denom) (R)
  40002B0h  2  SQRTCNT - Square Root Control (R/W)
  40002B4h  4  SQRT_RESULT - Square Root Result (R)
  40002B8h  8  SQRT_PARAM - Square Root Parameter Input (R/W)
  4000300h  4  POSTFLG - Undoc
  4000304h  2  POWCNT1 - Graphics Power Control Register (R/W)
ARM9 3D Display Engine
  4000320h..6A3h
DS 3D I/O Map
ARM9 Display Engine B
  4001000h  4    2D Engine B - DISPCNT - LCD Control (Read/Write)
  4001008h  50h  2D Engine B (same registers as GBA, some changed bits)
  400106Ch  2    2D Engine B - MASTER_BRIGHT - 16bit - Brightness Up/Down
ARM9 DSi Extra Registers
  40021Axh  ..  DSi Registers
  4004xxxh  ..  DSi Registers
ARM9 IPC/ROM
  4100000h  4    IPCFIFORECV - IPC Receive Fifo (R)
  4100010h  4    Gamecard bus 4-byte data in, for manual or dma read (R) (or W)
ARM9 DS Debug Registers (Emulator/Devkits)
  4FFF0xxh  ..   Ensata Emulator Debug Registers
  4FFFAxxh  ..   No$gba Emulator Debug Registers
ARM9 Hardcoded RAM Addresses for Exception Handling
  27FFD9Ch   ..  NDS9 Debug Stacktop / Debug Vector (0=None)
  DTCM+3FF8h 4   NDS9 IRQ Check Bits (hardcoded RAM address)
  DTCM+3FFCh 4   NDS9 IRQ Handler (hardcoded RAM address)
Main Memory Control
  27FFFFEh  2    Main Memory Control
Further Memory Control Registers
ARM CP15 System Control Coprocessor

ARM7 I/O Map
  4000004h  2   DISPSTAT
  4000006h  2   VCOUNT
  40000B0h  30h DMA Channels 0..3
  4000100h  10h Timers 0..3
  4000120h  4   Debug SIODATA32
  4000128h  4   Debug SIOCNT
  4000130h  2   KEYINPUT
  4000132h  2   KEYCNT
  4000134h  2   Debug RCNT
  4000136h  2   EXTKEYIN
  4000138h  1   RTC Realtime Clock Bus
  4000180h  2   IPCSYNC - IPC Synchronize Register (R/W)
  4000184h  2   IPCFIFOCNT - IPC Fifo Control Register (R/W)
  4000188h  4   IPCFIFOSEND - IPC Send Fifo (W)
  40001A0h  2   AUXSPICNT - Gamecard ROM and SPI Control
  40001A2h  2   AUXSPIDATA - Gamecard SPI Bus Data/Strobe
  40001A4h  4   Gamecard bus timing/control
  40001A8h  8   Gamecard bus 8-byte command out
  40001B0h  4   Gamecard Encryption Seed 0 Lower 32bit
  40001B4h  4   Gamecard Encryption Seed 1 Lower 32bit
  40001B8h  2   Gamecard Encryption Seed 0 Upper 7bit (bit7-15 unused)
  40001BAh  2   Gamecard Encryption Seed 1 Upper 7bit (bit7-15 unused)
  40001C0h  2   SPI bus Control (Firmware, Touchscreen, Powerman)
  40001C2h  2   SPI bus Data
ARM7 Memory and IRQ Control
  4000204h  2   EXMEMSTAT - External Memory Status
  4000206h  2   WIFIWAITCNT
  4000208h  4   IME - Interrupt Master Enable (R/W)
  4000210h  4   IE  - Interrupt Enable (R/W)
  4000214h  4   IF  - Interrupt Request Flags (R/W)
  4000218h  -   IE2  ;\DSi only (additional ARM7 interrupt sources)
  400021Ch  -   IF2  ;/
  4000240h  1   VRAMSTAT - VRAM-C,D Bank Status (R)
  4000241h  1   WRAMSTAT - WRAM Bank Status (R)
  4000300h  1   POSTFLG
  4000301h  1   HALTCNT (different bits than on GBA) (plus NOP delay)
  4000304h  2   POWCNT2  Sound/Wifi Power Control Register (R/W)
  4000308h  4   BIOSPROT - Bios-data-read-protection address
ARM7 Sound Registers
  4000400h 100h Sound Channel 0..15 (10h bytes each)
  40004x0h  4   SOUNDxCNT - Sound Channel X Control Register (R/W)
  40004x4h  4   SOUNDxSAD - Sound Channel X Data Source Register (W)
  40004x8h  2   SOUNDxTMR - Sound Channel X Timer Register (W)
  40004xAh  2   SOUNDxPNT - Sound Channel X Loopstart Register (W)
  40004xCh  4   SOUNDxLEN - Sound Channel X Length Register (W)
  4000500h  2   SOUNDCNT - Sound Control Register (R/W)
  4000504h  2   SOUNDBIAS - Sound Bias Register (R/W)
  4000508h  1   SNDCAP0CNT - Sound Capture 0 Control Register (R/W)
  4000509h  1   SNDCAP1CNT - Sound Capture 1 Control Register (R/W)
  4000510h  4   SNDCAP0DAD - Sound Capture 0 Destination Address (R/W)
  4000514h  2   SNDCAP0LEN - Sound Capture 0 Length (W)
  4000518h  4   SNDCAP1DAD - Sound Capture 1 Destination Address (R/W)
  400051Ch  2   SNDCAP1LEN - Sound Capture 1 Length (W)
ARM7 DSi Extra Registers
  40021Axh  ..  DSi Registers
  4004xxxh  ..  DSi Registers
  4004700h  2   DSi SNDEXCNT Register  ;\mapped even in DS mode
  4004C0xh  ..  DSi GPIO Registers     ;/
ARM7 IPC/ROM
  4100000h  4   IPCFIFORECV - IPC Receive Fifo (R)
  4100010h  4   Gamecard bus 4-byte data in, for manual or dma read (R) (or W)
ARM7 3DS
  4700000h  4   Disable ARM7 bootrom overlay (W) (3DS only)
ARM7 WLAN Registers
  4800000h  ..  Wifi WS0 Region (32K) (Wifi Ports, and 8K Wifi RAM)
  4808000h  ..  Wifi WS1 Region (32K) (mirror of above, other waitstates)
ARM7 Hardcoded RAM Addresses for Exception Handling
  380FFC0h  4   DSi7 IRQ IF2 Check Bits (hardcoded RAM address) (DSi only)
  380FFDCh  ..  NDS7 Debug Stacktop / Debug Vector (0=None)
  380FFF8h  4   NDS7 IRQ IF Check Bits (hardcoded RAM address)
  380FFFCh  4   NDS7 IRQ Handler (hardcoded RAM address)


DS Memory Maps

NDS9 Memory Map
  00000000h  Instruction TCM (32KB) (not moveable) (mirror-able to 1000000h)
  0xxxx000h  Data TCM        (16KB) (moveable)
  02000000h  Main Memory     (4MB)
  03000000h  Shared WRAM     (0KB, 16KB, or 32KB can be allocated to ARM9)
  04000000h  ARM9-I/O Ports
  05000000h  Standard Palettes (2KB) (Engine A BG/OBJ, Engine B BG/OBJ)
  06000000h  VRAM - Engine A, BG VRAM  (max 512KB)
  06200000h  VRAM - Engine B, BG VRAM  (max 128KB)
  06400000h  VRAM - Engine A, OBJ VRAM (max 256KB)
  06600000h  VRAM - Engine B, OBJ VRAM (max 128KB)
  06800000h  VRAM - "LCDC"-allocated (max 656KB)
  07000000h  OAM (2KB) (Engine A, Engine B)
  08000000h  GBA Slot ROM (max 32MB)
  0A000000h  GBA Slot RAM (max 64KB)
  FFFF0000h  ARM9-BIOS (32KB) (only 3K used)
The ARM9 Exception Vectors are located at FFFF0000h. The IRQ handler redirects to [DTCM+3FFCh].

NDS7 Memory Map
  00000000h  ARM7-BIOS (16KB)
  02000000h  Main Memory (4MB)
  03000000h  Shared WRAM (0KB, 16KB, or 32KB can be allocated to ARM7)
  03800000h  ARM7-WRAM (64KB)
  04000000h  ARM7-I/O Ports
  04800000h  Wireless Communications Wait State 0 (8KB RAM at 4804000h)
  04808000h  Wireless Communications Wait State 1 (I/O Ports at 4808000h)
  06000000h  VRAM allocated as Work RAM to ARM7 (max 256K)
  08000000h  GBA Slot ROM (max 32MB)
  0A000000h  GBA Slot RAM (max 64KB)
The ARM7 Exception Vectors are located at 00000000h. The IRQ handler redirects to [3FFFFFCh aka 380FFFCh].

Further Memory (not mapped to ARM9/ARM7 bus)
  3D Engine Polygon RAM (52KBx2)
  3D Engine Vertex RAM (72KBx2)
  Firmware (256KB) (built-in serial flash memory)
  GBA-BIOS (16KB) (not used in NDS mode)
  NDS Slot ROM (serial 8bit-bus, max 4GB with default protocol)
  NDS Slot FLASH/EEPROM/FRAM (serial 1bit-bus)

Shared-RAM
Even though Shared WRAM begins at 3000000h, programs are commonly using mirrors at 37F8000h (both ARM9 and ARM7). At the ARM7-side, this allows to use 32K Shared WRAM and 64K ARM7-WRAM as a continous 96K RAM block.

Undefined I/O Ports
On the NDS (at the ARM9-side at least) undefined I/O ports are always zero.

Undefined Memory Regions
16MB blocks that do not contain any defined memory regions (or that contain only mapped TCM regions) are typically completely undefined.
16MB blocks that do contain valid memory regions are typically containing mirrors of that memory in the unused upper part of the 16MB area (only exceptions are TCM and BIOS which are not mirrored).


DS Memory Control

Memory Control
DS Memory Control - Cache and TCM
DS Memory Control - Cartridges and Main RAM
DS Memory Control - WRAM
DS Memory Control - VRAM
DS Memory Control - BIOS

Memory Access Time
DS Memory Timings


DS Memory Control - Cache and TCM

TCM and Cache are controlled by the System Control Coprocessor,
ARM CP15 System Control Coprocessor

The specifications for the NDS9 are:

Tightly Coupled Memory (TCM)
  ITCM 32K, base=00000000h (fixed, not move-able)
  DTCM 16K, base=moveable  (default base=27C0000h)
Note: Although ITCM is NOT moveable, the NDS Firmware configures the ITCM size to 32MB, and so, produces ITCM mirrors at 0..1FFFFFFh. Furthermore, the PU can be used to lock/unlock memory in that region. That trick allows to move ITCM anywhere within the lower 32MB of memory.

Cache
  Data Cache 4KB, Instruction Cache 8KB
  4-way set associative method
  Cache line 8 words (32 bytes)
  Read-allocate method (ie. writes are not allocating cache lines)
  Round-robin and Pseudo-random replacement algorithms selectable
  Cache Lockdown, Instruction Prefetch, Data Preload
  Data write-through and write-back modes selectable

Protection Unit (PU)
Recommended/default settings are:
  Region  Name            Address   Size   Cache WBuf Code Data
  -       Background      00000000h 4GB    -     -    -    -
  0       I/O and VRAM    04000000h 64MB   -     -    R/W  R/W
  1       Main Memory     02000000h 4MB    On    On   R/W  R/W
  2       ARM7-dedicated  027C0000h 256KB  -     -    -    -
  3       GBA Slot        08000000h 128MB  -     -    -    R/W
  4       DTCM            027C0000h 16KB   -     -    -    R/W
  5       ITCM            01000000h 32KB   -     -    R/W  R/W
  6       BIOS            FFFF0000h 32KB   On    -    R    R
  7       Shared Work     027FF000h 4KB    -     -    -    R/W
Notes: In Nintendo's hardware-debugger, Main Memory is expanded to 8MB (for that reason, some addresses are at 27NN000h instead 23NN000h) (some of the extra memory is reserved for the debugger, some can be used for game development). Region 2 and 7 are not understood? GBA Slot should be max 32MB+64KB, rounded up to 64MB, no idea why it is 128MB? DTCM and ITCM do not use Cache and Write-Buffer because TCM is fast. Above settings do not allow to access Shared Memory at 37F8000h? Do not use cache/wbuf for I/O, doing so might suppress writes, and/or might read outdated values.
The main purpose of the Protection Unit is debugging, a major problem with GBA programs have been faulty accesses to memory address 00000000h and up (due to [base+offset] addressing with uninitialized (zero) base values). This problem has been fixed in the NDS, for the ARM9 processor at least, still there are various leaks: For example, the 64MB I/O and VRAM area contains only ca. 660KB valid addresses, and the ARM7 probably doesn't have a Protection Unit at all. Alltogether, the protection is better than in GBA, but it's still pretty crude compared with software debugging tools.
Region address/size are unified (same for code and data), however, cachabilty and access rights are non-unified (and may be separately defined for code and data).

Note: The NDS7 doesn't have any TCM, Cache, or CP15.


DS Memory Control - Cartridges and Main RAM

4000204h - NDS9 - EXMEMCNT - 16bit - External Memory Control (R/W)
4000204h - NDS7 - EXMEMSTAT - 16bit - External Memory Status (R/W..R)
  0-1   32-pin GBA Slot SRAM Access Time    (0-3 = 10, 8, 6, 18 cycles)
  2-3   32-pin GBA Slot ROM 1st Access Time (0-3 = 10, 8, 6, 18 cycles)
  4     32-pin GBA Slot ROM 2nd Access Time (0-1 = 6, 4 cycles)
  5-6   32-pin GBA Slot PHI-pin out   (0-3 = Low, 4.19MHz, 8.38MHz, 16.76MHz)
  7     32-pin GBA Slot Access Rights     (0=ARM9, 1=ARM7)
  8-10  Not used (always zero)
  11    17-pin NDS Slot Access Rights     (0=ARM9, 1=ARM7)
  12    Not used (always zero)
  13    NDS:Always set?  ;set/tested by DSi bootcode: Main RAM enable, CE2 pin?
  14    Main Memory Interface Mode Switch (0=Async/GBA/Reserved, 1=Synchronous)
  15    Main Memory Access Priority       (0=ARM9 Priority, 1=ARM7 Priority)
Bit0-6 can be changed by both NDS9 and NDS7, changing these bits affects the local EXMEM register only, not that of the other CPU.
Bit7-15 can be changed by NDS9 only, changing these bits affects both EXMEM registers, ie. both NDS9 and NDS7 can read the current NDS9 setting.
Bit14=0 is intended for GBA mode, however, writes to this bit appear to be ignored?
DS Main Memory Control

GBA Slot (8000000h-AFFFFFFh)
The GBA Slot can be mapped to ARM9 or ARM7 via EXMEMCNT.7.
For the selected CPU, memory at 8000000h-9FFFFFFh contains the "GBA ROM" region, and memory at A000000h-AFFFFFFh contains the "GBA SRAM" region (repeated every 64Kbytes). If there is no cartridge in GBA Slot, then the ROM/SRAM regions will contain open-bus values: SRAM region is FFh-filled (High-Z). And ROM region is filled by increasing 16bit values (Addr/2), possibly ORed with garbage depending on the selected ROM Access Time:
  6 clks   --> returns "Addr/2"
  8 clks   --> returns "Addr/2"
  10 clks  --> returns "Addr/2 OR FE08h" (or similar garbage)
  18 clks  --> returns "FFFFh" (High-Z)
For the deselected CPU, all memory at 8000000h-AFFFFFFh becomes 00h-filled, this is required for bugged games like Digimon Story: Super Xros Wars (which is accidently reading deselected GBA SRAM at [main_ram_base+main_ram_addr*4], whereas it does presumably want to read Main RAM at [main_ram_base+index*4]).


DS Memory Control - WRAM

4000247h - NDS9 - WRAMCNT - 8bit - WRAM Bank Control (R/W)
4000241h - NDS7 - WRAMSTAT - 8bit - WRAM Bank Status (R)
Should not be changed when using Nintendo's API.
  0-1   ARM9/ARM7 (0-3 = 32K/0K, 2nd 16K/1st 16K, 1st 16K/2nd 16K, 0K/32K)
  2-7   Not used
The ARM9 WRAM area is 3000000h-3FFFFFFh (16MB range).
The ARM7 WRAM area is 3000000h-37FFFFFh (8MB range).
The allocated 16K or 32K are mirrored everywhere in the above areas.
De-allocation (0K) is a special case: At the ARM9-side, the WRAM area is then empty (containing undefined data). At the ARM7-side, the WRAM area is then containing mirrors of the 64KB ARM7-WRAM (the memory at 3800000h and up).


DS Memory Control - VRAM

4000240h - NDS7 - VRAMSTAT - 8bit - VRAM Bank Status (R)
  0     VRAM C enabled and allocated to NDS7  (0=No, 1=Yes)
  1     VRAM D enabled and allocated to NDS7  (0=No, 1=Yes)
  2-7   Not used (always zero)
The register indicates if VRAM C/D are allocated to NDS7 (as Work RAM), ie. if VRAMCNT_C/D are enabled (Bit7=1), with MST=2 (Bit0-2). However, it does not reflect the OFS value.

4000240h - NDS9 - VRAMCNT_A - 8bit - VRAM-A (128K) Bank Control (W)
4000241h - NDS9 - VRAMCNT_B - 8bit - VRAM-B (128K) Bank Control (W)
4000242h - NDS9 - VRAMCNT_C - 8bit - VRAM-C (128K) Bank Control (W)
4000243h - NDS9 - VRAMCNT_D - 8bit - VRAM-D (128K) Bank Control (W)
4000244h - NDS9 - VRAMCNT_E - 8bit - VRAM-E (64K) Bank Control (W)
4000245h - NDS9 - VRAMCNT_F - 8bit - VRAM-F (16K) Bank Control (W)
4000246h - NDS9 - VRAMCNT_G - 8bit - VRAM-G (16K) Bank Control (W)
4000248h - NDS9 - VRAMCNT_H - 8bit - VRAM-H (32K) Bank Control (W)
4000249h - NDS9 - VRAMCNT_I - 8bit - VRAM-I (16K) Bank Control (W)
  0-2   VRAM MST              ;Bit2 not used by VRAM-A,B,H,I
  3-4   VRAM Offset (0-3)     ;Offset not used by VRAM-E,H,I
  5-6   Not used
  7     VRAM Enable (0=Disable, 1=Enable)
There is a total of 656KB of VRAM in Blocks A-I.
Table below shows the possible configurations.
  VRAM    SIZE  MST  OFS   ARM9, Plain ARM9-CPU Access (so-called LCDC mode)
  A       128K  0    -     6800000h-681FFFFh
  B       128K  0    -     6820000h-683FFFFh
  C       128K  0    -     6840000h-685FFFFh
  D       128K  0    -     6860000h-687FFFFh
  E       64K   0    -     6880000h-688FFFFh
  F       16K   0    -     6890000h-6893FFFh
  G       16K   0    -     6894000h-6897FFFh
  H       32K   0    -     6898000h-689FFFFh
  I       16K   0    -     68A0000h-68A3FFFh
  VRAM    SIZE  MST  OFS   ARM9, 2D Graphics Engine A, BG-VRAM (max 512K)
  A,B,C,D 128K  1    0..3  6000000h+(20000h*OFS)
  E       64K   1    -     6000000h
  F,G     16K   1    0..3  6000000h+(4000h*OFS.0)+(10000h*OFS.1)
  VRAM    SIZE  MST  OFS   ARM9, 2D Graphics Engine A, OBJ-VRAM (max 256K)
  A,B     128K  2    0..1  6400000h+(20000h*OFS.0)  ;(OFS.1 must be zero)
  E       64K   2    -     6400000h
  F,G     16K   2    0..3  6400000h+(4000h*OFS.0)+(10000h*OFS.1)
  VRAM    SIZE  MST  OFS   2D Graphics Engine A, BG Extended Palette
  E       64K   4    -     Slot 0-3  ;only lower 32K used
  F,G     16K   4    0..1  Slot 0-1 (OFS=0), Slot 2-3 (OFS=1)
  VRAM    SIZE  MST  OFS   2D Graphics Engine A, OBJ Extended Palette
  F,G     16K   5    -     Slot 0  ;16K each (only lower 8K used)
  VRAM    SIZE  MST  OFS   Texture/Rear-plane Image
  A,B,C,D 128K  3    0..3  Slot OFS(0-3)   ;(Slot2-3: Texture, or Rear-plane)
  VRAM    SIZE  MST  OFS   Texture Palette
  E       64K   3    -     Slots 0-3                 ;OFS=don't care
  F,G     16K   3    0..3  Slot (OFS.0*1)+(OFS.1*4)  ;ie. Slot 0, 1, 4, or 5
  VRAM    SIZE  MST  OFS   ARM9, 2D Graphics Engine B, BG-VRAM (max 128K)
  C       128K  4    -     6200000h
  H       32K   1    -     6200000h
  I       16K   1    -     6208000h
  VRAM    SIZE  MST  OFS   ARM9, 2D Graphics Engine B, OBJ-VRAM (max 128K)
  D       128K  4    -     6600000h
  I       16K   2    -     6600000h
  VRAM    SIZE  MST  OFS   2D Graphics Engine B, BG Extended Palette
  H       32K   2    -     Slot 0-3
  VRAM    SIZE  MST  OFS   2D Graphics Engine B, OBJ Extended Palette
  I       16K   3    -     Slot 0  ;(only lower 8K used)
  VRAM    SIZE  MST  OFS   <ARM7>, Plain <ARM7>-CPU Access
  C,D     128K  2    0..1  6000000h+(20000h*OFS.0)  ;OFS.1 must be zero

Notes
In Plain-CPU modes, VRAM can be accessed only by the CPU (and by the Capture Unit, and by VRAM Display mode). In "Plain <ARM7>-CPU Access" mode, the VRAM blocks are allocated as Work RAM to the NDS7 CPU.
In BG/OBJ VRAM modes, VRAM can be accessed by the CPU at specified addresses, and by the display controller.
In Extended Palette and Texture Image/Palette modes, VRAM is not mapped to CPU address space, and can be accessed only by the display controller (so, to initialize or change the memory, it should be temporarily switched to Plain-CPU mode).
All VRAM (and Palette, and OAM) can be written to only in 16bit and 32bit units (STRH, STR opcodes), 8bit writes are ignored (by STRB opcode). The only exception is "Plain <ARM7>-CPU Access" mode: The ARM7 CPU can use STRB to write to VRAM (the reason for this special feature is that, in GBA mode, two 128K VRAM blocks are used to emulate the GBA's 256K Work RAM).

Other Video RAM
Aside from the map-able VRAM blocks, there are also some video-related memory regions at fixed addresses:
  5000000h Engine A Standard BG Palette (512 bytes)
  5000200h Engine A Standard OBJ Palette (512 bytes)
  5000400h Engine B Standard BG Palette (512 bytes)
  5000600h Engine B Standard OBJ Palette (512 bytes)
  7000000h Engine A OAM (1024 bytes)
  7000400h Engine B OAM (1024 bytes)


DS Memory Control - BIOS

4000308h - NDS7 - BIOSPROT - Bios-data-read-protection address
Used to double-protect the first some KBytes of the NDS7 BIOS. The BIOS is split into two protection regions, one always active, one controlled by the BIOSPROT register. The overall idea is that only the BIOS can read from itself, any other attempts to read from that regions return FFh-bytes.
  Opcodes at...      Can read from      Expl.
  0..[BIOSPROT]-1    0..3FFFh           Double-protected (when BIOSPROT is set)
  [BIOSPROT]..3FFFh  [BIOSPROT]..3FFFh  Normal-protected (always active)
The initial BIOSPROT setting on power-up is zero (disabled). Before starting the cartridge, the BIOS boot code sets the register to 1204h (actually 1205h, but the mis-aligned low-bit is ignored). Once when initialized, further writes to the register are ignored.

The double-protected region contains the exception vectors, some bytes of code, and the cartridge KEY1 encryption seed (about 4KBytes). As far as I know, it is impossible to unlock the memory once when it is locked, however, with some trickery, it is possible execute code before it gets locked. Also, the two THUMB opcodes at 05ECh can be used to read all memory at 0..3FFFh,
  05ECh  ldrb r3,[r3,12h]      ;requires incoming r3=src-12h
  05EEh  pop  r2,r4,r6,r7,r15  ;requires dummy values & THUMB retadr on stack
Additionally most BIOS functions (eg. CpuSet), include a software-based protection which rejects source addresses in the BIOS area (the only exception is GetCRC16, though it still cannot bypass the BIOSPROT setting).

Note
The NDS9 BIOS doesn't include any software or hardware based read protection.


DS Memory Timings

System Clock
  Bus clock  = 33MHz (33.513982 MHz) (1FF61FEh Hertz)
  NDS7 clock = 33MHz (same as bus clock)
  NDS9 clock = 66MHz (internally twice bus clock; for cache/tcm)
Most timings in this document are specified for 33MHz clock (not for the 66MHz clock). Respectively, NDS9 timings are counted in "half" cycles.

Memory Access Times
Tables below show the different access times for code/data fetches on arm7/arm9 cpus, measured for sequential/nonsequential 32bit/16bit accesses.
  NDS7/CODE             NDS9/CODE
  N32 S32 N16 S16 Bus   N32 S32 N16 S16 Bus
  9   2   8   1   16    9   9   4.5 4.5 16  Main RAM (read) (cache off)
  1   1   1   1   32    4   4   2   2   32  WRAM,BIOS,I/O,OAM
  2   2   1   1   16    5   5   2.5 2.5 16  VRAM,Palette RAM
  16  12  10  6   16    19  19  9.5 9.5 16  GBA ROM (example 10,6 access)
  -   -   -   -   -     0.5 0.5 0.5 0.5 32  TCM, Cache_Hit
  -   -   -   -   -     (--Load 8 words--)  Cache_Miss

  NDS7/DATA             NDS9/DATA
  N32 S32 N16 S16 Bus   N32 S32 N16 S16 Bus
  10  2   9   1   16    10  2   9   1   16  Main RAM (read) (cache off)
  1   1   1   1   32    4   1   4   1   32  WRAM,BIOS,I/O,OAM
  1?  2   1   1   16    5   2   4   1   16  VRAM,Palette RAM
  15  12  9   6   16    19  12  13  6   16  GBA ROM (example 10,6 access)
  9   10  9   10  8     13  10  13  10  8   GBA RAM (example 10 access)
  -   -   -   -   -     0.5 0.5 0.5 -   32  TCM, Cache_Hit
  -   -   -   -   -     (--Load 8 words--)  Cache_Miss
  -   -   -   -   -     11  11  11  -   32  Cache_Miss (BIOS)
  -   -   -   -   -     23  23  23  -   16  Cache_Miss (Main RAM)
All timings are counted in 33MHz units (so "half" cycles can occur on NDS9).
Note: 8bit data accesses have same timings than 16bit data.

*** DS Memory Timing Notes ***

The NDS timings are altogether pretty messed up, with different timings for CODE and DATA fetches, and different timings for NDS7 and NDS9...

NDS7/CODE
Timings for this region can be considered as "should be" timings.

NDS7/DATA
Quite the same as NDS7/CODE. Except that, nonsequential Main RAM accesses are 1 cycle slower, and more strange, nonsequential GBA Slot accesses are 1 cycle faster.

NDS9/CODE
This is the most messiest timing. An infamous PENALTY of 3 cycles is added to all nonsequential accesses (except cache, tcm, and main ram). And, all opcode fetches are forcefully made nonsequential 32bit (the NDS9 simply doesn't support fast sequential opcode fetches). That applies also for THUMB code (two 16bit opcodes are fetched by a single nonsequential 32bit access) (so the time per 16bit opcode is one half of the 32bit fetch) (unless a branch causes only one of the two 16bit opcodes to be executed, then that opcode will have the full 32bit access time).

NDS9/DATA
Allows both sequential and nonsequential access, and both 16bit and 32bit access, so it's faster than NDS9/CODE. Nethertheless, it's still having the 3 cycle PENALTY on nonsequential accesses. And, similar as NDS7/DATA, it's also adding 1 cycle to nonsequential Main RAM accesses.

*** More Timing Notes / Lots of unsorted Info ***

Actual CPU Performance
The 33MHz NDS7 is running more or less nicely at 33MHz. However, the so-called "66MHz" NDS9 is having <much> higher waitstates, and it's effective bus speed is barely about 8..16MHz, the only exception is code/data in cache/tcm, which is eventually reaching real 66MHz (that, assuming cache HITS, otherwise, in case of cache MISSES, the cached memory timing might even drop to 1.4MHz or so?).
*********************
ARM9 opcode fetches are always N32 + 3 waits.
  S16 and N16 do not exist (because thumb-double-fetching) (see there).
  S32 becomes N32 (ie. the ARM9 does NOT support fast sequential timing).
That N32 is having same timing as normal N32 access on NDS7, plus 3 waits.
  Eg. an ARM9 N32 or S32 to 16bit bus will take: N16 + S16 + 3 waits.
  Eg. an ARM9 N32 or S32 to 32bit bus will take: N32 + 3 waits.
Main Memory is ALWAYS having the nonsequential 3 wait PENALTY (even on ARM7).
*********************
ARM9 Data fetches however are allowed to use sequential timing, as well as raw 16bit accesses (which aren't forcefully expanded to slow 32bit accesses).
Nethertheless, the 3 wait PENALTY is added to any NONSEQUENTIAL accesses.
Only exceptions are cache and tcm which do not have that penalty.
 Eg. LDRH on 16bit-data-bus is N16+3waits.
 Eg. LDR  on 16bit-data-bus is N16+S16+3waits.
 Eg. LDM  on 16bit-data-bus is N16+(n*2-1)*S16+3waits.
Eventually, data fetches can take place parallel with opcode fetches.
 That is NOT true for LDM (works only for LDR/LDRB/LDRH).
 That is NOT true for DATA in SAME memory region than CODE.
 That is NOT true for DATA in ITCM (no matter if CODE is in ITCM).
*********************

NDS9 Busses
Unlike ARM7, the ARM9 has separate code and data busses, allowing it to perform code and data fetches simultaneously (provided that both are in different memory regions).
Normally, opcode execution times are calculated as "(codetime+datatime)", with the two busses, it can (ideally) be "MAX(codetime,datatime)", so the data access time may virtually take "NULL" clock cycles.
In practice, DTCM and Data Cache access can take NULL cycles (however, data access to ITCM can't).
When executing code in cache/itcm, data access to non-cache/tcm won't be any faster than with only one bus (as it's best, it could subtract 0.5 cycles from datatime, but, the access must be "aligned" to the bus-clock, so the "datatime-0.5" will be rounded back to the original "datatime").
When executing code in uncached main ram, and accessing data (elsewhere than in main memory, cache/tcm), then execution time is typically "codetime+datatime-2".

NDS9 Internal Cycles
Additionally to codetime+datatime, some opcodes include one or more internal cycles. Compared with ARM7, the behaviour of that internal cycles is slightly different on ARM9. First of, on the NDS9, the internal cycles are of course "half" cycles (ie. counted in 66MHz units, not in 33MHz units) (although they may get rounded to "full" cycles upon next memory access outside tcm/cache). And, the ARM9 is in some cases "skipping" the internal cycles, that often depending on whether or not the next opcode is using the result of the current opcode.
Another big difference is that the ARM9 has lost the fast-multiply feature for small numbers; in some cases that may result in faster execution, but may also result in slower execution (one workaround would be to manually replace MUL opcodes by the new ARM9 halfword multiply opcodes); the slowest case are MUL opcodes that do update flags (eg. MULS, MLAS, SMULLS, etc. in ARM mode, and all ALL multiply opcodes in THUMB mode).

NDS9 Thumb Code
In thumb mode, the NDS9 is fetching two 16bit opcodes by a single 32bit read. In case of 32bit bus, this reduces the amount of memory traffic and may result in faster execution time, of course that works only if the two opcodes are within a word-aligned region (eg. loops at word-aligned addresses will be faster than non-aligned loops). However, the double-opcode-fetching is also done on 16bit bus memory, including for unnecessary fetches, such like opcodes after branch commands, so the feature may cause heavy slowdowns.

Main Memory
Reportedly, the main memory access times would be 5 cycles (nonsequential read), 4 cycles (nonsequential write), and 1 cycle (sequential read or write). Plus whatever termination cycles. Plus 3 cycles on nonsequential access to the last 2-bytes of a 32-byte block.
That's of course all wrong. Reads are much slower than 5 cycles. Not yet tested if writes are faster. And, I haven't been able to reproduce the 3 cycles on last 2-bytes effect, actually, it looks more as if that 3 cycles are accidently added to ALL nonsequential accesses, at ALL main memory addresses, and even to most OTHER memory regions... which might be the source of the PENALTY which occurs on VRAM/WRAM/OAM/Palette and I/O accesses.

DMA
In some cases DMA main memory read cycles are reportedly performed simultaneously with DMA write cycles to other memory.

NDS9
On the NDS9, all external memory access (and I/O) is delayed to bus clock (or actually MUCH slower due to the massive waitstates), so the full 66MHz can be used only internally in the NDS9 CPU core, ie. with cache and TCM.

Bus Clock
The exact bus clock is specified as 33.513982 MHz (1FF61FEh Hertz). However, on my own NDS, measured in relation to the RTC seconds IRQ, it appears more like 1FF6231h, that inaccuary of 1 cycle per 657138 cycles (about one second per week) on either oscillator, isn't too significant though.

GBA Slot
The access time for GBA slot can be configured via EXMEMCNT register.

VRAM Waitstates
Additionally, on NDS9, a one cycle wait can be added to VRAM accesses (when the video controller simultaneously accesses it) (that can be disabled by Forced Blank, see DISPCNT.Bit7). Moreover, additional VRAM waitstates occur when using the video capture function.
Note: VRAM being mapped to NDS7 is always free of additional waits.


DS Video

The NDS has two 2D Video Engines, each basically the same as in GBA, see
GBA LCD Video Controller

NDS Specific 2D Video Features
DS Video Stuff
DS Video BG Modes / Control
DS Video OBJs
DS Video Extended Palettes
DS Video Capture and Main Memory Display Mode
DS Video Display System Block Diagram

NDS/DSi File Formats for 2D video
DS Files - 2D Video

For Display Power Control (and Display Swap), and VRAM Allocation, see
DS Power Control
DS Power Management Device
DS Memory Control - VRAM


DS Video Stuff

DS Display Dimensions / Timings
Dot clock = 5.585664 MHz (=33.513982 MHz / 6)
H-Timing: 256 dots visible, 99 dots blanking, 355 dots total (15.7343KHz)
V-Timing: 192 lines visible, 71 lines blanking, 263 lines total (59.8261 Hz)
The V-Blank cycle for the 3D Engine consists of the 23 lines, 191..213.
Screen size 62.5mm x 47.0mm (each) (256x192 pixels)
Vertical space between screens 22mm (equivalent to 90 pixels)

400006Ch - NDS9 - MASTER_BRIGHT - 16bit - Master Brightness Up/Down
  0-4   Factor used for 6bit R,G,B Intensities (0-16, values >16 same as 16)
          Brightness up:   New = Old + (63-Old) * Factor/16
          Brightness down: New = Old - Old      * Factor/16
  5-13  Not used
  14-15 Mode (0=Disable, 1=Up, 2=Down, 3=Reserved)
  16-31 Not used

DISPSTAT/VCOUNT
The LY and LYC values are in range 0..262, so LY/LYC values have been expanded to 9bit values: LY = VCOUNT Bit 0..8, and LYC=DISPSTAT Bit8..15,7.
VCOUNT register is write-able, allowing to synchronize linked DS consoles.
For proper synchronization:
  write new LY values only in range of 202..212
  write only while old LY values are in range of 202..212
DISPSTAT/VCOUNT supported by NDS9 (Engine A Ports, without separate Engine B Ports), and by NDS7 (allowing to synchronize NDS7 with display timings).
Similar as on GBA, the VBlank flag isn't set in the last line (ie. only in lines 192..261, but not in line 262).
Although the drawing time is only 1536 cycles (256*6), the NDS9 H-Blank flag is "0" for a total of 1606 cycles (and, for whatever reason, a bit longer, 1613 cycles in total, on NDS7).

VRAM Waitstates
The display controller performs VRAM-reads once every 6 clock cycles, a 1 cycle waitstate is generated if the CPU simultaneously accesses VRAM. With capture enabled, additionally VRAM-writes take place once every 6 cycles, so the total VRAM-read/write access rate is then once every 3 cycles.

DS Window Glitches
The DS counts scanlines in range 0..262 (0..106h), of which only the lower 8bit are compared with the WIN0V/WIN1V register settings. Respectively, Y1 coordinates 00h..06h will be triggered in scanlines 100h-106h by mistake. That means, the window gets activated within VBlank period, and will be active in scanline 0 and up (that is no problem with Y1=0, but Y1=1..6 will appear as if if Y1 would be 0). Workaround would be to disable the Window during VBlank, or to change Y1 during VBlank (to a value that does not occur during VBlank period, ie. 7..191).
Also, there's a problem to fit the 256 pixel horizontal screen resolution into 8bit values: X1=00h is treated as 0 (left-most), X2=00h is treated as 100h (right-most). However, the window is not displayed if X1=X2=00h; the window width can be max 255 pixels.

2D Engines
Includes two 2D Engines, called A and B. Both engines are accessed by the ARM9 processor, each using different memory and register addresses:
  Region______Engine A______________Engine B___________
  I/O Ports   4000000h              4001000h
  Palette     5000000h (1K)         5000400h (1K)
  BG VRAM     6000000h (max 512K)   6200000h (max 128K)
  OBJ VRAM    6400000h (max 256K)   6600000h (max 128K)
  OAM         7000000h (1K)         7000400h (1K)
Engine A additionally supports 3D and large-screen 256-color Bitmaps, plus main-memory-display and vram-display modes, plus capture unit.

Viewing Angles
The LCD screens are best viewed at viewing angles of 90 degrees. Colors may appear distorted, and may even become invisible at other viewing angles.
When the console is handheld, both screens can be turned into preferred direction. When the console is settled on a table, only the upper screen can be turned, but the lower screen is stuck into horizontal position - which results in rather bad visibility (unless the user moves his/her head directly above of it).

4000070h - NDS9 - TVOUTCNT - Unknown (W)
  Bit0-3  "COMMAND"  (?)
  Bit4-7  "COMMAND2" (?)
  Bit8-11 "COMMAND3" (?)
This register has been mentioned in an early I/O map from Nintendo, as far as I know, the register isn't used by any games/firmware/bios, not sure if it does really exist on release-version, or if it's been prototype stuff...?

DS-Lite Screens
The screens in the DS-Lite seem to allow a wider range of vertical angles.
The bad news is that the colors of the DS-Lite are (no surprise) not backwards compatible with older NDS and GBA displays. The good news is that Nintendo has finally reached near-CRT-quality (without blurred colors), so one could hope that they won't show up with more displays with other colors in future.
Don't know if there's an official/recommended way to detect DS-Lite displays (?) possible methods would be whatever values in Firmware header, or by functionality of Power Managment device, or (not too LCD-related) by Wifi Chip ID.


DS Video BG Modes / Control

4000000h - NDS9 - DISPCNT
  Bit  Engine Expl.
  0-2   A+B   BG Mode
  3     A     BG0 2D/3D Selection (instead CGB Mode) (0=2D, 1=3D)
  4     A+B   Tile OBJ Mapping        (0=2D; max 32KB, 1=1D; max 32KB..256KB)
  5     A+B   Bitmap OBJ 2D-Dimension (0=128x512 dots, 1=256x256 dots)
  6     A+B   Bitmap OBJ Mapping      (0=2D; max 128KB, 1=1D; max 128KB..256KB)
  7-15  A+B   Same as GBA
  16-17 A+B   Display Mode (Engine A: 0..3, Engine B: 0..1, GBA: Green Swap)
  18-19 A     VRAM block (0..3=VRAM A..D) (For Capture & above Display Mode=2)
  20-21 A+B   Tile OBJ 1D-Boundary   (see Bit4)
  22    A     Bitmap OBJ 1D-Boundary (see Bit5-6)
  23    A+B   OBJ Processing during H-Blank (was located in Bit5 on GBA)
  24-26 A     Character Base (in 64K steps) (merged with 16K step in BGxCNT)
  27-29 A     Screen Base (in 64K steps) (merged with 2K step in BGxCNT)
  30    A+B   BG Extended Palettes   (0=Disable, 1=Enable)
  31    A+B   OBJ Extended Palettes  (0=Disable, 1=Enable)

BG Mode
Engine A BG Mode (DISPCNT LSBs) (0-6, 7=Reserved)
  Mode  BG0      BG1      BG2      BG3
  0     Text/3D  Text     Text     Text
  1     Text/3D  Text     Text     Affine
  2     Text/3D  Text     Affine   Affine
  3     Text/3D  Text     Text     Extended
  4     Text/3D  Text     Affine   Extended
  5     Text/3D  Text     Extended Extended
  6     3D       -        Large    -
Of which, the "Extended" modes are sub-selected by BGxCNT bits:
  BGxCNT.Bit7 BGxCNT.Bit2 Extended Affine Mode Selection
  0           CharBaseLsb rot/scal with 16bit bgmap entries (Text+Affine mixup)
  1           0           rot/scal 256 color bitmap
  1           1           rot/scal direct color bitmap
Engine B: Same as above, except that: Mode 6 is reserved (no Large screen bitmap), and BG0 is always Text (no 3D support).
Affine = formerly Rot/Scal mode (with 8bit BG Map entries)
Large Screen Bitmap = rot/scal 256 color bitmap (using all 512K of 2D VRAM)

Display Mode (DISPCNT.16-17):
  0  Display off (screen becomes white)
  1  Graphics Display (normal BG and OBJ layers)
  2  Engine A only: VRAM Display (Bitmap from block selected in DISPCNT.18-19)
  3  Engine A only: Main Memory Display (Bitmap DMA transfer from Main RAM)
Mode 2-3 display a raw direct color bitmap (15bit RGB values, the upper bit in each halfword is unused), without any further BG,OBJ,3D layers, these modes are completely bypassing the 2D/3D engines as well as any 2D effects, however the Master Brightness effect can be applied to these modes. Mode 2 is particulary useful to display captured 2D/3D images (in that case it can indirectly use the 2D/3D engine).

BGxCNT
character base extended from bit2-3 to bit2-5 (bit4-5 formerly unused)
  engine A screen base: BGxCNT.bits*2K + DISPCNT.bits*64K
  engine B screen base: BGxCNT.bits*2K + 0
  engine A char base: BGxCNT.bits*16K + DISPCNT.bits*64K
  engine B char base: BGxCNT.bits*16K + 0
char base is used only in tile/map modes (not bitmap modes)
screen base is used in tile/map modes,
screen base used in bitmap modes as BGxCNT.bits*16K, without DISPCNT.bits*64K
screen base however NOT used at all for Large screen bitmap mode
  bgcnt size  text     rotscal    bitmap   large bmp
  0           256x256  128x128    128x128  512x1024
  1           512x256  256x256    256x256  1024x512
  2           256x512  512x512    512x256  -
  3           512x512  1024x1024  512x512  -
bitmaps that require more than 128K VRAM are supported on engine A only.

For BGxCNT.Bit7 and BGxCNT.Bit2 in Extended Affine modes, see above BG Mode description (extended affine doesn't include 16-color modes, so color depth bit can be used for mode selection. Also, bitmap modes do not use charbase, so charbase.0 can be used for mode selection as well).

  for BG0CNT, BG1CNT only: bit13 selects extended palette slot
                           (BG0: 0=Slot0, 1=Slot2, BG1: 0=Slot1, 1=Slot3)

Direct Color Bitmap BG, and Direct Color Bitmap OBJ
BG/OBJ Supports 32K colors (15bit RGB value) - so far same as GBAs BG.
However, the upper bit (Bit15) is used as Alpha flag. That is, Alpha=0=Transparent, Alpha=1=Normal (ie. on the NDS, Direct Color values 0..7FFFh are NOT displayed).

Unlike GBA bitmap modes, NDS bitmap modes are supporting the Area Overflow bit (BG2CNT and BG3CNT, Bit 13).


DS Video OBJs

DS OBJ Priority
The GBA has been assigning OBJ priority in respect to the 7bit OAM entry number, regardless of the OBJs 2bit BG-priority attribute (which allowed to specify invalid priority orders). That problem has been fixed in DS mode by combining the above two values into a 9bit priority value.

OBJ Tile Mapping (DISPCNT.4,20-21):
  Bit4  Bit20-21  Dimension Boundary Total ;Notes
  0     x         2D        32       32K   ;Same as GBA 2D Mapping
  1     0         1D        32       32K   ;Same as GBA 1D Mapping
  1     1         1D        64       64K
  1     2         1D        128      128K
  1     3         1D        256      256K  ;Engine B: 128K max
TileVramAddress = TileNumber * BoundaryValue
Even if the boundary gets changed, OBJs are kept composed of 8x8 tiles.

Bitmap OBJ Mapping (DISPCNT.6,5,22):
Bitmap OBJs are 15bit Direct Color data, plus 1bit Alpha flag (in bit15).
  Bit6 Bit5 Bit22 Dimension    Boundary   Total ;Notes
  0    0    x     2D/128 dots  8x8 dots   128K  ;Source Bitmap width 128 dots
  0    1    x     2D/256 dots  8x8 dots   128K  ;Source Bitmap width 256 dots
  1    0    0     1D           128 bytes  128K  ;Source Width = Target Width
  1    0    1     1D           256 bytes  256K  ;Engine A only
  1    1    x     Reserved
In 1D mapping mode, the Tile Number is simply multiplied by the boundary value.
  1D_BitmapVramAddress = TileNumber(0..3FFh) * BoundaryValue(128..256)
  2D_BitmapVramAddress = (TileNo AND MaskX)*10h + (TileNo AND NOT MaskX)*80h
In 2D mode, the Tile Number is split into X and Y indices, the X index is located in the LSBs (ie. MaskX=0Fh, or MaskX=1Fh, depending on DISPCNT.5).

OBJ Attribute 0 and 2
Setting the OBJ Mode bits (Attr 0, Bit10-11) to a value of 3 has been prohibited in GBA, however, in NDS it selects the new Bitmap OBJ mode; in that mode, the Color depth bit (Attr 0, Bit13) should be set to zero; also in that mode, the color bits (Attr 2, Bit 12-15) are used as Alpha-OAM value (instead of as palette setting).

OBJ Vertical Wrap
On the GBA, a large OBJ (with 64pix height, scaled into double-size region of 128pix height) located near the bottom of the screen has been wrapped to the top of the screen (and was NOT displayed at the bottom of the screen).
This problem has been "corrected" in the NDS (except in GBA mode), that is, on the NDS, the OBJ appears BOTH at the top and bottom of the screen. That isn't necessarily better - the advantage is that one can manually enable/disable the OBJ in the desired screen-half on IRQ level; that'd be required only if the wrapped portion is non-transparent.


DS Video Extended Palettes

Extended Palettes
When allocating extended palettes, the allocated memory is not mapped to the CPU bus, so the CPU can access extended palette only when temporarily de-allocating it.

Color 0 of all standard/extended palettes is transparent, color 0 of BG standard palette 0 is used as backdrop. extended palette memory must be allocated to VRAM.

BG Extended Palette enabled in DISPCNT Bit 30, when enabled,
 standard palette --> 16-color tiles (with 16bit bgmap entries) (text)
                      256-color tiles (with 8bit bgmap entries) (rot/scal)
                      256-color bitmaps
                      backdrop-color (color 0)
 extended palette --> 256-color tiles (with 16bit bgmap entries)(text,rot/scal)
Allocated VRAM is split into 4 slots of 8K each (32K used in total), normally BG0..3 are using Slot 0..3, however BG0 and BG1 can be optionally changed to BG0=Slot2, and BG1=Slot3 via BG0CNT and BG1CNT.

OBJ Extended Palette enabled in DISPCNT Bit 31, when enabled,
 16 colors x 16 palettes --> standard palette memory (=256 colors)
 256 colors x 16 palettes --> extended palette memory (=4096 colors)
Extended OBJ palette memory must be allocated to VRAM F, G, or I (which are 16K) of which only the first 8K are used for extended palettes (=1000h 16bit entries).


DS Video Capture and Main Memory Display Mode

4000064h - NDS9 - DISPCAPCNT - 32bit - Display Capture Control Register (R/W)
Capture is supported for Display Engine A only.
  0-4   EVA               (0..16 = Blending Factor for Source A)
  5-7   Not used
  8-12  EVB               (0..16 = Blending Factor for Source B)
  13-15 Not used
  16-17 VRAM Write Block  (0..3 = VRAM A..D) (VRAM must be allocated to LCDC)
  18-19 VRAM Write Offset (0=00000h, 0=08000h, 0=10000h, 0=18000h)
  20-21 Capture Size      (0=128x128, 1=256x64, 2=256x128, 3=256x192 dots)
  22-23 Not used
  24    Source A          (0=Graphics Screen BG+3D+OBJ, 1=3D Screen)
  25    Source B          (0=VRAM, 1=Main Memory Display FIFO)
  26-27 VRAM Read Offset  (0=00000h, 0=08000h, 0=10000h, 0=18000h)
  28    Not used
  29-30 Capture Source    (0=Source A, 1=Source B, 2/3=Sources A+B blended)
  31    Capture Enable    (0=Disable/Ready, 1=Enable/Busy)
Notes:
VRAM Read Block (VRAM A..D) is selected in DISPCNT Bits 18-19.
VRAM Read Block can be (or must be ?) allocated to LCDC (MST=0).
VRAM Read Offset is ignored (zero) in VRAM Display Mode (DISPCNT.16-17).
VRAM Read/Write Offsets wrap to 00000h when exceeding 1FFFFh (max 128K).
Capture Sizes less than 256x192 capture the upper-left portion of the screen.
Blending factors EVA and EVB are used only if "Source A+B blended" selected.
After setting the Capture Enable bit, capture starts at next line 0, and the capture enable/busy bit is then automatically cleared (in line 192, regardless of the capture size).

Capture data is 15bit color depth (even when capturing 18bit 3D-images).
Capture A: Dest_Intensity = SrcA_Intensitity ; Dest_Alpha=SrcA_Alpha.
Capture B: Dest_Intensity = SrcB_Intensitity ; Dest_Alpha=SrcB_Alpha.
Capture A+B (blending):
 Dest_Intensity = (  (SrcA_Intensitity * SrcA_Alpha * EVA)
                   + (SrcB_Intensitity * SrcB_Alpha * EVB) ) / 16
 Dest_Alpha = (SrcA_Alpha AND (EVA>0)) OR (SrcB_Alpha AND EVB>0))

Capture provides a couple of interesting effects.
For example, 3D Engine output can be captured via source A (to LCDC-allocated VRAM), in the next frame, either Graphics Engine A or B can display the captured 3D image in VRAM image as BG2, BG3, or OBJ (from BG/OBJ-allocated VRAM); this method requires to switch between LCDC- and BG/OBJ-allocation.
Another example would be to capture Engine A output, the captured image can be displayed (via VRAM Display mode) in the following frames, simultaneously the new Engine A output can be captured, blended with the old captured image; in that mode moved objects will leave traces on the screen; this method works with a single LCDC-allocated VRAM block.
DS Video Display System Block Diagram

4000068h - NDS9 - DISP_MMEM_FIFO - 32bit - Main Memory Display FIFO (R?/W)
Intended to send 256x192 pixel 32K color bitmaps by DMA directly
 - to Screen A             (set DISPCNT to Main Memory Display mode), or
 - to Display Capture unit (set DISPCAPCNT to Main Memory Source).
The FIFO can receive 4 words (8 pixels) at a time, each pixel is a 15bit RGB value (the upper bit, bit15, is unused).
Set DMA to Main Memory mode, 32bit transfer width, word count set to 4, destination address to DISP_MMEM_FIFO, source address must be in Main Memory.
Transfer starts at next frame.
Main Memory Display/Capture is supported for Display Engine A only.


DS Video Display System Block Diagram
             _____________               __________
  VRAM A -->| 2D Graphics |--------OBJ->|          |
  VRAM B -->| Engine A    |--------BG3->| Layering |
  VRAM C -->|             |--------BG2->| and      |
  VRAM D -->|             |--------BG1->| Special  |
  VRAM E -->|             |   ___       | Effects  |
  VRAM F -->|             |->|SEL|      |          |          ______
  VRAM G -->| - - - - - - |  |BG0|-BG0->|          |----o--->|      |
            | 3D Graphics |->|___|      |__________|    |    |Select|
            | Engine      |                             |    |Video |
            |_____________|--------3D----------------.  |    |Input |
             _______      _______              ___   |  |    |      |
            |       |    |       |<-----------|SEL|<-'  |    |and   |-->
            |       |    |       |    _____   |A  |     |    |      |
  VRAM A <--|Select |    |Select |   |     |<-|___|<----'    |Master|
  VRAM B <--|Capture|<---|Capture|<--|Blend|   ___           |Bright|
  VRAM C <--|Dest.  |    |Source |   |_____|<-|SEL|<----.    |A     |
  VRAM D <--|       |    |       |            |B  |     |    |      |
            |_______|    |_______|<-----------|___|<-.  |    |      |
             _______                                 |  |    |      |
  VRAM A -->|Select |                                |  |    |      |
  VRAM B -->|Display|--------------------------------o------>|      |
  VRAM C -->|VRAM   |                                   |    |      |
  VRAM D -->|_______|   _____________                   |    |      |
                       |Main Memory  |                  |    |      |
  Main   ------DMA---->|Display FIFO |------------------o--->|______|
  Memory               |_____________|
             _____________               __________           ______
  VRAM C -->| 2D Graphics |--------OBJ->| Layering |         |      |
  VRAM D -->| Engine B    |--------BG3->| and      |         |Master|
  VRAM H -->|             |--------BG2->| Special  |-------->|Bright|-->
  VRAM I -->|             |--------BG1->| Effects  |         |B     |
            |_____________|--------BG0->|__________|         |______|


DS Files - 2D Video

eg. used in DSi Launcher "rom:\layout\cmn\launcher_d.szs\.."
http://www.romhacking.net/documents/[469]nds_formats.htm

 ____________________________ Nitro Color Palette _____________________________

Header
  000h 4    Chunk ID "RLCN" (aka NCLR backwards, Nitro Color Resource)
  004h 2    Byte Order    (FEFFh)
  006h 2    Version       (0100h)
  008h 4    Total Filesize
  00Ch 2    Offset to "TTLP" Chunk, aka Size of "RLCN" Chunk (0010h)
  00Eh 2    Total number of following Chunks (1=TTLP) (or 2=TTLP+PMCP ?)

TTLP Chunk
  000h 4    Chunk ID "TTLP" (aka PLTT backwards, Palette data)
  004h 4    Chunk Size (eg. 0218h)
  008h 4    Reportedly Color Depth (ie. "tile usage info") (3=4bpp, 4=8bpp)
  00Ch 4    Zero
  010h 4    Palette Data Size in bytes (eg. 200h) (or 200h-N? no, blah!)
  014h 4    Offset from TTLP+8 to Palette Data? (always 10h)
  018h N*2  Palete Data (16bit colors, 0000h..7FFFh)
Most DSi titles use full 200h-byte palettes (Paper Plane has a smaller one in Graphics.NARC\Seq\pause.zcl). There seem to be no DSi titles with PMCP chunks.

PMCP Chunk (if any) (reportedly exists, but not in DSi Launcher...?)
  000h 4    Chunk ID "PMCP" (aka PCMP backwards, Palette CMP?)
  004h 4    Chunk Size (reportedly always 12h ???)
  008h 2    Number of palettes in file (uh?)
  00Ah 2    Unused (BEEFh=Bullshit)
  00Ch 4    Offset from PMCP+8 to Palette IDs? (always 08h)
  DATA N*2  "Palette ID numbers for each palette (starting from 0)"

 ___________________________ Nitro Character Tiles ____________________________

  eg. DSi Launcher "rom:\debug\DebugFont.NCGR"         -- with SOPC chunk
  eg. DSi Launcher "rom:\layout\cmn\launcher_d.szs\.." -- without SOPC chunk

Header
  000h 4    Chunk ID "RGCN" (aka NCGR backwards, Nitro Char Graphics Resource)
  004h 2    Byte Order    (FEFFh)
  006h 2    Version       (0101h) (unknown if 0100h does also exist?)
  008h 4    Total Filesize
  00Ch 2    Offset to "RAHC" Chunk, aka Size of "RGCN" Chunk (0010h)
  00Eh 2    Total number of following Chunks (1=RAHC, or 2=RAHC+SOPC)

RAHC Chunk
  000h 4    Chunk ID "RAHC" (aka CHAR backwards)
  004h 4    Chunk Size (eg. 1420h)
  008h 2    Tile Data Size in Kilobytes   ;\or both set to FFFFh
  00Ah 2    Unknown (always 20h)          ;/(when size<>N*1024)
  00Ch 4    Color Depth (3=4bpp, 4=8bpp)
  010h 2    Zero   ;or 10h (when SOPC not exists? kbyte size rounded up?)
  012h 2    Zero   ;or 20h (when SOPC not exists?)
  014h 4    Zero
  018h 4    Tile Data Size in Bytes (eg. 1400h)
  01Ch 4    Offset from RAHC+8 to Tile Data?  ;=always 18h
  020h ...  Tile Data (eg. 20h-byte zerofilled for 4bpp SPC char?)
Nonzero [10h,12h] spotted in Paper Plane "rom:\Graphics.NARC\Plane\plane.zcg".

SOPC Chunk (only present if Tile Data size is N*1024 bytes)
  000h 4    Chunk ID "SOPC" (aka CPOS backwards)
  004h 4    Chunk Size (10h)
  008h 4    Zero
  00Ch 2    Same as [00Ah] in RAHC chunk? (always 20h)
  00Eh 2    Same as [008h] in RAHC chunk? (size in kilobytes)

 __________________________ Unknown Character Tiles ___________________________

Apart from above NCGR, there is reportedly another tile format:
  NCGR (Nitro Character Graphic Resource) - Graphical Tiles --> see above
  NBGR (Nitro Basic Graphic Resource)     - Graphical Tiles --> what ???
If it does really exist for real... the header ID might be "RGBN" (aka NBGR backwards), and file extension might be NBGR? But even if so, it's unknown if/when/where/why that NBGR format is used. If the "B" is for "Basic" then might have less features than NCGR, or maybe it might be "B" for non-tiled Bitmaps, or whatever?

 ___________________________ Nitro BG Maps Screens ____________________________

Header
  000h 4    Chunk ID "RCSN" (aka NSCR backwards, Nitro Screen Resource)
  004h 2    Byte Order    (FEFFh)
  006h 2    Version       (0100h)
  008h 4    Total Filesize
  00Ch 2    Offset to "NRCS" Chunk, aka Size of "RCSN" Chunk (0010h)
  00Eh 2    Total number of following Chunks (1=NRCS)

NRCS Chunk
  000h 4    Chunk ID "NRCS" (aka SCRN backwards, Screen)
  004h 4    Chunk Size
  008h 4    Screen Width in pixels
  00Ah 2    Screen Height in pixels
  00Ch 4    Zero
  010h 4    Screen Data Size (width/8)*(height/8)*2
  014h N*2  Screen Data (16bit BG Map entries, palette+xyflip+tileno)

 ____________________________ Nitro OBJ Animations ____________________________

Header
  000h 4    Chunk ID "RNAN" (aka NANR backwards, Nitro Animation Resource)
  004h 2    Byte Order    (FEFFh)
  006h 2    Version       (0100h)
  008h 4    Total Filesize
  00Ch 2    Offset to "KNBA" Chunk, aka Size of "RNAN" Chunk (0010h)
  00Eh 2    Total number of following Chunks (1=KNBA, or 3=KNBA+LBAL+TXEU)
One chunk exists in DSi Launcher
Three chunks exist in DSi Flipnote "rom:ManualData.Eu\md2res_narc.blz\data\obj

KNBA Chunk
  000h 4    Chunk ID "KNBA" (aka ABNK backwards, Animation Bank)
  004h 4    Chunk Size (always padded to 4-byte boundary if LABL chunk follows)
  008h 2    Number of 16-byte Animation Blocks ;implies NumLabels in LABL chunk
  00Ah 2    Number of 8-byte Frame Blocks
  00Ch 4    Offset from KNBA+8 to Animation Blocks ;=18h
  010h 4    Offset from KNBA+8 to Frame Blocks     ;=[0Ch]+[08h]*10h
  014h 4    Offset from KNBA+8 to Frame Data       ;=[10h]+[0Ah]*8
  018h 8    Zero
  DATA ..   Animation Blocks (16-byte entries)
   00h 4      Number of Frames
   04h 2      Unknown        (0)
   06h 2      Unknown Always (1)   ;reportedly "always unknown"
   08h 4      Unknown        (1..2)
   0Ch 4      Offset from FrameBlock+0 to First Frame
  DATA ..   Frame Blocks (8-byte entries)
   00h 4      Offset from FrameData+0 to whatever?   (always 4-byte aligned?)
   04h 2      Frame Width   ;3Ch or 01..06h   ;Time in 60Hz units? num meta's?
   06h 2      Unused (usually 0000h, or BEEFh=Bullshit)
  DATA ..   Frame Data (2-byte entries)
   00h 2      Unknown 16bit values? (maybe CELL index or whatever??)  (CCCCh=?)

LBAL Chunk
  000h 4    Chunk ID "LBAL" (aka LABL backwards, Labels)
  004h 4    Chunk Size (not padded to 4-byte size, following TXEU is unaligned)
  008h 4*N  Offsets from LabelArea+0 to Labels (for each Animation Block)
  ...  ..   Label Area (ASCII Strings, terminated by 00h)
The LabelArea starts at LBAL+8+NumLabels*4 (whereas, NumLabels is found in KNBA chunk).

TXEU Chunk
Caution: Not 4-byte aligned (the preceeding LBAL chunk can have odd size).
  000h 4    Chunk ID "TXEU" (aka UEXT backwards, Whatever Extension or so?)
  004h 4    Chunk Size (0Ch)
  008h 4    Unknown (usually 0) (reportedly 0 or 1)

 __________________________ Nitro OBJ Metatile Cells __________________________

Header
  000h 4    Chunk ID "RECN" (aka NCER backwards, Nitro Cell Resource)
  004h 2    Byte Order    (FEFFh)
  006h 2    Version       (0100h)
  008h 4    Total Filesize
  00Ch 2    Offset to "KBEC" Chunk, aka Size of "RECN" Chunk (0010h)
  00Eh 2    Total number of following Chunks (1=KBEC, or 3=KBEC+LBAL+TXEU)

KBEC Chunk
  000h 4    Chunk ID "KBEC" (aka CEBK backwards, Cell Bank)
  004h 4    Chunk Size (always padded to 4-byte boundary if LABL chunk follows)
  008h 2    Number of Metatiles
  00Ah 2    Metatiles Entry Size (0=Normal 8 bytes, 1=Extended 16 bytes)
              (DSi Launcher ..layout\cmn\launcher_u\.. uses 16-byte size)
  00Ch 4    Offset from KBEC+8 to Metatile Table? (18h)
  010h 4    Boundary Size (?)       (but is ZERO in layout\cmn\launcher_u\)
               "Specifies the area in which the image can be drawn,
               multiplied by 64, ie. 2 means that the area is 128x128 pixels."
  014h 0Ch  Zero
  020h ..   Metatile Table (8 bytes each) (or 16 bytes)
  ...  ..   OBJ Attribute Table (6-bytes each)
Metatile Table entries are (8-byte or 16-byte):
  000h 2    Number of OBJs
  002h 2    Unknown
  004h 4    OBJ Data Offset (from begin of OBJ Attr Table)
 (008h 2)   Unknown (can be 02h,10h,48h,74h)
 (00Ah 2)   Unknown (can be 08h)
 (00Ch 2)   Unknown (can be FFA0h..FFF0h) ;\maybe extra coordinate offsets?
 (00Eh 2)   Unknown (can be FFF0h..FFF9h) ;/
OBJ Attribute Table...
  starts at Number of Cells * 8 | each cell is made up of 6 bytes)
The 6-byte OBJ Attributes seem to be in normal OAM format, containing the coordinates, tile number, tile size, and other flags (however, the coordinates contain signed values; ie. one needs to add the current OBJ position to those values). For details on the OBJ Attributes, see:
LCD OBJ - OAM Attributes

LBAL and TEXU Chunks (if any)
Same as in Animation files (see there). In fact, the content seems to be SAME as the corresponding Animation file (for pairs of filename.NANR and filename.NCER), and the number of labels must be obtained from the NANR file's KNBA chunk (as such, it's rather useless to have LBAL in NCER files, except perhaps for error checking that the correct file pair was loaded).

Note: DSi Launcher layout\cmn\logodemo.szs has KBEC Chunk Size 2B6h (although the filesize is padded as if it were 2B8h bytes) (the file has no LBAL chunk, so it's unclear if/how it were aligned if present).

 ____________________________ Nitro Unknown Files  ____________________________

DSi Deep Psyche has two extra file types:
  .NMAR file (with "RAMN" header ID, and "KNBA"+"LBAL" chunks)
  .NMCR file (with "RCMN" header ID, and "KBCM" chunk)
The purpose is unknown, but they are probably also animating something...
  OBJ with 16bit x/y (instead 9bit/8bit)?
  OBJ with fractional x/y-stepping (moving/motion)?
  OBJ rotation/scaling?
  BG scroll offsets?
  BG tile replacement?
Going by the filename (a01_obj01.NMAR) they seem to be OBJ related. Labels include things like "a01_upNN" and "a01_windowNN".
The chunks seem to resemble those in RNAN/RECN files (Animation+Cells). Except, the KBCM has 8-byte entries (unlike the 6-byte ones in KBEC):
  000h 2    Unknown (000xh..007Ah, maybe time or so?)
  002h 2    Unknown (signed 16bit?)
  004h 2    Unknown (signed 16bit?)
  006h 2    Unknown (0x21h, with x=0..8)

 _________________________ Nitro More Unknown Files  __________________________

Some 2D folders contain more unknown files (eg. DSi Camera "rom:layout\cmn\fusion_camera.szs"):

JNBL (whatever, with .bnbl extension)
  000h 4     ID "JNBL"
  004h 2     Zero
  006h 2     Number of 6-byte entries (01h or more)
  008h N*6   Unknown

JNCL (whatever, with .bncl extension)
  000h 4     ID "JNCL"
  004h 2     Zero (0000h)
  006h 2     Number of 8-byte entries (01h or more)
  008h N*8   Unknown (eg. 80h,10h,C0h,20h,00h,00h,00h,00h)

JNLL (whatever, with .bnll extension)
  000h 4     ID "JNLL"
  004h 2     Zero (0000h)
  006h 2     Number of 16-byte entries (01h or more)
  008h N*16  Unknown (eg. 80h,50h,60h,10h,7Ch,29h,FFh,FDh,0Dh,19h,0,0,0,0,0,0)

BNGL (whatever, with .bngl extension)
  000h 4   ID "BNGL"   ;this same as file extension (not JNGL)
  004h 2   Zero (0000h)
  006h 2   Number of ?-byte entries (01h or more)
  008h 2   Unknown (can be 02h,04h,06h,0Ah)
  00Ah 2   Number of ?-byte other entries maybe (01h or more)
  ...
  ...      Entries?
  ...      Other Entries?
  ...      Maybe More Other Entries?
Filesize can range from 18h bytes to 24Ah bytes (or maybe yet smaller/biggger).

 ______________________________ .ntft and .ntfp _______________________________

.ntft file
Texture data (maybe for use as extra 2D layer), size is usually/always a power of 2 (ranging from 80h bytes to at least 64Kbytes (or even 512Kbytes?). Color depth can be 16bit or 8bit (and maybe less). Files with less than 16bit are bundled with a .ntfp palette file.

.ntfp file
Texture palette, with 16bit color numbers. The files can be quite small (eg. only 6 or 8 bytes).

 ______________________________ .wmif and .wmpf _______________________________

DSi Sudoku rom:\Textures\ has "Wild Magic" .wmif and .wmpf (image+palette) files.

.wmif file
  000h 1Bh  ID "Wild Magic Image File 3.00",00h
  01Bh 4    Palette Filename Length (eg. 0Dh)
  01Fh LEN  Palette Filename        (eg. "BG_Board.wmpf")
  ...  4    Texture Format (5=2bpp, 6=4bpp, 7=8bpp) (non-standard numbering)
  ...  4    Texture Width in pixels
  ...  4    Texture Height in pixels
  ...  ..   Texture data (vertically mirrored, starting with lower line)

.wmpf file
  000h 1Dh  ID "Wild Magic Palette File 1.00",00h
  01Dh 4    Zero?
  021h 4    Number of Colors
  025h ..   Colors, 16bit (0000h..7FFFh)

 _______________________________ .ntf and .xtf ________________________________

Walk with Me - Simple Texture (*.ntf)
  000h 4    Unknown, ID?     (always 0Ch)
  004h 4    Unknown, ID?     (always 01h) (maybe num textures, aa in .xtf ?)
  008h 2    Width in pixels  (usually 8 SHL W)
  00Ah 2    Height in pixels (usually 8 SHL H)
  00Ch 2    Width shift      (W)
  00Eh 2    Height shift     (H)
  010h 4?   Texture Format   (1..7)
  014h 4    Bitmap Size      (Width*Height*bpp/8)
  018h 4    Palette Size     (NumColors*2)
  01Ch 4    Unknown (0)
  020h ..   Bitmap Data
  ...  ..   Palette Data

Walk with Me - Extended Texture Archive (*.xtf)
  000h 4     Offset to Texture part
  004h 4     Number of Whatever (N)                     ;\
  008h 4     Unknown (0Ch)                              ; Attributes?
  00Ch N*8   Whatever List (CCCC00xxh,Offset)           ;
  ...  N*var Whatever Entries ...                       ;/
  ...  4     Unknown (08h)                              ;\
  ...  4     Number of Texture Blocks (1 or more)       ; Texture part
  ...  ..    Texture Block(s)                           ;/
 Texture Block:
  000h 2     Width           (usually 8 SHL W)  ;\
  002h 2     Height          (usually 8 SHL H)  ;
  004h 2     Width shift     (W)                ;
  006h 2     Height shift    (H)                ; one or more such blocks
  008h 4?    Texture Format  (1..7)             ;
  00Ch 4     Bitmap Size  (Width*Height*bpp/8)  ; (about same as in .ntf files)
  010h 4     Palette Size (NumColors*2)         ;
  014h 4     Unknown (0)                        ;
  018h ..    Bitmap Data                        ;
  ...  ..    Palette Data                       ;/

 ____________________________________ TEX. ____________________________________

Nanostray TEX.
  000h 4    ID ("TEX.")
  004h 4    Texture Format   (1..7)
  008h 4    Width shift      (W)
  00Ch 4    Height shift     (H)
  010h 4    Usually zero (or, 1 in menu\planet_a\waterplanet.tex) (color0 ?)
  014h 4    Width in pixels  (usually 8 SHL W)
  018h 4    Height in pixels (usually 8 SHL H, or sometimes less than 8 SHL H)
  01Ch 4    Compressed Palette Offset (34h)
  020h 4    Compressed Palette Size in bytes
  024h 4    Unknown Offset? (usually/always same as [02Ch])
  028h 4    Unknown Size?   (usually/always 0=None)
  02Ch 4    Compressed Bitmap Offset
  030h 4    Compressed Bitmap Size in bytes
  034h ..   Compressed Palette Data
  ...  ..   Compressed Bitmap Data
 The Compressed Data blocks look as so:
  000h 1    Compression Method (00h=Stored/uncompressed, 10h=LZSS/compressed)
  001h 3    Uncompressed Size
  004h ..   Compressed Data
  ...  ..   Padding to 4-byte boundary
 The bitmap is stored in some files, and compressed in other files.
 The palette is usually/always stored.

 __________________________________ PMB+TTLP __________________________________

Cooking Coach PMB (rom:\2d\bitmap\*)
  000h 4    ID (" PMB") (aka BMP backwards)
  004h 4    Compressed Bitmap Size in bytes (can be odd, footer is unaligned)
  008h ..   Compressed Bitmap (LZSS) (10h,size(24bit),compressed data)
  ..   2    Bitmap Width  (100h)
  ..   2    Bitmap Height (C0h)
  ..   4    Palette Filename length
  ...  ..   Palette Filename ("2d/palette/name", without any trailing zero)

Cooking Coach TTLP (rom:\2d\palette\*)
  000h 4    ID ("TTLP") (aka PLTT backwards)
  004h 4    Palette Size in bytes
  008h ..   Palette (uncompressed, 16bit entries)

 ____________________________________ NTFA ____________________________________

NTFA
Reportedly used by Nintendo Spot series for the whole menu (=for what?) (=DS Station downloads for DSi Nintendo Zone and/or DS Download Play?).
The whole file is LZSS compressed (sometimes compression isn't used, but usually only very small NTFA files are not compressed).
  000h 4   Maybe Header Size (maybe 1Ch or so?)
  004h 8   ID "NTFA0000"
  00Ch 2   Color 0 Transparency (0=Solid, Nonzero=Transparent)
  00Eh 2   Color Depth (3=4bpp, 4=8bpp)
  010h 2   Bitmap Width
  012h 2   Bitmap Height
  014h 4   Bitmap Offset  (maybe 1Ch+NumColors*2 ?)
  018h 4   Palette Offset (maybe 1Ch or so?)
  ...  N*2 Palette Data (RGB555)
  ...  ..  Bitmap Data
The number of palette entries can be determined by subtracting image offset by palette offset, and dividing the result by 2.
The palette is RGB15. The image is non-tiled.


DS Files - 3D Video

Some NDS games are using the following set of files for 3D Models:
DS Files - 3D Video BMD0 (.NSBMD Model Data)
DS Files - 3D Video BTX0 (.NSBTX Texture Data)
DS Files - 3D Video BCA0 (.NSBCA Character Skeletal Animation)
DS Files - 3D Video BTA0 (.NSBTA Texture Coordinate Animation)
DS Files - 3D Video BTP0 (.NSBTP Texture Pattern Animation)
DS Files - 3D Video BMA0 (.NSBMA Material Animation)
DS Files - 3D Video NVA0 (.NSBVA Unknown Vis Animation)
The format was used in Nintendo's own titles somewhere between 2005 and 2009 (older launch titles did use an older .bin or .bxx format instead of .nsbxx format, and later mini-games often don't support 3D video at all, and third-party games tend to use their own formats). Some known titles that do use .nsbxx are:
  type BMD0/BCA0/BTA0/BTX0/BTP0/BMA0 is used by Mariokart DS (2005)
  type BMD0/BCA0/BTA0 is used by Walk with Me (2008-2009)
  type BVA0 is used by what... if it was ever used?
Note: The format resembles the later CGFX format used on 3DS.

Dict - Directory with Name/Data (used in various places in 3D video files)
  000h 1     Dummy (00h)
  001h 1     Number of entries (N)
  002h 2     Size of whole Dict (Hdr(8)+Tree(4+X*4)+Data(4+N*siz)+Name(N*10h))
  004h 2     Offset to Tree Section (always 08h)
  006h 2     Offset to Data Section (0Ch+X*4)
  008h 4     Tree entry 0    (Patricia Tree Root entry)                 ;\Tree
  00Ch X*4   Tree entry 1..X (Patricia Tree and actual Names/Data)      ;/
  ...  2     Size of each Data entry (siz) (usually 4 or 8)             ;\
  ...  2     Size of this Data Info Section (4+N*siz)                   ; Data
  ...  N*siz Data (siz bytes, for each entry)                           ;/
  ...  N*10h Name Strings (10h-byte ASCII, zeropadded, for each entry)  ;-Names
Patricia Tree Root entry:
  000h 1     Patricia Tree First Bit-number (always 7Fh=Last=char[0Fh].bit7)
  001h 1     Patricia Tree First entry (1..X) (usually points to rightmost bit)
  002h 2     Patricia Tree Unused (zerofilled)
Patricia Tree entry 1..X format:
  000h 1     Patricia Tree Bit-number to be tested (0=Bit0 of 1st char)
  001h 1     Patricia Tree Next entry when test=0  ;\upon match: Next=Curr
  002h 1     Patricia Tree Next entry when test=1  ;/upon error: Next=0
  003h 1     Entry number in Data and Name tables (used when Next=Curr entry)
The Patricia Tree is intended for searching Symbols by testing a few bits (without comparing all characters).
The Data content depends on what the Dict is used for. Each name can have a small amount of data stored inside of the Dict (and, that Data may contain offsets to larger data stored elsewhere).

References
https://github.com/scurest/nsbmd_docs/blob/master/nsbmd_docs.txt
Errata:
  3D Video Container/Headers have version=1 (except: BMD0 has version=2)
  BoundingBox seems to have "origin/size" values (not "min/max" values)
  SHININESS is a 128-byte array, that's definietly not encoded in 4-byte entry
  Material seems to contain OR-mask and AND-mask values for POLYGON_ATTR ?
  Material can have further parameters, in the TODO part?
  MaterialIdxList offsets are relative to Model[008h], not to MaterialIdxList
  Pivot should use C=B and D=A (not C=A and D=B) for sine/cosine rotations?
  BasisMatrix description could be simplified, and are the unknown 2bit used?
  Animations have IDs "J.AC","M.AT", "M.PT", "M.AM" (with "."=00h)
  Dict's (aka NameList's) contain Patricia Trees for fast lookup (alike 3DS)
  SRT0 does "Texture Coordinate Animation" (not "Material Animation")
  SRT0 probably supports texture Scale/Rotate/Translate (not just Translate)
  TEX0[04h]=Size of TEX0
  TEX0[18h]=Padding32bit (is MISSING in .txt, insert this after "block1_off")
  TEX0[1Eh]=CompressedTextureDictOffs (alias for TEX[0Eh]=TextureDictOffs)
  Texture[004h] is 11bit width, 11bit height (from TEXIMAGE bits), and bit31=1
  NSBMA files do exists (eg. in Mariokart DS), and could/should be described
  NSBVA files... would be nice to know if they are used by any games?


DS Files - 3D Video BMD0 (.NSBMD Model Data)

BMD0 Header (in .NSBMD files)
  000h 4     ID "BMD0" (Basic Model Data)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (2) (unknown if version 1 did also exist)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=MDL0 or 2=MDL0+TEX0)
  010h 4     Offset from BMD0 to MDL0 Chunk
  014h 4     Offset from BMD0 to TEX0 Chunk (if any)

TEX0 Chunk (if any)
Same as in BTX0 files, see there for details.
DS Files - 3D Video BTX0 (.NSBTX Texture Data)

MDL0 Chunk
  000h 4     Chunk ID "MDL0" (Model Block)
  004h 4     Chunk Size
  008h ..    Model Dict (with 32bit offsets from MDL0 to Models)
  ...  ..    Models

Model
A Model is 3D model. The process of drawing a Model consists of executing a list of RenderCommands, which calculate skinning matrices, set material properties, and draw the individual pieces of the Model (the Meshes).
  000h 4   Size of Model in bytes
  004h 4   Offset from Model to RenderCommandList
  008h 4   Offset from Model to Material info
  00Ch 4   Offset from Model to Dict for Meshes
  010h 4   Offset from Model to InvBindMatrices
  014h 1   Unknown (00h)
  015h 1   Unknown (00h or 01h)
  016h 1   Unknown (00h)
  017h 1   Number of BoneMatrices
  018h 1   Number of Materials
  019h 1   Number of Meshes
  01Ah 2   Unknown (can be ZERO, or same as Number of BoneMatrices?)
  01Ch 4   Scaling Factor for Up Scale command   (fixed point, 1.19.12)
  020h 4   Scaling Factor for Down Scale command (fixed point, 1.19.12)
  024h 2   Number of Vertices
  026h 2   Number of Polygons (Triangles+Quads)
  028h 2   Number of Triangles
  02Ah 2   Number of Quads
  02Ch 2   Bounding Box X-Coordinate   (fixed point, 1.3.12) ;\
  02Eh 2   Bounding Box Y-Coordinate   (fixed point, 1.3.12) ;
  030h 2   Bounding Box Z-Coordinate   (fixed point, 1.3.12) ; for BOX_TEST
  032h 2   Bounding Box X-Size, Width  (fixed point, 1.3.12) ; command
  034h 2   Bounding Box Y-Size, Height (fixed point, 1.3.12) ;
  036h 2   Bounding Box T-Size, Depth  (fixed point, 1.3.12) ;/
  038h 4   Unknown (1000h)  ;\maybe fixed point value 1.0 ?
  03Ch 4   Unknown (1000h)  ;/
  040h ..  Dict for BoneMatrices (with 32bit offsets from 040h to BoneMatrices)
  [04h]   .. RenderCommandList
  [08h]+0 2  Offset from [08h] to Dict for Material-to-Texture Pairings      ;\
  [08h]+2 2  Offset from [08h] to Dict for Material-to-Palette Pairings      ;
  [08h]+4 .. Dict for Materials (with 32bit offsets from [08h] to Materials) ;
  ...     .. Dict for Material-to-Texture Pairings (with 4-byte entries)     ;
  ...     .. Dict for Material-to-Palette Pairings (with 4-byte entries)     ;/
  [0Ch]   .. Dict for Meshes    (with 32bit offsets from [0Ch] to VertexMeshes)
  [10h]   .. InvBindMatrices (54h-byte each)

 _____________________________ RenderCommandList ______________________________

RenderCommandList
The RenderCommandList is a software script for drawing the Model. The list consists of command bytes and parameter bytes, the list is terminated by command 01h.
The commands must be processed by software (they aren't GPU commands). Apart from the commands bytes, the upper 3bit of the command number do contain some parameter bits that affect the behaviour of the command.
  Cmd  Params Description
  00h  0      Nop (no operation?)
  40h  0      Nop (same as above?)
  80h  0      Nop (same as above?)
  01h  0      End of RenderCommandList
  02h  2      Unknown   ;reportedly, params: Node ID, Visibility
  03h  1      Load Matrix from Stack (param=StackIndex)
  04h  1      Bind Material for subsequent Draw command (param=MaterialIndex)
  24h  1      Bind Material (same as above?)
  44h  1      Bind Material (same as above?)
  05h  1      Draw VertexMesh (param=VertexMeshIndex)
  06h  3      Multiply Matrix by BoneMatrix (see below)
  26h  4      Multiply Matrix by BoneMatrix and Store Matrix to Stack
  46h  4      Multiply Matrix by BoneMatrix and Load Matrix from Stack
  66h  5      Multiply Matrix by BoneMatrix and Load/Store Matrix from/to Stack
  07h  1      Unknown
  47h  2?     Unknown (as above? but with 2 params?)
  08h  1      Unknown
  09h  var    Calculate Skinning Equation (see below)
  0Ah  -      Unused?
  0Bh  0      Scale Up   (using the scale factor in Model[01Ch])  ;or "BEGIN"?
  2Bh  0      Scale Down (using the scale factor in Model[020h](  ;or "END"?
  0Ch  2      Unknown
  0Dh  2      Unknown
  0Eh  -      Unused?
  0Fh  -      Unused?
  1xh  -      Unused?

Multiply Current Matrix with Bone Matrix (cmd 06h, 26h, 46h, 66h)
Multiplies the current matrix by a BoneMatrix. This is used to build the local-to-world matrices out of the BoneMatrices.
  bone_idx = next_param     ;index of BoneMatrix         ;1st param
  parent_idx = next_param   ;Parent of the Bone          ;2nd param
  unknown = next_param      ;?                           ;3rd param
  if cmd.bit6 then CurrMatrix = MatrixStack[next_param]  ;4th param (if any)
  CurrMatrix *= BoneMatrices[bone_idx]
  if cmd.bit5 then MatrixStack[next_param] = CurrMatrix  ;Last param (if any)
Note: If bone_idx is the index of bone B, then parent_idx will be the index of the parent of B. "I don't think it's used at all at runtime."

Calculate Skinning Equation (cmd 09h, with 2+N*3 parameters)
This (the "Equation"?) is the matrix applied to a vertex influenced by multiple bones. The inverse bind matrices bring the vertex into the local space of each bone and the local-to-world transforms send it to its world space position.
  CurrMatrix = 0
  store_index = next_param                                     ;1st param
  num_terms = next_param                                       ;2nd param
  loop num_terms times:
    term = MatrixStack[next_param]    ;local-to-world matrix   ;3rd,6th,..
    term *= InvBindMatrices[next_param]                        ;4th,7th,..
    term *= next_param / 256          ;weight                  ;5th,8th,..
    CurrMatrix += term
  MatrixStack[store_index] = CurrMatrix
This command is only used when there are vertices influenced by multiple bones (if a vertex is only influenced by a single bone, then its position will just be stored (in the Mesh) in the space of that bone, so there's no need for an InvBindMatrix to bring it into the correct space).

 _______________________________ InvBindMatrix ________________________________

InvBindMatrix entries
InvBindMatrices are used for computing the skinning matrix via render command 09h.
  000h 30h  Position Matrix (3x4, fixed point 1.19.12) (rotate,scale,translate)
  030h 24h  Vector Matrix   (3x3, fixed point 1.19.12) (rotate only, for light)

 _________________________________ VertexMesh _________________________________

VertexMesh
A Mesh contains actual vertex data in the form of a blob of GPU commands/parameters. To draw a Mesh, you just submit the blob of commands to the GPU's Geometry Command FIFO (GXFIFO).
  000h 2   Dummy
  002h 2   Unknown (0010h, possibly the size of VertexMesh?)
  004h 4   Unknown
  008h 4   Offset from VertexMesh to GXFIFO Command List
  00Ch 4   Size of GXFIFO Command List in bytes
Only certain GPU commands appear in a Mesh. Here is a list:
  00h=NOP, 14h=MTX_RESTORE, 1Bh=MTX_SCALE, 40h=BEGIN_VTXS, 41h=END_VTXS
  20h=COLOR, 21h=NORMAL, 22h=TEXCOORD
  23h=VTX_16, 24h=VTX_10,25h=VTX_XY, 26h=VTX_XZ, 27h=VTX_YZ, 28h=VTX_DIFF

 _________________________________ Materials __________________________________

Material
A Material is a bunch of GPU state (eg. colors, whether backface culling is enabled, etc.) to be set when the Material is bound. It also determines the texture/palette to use, though that isn't stored in this Material object itself.
  000h 2  Dummy (0)
  002h 2  Size of this Material in bytes (002Ch)
  004h 4  Value for DIF_AMB register
  008h 4  Value for SPE_EMI register
  00Ch 4  Value for POLYGON_ATTR register               ;<-- OR value?
  010h 4  Mask for POLYGON_ATTR register (1F3FF8FFh) ?  ;<-- AND value?
  014h 4  Value for TEXIMAGE_PARAMS register (bit16-19 and 30-31, see below)
  018h 4  Unknown (FFFFFFFFh)
  01Ch 4  Unknown (1FCE0000h)
  020h 2  Texture_width
  022h 2  Texture_height
  024h 4  Unknown (00001000h)
  028h 4  Unknown (00001000h)
    XXX above is 2Ch-bytes (other source says "Usually 48 bytes" aka 30h-byte)
    XXX unknown if above can have optionaly extra entries
    XXX reportedly above can optionally contain a texcoord transform matrix?
    XXX unknown if above contains 16bit COLOR (eg. for texture-less polygons)
Only some TEXIMAGE_PARAMS bits are stored here; the others are zeroed out. They are stored in the teximage_params in the Texture object. These two teximage_param u32s are or-ed together to give the final argument to TEXIMAGE_PARAMS. The fields stored here are:
  0-15  Zero in Model/Material (instead, derived from TEX0)
  16    Repeat in S Direction  (0=Clamp Texture, 1=Repeat Texture)
  17    Repeat in T Direction  (0=Clamp Texture, 1=Repeat Texture)
  18    Flip in S Direction    (0=No, 1=Flip each 2nd Texture; requires Repeat)
  19    Flip in T Direction    (0=No, 1=Flip each 2nd Texture; requires Repeat)
  20-29 Zero in Model          (instead, derived from TEX0)
  30-31 Texture Coordinates Transformation Mode (0..3)

4-byte entries in Dict for Material-to-Texture/Palette Pairings
  000h 2  Offset from Model[008h] (?) to List of 8bit Materials Indices
  002h 1  Number of entries in the List of 8bit Materials Indices
  003h 1  Dummy (0)
The Texture/Palette names for different Materials are stored in Dict's with the above 4-byte entries. The assignement is somewhat reversed (normally one would define "Material 5 uses Texture Name 8", but the Dict's are instead defining "Texture Name 8 is used by Material Name 2, 5 and 6").

 ________________________________ BoneMatrices ________________________________

BoneMatrix
A BoneMatrix stores the local-to-parent transform of some bone.
When a Model is animated by an Skeletal Animation, the only thing that changes are its BoneMatrices.
Note: A Model doesn't contain any actual bones or skeleton information (but see the parent_idx parameter to render command 06h); that has all been compiled down to an imperative list of rendering commands that build up all the necessary skinning matrices directly. The BoneMatrices just store the data from the bones that are needed by these rendering commands.
  00h 2   Flags
            0     Disable Translation      (0=Enable, 1=Disable)
            1     Disable Rotation         (0=Enable, 1=Disable)
            2     Disable Scale            (0=Enable, 1=Disable)
            3     Matrix Type for Rotation (0=3x3 Matrix, 1=Pivot Matrix)
            4-7   Rotation Pivot Form    ;\
            8     Rotation Pivot NegI    ; for Pivot Matrix Rotation
            9     Rotation Pivot NegC    ;
            10    Rotation Pivot NegD    ;/
            11-15 Unused (0)
  02h 2   Rotation Matrix m0 (fixed point, 1.3.12) ;-here for alignment reasons
  ... 4   Translation X      (fixed point, 1.19.12) ;\
  ... 4   Translation Y      (fixed point, 1.19.12) ; only if flags.bit0=0
  ... 4   Translation Z      (fixed point, 1.19.12) ;/
  ... 2   Rotation Matrix m1 (fixed point, 1.3.12) ;\
  ... 2   Rotation Matrix m2 (fixed point, 1.3.12) ; only if Flags.bit3=0=3x3
  ... 2   Rotation Matrix m3 (fixed point, 1.3.12) ; and Flags.bit1=0
  ... 2   Rotation Matrix m4 (fixed point, 1.3.12) ;   [ m0 m3 m6 ]
  ... 2   Rotation Matrix m5 (fixed point, 1.3.12) ;   [ m1 m4 m7 ]
  ... 2   Rotation Matrix m6 (fixed point, 1.3.12) ;   [ m2 m5 m8 ]
  ... 2   Rotation Matrix m7 (fixed point, 1.3.12) ;
  ... 2   Rotation Matrix m8 (fixed point, 1.3.12) ;/
  ... 2   Rotation Pivot A   (fixed point, 1.3.12) ;\only if Flags.bit3=1=Pivot
  ... 2   Rotation Pivot B   (fixed point, 1.3.12) ;/ (and Flags.bit1=0?)
  ... 4   Scale X            (fixed point, 1.19.12) ;\
  ... 4   Scale Y            (fixed point, 1.19.12) ; only if Flags.bit2=0
  ... 4   Scale Z            (fixed point, 1.19.12) ;/
The Pivot Matrix can be used for simple rotation around X, Y, or Z axis; see the Skeletal Animation chapter for info on how to convert the Pivot parameters (A, B, Form, NegI, NegC, NegD) into a 3x3 matrix.


DS Files - 3D Video BTX0 (.NSBTX Texture Data)

Contains Texture bitmaps and Palettes. The TEX0 Chunk can exist in .NSBTX Texture files, or in .NSBMD Model files.

BTX0 Header (in .NSBTX files)
  000h 4     ID "BTX0" (Basic Texture)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (1)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=TEX0)
  010h 4     Offset from BTX0 to TEX0 Chunk

TEX0 Chunk (can occur in .NSBTX and .NSBMD files)
  000h  4       Chunk ID "TEX0" (Texture Block)
  004h  4       Chunk Size
  008h  4       Padding (0)
  00Ch  2       Texture Data Size/8                            ;\Texture
  00Eh  2       Texture Dict Offset (03Ch)                     ; (Format 1..4
  010h  4       Padding (0)                                    ; and 6..7)
  014h  4       Texture Data Offset                            ;/
  018h  4       Padding (0)
  01Ch  2       Compressed Texture Data Size/12 (often 0=none) ;\
  01Eh  2       Compressed Texture Dict Offset (03Ch, too)     ; Compressed
  020h  4       Padding (0)                                    ; Texture
  024h  4       Compressed Texture Offset for 4x4-Texel Data   ; (Format 5)
  028h  4       Compressed Texture Offset for 4x4-Texel Attr   ;/
  02Ch  4       Padding (0)
  030h  4       Palette Data Size/8                            ;\
  034h  4       Palette Dict Offset                            ; Palette
  038h  4       Palette Data Offset                            ;/
  [0Eh] ..      Texture Dict (with 8-byte entries, see below)  ;\Dict's
  [34h] ..      Palette Dict (with 4-byte entries, see below)  ;/
  [14h] [0Ch]*8 Texture Data                                   ;\
  [24h] [1Ch]*8 Compressed Texture 4x4-Texel Data (2bpp)       ; VRAM Data
  [28h] [1Ch]*4 Compressed Texture 4x4-Texel Attr (1bpp)       ;
  [38h] [30h]*8 Palette Data Section                           ;/

8-byte entries in Texture Dict:
This Dict is shared for Textures and Compressed Textures (ie. TEX0 entries [00Eh] and [01Eh] do both point to the same Dict).
  000h 4   Value for TEXIMAGE_PARAM register
             0-15   Texture Data       (Offset/8, in File Data / VRAM Data)
             16-19  Zero in TEX0       (instead, derived from Model's Material)
             20-22  Texture S-Size (W) (for W=0..7: Width=(8 SHL W)
             23-25  Texture T-Size (H) (for H=0..7: Height=(8 SHL H)
             26-28  Texture Format     (0..7)
             29     Palette Color 0    (0=Displayed, 1=Made Transparent)
             30-31  Zero in TEX0       (instead, derived from Model's Material)
  004h 4   Width/Height (contains the above 3bit W/H values decoded to 11bit)
             0-10   Width in pixels    (8 shl W) (8..1024)
             11-21  Height in pixels   (8 shl H) (8..1024)
             22-30  Unknown            (0)
             31     Unknown            (1)

4-byte entries in Palette Dict:
  000h 2   Value for PLTT_BASE register
             0-12   Palette Base       (Offset/8, in File Data / VRAM Data)
             13-15  Unused             (0)
  002h 2   Unknown (usually 0, sometimes 1)  ;unrelated to number of colors

Note
The offsets in LSBs of TEXIMAGE_PARAM and PLTT_BASE are relative the begin of the corresponding Data block (and need to be adjusted depending on where the data is stored in VRAM).

Texture/Palette Names
TEX0 has Textures and Palettes are stored in separate Dict's. One could usually guess which Texture belongs to which Palette, but there is no clear naming scheme.
For example, MarioKart DS "rom:\data\Course\mini_stage1Tex.carc\*.nsbtx":
  Texture Name: "MS_ttl_1_2"      ;\both SAME name
  Palette Name: "MS_ttl_1_2"      ;/
  Texture Name: "MS_ttl_3"        ;\palette with extra "_pl" suffix (or "_p")
  Palette Name: "MS_ttl_3_pl"     ;/
  Texture Name: "MS1_11_2"        ;\palette without suffix
  Palette Name: "MS1_11"          ;/
  Texture Name: "nr_space3_2"     ;\palette without prefix
  Palette Name: "space3_2"        ;/


DS Files - 3D Video BCA0 (.NSBCA Character Skeletal Animation)

An Animation is a skeletal animation of a Model. It changes the values of the BoneMatrices in a Model over time. All animations are frame-based, so "time" always means "frame number".

An Animation contains a collection of Tracks. A Track targets one of the BoneMatrices in a Model and tells you what its value should be at each time.

BCA0 Header (in .NSBCA files)
  000h 4     ID "BCA0" (Basic Character Animation)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (1)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=JNT0)
  010h 4     Offset from BCA0 to JNT0 Chunk

JNT0 Chunk
  000h 4     Chunk ID "JNT0" (Joint Block)
  004h 4     Chunk Size
  008h ..    Joint Dict (with 32bit offsets from JNT0 to J.AC)

Joint Animations
  000h 4    ID "J",00h,"AC" (nicknamed "J.AC") (Joint Animation Content ?)
  004h 2    Number of Frames
  006h 2    Number of Tracks (T)
  008h 4    Unknown (3)
  00Ch 4    Offset from J.AC to PivotMatrices
  010h 4    Offset from J.AC to BasisMatrices
  014h 2*T  Offsets from J.AC to AnimationTrack(s)
  ...  ..   Padding to 4-byte boundary (if needed)
  ...  ..   AnimationTrack(s)
  ...  ..   PivotMatrices (06h-bytes each)   ;\used for Rotations
  ...  ..   BasisMatrices (0Ah-bytes each)   ;/(see "Curve" entries)

AnimationTrack
  000h 2    Flags (eg. 3028h)
              0     No Channel
              1-2   No Translation channels    ;why 2bit?
              3     Translation X is constant
              4     Translation Y is constant
              5     Translation Z is constant
              6-7   No Rotation channel        ;why 2bit?
              8     Rotation is constant
              9-10  No Scale channels          ;why 2bit?
              11    Scale X is constant
              12    Scale Y is constant
              13    Scale Z is constant
              14-15 Unknown (0) (unused?)
  002h 1    Dummy (00h)
  003h 1    target_index (the index of the BoneMatrix this track targets?)
  ...  ..   Curve, Translation X   ;\
  ...  ..   Curve, Translation Y   ; only if Flags.bit0=0 and Flags.bit1-2=0
  ...  ..   Curve, Translation Z   ;/
  ...  ..   Curve, Rotation        ;-only if Flags.bit0=0 and Flags.bit6-7=0
  ...  ..   Curve, Scale X         ;\
  ...  ..   Curve, Scale Y         ; only if Flags.bit0=0 and Flags.bit9-10=0
  ...  ..   Curve, Scale Z         ;/

 ___________________________________ Curves ___________________________________

Curve
The format of the Curve entries varies for Translation, Rotation, Scaling, and depends on whether the above Flags entry has Constant=1 (ie. using the same value for all frames).
  When Constant=1 and Translation X/Y/Z:
    000h 4  Translation value (fixed point, 1.19.12)
  When Constant=1 and Rotation:
    000h 2  Matrix Index/Type (bit0-14=Index, bit15=Type: 0=Basis, 1=Pivot)
    002h 2  Unused            (padding for alignment, probably)
  When Constant=1 and Scaling X/Y/Z:
    000h 4  Scaling Value     (fixed point, 1.19.12)
    004h 4  Unknown           (fixed point, 1.19.12)
  When Constant=0:
    000h 4  Frame Info
              bit0-15   Start_frame (start on this frame, step=samplerate)
              bit16-27  End_frame   (up to excluding this frame)
              bit28-29  Width for Scale/Translate (0=32bit, 1=16bit)
              bit30-31  Samplerate (0,1,2,3 = Each 1,2,4,8 frames)
    004h 4  Offset from J.AC to SampledCurve

SampledCurve (when Constant=0)
A sampled curve is always sampled at a fixed rate between two endpoints: one sample is stored at each of the frames
    num_samples=(end_frame-start_frame)/samplerate
  When Translation X/Y/Z, and Width=0:
    000h 4  Sample            (fixed point, 1.19.12)
  When Translation X/Y/Z, and Width=1:
    000h 2  Sample            (fixed point, 1.3.12)
  When Rotation:
    000h 2  Matrix Index/Type (bit0-14=Index, bit15=Type: 0=Basis, 1=Pivot)
  Whan Scaling X/Y/Z, and Width=0:
    000h 4  Sample            (fixed point, 1.19.12)
    004h 4  Unknown           (fixed point, 1.19.12)
  Whan Scaling X/Y/Z, and Width=1:
    000h 2  Sample            (fixed point, 1.3.12)
    002h 2  Unknown           (fixed point, 1.3.12)
The rotation Matrix Index/Type points to a rotation matrix stored in the PivotMatrices or BasisMatrices arrays for this Animation. The highest bit tells you which array it's in, and the low bits give the index into that array.

 ________________________________ PivotMatrix _________________________________

A PivotMatrix encodes a rotation matrix for X, Y, or Z-axis in 6 bytes.
  000h 2  Flags (bit0-3=Form, bit4=NegI, bit5=NegC, bit6=NegD, bit7-15=Unused)
  002h 2  Value A (fixed point, 1.3.12)   ;\usually cos/sin values
  003h 2  Value B (fixed point, 1.3.12)   ;/
To get the whole matrix, set C=A, D=B, I=1.0, negate them if NegC, NegD, NegI are set, then arrange A,B,C,D,I depending on the Form bits:
          [ i 0 0 ]            [ 0 a c ]            [ 0 a c ]
  Form0 = [ 0 a c ]    Form1 = [ i 0 0 ]    Form2 = [ 0 b d ]
  (X)     [ 0 b d ]            [ 0 b d ]            [ i 0 0 ]

          [ 0 i 0 ]            [ a 0 c ]            [ a 0 c ]
  Form3 = [ a 0 c ]    Form4 = [ 0 i 0 ]    Form5 = [ b 0 d ]
          [ b 0 d ]    (Y)     [ b 0 d ]            [ 0 i 0 ]

          [ 0 0 i ]            [ a c 0 ]            [ a c 0 ]
  Form6 = [ a c 0 ]    Form7 = [ 0 0 i ]    Form8 = [ b d 0 ]
          [ b d 0 ]            [ b d 0 ]    (Z)     [ 0 0 i ]
XXX shouldn't that use C=B and D=A for usual sine/cosine rotations?
XXX or does that have rows/columns swapped, to match gbatek notation?
XXX what is the practical use of nine formats? three are for x/y/z axis...
XXX what is the default for NegC, NegD, NegI

 ________________________________ BasisMatrix _________________________________

A BasisMatrix encodes an arbitrary rotation matrix as six 13bit fixed point 1.0.12 values in 10 bytes.
  000h 2  bit3-15=a0.bit0-12, and bit0-2=b2.bit9-11
  002h 2  bit3-15=a1.bit0-12, and bit0-2=b2.bit6-8
  004h 2  bit3-15=a2.bit0-12, and bit0-2=b2.bit3-5
  006h 2  bit3-15=b0.bit0-12, and bit0-2=b2.bit0-2
  008h 2  bit3-15=b1.bit0-12, and bit0=b2.bit12, and bit1-2=unknown?
The remaining three matrix elements are computed as:
  (c0,c1,c2) = (a0,a1,a2) x (b0,b1,b2)  ;cross product
And the rotation matrix is then:
  [ a0  b0  c0 ]
  [ a1  b1  c1 ]
  [ a2  b2  c2 ]
XXX or does that have rows/columns swapped, to match gbatek notation?


DS Files - 3D Video BTA0 (.NSBTA Texture Coordinate Animation)

Allows Texture scrolling... and maybe also texture scale/rotate?

BTA0 Header (in .NSBTA files)
  000h 4     ID "BTA0" (Texture Animation)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (1)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=SRT0)
  010h 4     Offset from BTA0 to SRT0 Chunk

SRT0 Chunk
  000h 4     Chunk ID "SRT0" (maybe short for Scale/Rotate/Translate?)
  004h 4     Chunk Size
  008h ..    Dict (with 32bit offsets from SRT0 to Animations)
  ...  ..    Animation(s)

Animation
  000h 4     ID "M",00h,"AT" (nicknamed "M.AT")
  004h 2     Unknown (can be 3Bh)   ;is that Number of Frames?
  006h 2     Unknown (can be 0)
  008h ..    Dict (with 28h-byte Track entries)
  ...  ..    Key Frames

Track Entries (in Dict)
  000h 8     Channel 0 - unknown, maybe Scale U       ;\
  008h 8     Channel 1 - unknown, maybe Scale V       ; maybe scale/rotate?
  010h 8     Channel 2 - unknown, maybe Rotate Matrix ;/
  018h 8     Channel 3 - Translation U                ;\texture scrolling
  020h 8     Channel 4 - Translation V                ;/

Channel (within Tracks in Dict)
  000h 2     Number of Keyframes (can be 3Bh)
  002h 2     Flags (1000h, 2000h or 3000h) (maybe loop flags and/or rate?)
  004h 4     When Flags=1000h: Offset from "M.AT" to Keyframe(s)
             When Flags=2000h: Unknown (10000000h)   ;\maybe disable, or fixed
             When Flags=3000h: Unknown (1000h or 0)  ;/setting for all frames?

Keyframe Entries
  000h 2     Value (for Translation: fixed point 1.10.5)


DS Files - 3D Video BTP0 (.NSBTP Texture Pattern Animation)

Allows to use different textures/palettes in each frame (ie. to use a short "movie clip" instead of a static "bitmap" as texture).

BTP0 Header (in .NSBTP files)
  000h 4     ID "BTP0" (Texture Pattern Animation)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (1)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=PAT0)
  010h 4     Offset from BTP0 to PAT0 Chunk

PAT0 Chunk
  000h 4     Chunk ID "PAT0" (Pattern Block)
  004h 4     Chunk Size
  008h ..    Dict (with 32bit offsets from PAT0 to Pattern Animations)
  ...  ..    Pattern Animation(s)

Pattern Animation
  000h 4     ID "M",00h,"PT" (nicknamed "M.PT")
  004h 2     Unknown (can be 08h or 32h)   ;rather NOT Number of Frames?
  006h 1     Number of Texture Names (Y)
  007h 1     Number of Palette Names (Z)
  008h 2     Offset from "M.PT" to Texture Names
  00Ah 2     Offset from "M.PT" to Palette Names
  00Ch ..    Dict (with 8-byte Track entries; includes offsets to Key Frames)
  ...  X*4   Key Frames
  ...  Y*10h Texture Names (each 10h-byte ASCII, zeropadded)
  ...  Z*10h Palette Names (each 10h-byte ASCII, zeropadded)

Track Entries (in Dict)
  000h 4     Number of Keyframes
  004h 2     Unknown (1000h or 00F5h) (maybe loop flags and/or framerate etc.)
  006h 2     Offset from "M.PT" to Keyframe(s)

Keyframe Entries
  000h 2     Frame Number (increasing 0000h..NumKeyFrames-1)
  002h 1     Index into Texture Names
  003h 1     Index into Palette Names


DS Files - 3D Video BMA0 (.NSBMA Material Animation)

Allows to animate "Material" whatever that means... maybe colors/lights?

BMA0 Header (in .NSBMA files)
  000h 4     ID "BMA0" (Material Animation)
  004h 2     Byte Order (FEFFh)
  006h 2     Version (1)
  008h 4     Total Filesize
  00Ch 2     Header size, excluding the Chunk offsets (always 10h)
  00Eh 2     Number of chunks (1=MAT0)
  010h 4     Offset from BMA0 to MAT0 Chunk

MAT0 Chunk
  000h 4     Chunk ID "MAT0" (Material Block)
  004h 4     Chunk Size
  008h ..    Dict (with 32bit offsets from PAT0 to Pattern Animations)
  ...  ..    Animation(s)

Animations
  000h 4     ID "M",00h,"AM" (nicknamed "M.AM")
  004h 2     Unknown (can be 5Ah)   ;is that Number of Frames?
  006h 2     Unknown (can be 3)
  008h ..    Dict (with 14h-byte Track entries)
  ...  ..    Key Frames

Track Entries (in Dict)
  000h 2     Unknown (40h)   Offset from "M.AM" to Keyframes        ;\
  002h 1     Unknown (5Ah)   Number of Keyframes (5Ah*2=B4h bytes)  ; ch0
  003h 1     Unknown (0)     Flags                                  ;/
  004h 2     Unknown (F4h)   Offset from "M.AM" to Keyframes        ;\
  006h 1     Unknown (5Ah)   Number of Keyframes (5Ah*2=B4h bytes)  ; ch1
  007h 1     Unknown (0)     Flags                                  ;/
  008h 2     Unknown (0)     Maybe fixed value for all frames?      ;\
  00Ah 1     Unknown (5Ah)   Number of Keyframes                    ; ch2
  00Bh 1     Unknown (20h)   Flags (20h=Fixed/Disabled?)            ;/
  00Ch 2     Unknown (0)     Maybe fixed value for all frames?      ;\
  00Eh 1     Unknown (5Ah)   Number of Keyframes                    ; ch3
  00Fh 1     Unknown (20h)   Flags (20h=Fixed/Disabled?)            ;/
  010h 2     Unknown (1Fh)   Maybe fixed value for all frames?      ;\
  012h 1     Unknown (5Ah)   Number of Keyframes                    ; ch4
  013h 1     Unknown (20h)   Flags (20h=Fixed/Disabled?)            ;/

Keyframe Entries
  000h 2     Unknown


DS Files - 3D Video NVA0 (.NSBVA Unknown Vis Animation)

Allows to do dunno what... maybe animate alpha/transparency?

BVA0 Header (in .NSBVA files)
  000h 4     ID "BVA0" (whatever Vis... Animation?)
  ...  ..    XXX

VIS0 Chunk
  000h 4     Chunk ID "VIS0" (Visibility...?)
  004h 4     Chunk Size
  ...  ..    Unknown


DS 3D Video

DS 3D Overview
DS 3D I/O Map
DS 3D Display Control
DS 3D Geometry Commands
DS 3D Matrix Load/Multiply
DS 3D Matrix Types
DS 3D Matrix Stack
DS 3D Matrix Examples (Projection)
DS 3D Matrix Examples (Rotate/Scale/Translate)
DS 3D Matrix Examples (Maths Basics)
DS 3D Polygon Attributes
DS 3D Polygon Definitions by Vertices
DS 3D Polygon Light Parameters
DS 3D Shadow Polygons
DS 3D Texture Attributes
DS 3D Texture Formats
DS 3D Texture Coordinates
DS 3D Texture Blending
DS 3D Toon, Edge, Fog, Alpha-Blending, Anti-Aliasing
DS 3D Status
DS 3D Tests
DS 3D Rear-Plane
DS 3D Final 2D Output

3D is more or less (about 92%) understood and described.


DS 3D Overview

The NDS 3D hardware consists of a Geometry Engine, and a Rendering Engine.

Geometry Engine (Precalculate coordinates & assign polygon attributes)
Geometry commands can be sent via Ports 4000440h and up (or alternately, written directly to Port 4000400h).
The commands include matrix and vector multiplications, the purpose is to rotate/scale/translate coordinates (vertices), the resulting coordinates are stored in Vertex RAM.
Moreover, it allows to assign attributes to the polygons and vertices, that includes vertex colors (or automatically calculated light colors), texture attributes, number of vertices per polygon (three or four), and a number of flags, these attributes are stored in Polygon RAM. Polygon RAM also contains pointers to the corresponding vertices in Vertex RAM.

Swap Buffers (Pass data from the Geometry Engine to the Rendering Engine)
The hardware includes two sets of Vertex/Polygon RAM, one used by the Geometry Engine, one by the Rendering Engine. The SwapBuffers command simply exchanges these buffers (so the new Geometry Data is passed to the Rendering Engine) (and the old buffer is emptied, so the Geometry engine can write new data to it). Additionally, the two parameter bits from the <previous> SwapBuffers command are copied to the Geometry Engine.
Data that is NOT swapped: SwapBuffers obviously can't swap Texture memory (so software must take care that Texture memory is kept mapped throughout rendering). Moreover, the rendering control registers (ports 4000060h, and 4000330h..40003BFh) are not swapped (so that values must be kept intact during rendering, too).

Rendering Engine (Display Output)
The Rendering Engine draws the various Polygons, and outputs them as BG0 layer to the 2D Video controller (which may then output them to the screen, or to the video capture unit). The Rendering part is done automatically by hardware, so the software has little influence on it.
Rendering is done scanline-by-scanline, so there's only a limited number of clock cycles per scanline, which is limiting the maximum number of polygons per scanline. However, due to the 48-line cache (see below), some scanlines are allowed to exceed that maximum.
Rendering starts 48 lines in advance (while still in the Vblank period) (and does then continue throughout the whole display period), the rendered data is written to a small cache that can hold up to 48 scanlines.

Scanline Cache vs Framebuffer
Note: There's only the 48-line cache (not a full 192-line framebuffer to store the whole rendered image). That is perfectly reasonable since animated data is normally drawn only once (so there would be no need to store it). That, assuming that the Geometry Engine presents new data every frame (otherwise, if the Geometry software is too slow, or if the image isn't animated, then the hardware is automatically rendering the same image again, and again).


DS 3D I/O Map

3D I/O Map
  Address  Siz Name            Expl.
  Rendering Engine (per Frame settings)
  4000060h 2   DISP3DCNT       3D Display Control Register (R/W)
  4000320h 1   RDLINES_COUNT   Rendered Line Count Register (R)
  4000330h 10h EDGE_COLOR      Edge Colors 0..7 (W)
  4000340h 1   ALPHA_TEST_REF  Alpha-Test Comparision Value (W)
  4000350h 4   CLEAR_COLOR     Clear Color Attribute Register (W)
  4000354h 2   CLEAR_DEPTH     Clear Depth Register (W)
  4000356h 2   CLRIMAGE_OFFSET Rear-plane Bitmap Scroll Offsets (W)
  4000358h 4   FOG_COLOR       Fog Color (W)
  400035Ch 2   FOG_OFFSET      Fog Depth Offset (W)
  4000360h 20h FOG_TABLE       Fog Density Table, 32 entries (W)
  4000380h 40h TOON_TABLE      Toon Table, 32 colors (W)
  Geometry Engine (per Polygon/Vertex settings)
  4000400h 40h GXFIFO          Geometry Command FIFO (W)
  4000440h ... ...             Geometry Command Ports (see below)
  4000600h 4   GXSTAT          Geometry Engine Status Register (R and R/W)
  4000604h 4   RAM_COUNT       Polygon List & Vertex RAM Count Register (R)
  4000610h 2   DISP_1DOT_DEPTH 1-Dot Polygon Display Boundary Depth (W)
  4000620h 10h POS_RESULT      Position Test Results (R)
  4000630h 6   VEC_RESULT      Vector Test Results (R)
  4000640h 40h CLIPMTX_RESULT  Read Current Clip Coordinates Matrix (R)
  4000680h 24h VECMTX_RESULT   Read Current Directional Vector Matrix (R)

Geometry Commands (can be invoked by Port Address, or by Command ID)
Table shows Port Address, Command ID, Number of Parameters, and Clock Cycles.
  Address  Cmd Pa.Cy.
  N/A      00h -  -   NOP - No Operation (for padding packed GXFIFO commands)
  4000440h 10h 1  1   MTX_MODE - Set Matrix Mode (W)
  4000444h 11h -  17  MTX_PUSH - Push Current Matrix on Stack (W)
  4000448h 12h 1  36  MTX_POP - Pop Current Matrix from Stack (W)
  400044Ch 13h 1  17  MTX_STORE - Store Current Matrix on Stack (W)
  4000450h 14h 1  36  MTX_RESTORE - Restore Current Matrix from Stack (W)
  4000454h 15h -  19  MTX_IDENTITY - Load Unit Matrix to Current Matrix (W)
  4000458h 16h 16 34  MTX_LOAD_4x4 - Load 4x4 Matrix to Current Matrix (W)
  400045Ch 17h 12 30  MTX_LOAD_4x3 - Load 4x3 Matrix to Current Matrix (W)
  4000460h 18h 16 35* MTX_MULT_4x4 - Multiply Current Matrix by 4x4 Matrix (W)
  4000464h 19h 12 31* MTX_MULT_4x3 - Multiply Current Matrix by 4x3 Matrix (W)
  4000468h 1Ah 9  28* MTX_MULT_3x3 - Multiply Current Matrix by 3x3 Matrix (W)
  400046Ch 1Bh 3  22  MTX_SCALE - Multiply Current Matrix by Scale Matrix (W)
  4000470h 1Ch 3  22* MTX_TRANS - Mult. Curr. Matrix by Translation Matrix (W)
  4000480h 20h 1  1   COLOR - Directly Set Vertex Color (W)
  4000484h 21h 1  9*  NORMAL - Set Normal Vector (W)
  4000488h 22h 1  1   TEXCOORD - Set Texture Coordinates (W)
  400048Ch 23h 2  9   VTX_16 - Set Vertex XYZ Coordinates (W)
  4000490h 24h 1  8   VTX_10 - Set Vertex XYZ Coordinates (W)
  4000494h 25h 1  8   VTX_XY - Set Vertex XY Coordinates (W)
  4000498h 26h 1  8   VTX_XZ - Set Vertex XZ Coordinates (W)
  400049Ch 27h 1  8   VTX_YZ - Set Vertex YZ Coordinates (W)
  40004A0h 28h 1  8   VTX_DIFF - Set Relative Vertex Coordinates (W)
  40004A4h 29h 1  1   POLYGON_ATTR - Set Polygon Attributes (W)
  40004A8h 2Ah 1  1   TEXIMAGE_PARAM - Set Texture Parameters (W)
  40004ACh 2Bh 1  1   PLTT_BASE - Set Texture Palette Base Address (W)
  40004C0h 30h 1  4   DIF_AMB - MaterialColor0 - Diffuse/Ambient Reflect. (W)
  40004C4h 31h 1  4   SPE_EMI - MaterialColor1 - Specular Ref. & Emission (W)
  40004C8h 32h 1  6   LIGHT_VECTOR - Set Light's Directional Vector (W)
  40004CCh 33h 1  1   LIGHT_COLOR - Set Light Color (W)
  40004D0h 34h 32 32  SHININESS - Specular Reflection Shininess Table (W)
  4000500h 40h 1  1   BEGIN_VTXS - Start of Vertex List (W)
  4000504h 41h -  1   END_VTXS - End of Vertex List (W)
  4000540h 50h 1  392 SWAP_BUFFERS - Swap Rendering Engine Buffer (W)
  4000580h 60h 1  1   VIEWPORT - Set Viewport (W)
  40005C0h 70h 3  103 BOX_TEST - Test if Cuboid Sits inside View Volume (W)
  40005C4h 71h 2  9   POS_TEST - Set Position Coordinates for Test (W)
  40005C8h 72h 1  5   VEC_TEST - Set Directional Vector for Test (W)
All cycle timings are counted in 33.51MHz units. NORMAL commands takes 9..12 cycles, depending on the number of enabled lights in PolyAttr (Huh, 9..12 (four timings) cycles for 0..4 (five settings) lights?) Total execution time of SwapBuffers is Duration until VBlank, plus 392 cycles.
In MTX_MODE=2 (Simultanous Set), MTX_MULT/TRANS take additional 30 cycles.


DS 3D Display Control

4000060h - DISP3DCNT - 3D Display Control Register (R/W)
  0     Texture Mapping      (0=Disable, 1=Enable)
  1     PolygonAttr Shading  (0=Toon Shading, 1=Highlight Shading)
  2     Alpha-Test           (0=Disable, 1=Enable) (see ALPHA_TEST_REF)
  3     Alpha-Blending       (0=Disable, 1=Enable) (see various Alpha values)
  4     Anti-Aliasing        (0=Disable, 1=Enable)
  5     Edge-Marking         (0=Disable, 1=Enable) (see EDGE_COLOR)
  6     Fog Color/Alpha Mode (0=Alpha and Color, 1=Only Alpha) (see FOG_COLOR)
  7     Fog Master Enable    (0=Disable, 1=Enable)
  8-11  Fog Depth Shift      (FOG_STEP=400h shr FOG_SHIFT) (see FOG_OFFSET)
  12    Color Buffer RDLINES Underflow (0=None, 1=Underflow/Acknowledge)
  13    Polygon/Vertex RAM Overflow    (0=None, 1=Overflow/Acknowledge)
  14    Rear-Plane Mode                (0=Blank, 1=Bitmap)
  15-31 Not used

4000540h - Cmd 50h - SWAP_BUFFERS - Swap Rendering Engine Buffer (W)
SwapBuffers exchanges the two sets of Polygon/Vertex RAM buffers, that is, the newly defined polygons/vertices are passed to the rendering engine (and will be displayed in following frame(s)). The other buffer is emptied, and passed to the Geometry Engine (to be filled with new polygons/vertices by Geometry Commands).
  0     Translucent polygon Y-sorting (0=Auto-sort, 1=Manual-sort)
  1     Depth Buffering  (0=With Z-value, 1=With W-value)
        (mode 1 does not function properly with orthogonal projections)
  2-31  Not used
SwapBuffers isn't executed until next VBlank (Scanline 192) (the Geometry Engine is halted for that duration). SwapBuffers should not be issued within Begin/End. The two parameter bits of the SwapBuffers command are used for the following gxcommands (ie. not for the old gxcommands prior to SwapBuffers).
SwapBuffers does lock-up the 3D hardware if an incomplete polygon list has been defined (eg. a triangle with only 2 vertices). On lock-up, only 2D video is kept working, any wait-loops for GXSTAT.27 will hang the program. Once lock-up has occured, there seems to be no way to recover by software, not by sending the missing veric(es), and not even by pulsing POWCNT1.Bit2-3.

4000580h - Cmd 60h - VIEWPORT - Set Viewport (W)
  0-7   Screen/BG0 Coordinate X1 (0..255) (For Fullscreen: 0=Left-most)
  8-15  Screen/BG0 Coordinate Y1 (0..191) (For Fullscreen: 0=Bottom-most)
  16-23 Screen/BG0 Coordinate X2 (0..255) (For Fullscreen: 255=Right-most)
  24-31 Screen/BG0 Coordinate Y2 (0..191) (For Fullscreen: 191=Top-most)
Coordinate 0,0 is the lower-left (unlike for 2D where it'd be upper-left).
The 3D view-volume (size as defined by the Projection Matrix) is automatically scaled to match into the Viewport area. Although polygon vertices are clipped to the view-volume, some vertices may still exceed to X2,Y1 (lower-right) boundary by one pixel, due to some sort of rounding errors. The Viewport settings don't affect the size or position of the 3D Rear-Plane. Viewport should not be issued within Begin/End.

4000610h - DISP_1DOT_DEPTH - 1-Dot Polygon Display Boundary Depth (W)
1-Dot Polygons are very small, or very distant polygons, which would be rendered as a single pixel on screen. Polygons with a depth value greater (more distant) than DISP_1DOT_DEPTH can be automatically hidden; in order to reduce memory consumption, or to reduce dirt on the screen.
  0-14  W-Coordinate (Unsigned, 12bit integer, 3bit fractional part)
  15-31 Not used                 (0000h=Closest, 7FFFh=Most Distant)
The DISP_1DOT_DEPTH comparision can be enabled/disabled per polygon (via POLYGON_ATTR.Bit13), so "important" polygons can be displayed regardless of their size and distance.
Note: The comparision is always using the W-coordinate of the vertex (not the Z-coordinate) (ie. no matter if using Z-buffering, or W-buffering). The polygon is rendered if at least one of its vertices is having a w-coordinate less or equal than DISP_1DOT_DEPTH. NB. despite of checking the w-coords of ALL vertices, the polygon is rendered using the color/depth/texture of its FIRST vertex.
Note: The hardware does round-up the width and height of all polygons to at least 1, so polygons of 0x0, 1x0, 0x1, and 1x1 dots will be all rounded-up to a size of 1x1. Of which, the so-called "1dot" depth check is applied only to the 0x0 dot variant (so "0dot" depth check would be a better name for it).
Caution: Although DISP_1DOT_DEPTH is a Geometry Engine parameter, it is NOT routed through GXFIFO, ie. changes will take place immediately, and will affect all following polygons, including such that are still in GXFIFO. Workaround: ensure that GXFIFO is empty before changing this parameter.

4000340h - ALPHA_TEST_REF - Alpha-Test Comparision Value (W)
Alpha Test can be enabled in DISP3DCNT.Bit2. When enabled, pixels are rendered only if their Alpha value is GREATER than ALPHA_TEST_REF. Otherwise, when disabled, pixels are rendered only if their Alpha value is GREATER than zero. Alpha Test is performed on the final polygon pixels (ie. after texture blending).
  0-4   Alpha-Test Comparision Value (0..31) (Draw pixels if Alpha>AlphaRef)
  5-31  Not used
Value 00h is effectively the same as when Alpha Test is disabled. Value 1Fh hides all polygons, including opaque ones.


DS 3D Geometry Commands

4000400h - GXFIFO - Geometry Command FIFO (W) (mirrored up to 400043Fh?)
Used to send packed commands, unpacked commands,
  0-7   First  Packed Command (or Unpacked Command)
  8-15  Second Packed Command (or 00h=None)
  16-23 Third  Packed Command (or 00h=None)
  24-31 Fourth Packed Command (or 00h=None)
and parameters,
  0-31  Parameter data for the previously sent (packed) command(s)
to the Geometry engine.

FIFO / PIPE Number of Entries
The FIFO has 256 entries, additionally, there is a PIPE with four entries (giving a total of 260 entries). If the FIFO is empty, and if the PIPE isn't full, then data is moved directly into the PIPE, otherwise it is moved into the FIFO. If the PIPE runs half empty (less than 3 entries) then 2 entries are moved from the FIFO to the PIPE. The state of the FIFO can be obtained in GXSTAT.Bit16-26, observe that there may be still data in the PIPE, even if the FIFO is empty. Check the busy flag in GXSTAT.Bit27 to see if the PIPE or FIFO contains data (or if a command is still executing).
Each PIPE/FIFO entry consists of 40bits of data (8bit command code, plus 32bit parameter value). Commands without parameters occupy 1 entry, and Commands with N parameters occupy N entries.

Sending Commands by Ports 4000440h..40005FFh
Geometry commands can be indirectly sent to the FIFO via ports 4000440h and up.
For a command with N parameters: issue N writes to the port.
For a command without parameters: issue one dummy-write to the port.
That mechanism puts the 8bit command + 32bit parameter into the FIFO/PIPE.
If the FIFO is full, then a wait is generated until data is removed from the FIFO, ie. the STR opcode gets freezed, during the wait, the bus cannot be used even by DMA, interrupts, or by the NDS7 CPU.

GXFIFO Access via DMA
Larger pre-calculated data blocks can be sent directly to the FIFO. This is usually done via DMA (use DMA in Geometry Command Mode, 32bit units, Dest=4000400h/fixed, Length=NumWords, Repeat=0). The timings are handled automatically, ie. the system (should) doesn't freeze when the FIFO is full (see below Overkill note though). DMA starts when the FIFO becomes less than half full, the DMA does then write 112 words to the GXFIFO register (or less, if the remaining DMA transfer length gets zero).

GXFIFO Access via STR,STRD,STM
If desired, STR,STRD,STM opcodes can be used to write to the FIFO.
Opcodes that write more than one 32bit value (ie. STRD and STM) can be used to send ONE UNPACKED command, plus any parameters which belong to that command. After that, there must be a 1 cycle delay before sending the next command (ie. one cannot sent more than one command at once with a single opcode, each command must be invoked by a new opcode). STRD and STM can be used because the GXFIFO register is mirrored to 4000400h..43Fh (16 words).
As with Ports 4000440h and up, the CPU gets stopped if (and as long as) the FIFO is full.

GXFIFO / Unpacked Commands
  - command1 (upper 24bit zero)
  - parameter(s) for command1 (if any)
  - command2 (upper 24bit zero)
  - parameter(s) for command2 (if any)
  - command3 (upper 24bit zero)
  - parameter(s) for command3 (if any)

GXFIFO / Packed Commands
  - command1,2,3,4 packed into one 32bit value (all bits used)
  - parameter(s) for command1 (if any)
  - parameter(s) for command2 (if any)
  - parameter(s) for command3 (if any)
  - parameter(s) for command4 (top-most packed command MUST have parameters)
  - command5,6 packed into one 32bit value (upper 16bit zero)
  - parameter(s) for command5 (if any)
  - parameter(s) for command6 (top-most packed command MUST have parameters)
  - command7,8,9 packed into one 32bit value (upper 8bit zero)
  - parameter(s) for command7 (if any)
  - parameter(s) for command8 (if any)
  - parameter(s) for command9 (top-most packed command MUST have parameters)
Packed commands are first decompressed and then stored in command the FIFO.

GXFIFO DMA Overkill on Packed Commands Without Parameters
Normally, the 112 word limit ensures that the FIFO (256 entries) doesn't get full, however, this limit is much too high for sending a lot of "Packed Commands Without Parameters" (ie. PUSH, IDENTITY, or END) - eg. sending 112 x Packed(00151515h) to GXFIFO would write 336 x Cmd(15h) to the FIFO, which is causing the FIFO to get full, and which is causing the DMA (and CPU) to be paused (for several seconds, in WORST case) until enough FIFO commands have been processed to allow the DMA to finish the 112 word transfer.
Not sure if there's much chance to get Overkills in practice. Normally most commands DO have parameters, and so, usually even LESS than 112 FIFO entries are occupied (since 8bit commands with 32bit parameters are merged into single 40bit FIFO entries).

Invalid GX commands
Invalid commands (anything else than 10h..1Ch, 20h..2Bh, 30h..33h, 40h..41h, 50h, 60h, or 70h..72h) seem to be simply ignored by the hardware (at least, testing has confirmed that they do not fetch any parameters from the gxfifo).


DS 3D Matrix Load/Multiply

4000440h - Cmd 10h - MTX_MODE - Set Matrix Mode (W)
  0-1   Matrix Mode (0..3)
         0  Projection Matrix
         1  Position Matrix (aka Modelview Matrix)
         2  Position & Vector Simultaneous Set mode (used for Light+VEC_TEST)
         3  Texture Matrix (see DS 3D Texture Coordinates chapter)
  2-31  Not used
Selects the current Matrix, all following MTX commands (load, multiply, push, pop, etc.) are applied to that matrix. In Mode 2, all MTX commands are applied to both the Position and Vector matrices. There are two special cases:
  MTX_SCALE in Mode 2:                  uses ONLY Position Matrix
  MTX_PUSH/POP/STORE/RESTORE in Mode 1: uses BOTH Position AND Vector Matrices
Ie. the four stack commands act like mode 2 (even when in mode 1; keeping the two stacks somewhat in sync), and scale acts like mode 1 (even when in mode 2; keeping the light vector length's intact).

4000454h - Cmd 15h - MTX_IDENTITY - Load Unit Matrix to Current Matrix (W)
Sets C=I. Parameters: None
The Identity Matrix (I), aka Unit Matrix, consists of all zeroes, with a diagonal row of ones. A matrix multiplied by the Unit Matrix is left unchanged.

4000458h - Cmd 16h - MTX_LOAD_4x4 - Load 4x4 Matrix to Current Matrix (W)
Sets C=M. Parameters: 16, m[0..15]

400045Ch - Cmd 17h - MTX_LOAD_4x3 - Load 4x3 Matrix to Current Matrix (W)
Sets C=M. Parameters: 12, m[0..11]

4000460h - Cmd 18h - MTX_MULT_4x4 - Multiply Current Matrix by 4x4 Matrix (W)
Sets C=M*C. Parameters: 16, m[0..15]

4000464h - Cmd 19h - MTX_MULT_4x3 - Multiply Current Matrix by 4x3 Matrix (W)
Sets C=M*C. Parameters: 12, m[0..11]

4000468h - Cmd 1Ah - MTX_MULT_3x3 - Multiply Current Matrix by 3x3 Matrix (W)
Sets C=M*C. Parameters: 9, m[0..8]

400046Ch - Cmd 1Bh - MTX_SCALE - Multiply Current Matrix by Scale Matrix (W)
Sets C=M*C. Parameters: 3, m[0..2]
Note: MTX_SCALE doesn't change Vector Matrix (even when in MTX_MODE=2) (that's done so for keeping the length of the light vector's intact).

4000470h - Cmd 1Ch - MTX_TRANS - Mult. Curr. Matrix by Translation Matrix (W)
Sets C=M*C. Parameters: 3, m[0..2] (x,y,z position)

4000640h..67Fh - CLIPMTX_RESULT - Read Current Clip Coordinates Matrix (R)
This 64-byte region (16 words) contains the m[0..15] values of the Current Clip Coordinates Matrix, arranged in 4x4 Matrix format. Make sure that the Geometry Engine is stopped (GXSTAT.27) before reading from these registers.
The Clip Matrix is internally used to convert vertices to screen coordinates, and is internally re-calculated anytime when changing the Position or Projection matrices:
  ClipMatrix = PositionMatrix * ProjectionMatrix
To read only the Position Matrix, or only the Projection Matrix: Use Load Identity on the OTHER matrix, so the ClipMatrix becomes equal to the DESIRED matrix (multiplied by the Identity Matrix, which has no effect on the result).

4000680h..6A3h - VECMTX_RESULT - Read Current Directional Vector Matrix (R)
This 36-byte region (9 words) contains the m[0..8] values of the Current Directional Vector Matrix, arranged in 3x3 Matrix format (the fourth row/column may contain any values).
Make sure that the Geometry Engine is stopped (GXSTAT.27) before reading from these registers.


DS 3D Matrix Types

Essentially, all matrices in the NDS are 4x4 Matrices, consisting of 16 values, m[0..15]. Each element is a signed fixed-point 32bit number, with a fractional part in the lower 12bits.
The other Matrix Types are used to reduce the number of parameters being transferred, for example, 3x3 Matrix requires only nine parameters, the other seven elements are automatically set to 0 or 1.0 (whereas "1.0" means "1 SHL 12" in 12bit fixed-point notation).

   _      4x4 Matrix       _        _    Identity Matrix    _
  | m[0]  m[1]  m[2]  m[3]  |      |  1.0   0     0     0    |
  | m[4]  m[5]  m[6]  m[7]  |      |  0     1.0   0     0    |
  | m[8]  m[9]  m[10] m[11] |      |  0     0     1.0   0    |
  |_m[12] m[13] m[14] m[15]_|      |_ 0     0     0     1.0 _|

   _      4x3 Matrix       _        _  Translation Matrix   _
  | m[0]  m[1]  m[2]   0    |      |  1.0   0     0     0    |
  | m[3]  m[4]  m[5]   0    |      |  0     1.0   0     0    |
  | m[6]  m[7]  m[8]   0    |      |  0     0     1.0   0    |
  |_m[9]  m[10] m[11]  1.0 _|      |_m[0]  m[1]  m[2]   1.0 _|

   _      3x3 Matrix       _        _     Scale Matrix      _
  | m[0]  m[1]  m[2]   0    |      | m[0]   0     0     0    |
  | m[3]  m[4]  m[5]   0    |      |  0    m[1]   0     0    |
  | m[6]  m[7]  m[8]   0    |      |  0     0    m[2]   0    |
  |_ 0     0     0     1.0 _|      |_ 0     0     0     1.0 _|


DS 3D Matrix Stack

Matrix Stack
The NDS has three Matrix Stacks, and two Matrix Stack Pointers (the Coordinate Matrix stack pointer is also shared for Directional Matrix Stack).
  Matrix Stack________Valid Stack Area____Stack Pointer___________________
  Projection Stack    0..0  (1 entry)     0..1  (1bit) (GXSTAT: 1bit)
  Coordinate Stack    0..30 (31 entries)  0..63 (6bit) (GXSTAT: 5bit only)
  Directional Stack   0..30 (31 entries)  (uses Coordinate Stack Pointer)
  Texture Stack       One..None?          0..1  (1bit) (GXSTAT: N/A)
Which of the stacks/matrices depends on the current Matrix Mode (as usually,
but with one exception; stack operations MTX_PUSH/POP/STORE/RESTORE in Mode 1 are acting same as in Mode 2):
  MTX_MODE = 0      --> Projection Stack
  MTX_MODE = 1 or 2 --> BOTH Coordinate AND Directional Stack
  MTX_MODE = 3      --> Texture Stack
The initial value of the Stack Pointers is zero, the current value of the pointers can be read from GXSTAT (read-only), that register does also indicate stack overflows (errors flag gets set on read/write to invalid entries, ie. entries 1 or 1Fh..3Fh). For all stacks, the upper half (ie. 1 or 20h..3Fh) are mirrors of the lower half (ie. 0 or 0..1Fh).

4000444h - Cmd 11h - MTX_PUSH - Push Current Matrix on Stack (W)
Parameters: None. Sets [S]=C, and then S=S+1.

4000448h - Cmd 12h - MTX_POP - Pop Current Matrix from Stack (W)
Sets S=S-N, and then C=[S].
  Parameter Bit0-5:  Stack Offset (signed value, -30..+31) (usually +1)
  Parameter Bit6-31: Not used
Offset N=(+1) pops the most recently pushed value, larger offsets of N>1 will "deallocate" N values (and load the Nth value into C). Zero or negative values can be used to pop previously "deallocated" values.
The stack has only one level (at address 0) in projection mode, in that mode, the parameter value is ignored, the offset is always +1 in that mode.

400044Ch - Cmd 13h - MTX_STORE - Store Current Matrix on Stack (W)
Sets [N]=C. The stack pointer S is not used, and is left unchanged.
  Parameter Bit0-4:  Stack Address (0..30) (31 causes overflow in GXSTAT.15)
  Parameter Bit5-31: Not used
The stack has only one level (at address 0) in projection mode, in that mode, the parameter value is ignored.

4000450h - Cmd 14h - MTX_RESTORE - Restore Current Matrix from Stack (W)
Sets C=[N]. The stack pointer S is not used, and is left unchanged.
  Parameter Bit0-4:  Stack Address (0..30) (31 causes overflow in GXSTAT.15)
  Parameter Bit5-31: Not used
The stack has only one level (at address 0) in projection mode, in that mode, the parameter value is ignored.

In Projection mode, the parameter for POP, STORE, and RESTORE is unused - not sure if the parameter (ie. a dummy value) is - or is not - to be written to the command FIFO?
There appear to be actually 32 entries in Coordinate & Directional Stacks, entry 31 appears to exist, and appears to be read/write-able (although the stack overflow flag gets set when accessing it).


DS 3D Matrix Examples (Projection)

The most important matrix is the Projection Matrix (to be initialized with MTX_MODE=0 via MTX_LOAD_4x4 command). It does specify the dimensions of the view volume.

With Perspective Projections more distant objects will appear smaller, with Orthogonal Projects the size of the objects is always same regardless of their distance.

  Perspective Projection     Orthogonal Projection
                   __                  __________
       top __..--''  |            top |          |
          |   view   |                |   view   |
  Eye ----|--------->|        Eye ----|--------->|
          |__volume  |                |  volume  |
     bottom  ''--..__|          bottom|__________|
        near        far             near        far

Correctly initializing the projection matrix (as shown in the examples below) can be quite difficult (mind that fixed point multiply/divide requires to adjust the fixed-point width before/after calculation). For beginners, it may be recommended to start with a simple Identity Matrix (MTX_IDENTITY command) used as Projection Matrix (ie. Ortho with t,b,l,r set to +/-1).

Orthogonal Projections (Ortho)
  | (2.0)/(r-l)       0             0            0     |
  |      0       (2.0)/(t-b)        0            0     |
  |      0            0        (2.0)/(n-f)       0     |
  | (l+r)/(l-r)  (b+t)/(b-t)   (n+f)/(n-f)      1.0    |
n,f specify the distance from eye to near and far clip planes. t,b,l,r are the coordinates of near clip plane (top,bottom,left,right). For a symmetrical view (ie. the straight-ahead view line centered in the middle of viewport) t,b,l,r should be usually t=+ysiz/2, b=-ysiz/2, r=+xsiz/2, l=-xsiz/2; the (xsiz/ysiz) ratio should be usually equal to the viewport's (width/heigh) ratio. Examples for a asymmetrical view would be b=0 (frog's view), or t=0 (bird's view).

Left-Right Asymmetrical Perspective Projections (Frustum)
  | (2*n)/(r-l)       0             0            0     |
  |      0       (2*n)/(t-b)        0            0     |
  | (r+l)/(r-l)  (t+b)/(t-b)   (n+f)/(n-f)     -1.0    |
  |      0            0       (2*n*f)/(n-f)      0     |
n,f,t,b,l,r have same meanings as above (Ortho), the difference is that more distant objects will appear smaller with Perspective Projection (unlike Orthogonal Projection where the size isn't affected by the distance).

Left-Right Symmetrical Perspective Projections (Perspective)
  | cos/(asp*sin)     0             0            0     |
  |      0         cos/sin          0            0     |
  |      0            0        (n+f)/(n-f)     -1.0    |
  |      0            0       (2*n*f)/(n-f)      0     |
Quite the same as above (Frustum), but with symmetrical t,b values (which are in this case obtained from a vertical view range specified in degrees), and l,r are matched to the aspect ratio of the viewport (asp=height/width).

Moving the Camera
After initializing the Projection Matrix, you may multiply it with Rotate and/or Translation Matrices to change camera's position and view direction.


DS 3D Matrix Examples (Rotate/Scale/Translate)

Identity Matrix
The MTX_IDENTITY command can be used to initialize the Position Matrix before doing any Translation/Scaling/Rotation, for example:
  Load(Identity)                           ;no rotation/scaling used
  Load(Identity), Mul(Rotate), Mul(Scale)  ;rotation/scaling (not so efficient)
  Load(Rotate), Mul(Scale)                 ;rotation/scaling (more efficient)

Rotation Matrices
Rotation can be performed with MTX_MULT_3x3 command, simple examples are:
  Around X-Axis          Around Y-Axis          Around Z-Axis
  | 1.0  0     0   |     | cos   0    sin |     | cos   sin   0   |
  | 0    cos   sin |     | 0     1.0  0   |     | -sin  cos   0   |
  | 0    -sin  cos |     | -sin  0    cos |     | 0     0     1.0 |

Scale Matrix
The MTX_SCALE command allows to adjust the size of the polygon. The x,y,z parameters should be normally all having the same value, x=y=z (unless if you want to change only the height of the object, for example). Identical results can be obtained with MTX_MULT commands, however, when using lighting (MTX_MODE=2), then scaling should be done ONLY with MTX_SCALE (which keeps the length of the light's directional vector intact).

Translation Matrix
The MTX_TRANS command allows to move polygons to the desired position. The polygon VTX commands are spanning only a small range of coordinates (near zero-coordinate), so translation is required to move the polygons to other locations in the world coordinates. Aside from that, translation is useful for moved objects (at variable coordinates), and for re-using an object at various locations (eg. you can create a forest by translating a tree to different coordinates).

Matrix Multiply Order
The Matrix must be set up BEFORE sending the Vertices (which are then automatically multiplied by the matrix). When using multiple matrices multiplied with each other: Mind that, for matrix maths A*B is NOT the same as B*A. For example, if you combine Rotate and Translate Matrices, the object will be either rotated around it's own zero-coordinate, or around world-space zero-coordinate, depending on the multiply order.


DS 3D Matrix Examples (Maths Basics)

Below is a crash-course on matrix maths. Most of it is carried out automatically by the hardware. So this chapter is relevant only if you are interested in details about what happens inside of the 3D engine.

Matrix-by-Matrix Multiplication
Matrix multiplication, C = A * B, is possible only if the number of columns in A is equal to the number of rows in B, so it works fine with the 4x4 matrices which are used in the NDS. For the multiplication, assume matrix C to consist of elements cyx, and respecitively, matrix A and B to consist of elements ayx and byx. So that C = A * B looks like:
  | c11 c12 c13 c14 |     | a11 a12 a13 a14 |     | b11 b12 b13 b14 |
  | c21 c22 c23 c24 |  =  | a21 a22 a23 a24 |  *  | b21 b22 b23 b24 |
  | c31 c32 c33 c34 |     | a31 a32 a33 a34 |     | b31 b32 b33 b34 |
  | c41 c42 c43 c44 |     | a41 a42 a43 a44 |     | b41 b42 b43 b44 |
Each element in C is calculated by multiplying the elements from one row in A by the elements from the corresponding column in B, and then taking the sum of the products, ie.
  cyx = ay1*b1x + ay2*b2x + ay3*b3x + ay4*b4x
In total, that requires 64 multiplications (four multiplications for each of the 16 cyx elements), and 48 additions (three per cyx element), the hardware carries out that operation at a relative decent speed of 30..35 clock cycles, possibly by performing several multiplications simultaneously with separate multiply units.
Observe that for matrix multiplication, A*B is NOT the same as B*A.

Matrix-by-Vector & Vector-by-Matrix Multiplication
Vectors are Matrices with only one row, or only one column. Multiplication works as for normal matrices; the number of rows/columns must match up, repectively, row-vectors can be multiplied by matrices; and matrices can be multiplied by column-vectors (but not vice-versa). Eg. C = A * B:
                                                  | b11 b12 b13 b14 |
  | c11 c12 c13 c14 |  =  | a11 a12 a13 a14 |  *  | b21 b22 b23 b24 |
                                                  | b31 b32 b33 b34 |
                                                  | b41 b42 b43 b44 |
The formula for calculating the separate elements is same as above,
  cyx = ay1*b1x + ay2*b2x + ay3*b3x + ay4*b4x
Of which, C and A have only one y-index, so one may replace "cyx and ayx" by "c1x and a1x", or completely leave out the y-index, ie. "cx and ax".

Matrix-by-Number Multiplication
Simply multiply all elements of the Matrix by the number, C = A * n:
  cyx = ayx*n
Of course, works also with vectors (matrices with only one row/column).

Matrix-to-Matrix Addition/Subtraction
Both matrices must have the same number of rows & columns, add/subtract all elements with corresponding elements in other matrix, C = A +/- B:
  cyx = ayx +/- byx
Of course, works also with vectors (two matrices with only one row/column).

Vectors
A vector, for example (x,y,z), consists of offsets along x-,y-, and z-axis. The line from origin to origin-plus-offset is having two characteristics: A direction, and a length.
The length (aka magnitude) can be calculated as L=sqrt(x^2+y^2+z^2).

Vector-by-Vector Multiplication
This can be processed as LineVector*RowVector, so the result is a number (aka scalar) (aka a matrix with only 1x1 elements). Multiplying two (normalized) vectors results in: "cos(angle)=vec1*vec2", ie. the cosine of the angle between the two vectors (eg. used for light vectors). Multiplying a vector with itself, and taking the square root of the result obtains its length, ie. "length=sqrt(vec^2)".
That stuff should be done with 3-dimensional vectors (not 4-dimensionals).

Normalized Vectors
Normalized Vectors (aka Unit Vectors) are vectors with length=1.0. To normalize a vector, divide its coordinates by its length, ie. x=x/L, y=y/L, z=z/L, the direction remains the same, but the length is now 1.0.
On the NDS, normalized vectors should have a length of something less than 1.0 (eg. something like 0.99) because several NDS registers are limited to 1bit sign, 0bit integer, Nbit fractional part (so vectors that are parallel to the x,y,z axes, or that become parallel to them after rotation, cannot have a length of 1.0).

Fixed-Point Numbers
The NDS uses fixed-point numbers (rather than floating point numbers). Addition and Subtraction works as with normal integers, provided that the fractional part is the same for both numbers. If it is not the same: Shift-left the value with the smaller fractional part.
For multiplication, the fractional part of result is the sum of the fractional parts (eg. 12bit fraction * 12bit fraction = 24bit fraction; shift-right the result by 12 to convert it 12bit fraction). The NDS matrix multiply unit is maintaining the full 24bit fraction when processing the
  cyx = ay1*b1x + ay2*b2x + ay3*b3x + ay4*b4x
formula, ie. the three additions are using full 24bit fractions (with carry-outs to upper bits), the final result of the additions is then shifted-right by 12.
For division, it's vice versa, the fractions of the operands are substracted, 24bit fraction / 12bit fraction = 12bit fraction. When dividing two 12bit numbers, shift-left the first number by 12 before division to get a result with 12bit fractional part.

Four-Dimensional Matrices
The NDS uses four-dimensional matrices and vectors, ie. matrices with 4x4 elements, and vectors with 4 elements. The first three elements are associated with the X,Y,Z-axes of the three-dimensional space. The fourth element is somewhat a "W-axis".
With 4-dimensional matrices, the Translate matrix can be used to move an object to another position. Ie. once when you've setup a matrix (which may consists of pre-multiplied scaling, rotation, translation matrices), then that matrix can be used on vertices to perform the rotation, scaling, translation all-at-once; by a single Vector*Matrix operation.
With 3-dimensional matrices, translation would require a separate addition, additionally to the multiply operation.


DS 3D Polygon Attributes

40004A4h - Cmd 29h - POLYGON_ATTR - Set Polygon Attributes (W)
  0-3   Light 0..3 Enable Flags (each bit: 0=Disable, 1=Enable)
  4-5   Polygon Mode  (0=Modulation,1=Decal,2=Toon/Highlight Shading,3=Shadow)
  6     Polygon Back Surface   (0=Hide, 1=Render)  ;Line-segments are always
  7     Polygon Front Surface  (0=Hide, 1=Render)  ;rendered (no front/back)
  8-10  Not used
  11    Depth-value for Translucent Pixels    (0=Keep Old, 1=Set New Depth)
  12    Far-plane intersecting polygons       (0=Hide, 1=Render/clipped)
  13    1-Dot polygons behind DISP_1DOT_DEPTH (0=Hide, 1=Render)
  14    Depth Test, Draw Pixels with Depth    (0=Less, 1=Equal) (usually 0)
  15    Fog Enable                            (0=Disable, 1=Enable)
  16-20 Alpha      (0=Wire-Frame, 1..30=Translucent, 31=Solid)
  21-23 Not used
  24-29 Polygon ID (00h..3Fh, used for translucent, shadow, and edge-marking)
  30-31 Not used
Writes to POLYGON_ATTR have no effect until next BEGIN_VTXS command.
Changes to the Light bits have no effect until lighting is re-calculated by Normal command. The interior of Wire-frame polygons is transparent (Alpha=0), and only the lines at the polygon edges are rendered, using a fixed Alpha value of 31.

4000480h - Cmd 20h - COLOR - Directly Set Vertex Color (W)
  Parameter 1, Bit 0-4    Red
  Parameter 1, Bit 5-9    Green
  Parameter 1, Bit 10-14  Blue
  Parameter 1, Bit 15-31  Not used
The 5bit RGB values are internally expanded to 6bit RGB as follows: X=X*2+(X+31)/32, ie. zero remains zero, all other values are X=X*2+1.
Aside from by using the Color command, the color can be also changed by MaterialColor0 command (if MaterialColor0.Bit15 is set, it acts identical as the Color Command), and by the Normal command (which calculates the color based on light/material parameters).

Depth Test
The Depth Test compares the depth of the pixels of the polygon with the depth of previously rendered polygons (or of the rear plane if there have been none rendered yet). The new pixels are drawn if the new depth is Less (closer to the camera), or if it is Equal, as selected by POLYGON_ATTR.Bit14.
Normally, Depth Equal would work only exact matches (ie. if the overlapping polygons have exactly the same coordinates; and thus have the same rounding errors), however, the NDS hardware is allowing "Equal" to have a tolerance of +/-200h (within the 24bit depth range of 0..FFFFFFh), that may bypass rounding errors, but it may also cause nearby polygons to be accidently treated to have equal depth.


DS 3D Polygon Definitions by Vertices

The DS supports polygons with 3 or 4 edges, triangles and quadliterals.
The position of the edges is defined by vertices, each consisting of (x,y,z) values.

For Line Segments, use Triangles with twice the same vertex, Line Segments are rendered always because they do not have any front and back sides.
The Prohibited Quad shapes may produce unintended results, namely, that are Quads with crossed sides, and quads with angles greater than 180 degrees.

  Separate Tri.     Triangle Strips   Line Segment
  v0                 v2___v4____v6
  |\      v3         /|\  |\    /\     v0    v1
  | \     /\      v0( | \ | \  /  \     ------
  |__\   /__\        \|__\|__\/____\         v2
  v1 v2 v4  v5       v1   v3  v5   v7

  Separate Quads          Quadliteral Strips         Prohibited Quads
    v0__v3                 v0__v2____v4     v10__    v0__v3     v4
     /  \   v4____v7        /  \     |\ _____ / /v11   \/       |\
    /    \   |    \        /    \    | |v6 v8| /       /\     v5| \
   /______\  |_____\      /______\___|_|_____|/       /__\     /___\
   v1    v2  v5    v6     v1    v3  v5 v7   v9       v2   v1   v6   v7

The vertices are normally arranged anti-clockwise, except that: in triangle-strips each second polygon uses clockwise arranged vertices, and quad-strips are sorts of "up-down" arranged (whereas "up" and "down" may be anywhere due to rotation). Other arrangements may result in quads with crossed lines, or may swap the front and back sides of the polygon (above examples are showing the front sides).

4000500h - Cmd 40h - BEGIN_VTXS - Start of Vertex List (W)
  Parameter 1, Bit 0-1    Primitive Type (0..3, see below)
  Parameter 1, Bit 2-31   Not used
Indicates the Start of a Vertex List, and its Primitive Type:
  0  Separate Triangle(s)    ;3*N vertices per N triangles
  1  Separate Quadliteral(s) ;4*N vertices per N quads
  2  Triangle Strips         ;3+(N-1) vertices per N triangles
  3  Quadliteral Strips      ;4+(N-1)*2 vertices per N quads
The BEGIN_VTX command should be followed by VTX_-commands to define the Vertices of the list, and should be then terminated by END_VTX command.
BEGIN_VTX additionally applies changes to POLYGON_ATTR.

4000504h - Cmd 41h - END_VTXS - End of Vertex List (W)
Parameters: None. This is a Dummy command for OpenGL compatibility. It should be used to terminate a BEGIN_VTX, VTX_<values> sequence. END_VTXS is possibly required for Nintendo's software emulator? On real NDS consoles (and in no$gba) it does have no effect, it can be left out, or can be issued multiple times inside of a vertex list, without disturbing the display.

400048Ch - Cmd 23h - VTX_16 - Set Vertex XYZ Coordinates (W)
  Parameter 1, Bit 0-15   X-Coordinate (signed, with 12bit fractional part)
  Parameter 1, Bit 16-31  Y-Coordinate (signed, with 12bit fractional part)
  Parameter 2, Bit 0-15   Z-Coordinate (signed, with 12bit fractional part)
  Parameter 2, Bit 16-31  Not used

4000490h - Cmd 24h - VTX_10 - Set Vertex XYZ Coordinates (W)
  Parameter 1, Bit 0-9    X-Coordinate (signed, with 6bit fractional part)
  Parameter 1, Bit 10-19  Y-Coordinate (signed, with 6bit fractional part)
  Parameter 1, Bit 20-29  Z-Coordinate (signed, with 6bit fractional part)
  Parameter 1, Bit 30-31  Not used
Same as VTX_16, with only one parameter, with smaller fractional part.

4000494h - Cmd 25h - VTX_XY - Set Vertex XY Coordinates (W)
  Parameter 1, Bit 0-15   X-Coordinate (signed, with 12bit fractional part)
  Parameter 1, Bit 16-31  Y-Coordinate (signed, with 12bit fractional part)
The Z-Coordinate is kept unchanged, and re-uses the value from previous VTX.

4000498h - Cmd 26h - VTX_XZ - Set Vertex XZ Coordinates (W)
  Parameter 1, Bit 0-15   X-Coordinate (signed, with 12bit fractional part)
  Parameter 1, Bit 16-31  Z-Coordinate (signed, with 12bit fractional part)
The Y-Coordinate is kept unchanged, and re-uses the value from previous VTX.

400049Ch - Cmd 27h - VTX_YZ - Set Vertex YZ Coordinates (W)
  Parameter 1, Bit 0-15   Y-Coordinate (signed, with 12bit fractional part)
  Parameter 1, Bit 16-31  Z-Coordinate (signed, with 12bit fractional part)
The X-Coordinate is kept unchanged, and re-uses the value from previous VTX.

40004A0h - Cmd 28h - VTX_DIFF - Set Relative Vertex Coordinates (W)
  Parameter 1, Bit 0-9    X-Difference (signed, with 9/12bit fractional part)
  Parameter 1, Bit 10-19  Y-Difference (signed, with 9/12bit fractional part)
  Parameter 1, Bit 20-29  Z-Difference (signed, with 9/12bit fractional part)
  Parameter 1, Bit 30-31  Not used
Sets XYZ-Coordinate relative to the XYZ-Coordinates from previous VTX. In detail: The 9bit fractional values are divided by 8 (sign expanded to 12bit fractions, in range +/-0.125), and that 12bit fraction is then added to the old vtx coordinates. The result of the addition should not overflow 16bit vertex coordinate range (1bit sign, 3bit integer, 12bit fraction).

Notes on VTX commands
On each VTX command, the viewport coordinates of the vertex are calculated and stored in Vertex RAM,
  ( xx, yy, zz, ww ) = ( x, y, z, 1.0 ) * ClipMatrix
The actual screen position (in pixels) is then,
  screen_x = (xx+ww)*viewport_width / (2*ww) + viewport_x1
  screen_y = (yy+ww)*viewport_height / (2*ww) + viewport_y1
Each VTX command that completes the definition of a polygon (ie. each 3rd for Separate Trangles) does additionally store data in Polygon List RAM.
VTX commands may be issued only between Begin and End commands.

Clipping
Polygons are clipped to the 6 sides of the view volume (ie. to the left, right, top, bottom, near, and far edges). If one or more vertic(es) exceed one of these sides, then these vertic(es) are replaced by two newly created vertices (which are located on the intersections of the polygon edges and the view volume edge).
Depending on the number of clipped vertic(es), this may increase or decrease the number of entries in Vertex RAM (ie. minus N clipped vertices, plus 2 new vertices). Also, clipped polygons which are part of polygon strips are converted to separate polygons (which does increase number of entries in Vertex RAM). Polygons that are fully outside of the View Volume aren't stored in Vertex RAM, nor in Polygon RAM (the only exception are polygons that are located exactly one pixel below of, or right of lower/right edges, which appear to be accidently stored in memory).


DS 3D Polygon Light Parameters

The lighting operation is performed by executing the Normal command (which sets the VertexColor based on the Light/Material parameters) (to the rest of the hardware it doesn't matter if the VertexColor was set by Color command or by Normal command). Light is calculated only for the Front side of the polygon (assuming that the Normal is matched to that side), so the Back side will be (incorrectly) using the same color.

40004C8h - Cmd 32h - LIGHT_VECTOR - Set Light's Directional Vector (W)
Sets direction of the specified light (ie. the light selected in Bit30-31).
  0-9   Directional Vector's X component (1bit sign + 9bit fractional part)
  10-19 Directional Vector's Y component (1bit sign + 9bit fractional part)
  20-29 Directional Vector's Z component (1bit sign + 9bit fractional part)
  30-31 Light Number                     (0..3)
Upon executing this command, the incoming vector is multiplied by the current Directional Matrix, the result is then applied as LightVector. This allows to rotate the light direction. However, normally, to keep the light unrotated, be sure to use LoadIdentity (in MtxMode=2) before setting the LightVector.

40004CCh - Cmd 33h - LIGHT_COLOR - Set Light Color (W)
Sets the color of the specified light (ie. the light selected in Bit30-31).
  0-4   Red          (0..1Fh)      ;\light color this will be combined with
  5-9   Green        (0..1Fh)      ; diffuse, specular, and ambient colors
  10-14 Blue         (0..1Fh)      ;/upon execution of the normal command
  15-29 Not used
  30-31 Light Number (0..3)

40004C0h - Cmd 30h - DIF_AMB - MaterialColor0 - Diffuse/Ambient Reflect. (W)
  0-4   Diffuse Reflection Red     ;\light(s) that directly hits the polygon,
  5-9   Diffuse Reflection Green   ; ie. max when NormalVector has opposite
  10-14 Diffuse Reflection Blue    ;/direction of LightVector
  15    Set Vertex Color (0=No, 1=Set Diffuse Reflection Color as Vertex Color)
  16-20 Ambient Reflection Red     ;\light(s) that indirectly hits the polygon,
  21-25 Ambient Reflection Green   ; ie. assuming that light is reflected by
  26-30 Ambient Reflection Blue    ;/walls/floor, regardless of LightVector
  31    Not used
With Bit15 set, the lower 15bits are applied as VertexColor (exactly as when when executing the Color command), the purpose is to use it as default color (eg. when outcommenting the Normal command), normally, when using lighting, the color setting gets overwritten (as soon as executing the Normal command).

40004C4h - Cmd 31h - SPE_EMI - MaterialColor1 - Specular Ref. & Emission (W)
  0-4   Specular Reflection Red    ;\light(s) reflected towards the camera,
  5-9   Specular Reflection Green  ; ie. max when NormalVector is in middle of
  10-14 Specular Reflection Blue   ;/LightVector and ViewDirection
  15    Specular Reflection Shininess Table (0=Disable, 1=Enable)
  16-20 Emission Red               ;\light emitted by the polygon itself,
  21-25 Emission Green             ; ie. regardless of light colors/vectors,
  26-30 Emission Blue              ;/and no matter if any lights are enabled
  31    Not used
Caution: Specular Reflection WON'T WORK when the ProjectionMatrix is rotated.

40004D0h - Cmd 34h - SHININESS - Specular Reflection Shininess Table (W)
Write 32 parameter words (each 32bit word containing four 8bit entries), entries 0..3 in the first word, through entries 124..127 in the last word:
  0-7   Shininess 0 (unsigned fixed-point, 0bit integer, 8bit fractional part)
  8-15  Shininess 1 ("")
  16-23 Shininess 2 ("")
  24-31 Shininess 3 ("")
If the table is disabled (by MaterialColor1.Bit15), then reflection will act as if the table would be filled with linear increasing numbers.

4000484h - Cmd 21h - NORMAL - Set Normal Vector (W)
In short, this command does calculate the VertexColor, based on the various light-parameters.
In detail, upon executing this command, the incoming vector is multiplied by the current Directional Matrix, the result is then applied as NormalVector (giving it the same rotation as used for the following polygon vertices).
  0-9   X-Component of Normal Vector (1bit sign + 9bit fractional part)
  10-19 Y-Component of Normal Vector (1bit sign + 9bit fractional part)
  20-29 Z-Component of Normal Vector (1bit sign + 9bit fractional part)
  30-31 Not used
Defines the Polygon's Normal. And, does then update the Vertex Color; by recursing the View Direction, the NormalVector, the LightVector(s), and Light/Material Colors. The execution time of the Normal command varies depending on the number of enabled light(s).

Additional Light Registers
Additionally to above registers, light(s) must be enabled in PolygonAttr (mind that changes to PolygonAttr aren't applied until next Begin command). And, the Directional Matrix must be set up correctly (in MtxMode=2) for the LightVector and NormalVector commands.

Normal Vector
The Normal vector must point "away from the polygon surface" (eg. for the floor, the Normal should point upwards). That direction is implied by the polygon vertices, however, the hardware cannot automatically calculate it, so it must be set manually with the Normal command (prior to the VTX-commands).
When using lighting, the Normal command must be re-executed after switching Lighting on/off, or after changing light/material parameters. And, of course, also before defining polygons with different orientation. Polygons with same orientation (eg. horizontal polygon surfaces) and same material color can use the same Normal. Changing the Normal per polygon gives differently colored polygons with flat surfaces, changing the Normal per vertex gives the illusion of curved surfaces.

Light Vector
Each light consists of parallel beams; similar to sunlight, which appears to us (due to the great distance) to consist of parallel beams, all emmitted into the same direction; towards Earth.
In reality, light is emitted into ALL directions, originated from the light source (eg. a candle), the hardware doesn't support that type of non-parallel light. However, the light vectors can be changed per polygon, so a polygon that is located north of the light source may use different light direction than a polygon that is east of the light source.
And, of course, Light 0..3 may (and should) have different directions.

Normalized Vectors
The Normal Vector and the Light Vectors should be normalized (ie. their length should be 1.0) (in practice: something like 0.99, since the registers have only fractional parts) (a length of 1.0 can cause overflows).

Lighting Limitations
The functionality of the light feature is limited to reflecting light to the camera (light is not reflected to other polygons, nor does it cast shadows on other polygons). However, independently of the lighting feature, the DS hardware does allow to create shadows, see:
DS 3D Shadow Polygons

Internal Operation on Normal Command
  IF TexCoordTransformMode=2 THEN TexCoord=NormalVector*Matrix (see TexCoord)
  NormalVector=NormalVector*DirectionalMatrix
  VertexColor = EmissionColor
  FOR i=0 to 3
   IF PolygonAttrLight[i]=enabled THEN
    DiffuseLevel = max(0,-(LightVector[i]*NormalVector))
    ShininessLevel = max(0,(-HalfVector[i])*(NormalVector))^2
    IF TableEnabled THEN ShininessLevel = ShininessTable[ShininessLevel]
    ;note: below processed separately for the R,G,B color components...
    VertexColor = VertexColor + SpecularColor*LightColor[i]*ShininessLevel
    VertexColor = VertexColor + DiffuseColor*LightColor[i]*DiffuseLevel
    VertexColor = VertexColor + AmbientColor*LightColor[i]
   ENDIF
  NEXT i

Internal Operation on Light_Vector Command (for Light i)
  LightVector[i] = (LightVector*DirectionalMatrix)
  HalfVector[i] = (LightVector[i]+LineOfSightVector)/2

LineOfSightVector (how it SHOULD work)
Ideally, the LineOfSightVector should point from the camera to the vertic(es), however, the vertic(es) are still unknown at time of normal command, so it is just pointing from the camera to the screen, ie.
  LineOfSightVector = (0,0,-1.0)
Moreover, the LineOfSightVector should be multiplied by the Projection Matrix (so the vector would get rotated accordingly when the camera gets rotated), and, after multiplication by a scaled matrix, it'd be required to normalize the resulting vector.

LineOfSightVector (how it DOES actually work)
However, the NDS cannot normalize vectors by hardware, and therefore, it does completely leave out the LineOfSightVector*ProjectionMatrix multiplication. So, the LineOfSightVector is always (0,0,-1.0), no matter of any camera rotation. That means,
  Specular Reflection WON'T WORK when the ProjectionMatrix is rotated (!)
So, if you want to rotate the "camera" (in MTX_MODE=0), then you must instead rotate the "world" in the opposite direction (in MTX_MODE=2).
That problem applies only to Specular Reflection, ie. only if Lighting is used, and only if the Specular Material Color is nonzero.

Maths Notes
Note on Vector*Vector multiplication: Processed as LineVector*RowVector, so the result is a number (aka scalar) (aka a matrix with only 1x1 elements), multiplying two (normalized) vectors results in: "cos(angle)=vec1*vec2", ie. the cosine of the angle between the two vectors.
The various Normal/Light/Half/Sight vectors are only 3-dimensional (x,y,z), ie. only the upper-left 3x3 matrix elements are used on multiplications with the 4x4 DirectionalMatrix.


DS 3D Shadow Polygons

The DS hardware's Light-function allows to reflect light to the camera, it does not reflect light to other polygons, and it does not cast any shadows. For shadows at fixed locations it'd be best to pre-calculate their shape and position, and to change the vertex color of the shaded polygons.
Additionally, the Shadow Polygon feature can be used to create animated shadows, ie. moved objects and variable light sources.

Shadow Polygons and Shadow Volume
The software must define a Shadow Volume (ie. the region which doesn't contain light), the hardware does then automatically draw the shadow on all pixels whose x/y/z-coordinates are inside of that region.
The Shadow Volume must be defined by several Shadow Polygons which are enclosing the shaded region. The 'top' of the shadow volume should be usually translated to the position of the object that casts the shadow, if the light direction changes then the shadow volume should be also rotated to match the light direction. The 'length' of the shadow volume should be (at least) long enough to reach from the object to the walls/floor where the shadow is to be drawn. The shadow volume must be passed TWICE to the hardware:

Step 1 - Shadow Volume for Mask
Set Polygon_Attr Mode=Shadow, PolygonID=00h, Back=Render, Front=Hide, Alpha=01h..1Eh, and pass the shadow volume (ie. the shadow polygons) to the geometry engine.
The Back=Render / Front=Hide setting causes the 'rear-side' of the shadow volume to be rendered, of course only as far as it is in front of other polygons. The Mode=Shadow / ID=00h setting causes the polygon NOT to be drawn to the Color Buffer - instead, flags are set in the Stencil Buffer (to be used in Step 2).

Step 2 - Shadow Volume for Rendering
Simply repeat step 1, but with Polygon_Attr Mode=Shadow, PolygonID=01h..3Fh, Back=Render(what/why?), Front=Render, Alpha=01h..1Eh.
The Front=Render setting causes the 'front-side' of the shadow volume to be rendered, again, only as far as it is in front of other polygons. The Mode=Shadow / ID>00h setting causes the polygon to be drawn to the Color Buffer as usually, but only if the Stencil Buffer bits are zero (ie. the portion from Step 1 is excluded) (additionally, Step 2 resets the stencil bits after checking them). Moreover, the shadow is rendered only if its Polygon ID differs from the ID in the Attribute Buffer.

Shadow Alpha and Shadow Color
The Alpha=Translucent setting in Step 1 and 2 ensures that the Shadow is drawn AFTER the normal (opaque) polygons have been rendered. In Step 2 it does additionally specify the 'intensity' of the shadow. For normal shadows, the Vertex Color should be usually black, however, the shadow volume may be also used as 'spotlight volume' when using other colors.

Rendering Order
The Mask Volume must be rendered prior to the Rendering Volume, ie. Step 1 and 2 must be performed in that order, and, to keep that order intact, Auto-sorting must have been disabled in the previous Swap_Buffers command.
The shadow volume must be rendered after the 'target' polygons have been rendered, for opaque targets this is done automatically (due to the translucent alpha setting; translucent polygons are always rendered last, even with auto-sort disabled).

Translucent Targets
Casting shadows on Translucent Polygons. First draw the translucent target (with update depth buffer enabled, required for the shadow z-coordinates), then draw the Shadow Mask/Rendering volumes.
Due to the updated depth buffer the shadow will be cast only on the translucent target (not on any other polygons underneath of the translucent polygon). If you want the shadow to appear on both: Draw draw the Shadow Mask/Rendering volume TWICE (once before, and once after drawing the translucent target).

Polygon ID and Fog Enable
The "Render only if Polygon ID differs" feature (see Step 2) allows to prevent the shadow to be cast on the object that casts the shadow (ie. the object and shadow should have the same IDs). The feature also allows to select whether overlapping shadows (with same/different IDs) are shaded once or twice.
The old Fog Enable flag in the Attribute Buffer is ANDed with the Fog Enable flag of the Shadow Polygons, this allows to exclude Fog in shaded regions.

Shadow Volume Open/Closed Shapes
Normally, the shadow volume should have a closed shape, ie. should have rear-sides (step 1), and corresponding front-sides (step 2) for all possible viewing angles. That is required for the shadow to be drawn correctly, and also for the Stencil Buffer to be reset to zero (in step 2, so that the stencil bits won't disturb other shadow volumes).
Due to that, drawing errors may occur if the shadow volume's front or rear side gets clipped by near/far clip plane.
One exception is that the volume doesn't need a bottom-side (with a suitable volume length, the bottom may be left open, since it vanishes in the floor/walls anyways).


DS 3D Texture Attributes

4000488h - Cmd 22h - TEXCOORD - Set Texture Coordinates (W)
Specifies the texture source coordinates within the texture bitmap which are to be associated with the next vertex.
  Parameter 1, Bit 0-15   S-Coordinate (X-Coordinate in Texture Source)
  Parameter 1, Bit 16-31  T-Coordinate (Y-Coordinate in Texture Source)
  Both values are 1bit sign + 11bit integer + 4bit fractional part.
  A value of 1.0 (=1 SHL 4) equals to one Texel.
With Position 0.0 , 0.0 drawing starts from upperleft of the Texture.
With positive offsets, drawing origin starts more "within" the texture.
With negative offsets, drawing starts "before" the texture.
"When texture mapping, the Geometry Engine works faster if you issue commands in the order TexCoord -> Normal -> Vertex."

40004A8h - Cmd 2Ah - TEXIMAGE_PARAM - Set Texture Parameters (W)
  0-15  Texture VRAM Offset div 8 (0..FFFFh -> 512K RAM in Slot 0,1,2,3)
        (VRAM must be allocated as Texture data, see Memory Control chapter)
  16    Repeat in S Direction (0=Clamp Texture, 1=Repeat Texture)
  17    Repeat in T Direction (0=Clamp Texture, 1=Repeat Texture)
  18    Flip in S Direction   (0=No, 1=Flip each 2nd Texture) (requires Repeat)
  19    Flip in T Direction   (0=No, 1=Flip each 2nd Texture) (requires Repeat)
  20-22 Texture S-Size        (for N=0..7: Size=(8 SHL N); ie. 8..1024 texels)
  23-25 Texture T-Size        (for N=0..7: Size=(8 SHL N); ie. 8..1024 texels)
  26-28 Texture Format        (0..7, see below)
  29    Color 0 of 4/16/256-Color Palettes (0=Displayed, 1=Made Transparent)
  30-31 Texture Coordinates Transformation Mode (0..3, see below)
Texture Formats:
  0  No Texture                     -
  1  A3I5 Translucent Texture       8bpp
  2  4-Color Palette Texture        2bpp
  3  16-Color Palette Texture       4bpp
  4  256-Color Palette Texture      8bpp
  5  4x4-Texel Compressed Texture   3bpp
  6  A5I3 Translucent Texture       8bpp
  7  Direct Texture                 16bpp
Texture Coordinates Transformation Modes:
  0  Do not Transform texture coordinates
  1  TexCoord source
  2  Normal source
  3  Vertex source
The S-Direction equals to the horizontal direction of the source bitmap.
The T-Direction, T-repeat, and T-flip are the same in vertical direction.
For a "/" shaped texture, the S-clamp, S-repeat, and S-flip look like so:
  Clamp _____  Repeat       Repeat+Flip
  _____/       ///////////  /\/\/\/\/\/
With "Clamp", the texture coordinates are clipped to MinMax(0,Size-1), so the texels at the edges of the texture bitmap are repeated (to avoid that effect, fill the bitmap edges by texels with alpha=0, so they become invisible).

40004ACh - Cmd 2Bh - PLTT_BASE - Set Texture Palette Base Address (W)
  0-12   Palette Base Address (div8 or div10h, see below)
         (Not used for Texture Format 7: Direct Color Texture)
         (0..FFF8h/8 for Texture Format 2: ie. 4-color-palette Texture)
         (0..17FF0h/10h for all other Texture formats)
  13-31  Not used
The palette data occupies 16bit per color:
  Bit0-4:   Red
  Bit5-9:   Green
  Bit10-14: Blue
  Bit15:    Not used
VRAM must be allocated as Texture Palette, there can be up to 6 Slots allocated, ie. the addressable 18000h bytes, see Memory Control chapter.

TexImageParam and TexPlttBase
Can be issued per polygon (except within polygon strips).


DS 3D Texture Formats

Format 2: 4-Color Palette Texture
Each Texel occupies 2bit, the first Texel is located in LSBs of 1st byte.
In this format, the Palette Base is specified in 8-byte steps; all other formats use 16-byte steps (see PLTT_BASE register).

Format 3: 16-Color Palette Texture
Each Texel occupies 4bit, the 1st Texel is located in LSBs of 1st byte.

Format 4: 256-Color Palette Texture
Each Texel occupies 8bit, the 1st Texel is located in 1st byte.

Format 7: Direct Color Texture
Each Texel occupies 16bit, the 1st Texel is located in 1st halfword.
Bit0-4: Red, Bit5-9: Green, Bit10-14: Blue, Bit15: Alpha

Format 1: A3I5 Translucent Texture (3bit Alpha, 5bit Color Index)
Each Texel occupies 8bit, the 1st Texel is located in 1st byte.
  Bit0-4: Color Index (0..31) of a 32-color Palette
  Bit5-7: Alpha       (0..7; 0=Transparent, 7=Solid)
The 3bit Alpha value (0..7) is internally expanded into a 5bit Alpha value (0..31) as follows: Alpha=(Alpha*4)+(Alpha/2).

Format 6: A5I3 Translucent Texture (5bit Alpha, 3bit Color Index)
Each Texel occupies 8bit, the 1st Texel is located in 1st byte.
  Bit0-2: Color Index (0..7) of a 8-color Palette
  Bit3-7: Alpha       (0..31; 0=Transparent, 31=Solid)

Format 5: 4x4-Texel Compressed Texture
Consists of 4x4 Texel blocks in Slot 0 or 2, 32bit per block, 2bit per Texel,
  Bit0-7   Upper 4-Texel row (LSB=first/left-most Texel)
  Bit8-15  Next  4-Texel row ("")
  Bit16-23 Next  4-Texel row ("")
  Bit24-31 Lower 4-Texel row ("")
Additional Palette Index Data for each 4x4 Texel Block is located in Slot 1,
  Bit0-13  Palette Offset in 4-byte steps; Addr=(PLTT_BASE*10h)+(Offset*4)
  Bit14-15 Transparent/Interpolation Mode (0..3, see below)
whereas, the Slot 1 offset is related to above Slot 0 or 2 offset,
  slot1_addr = slot0_addr / 2           ;lower 64K of Slot1 assoc to Slot0
  slot1_addr = slot2_addr / 2 + 10000h  ;upper 64K of Slot1 assoc to Slot2
The 2bit Texel values (0..3) are intepreted depending on the Mode (0..3),
  Texel  Mode 0       Mode 1             Mode 2         Mode 3
  0      Color 0      Color0             Color 0        Color 0
  1      Color 1      Color1             Color 1        Color 1
  2      Color 2      (Color0+Color1)/2  Color 2        (Color0*5+Color1*3)/8
  3      Transparent  Transparent        Color 3        (Color0*3+Color1*5)/8
Mode 1 and 3 are using only 2 Palette Colors (which requires only half as much Palette memory), the 3rd (and 4th) Texel Colors are automatically set to above values (eg. to gray-shades if color 0 and 1 are black and white).
Note: The maximum size for 4x4-Texel Compressed Textures is 1024x512 or 512x1024 (which are both occupying the whole 128K in slot 0 or 2, plus 64K in slot1), a larger size of 1024x1024 cannot be used because of the gap between slot 0 and 2.


DS 3D Texture Coordinates

For textured polygons, a texture coordinate must be associated with each vertex of the polygon. The coordinates (S,T) are defined by TEXCOORD command (typically issued prior to each VTX command), and can be optionally automatically transformed, by the Transformation Mode selected in TEXIMAGE_PARAM register.

Texture Matrix
Although the texture matrix is 4x4, with values m[0..15], only the left two columns of this matrix are actually used. In Mode 2 and 3, the bottom row of the matrix is replaced by S and T values from most recent TEXCOORD command.

Texture Coordinates Transformation Mode 0 - No Transform
The values are set upon executing the TEXCOORD command,
  ( S' T' )  =  ( S  T )
Simple coordinate association, without using the Texture Matrix at all.

Texture Coordinates Transformation Mode 1 - TexCoord source
The values are calculated upon executing the TEXCOORD command,
                                     | m[0]  m[1]  |
  ( S' T' )  =  ( S  T 1/16 1/16 ) * | m[4]  m[5]  |
                                     | m[8]  m[9]  |
                                     | m[12] m[13] |
Can be used to produce a simple texture scrolling, rotation, or scaling, by setting a translate, rotate, or scale matrix for the texture matrix.

Texture Coordinates Transformation Mode 2 - Normal source
The values are calculated upon executing the NORMAL command,
                                     | m[0]  m[1]  |
  ( S' T' )  =  ( Nx  Ny  Nz 1.0 ) * | m[4]  m[5]  |
                                     | m[8]  m[9]  |
                                     | S     T     |
Can be used to produce spherical reflection mapping by setting the texture matrix to the current directional vector matrix, multiplied by a scaling matrix that expands the directional vector space from -1.0..+1.0 to one half of the texture size. For that purpose, translate the origin of the texture coordinate to the center of the spherical texture by using TexCoord command (spherical texture means a bitmap that contains some circle-shaped image).

Texture Coordinates Transformation Mode 3 - Vertex source
The values are calculated upon executing any VTX commands,
                                     | m[0]  m[1]  |
  ( S' T' )  =  ( Vx  Vy  Vz 1.0 ) * | m[4]  m[5]  |
                                     | m[8]  m[9]  |
                                     | S     T     |
Can be used to produce texture scrolls dependent on the View coordinates by copying the current position coordinate matrix into the texture matrix. For example, the PositionMatrix can be obtained via CLIPMTX_RESULT (see there for details), and that values can be then manually copied to the TextureMatrix.

Sign+Integer+Fractional Parts used in above Formulas
  Matrix    m[..]     1+19+12 (32bit)
  Vertex    Vx,Vy,Vz  1+3+12  (16bit)
  Normal    Nx,Ny,Nz  1+0+9   (10bit)
  Constant  1.0       0+1+0   (1bit)
  Constant  1/16      0+0+4   (4bit)
  TexCoord  S,T       1+11+4  (16bit)
  Result    S',T'     1+11+4  (16bit) <-------- clipped to that size !
Observe that the S',T' values are clipped to 16bit size. Ie. after the Vector*Matrix calaction, the result is shifted right (to make it having a 4bit fraction), and the value is then masked to 16bit size.


DS 3D Texture Blending

Polygon pixels consist of a Vertex Color, and of Texture Colors.
These colors can be blended as described below. Or, to use only either one:
To use only the Vertex Color: Select No Texture in TEXIMAGE_PARAM.
To use only the Texture Color: Select Modulation Mode and Alpha=31 in POLYGON_ATTR, and set COLOR to 7FFFh (white), or to gray values (to decrease brightness of the texture color).

Vertex Color (Rv,Gv,Bv,Av)
The Vertex Color (Rv,Gv,Bv) can be changed per Vertex (either by Color, Normal, or Material0 command), pixels between vertices are shaded to medium values of the surrounding vertices. The Vertex Alpha (Av), can be changed only per polygon (by PolygonAttr command).

Texture Colors (Rt,Gt,Bt,At)
The Texture Colors (Rt,Gt,Bt), and Alpha value (At), are defined by the Texture Bitmap. For formats without Alpha value, assume At=31 (solid), and for formats with 1bit Alpha assume At=A*31.

Shading Table Colors (Rs,Gs,Bs)
In Toon/Highlight Shading Mode, the red component of the Vertex Color (Rv) is mis-used as an index in the Shading Table, ie. Rv is used to read Shading Colors (Rs,Gs,Bs) from the table; the green and blue components of the Vertex Color (Gv,Bv) are unused in this mode. The Vertex Alpha (Av) is kept used.
Shading is used in Polygon Mode 2, whether it is Toon or Highlight Shading is selected in DISP3DCNT; this is a per-frame selection, so only either one can be used.

Texture Blending - Modulation Mode (Polygon Attr Mode 0)
  R = ((Rt+1)*(Rv+1)-1)/64
  G = ((Gt+1)*(Gv+1)-1)/64
  B = ((Bt+1)*(Bv+1)-1)/64
  A = ((At+1)*(Av+1)-1)/64
The multiplication result is decreased intensity (unless both factors are 63).

Texture Blending - Decal Mode (Polygon Attr Mode 1)
  R = (Rt*At + Rv*(63-At))/64  ;except, when At=0: R=Rv, when At=31: R=Rt
  G = (Gt*At + Gv*(63-At))/64  ;except, when At=0: G=Gv, when At=31: G=Gt
  B = (Bt*At + Bv*(63-At))/64  ;except, when At=0: B=Bv, when At=31: B=Bt
  A = Av
The At value is used (only) as ratio for Texture color vs Vertex Color.

Texture Blending - Toon Shading (Polygon Mode 2, DISP3DCNT=Toon)
The vertex color Red component (Rv) is used as an index in the toon table.
  R = ((Rt+1)*(Rs+1)-1)/64   ;Rs=ToonTableRed[Rv]
  G = ((Gt+1)*(Gs+1)-1)/64   ;Gs=ToonTableGreen[Rv]
  B = ((Bt+1)*(Bs+1)-1)/64   ;Bs=ToonTableBlue[Rv]
  A = ((At+1)*(Av+1)-1)/64
This is same as Modulation Mode, but using Rs,Gs,Bs instead Rv,Gv,Bv.

Texture Blending - Highlight Shading (Polygon Mode 2, DISP3DCNT=Highlight)
  R = ((Rt+1)*(Rs+1)-1)/64+Rs ;truncated to MAX=63
  G = ((Gt+1)*(Gs+1)-1)/64+Gs ;truncated to MAX=63
  B = ((Bt+1)*(Bs+1)-1)/64+Bs ;truncated to MAX=63
  A = ((At+1)*(Av+1)-1)/64
Same as Toon Shading, with additional addition offset, the addition may increase the intensity, however, it may also change the hue of the color.

Above formulas are for 6bit RGBA values, ie. 5bit values internally expanded to 6bit as such: IF X>0 THEN X=X*2+1.

Uni-Colored Textures
Although textures are normally containing "pictures", in some cases it makes sense to use "blank" textures that are filled with a single color:
Wire-frame polygons are always having Av=31, however, they can be made transparent by using Translucent Textures (ie. A5I3 or A3I5 formats) with At<31.
In Toon/Highlight shading modes, the Vertex Color is mis-used as table index, however, Toon/Highlight shading can be used on uni-colored textures, which is more or less the same as using Toon/Highlight shading on uni-colored Vertex-colors.


DS 3D Toon, Edge, Fog, Alpha-Blending, Anti-Aliasing

4000380h..3BFh - TOON_TABLE - Toon Table (W)
This 64-byte region contains the 32 toon colors (16bit per color), used for both Toon and Highlight Shading. In both modes, the Red (R) component of the RGBA vertex color is mis-used as index to obtain the new RGB value from the toon table, vertex Alpha (A) is kept used as is.
  Bit0-4: Red, Bit5-9: Green, Bit10-14: Blue, Bit15: Not Used
Shading can be enabled (per polygon) in Polygon_Attr, whether it is Toon or Highlight Shading is set (per frame) in DISP3DCNT. For more info on shading, see:
DS 3D Texture Blending

4000330h..33Fh - EDGE_COLOR - Edge Colors 0..7 (W)
This 16-byte region contains the 8 edge colors (16bit per color), Edge Color 0 is used for Polygon ID 00h..07h, Color 1 for ID 08h..0Fh, and so on.
  Bit0-4: Red, Bit5-9: Green, Bit10-14: Blue, Bit15: Not Used
Edge Marking allows to mark the edges of an object (whose polygons all have the same ID) in a wire-frame style. Edge Marking can be enabled (per frame) in DISP3DCNT. When enabled, the polygon edges are drawn at the edge color, but only if the old ID value in the Attribute Buffer is different than the Polygon ID of the new polygon, so no edges are drawn between connected or overlapping polygons with same ID values.
Edge Marking is applied ONLY to opaque polygons (including wire-frames).
Edge Marking increases the size of opaque polygons (see notes below).
Edge Marking doesn't work very well with Anti-Aliasing (see Anti-Aliasing).
Technically, when rendering a polygon, it's edges (ie. the wire-frame region) are flagged as possible-edges (but it's still rendered normally, without using the edge-color). Once when all opaque polygons (*) have been rendered, the edge color is applied to these flagged pixels, under following conditions: At least one of the four surrounding pixels (up, down, left, right) must have different polygon_id than the edge, and, the edge depth must be LESS than the depth of that surrounding pixel (ie. no edges are rendered if the depth is GREATER or EQUAL, even if the polygon_id differs). At the screen borders, edges seem to be rendered in respect to the rear-plane's polygon_id entry (see Port 4000350h).
(*) Actually, edge-marking is reportedly performed not until all opaque AND translucent polygons have been rendered. That brings up some effects/problems when edges are covered by translucent polys: The edge-color is probably drawn as is (ie. it'll overwrite the translucent color, rather than being blended with the translucent color). And, any translucent polygons that do update the depth buffer will cause total edge-marking malfunction (since edge-marking involves the comparision of the current/surrounding pixel's depth values).

4000358h - FOG_COLOR - Fog Color (W)
Fog can be used to let more distant polygons to disappear in foggy grayness (or in darkness, or other color). This is particulary useful to "hide" the far clip plane. Fog can be enabled in DISP3DCNT.Bit7, moreover, when enabled, it can be activated or deactivated per polygon (POLYGON_ATTR.Bit15), and per Rear-plane (see there).
  0-4    Fog Color, Red     ;\
  5-9    Fog Color, Green   ; used only when DISP3DCNT.Bit6 is zero
  10-14  Fog Color, Blue    ;/
  15     Not used
  16-20  Fog Alpha          ;-used no matter of DISP3DCNT.Bit6
  21-31  Not used
Whether or not fog is applied to a pixel depends on the Fog flag in the framebuffer, the initial value of that flag can be defined in the rear-plane. When rendering opaque pixels, the framebuffer's fog flag gets replaced by PolygonAttr.Bit15. When rendering translucent pixels, the old flag in the framebuffer gets ANDed with PolygonAttr.Bit15.

400035Ch - FOG_OFFSET - Fog Depth Offset (W)
  0-14   Fog Offset (Unsigned) (0..7FFFh)
  15-31  Not used
FogDepthBoundary[0..31] (for FogDensity[0..31]) are defined as:
  FogDepthBoundary[n] = FOG_OFFSET + FOG_STEP*(n+1)   ;with n = 0..31
Whereas FOG_STEP is derived from the FOG_SHIFT value in DISP3DCNT.Bit8-11 (FOG_STEP=400h shr FOG_SHIFT) (normally FOG_SHIFT should be 0..10 (bigger shift amounts of 11..15 would cause FOG_STEP to become zero, so only Density[0] and Density[31] would be used).
The meaning of the depth values depends on whether z-values or w-values are stored in the framebuffer (see SwapBuffers.Bit1).
For translucent polygons, the depth value (and therefore: the amount of fog) depends on the depth update bit (see PolygonAttr.Bit11).

4000360h..37Fh - FOG_TABLE - Fog Density Table (W)
This 32-byte region contains FogDensity[0..31] (used at FogDepthBoundary[n]),
  0-6    Fog Density (00h..7Fh = None..Full) (usually increasing values)
  7      Not used
FogDensity[0] is used for all pixels closer than FogDepthBoundary[0], FogDensity[31] is used for all pixels more distant than FogDepthBoundary[0].
Density is linear interpolated for pixels that are between two Density depth boundaries. The formula for Fog Blending is:
  FrameBuffer[R] = (FogColor[R]*Density + FrameBuffer[R]*(128-Density)) / 128
  FrameBuffer[G] = (FogColor[G]*Density + FrameBuffer[G]*(128-Density)) / 128
  FrameBuffer[B] = (FogColor[B]*Density + FrameBuffer[B]*(128-Density)) / 128
  FrameBuffer[A] = (FogColor[A]*Density + FrameBuffer[A]*(128-Density)) / 128
If DISP3DCNT.Bit6 is set (=Alpha Only), then only FrameBuffer[A] is updated, and FrameBuffer[RGB] are kepth unchanged. Density=127 is handled as if Density=128.
Fog Glitch: The fog_alpha value appears to be ignored (treated as fog_alpha=1Fh) in the region up to the first density boundary. However, normally that value will be multiplied by zero (assumung that density[0] is usually zero), so you won't ever notice that hardware glitch.

Alpha-Blending (Polygon vs FrameBuffer)
Alpha-Blending occurs for pixels of translucent polygons,
  FrameBuf[R] = (Poly[R]*(Poly[A]+1) + FrameBuf[R]*(31-(Poly[A])) / 32
  FrameBuf[G] = (Poly[G]*(Poly[A]+1) + FrameBuf[G]*(31-(Poly[A])) / 32
  FrameBuf[B] = (Poly[B]*(Poly[A]+1) + FrameBuf[B]*(31-(Poly[A])) / 32
  FrameBuf[A] = max(Poly[A],FrameBuf[A])
There are three situations in which Alpha-Blending is bypassed (the old Framebuf[R,G,B,A] value is then simply overwritten by Poly[R,G,B,A]):
  1) Alpha-Blending is disabled                       (DISP3DCNT.Bit3=0)
  2) The polygon pixel is opaque                      (Poly[A]=31)
  3) The old framebuffer value is totally transparent (FrameBuf[A]=0)
The third case can happen if the rear-plane was initialized with Alpha=0, which causes the polygon not to be blended with the rear-plane (which may give better results when subsequently blending the 3D layer with the 2D engine).
Note: Totally transparent pixels (with Poly[A]=0) are not rendered (ie. neither FrameBuf[R,G,B,A] nor FrameBuf[Depth,Fog,PolyID,etc.] are updated.

Anti-Aliasing
Anti-Aliasing can be enabled in DISP3DCNT, when enabled, the edges of opaque polygons will be anti-aliased (ie. the pixels at the edges may become translucent).
Anti-Aliasing is not applied on translucent polygons. And, Anti-Aliasing is not applied on the interiors of the poylgons (eg. an 8x8 chessboard texture will be anti-aliased only at the board edges, not at the edges of the 64 fields).
Anti-Aliasing is (accidently) applied to opaque 1dot polygongs, line-segments and wire-frames (which results in dirty lines with missing pixels, 1dot polys become totally invisible), workaround is to use translucent dots, lines and wires (eg. with alpha=30).
Anti-Aliasing is (correctly) not applied to edges of Edge-Marked polygons, in that special case even opaque line-segments and wire-frames are working even if anti-aliasing is enabled (provided that they are edge-marked, ie. if their polygon ID differs from the framebuffer's ID).
Anti-Aliasing is (accidently) making the edges of Edge-Marked polygons translucent (with alpha=16 or so?), that reduces the contrast of the edge colors. Moreover, if two of these translucent edges do overlap, then they are blended twice (even if they have the same polygon_id, and even if the depth_update bit in polygon_attr is set; both should normally prevent double-blending), that scatters the brightness of such edges.

Polygon Size
In some cases, the NDS hardware doesn't render the lower/right edges of certain polygons. That feature reduces rendering load, and, when rendering connected polygons (eg. strips), then it'd be unnecessary to render that edges (since they'd overlap with the upper/left edges of the other polygon). On the contrary, if there's no connected polygon displayed, then the polygon may appear smaller than expected. Small polygons with excluded edges are:
  Opaque polygons (except wire-frames) without Edge-Marking and Anti-Aliasing,
  and, all polygons with vertical right-edges (except line-segments).
  Plus, Translucent Polys when Alpha-Blending is disabled in DISP3DCNT.Bit3.
All other polygons are rendered at full size with all edges included (except vertical right edges). Note: To disable the small-polygon feature, you can enable edge-marking (which does increase the polygon size, even if no edges are drawn, ie. even if all polys do have the same ID).


DS 3D Status

4000600h - GXSTAT - Geometry Engine Status Register (R and R/W)
Bit 30-31 are R/W. Writing "1" to Bit15 does reset the Error Flag (Bit15), and additionally resets the Projection Stack Pointer (Bit13), and probably (?) also the Texture Stack Pointer. All other GXSTAT bits are read-only.
  0     BoxTest,PositionTest,VectorTest Busy (0=Ready, 1=Busy)
  1     BoxTest Result  (0=All Outside View, 1=Parts or Fully Inside View)
  2-7   Not used
  8-12  Position & Vector Matrix Stack Level (0..31) (lower 5bit of 6bit value)
  13    Projection Matrix Stack Level        (0..1)
  14    Matrix Stack Busy (0=No, 1=Yes; Currently executing a Push/Pop command)
  15    Matrix Stack Overflow/Underflow Error (0=No, 1=Error/Acknowledge/Reset)
  16-24 Number of 40bit-entries in Command FIFO  (0..256)
 (24)   Command FIFO Full (MSB of above)  (0=No, 1=Yes; Full)
  25    Command FIFO Less Than Half Full  (0=No, 1=Yes; Less than Half-full)
  26    Command FIFO Empty                (0=No, 1=Yes; Empty)
  27    Geometry Engine Busy (0=No, 1=Yes; Busy; Commands are executing)
  28-29 Not used
  30-31 Command FIFO IRQ (0=Never, 1=Less than half full, 2=Empty, 3=Reserved)
When GXFIFO IRQ is enabled (setting 1 or 2), the IRQ flag (IF.Bit21) is set while and as long as the IRQ condition is true (and attempts to acknowledge the IRQ by writing to IF.Bit21 have no effect). So that, the IRQ handler must either fill the FIFO, or disable the IRQ (setting 0), BEFORE trying to acknowledge the IRQ.

4000604h - RAM_COUNT - Polygon List & Vertex RAM Count Register (R)
  0-11   Number of Polygons currently stored in Polygon List RAM (0..2048)
  12-15  Not used
  16-28  Number of Vertices currently stored in Vertex RAM       (0..6144)
  13-15  Not used
If a SwapBuffers command has been sent, then the counters are reset 10 cycles (at 33.51MHz clock) after next VBlank.

4000320h - RDLINES_COUNT - Rendered Line Count Register (R)
Rendering starts in scanline 214, the rendered lines are stored in a buffer that can hold up to 48 scanlines. The actual screen output begins after scanline 262, the lines are then read from the buffer and sent to the display. Simultaneously, the rendering engine keeps writing new lines to the buffer (ideally at the same speed than display output, so the buffer would always contain 48 pre-calculated lines).
  0-5    Minimum Number (minus 2) of buffered lines in previous frame (0..46)
  6-31   Not used
If rendering becomes slower than the display output, then the number of buffered lines decreases. Smaller values in RDLINES indicate that additional load to the rendering engine may cause buffer underflows in further frames, if so, the program should reduce the number of polygons to avoid display glitches.
Even if RDLINES becomes zero, it doesn't indicate whether actual buffer underflows have occured or not (underflows are indicated in DISP3DCNT Bit12).


DS 3D Tests

40005C0h - Cmd 70h - BOX_TEST - Test if Cuboid Sits inside View Volume (W)
The BoxTest result indicates if one or more of the 6 faces of the box are fully or parts of inside of the view volume. Can be used to reduce unnecessary overload, ie. if the result is false, then the program can skip drawing of objects which are inside of the box.
BoxTest verifies only if the faces of the box are inside view volume, and so, it will return false if the whole view volume is located inside of the box (still objects inside of the box may be inside of view).
  Parameter 1, Bit 0-15   X-Coordinate
  Parameter 1, Bit 16-31  Y-Coordinate
  Parameter 2, Bit 0-15   Z-Coordinate
  Parameter 2, Bit 16-31  Width  (presumably: X-Offset?)
  Parameter 3, Bit 0-15   Height (presumably: Y-Offset?)
  Parameter 3, Bit 16-31  Depth  (presumably: Z-Offset?)
  All values are 1bit sign, 3bit integer, 12bit fractional part
The result of the "coordinate+offset" additions should not overflow 16bit vertex coordinate range (1bit sign, 3bit integer, 12bit fraction).
Before using BoxTest, be sure that far-plane-intersecting & 1-dot polygons are enabled, if they aren't: Send the PolygonAttr command (with bit12,13 set to enable them), followed by dummy Begin and End commands (required to apply the new PolygonAttr settings). BoxTest should not be issued within Begin/End.
After sending the BoxTest command, wait until GXSTAT.Bit0 indicates Ready, then read the result from GXSTAT.Bit1.

40005C4h - Cmd 71h - POS_TEST - Set Position Coordinates for Test (W)
  Parameter 1, Bit 0-15   X-Coordinate
  Parameter 1, Bit 16-31  Y-Coordinate
  Parameter 2, Bit 0-15   Z-Coordinate
  Parameter 2, Bit 16-31  Not used
  All values are 1bit sign, 3bit integer, 12bit fractional part.
Multiplies the specified line-vector (x,y,z,1) by the clip coordinate matrix.
After sending the command, wait until GXSTAT.Bit0 indicates Ready, then read the result from POS_RESULT registers. POS_TEST can be issued anywhere (except within polygon strips, huh?).
Caution: POS_TEST overwrites the internal VTX registers, so the next vertex should be <fully> defined by VTX_10 or VTX_16, otherwise, when using VTX_XY, VTX_XZ, VTX_YZ, or VTX_DIFF, then the new vertex will be relative to the POS_TEST coordinates (rather than to the previous vertex).

4000620h..62Fh - POS_RESULT - Position Test Results (R)
This 16-byte region (4 words) contains the resulting clip coordinates (x,y,z,w) from the POS_TEST command. Each value is 1bit sign, 19bit integer, 12bit fractional part.

40005C8h - Cmd 72h - VEC_TEST - Set Directional Vector for Test (W)
  Parameter 1, Bit 0-9    X-Component
  Parameter 1, Bit 10-19  Y-Component
  Parameter 1, Bit 20-29  Z-Component
  Parameter 1, Bit 30-31  Not used
  All values are 1bit sign, 9bit fractional part.
Multiplies the specified line-vector (x,y,z,0) by the directional vector matrix. Similar as for the NORMAL command, it does require Matrix Mode 2 (ie. Position & Vector Simultaneous Set mode).
After sending the command, wait until GXSTAT.Bit0 indicates Ready, then read the result ("the directional vector in the View coordinate space") from VEC_RESULT registers.

4000630h..635h - VEC_RESULT - Vector Test Results (R)
This 6-byte region (3 halfwords) contains the resulting vector (x,y,z) from the VEC_TEST command. Each value is 4bit sign, 0bit integer, 12bit fractional part. The 4bit sign is either 0000b (positive) or 1111b (negative).
There is no integer part, so values >=1.0 or <-1.0 will cause overflows.
(Eg. +1.0 aka 1000h will be returned as -1.0 aka F000h due to overflow and sign-expansion).


DS 3D Rear-Plane

Other docs seem to refer to this as Clear-plane, rather than Rear-plane, anyways, the plane can be an image, so it isn't always "cleared".
The view order is as such:
  --> 2D Layers --> 3D Polygons --> 3D Rear-plane --> 2D Layers --> 2D Backdrop
The rear-plane can be disabled (by making it transparent; alpha=0), so that the 2D layers become visible as background.
2D layers can be moved in front of, or behind the 3D layer-group (which is represented as BG0 to the 2D Engine), 2D layers behind BG0 can be used instead of, or additionally to the rear-plane.

The rear-plane can be initialized via below two registers (so all pixels in the plane have the same colors and attributes), this method is used when DISP3DCNT.14 is zero:

4000350h - CLEAR_COLOR - Clear Color Attribute Register (W)
  0-4    Clear Color, Red
  5-9    Clear Color, Green
  10-14  Clear Color, Blue
  15     Fog (enables Fog to the rear-plane) (doesn't affect Fog of polygons)
  16-20  Alpha
  21-23  Not used
  24-29  Clear Polygon ID (affects edge-marking, at the screen-edges?)
  30-31  Not used

4000354h - CLEAR_DEPTH - Clear Depth Register (W)
  0-14   Clear Depth (0..7FFFh) (usually 7FFFh = most distant)
  15     Not used
  16-31  See Port 4000356h, CLRIMAGE_OFFSET
The 15bit Depth is expanded to 24bit as "X=(X*200h)+((X+1)/8000h)*1FFh".

Rear Color/Depth Bitmaps
Alternately, the rear-plane can be initialized by bitmap data (allowing to assign different colors & attributes to each pixel), this method is used when DISP3DCNT.14 is set:
Consists of two bitmaps (one with color data, one with depth data), each containing 256x256 16bit entries, and so, each occupying a whole 128K slot,
  Rear Color Bitmap (located in Texture Slot 2)
    0-4    Clear Color, Red
    5-9    Clear Color, Green
    10-14  Clear Color, Blue
    15     Alpha (0=Transparent, 1=Solid) (equivalent to 5bit-alpha 0 and 31)
  Rear Depth Bitmap (located in Texture Slot 3)
    0-14   Clear Depth, expanded to 24bit as X=(X*200h)+((X+1)/8000h)*1FFh
    15     Clear Fog (Initial fog enable value)
This method requires VRAM to be allocated to Texture Slot 2 and 3 (see Memory Control chapter). Of course, in that case the VRAM is used as Rear-plane, and cannot be used for Textures.
The bitmap method is restricted to 1bit alpha values (the register-method allows to use a 5bit alpha value).
The Clear Polygon ID is kept defined in the CLEAR_COLOR register, even in bitmap mode.

4000356h - CLRIMAGE_OFFSET - Rear-plane Bitmap Scroll Offsets (W)
The visible portion of the bitmap is 256x192 pixels (regardless of the viewport setting, which is used only for polygon clipping). Internally, the bitmap is 256x256 pixels, so the bottom-most 64 rows are usually offscreen, unless scrolling is used to move them into view.
  Bit0-7   X-Offset (0..255; 0=upper row of bitmap)
  Bit8-14  Y-Offset (0..255; 0=left column of bitmap)
The bitmap wraps to the upper/left edges when exceeding the lower/right edges.


DS 3D Final 2D Output

The final 3D image (consisting of polygons and rear-plane) is passed to 2D Engine A as BG0 layer (provided that DISPCNT is configured to use 3D as BG0).

Scrolling
The BG0HOFS register (4000010h) can be used the scroll the 3D layer horizontally, the scroll region is 512 pixels, consisting of 256 pixels for the 3D image, followed by 256 transparent pixels, and then wrapped to the 3D image again. Vertical scrolling (and rotation/scaling) cannot be used on the 3D layer.

BG Priority Order
The lower 2bit of the BG0CNT register (4000008h) control the priority relative to other BGs and OBJs, so the 3D layer can be in front of or behind 2D layers. All other bits in BG0CNT have no effect on 3D, namely, mosaic cannot be used on the 3D layer.

Special Effects
Special Effects Registers (4000050h..54h) can be used as such:
  Brightness up/down with BG0 as 1st Target via EVY   (as for 2D)
  Blending with BG0 as 2nd Target via EVA/EVB         (as for 2D)
  Blending with BG0 as 1st Target via 3D Alpha-values (unlike as for 2D)
The latter method probably (?) uses per-pixel 3D alpha values as such: EVA=A/2, and EVB=16-A/2, without using the EVA/EVB settings in 4000052h.

Window Feature
Window Feature (4000040h..4Bh) can be used as for 2D.
"If the 3D screen has highest priority, then alpha-blending is always enabled, regardless of the Window Control register's color effect enable flag [ie. regardless of Bit5 of WIN0IN, WIN1IN, WINOBJ, WINOUT registers]"... not sure if that is true, and if it superseedes the effect selection in Port 4000050h...?


DS Sound

DS Sound Hardware
The DS contains 16 hardware sound channels.
The console contains two speakers, arranged left and right of the upper screen, and so, provides stereo sound even without using the headphone socket.
DS Sound Channels 0..15
DS Sound Control Registers
DS Sound Capture
DS Sound Block Diagrams
DS Sound Notes

DS Sound Files
DS Files - Sound (SDAT etc.)

Power control
When restoring power supply to the sound circuit, do not output any sound during the first 15 milliseconds.


DS Sound Channels 0..15

Each of the 16 sound channels occopies 16 bytes in the I/O region, starting with channel 0 at 4000400h..400040Fh, up to channel 15 at 40004F0h..40004FFh.

40004x0h - NDS7 - SOUNDxCNT - Sound Channel X Control Register (R/W)
  Bit0-6    Volume Mul   (0..127=silent..loud)
  Bit7      Not used     (always zero)
  Bit8-9    Volume Div   (0=Normal, 1=Div2, 2=Div4, 3=Div16)
  Bit10-14  Not used     (always zero)
  Bit15     Hold         (0=Normal, 1=Hold last sample after one-shot sound)
  Bit16-22  Panning      (0..127=left..right) (64=half volume on both speakers)
  Bit23     Not used     (always zero)
  Bit24-26  Wave Duty    (0..7) ;HIGH=(N+1)*12.5%, LOW=(7-N)*12.5% (PSG only)
  Bit27-28  Repeat Mode  (0=Manual, 1=Loop Infinite, 2=One-Shot, 3=Prohibited)
  Bit29-30  Format       (0=PCM8, 1=PCM16, 2=IMA-ADPCM, 3=PSG/Noise)
  Bit31     Start/Status (0=Stop, 1=Start/Busy)
All channels support ADPCM/PCM formats, PSG rectangular wave can be used only on channels 8..13, and white noise only on channels 14..15.

40004x4h - NDS7 - SOUNDxSAD - Sound Channel X Data Source Register (W)
  Bit0-26  Source Address (must be word aligned, bit0-1 are always zero)
  Bit27-31 Not used

40004x8h - NDS7 - SOUNDxTMR - Sound Channel X Timer Register (W)
  Bit0-15  Timer Value, Sample frequency, timerval=-(33513982Hz/2)/freq
The PSG Duty Cycles are composed of eight "samples", and so, the frequency for Rectangular Wave is 1/8th of the selected sample frequency.
For PSG Noise, the noise frequency is equal to the sample frequency.

40004xAh - NDS7 - SOUNDxPNT - Sound Channel X Loopstart Register (W)
  Bit0-15  Loop Start, Sample loop start position
           (counted in words, ie. N*4 bytes)

40004xCh - NDS7 - SOUNDxLEN - Sound Channel X Length Register (W)
The number of samples for N words is 4*N PCM8 samples, 2*N PCM16 samples, or 8*(N-1) ADPCM samples (the first word containing the ADPCM header). The Sound Length is not used in PSG mode.
  Bit0-21  Sound length (counted in words, ie. N*4 bytes)
  Bit22-31 Not used
Minimum length (the sum of PNT+LEN) is 4 words (16 bytes), smaller values (0..3 words) are causing hang-ups (busy bit remains set infinite, but no sound output occurs).

In One-shot mode, the sound length is the sum of (PNT+LEN).
In Looped mode, the length is (1*PNT+Infinite*LEN), ie. the first part (PNT) is played once, the second part (LEN) is repeated infinitely.


DS Sound Control Registers

4000500h - NDS7 - SOUNDCNT - Sound Control Register (R/W)
  Bit0-6   Master Volume       (0..127=silent..loud)
  Bit7     Not used            (always zero)
  Bit8-9   Left Output from    (0=Left Mixer, 1=Ch1, 2=Ch3, 3=Ch1+Ch3)
  Bit10-11 Right Output from   (0=Right Mixer, 1=Ch1, 2=Ch3, 3=Ch1+Ch3)
  Bit12    Output Ch1 to Mixer (0=Yes, 1=No) (both Left/Right)
  Bit13    Output Ch3 to Mixer (0=Yes, 1=No) (both Left/Right)
  Bit14    Not used            (always zero)
  Bit15    Master Enable       (0=Disable, 1=Enable)
  Bit16-31 Not used            (always zero)

4000504h - NDS7 - SOUNDBIAS - Sound Bias Register (R/W)
  Bit0-9   Sound Bias    (0..3FFh, usually 200h)
  Bit10-31 Not used      (always zero)
After applying the master volume, the signed left/right audio signals are in range -200h..+1FFh (with medium level zero), the Bias value is then added to convert the signed numbers into unsigned values (with medium level 200h).
BIAS output is always enabled, even when Master Enable (SOUNDCNT.15) is off.

The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits.


DS Sound Capture

The DS contains 2 built-in sound capture devices that can capture output waveform data to memory.
Sound capture 0 can capture output from left-mixer or output from channel 0.
Sound capture 1 can capture output from right-mixer or output from channel 2.

4000508h - NDS7 - SNDCAP0CNT - Sound Capture 0 Control Register (R/W)
4000509h - NDS7 - SNDCAP1CNT - Sound Capture 1 Control Register (R/W)
  Bit0     Control of Associated Sound Channels (ANDed with Bit7)
            SNDCAP0CNT: Output Sound Channel 1 (0=As such, 1=Add to Channel 0)
            SNDCAP1CNT: Output Sound Channel 3 (0=As such, 1=Add to Channel 2)
            Caution: Addition mode works only if BOTH Bit0 and Bit7 are set.
  Bit1     Capture Source Selection
            SNDCAP0CNT: Capture 0 Source (0=Left Mixer, 1=Channel 0/Bugged)
            SNDCAP1CNT: Capture 1 Source (0=Right Mixer, 1=Channel 2/Bugged)
  Bit2     Capture Repeat        (0=Loop, 1=One-shot)
  Bit3     Capture Format        (0=PCM16, 1=PCM8)
  Bit4-6   Not used              (always zero)
  Bit7     Capture Start/Status  (0=Stop, 1=Start/Busy)

4000510h - NDS7 - SNDCAP0DAD - Sound Capture 0 Destination Address (R/W)
4000518h - NDS7 - SNDCAP1DAD - Sound Capture 1 Destination Address (R/W)
  Bit0-26  Destination address (word aligned, bit0-1 are always zero)
  Bit27-31 Not used (always zero)
Capture start address (also used as re-start address for looped capture).

4000514h - NDS7 - SNDCAP0LEN - Sound Capture 0 Length (W)
400051Ch - NDS7 - SNDCAP1LEN - Sound Capture 1 Length (W)
  Bit0-15  Buffer length (1..FFFFh words) (ie. N*4 bytes)
  Bit16-31 Not used
Minimum length is 1 word (attempts to use 0 words are interpreted as 1 word).

SOUND1TMR - NDS7 - Sound Channel 1 Timer shared as Capture 0 Timer
SOUND3TMR - NDS7 - Sound Channel 3 Timer shared as Capture 1 Timer
There are no separate capture frequency registers, instead, the sample frequency of Channel 1/3 is shared for Capture 0/1. These channels are intended to output the captured data, so it makes sense that both capture and sound output use the same frequency.

For Capture 0, a=0, b=1, x=0.
For Capture 1, a=2, b=3, x=1.

Capture Bugs
The NDS contains two hardware bugs which do occur when capturing data from ch(a) (SNDCAPxCNT.Bit1=1), if so, either bug occurs depending on whether ch(a)+ch(b) addition is enabled or disabled (SNDCAPxCNT.Bit0).
  1) Both Negative Bug - SNDCAPxCNT Bit1=1, Bit0=0 (addition disabled)
   Capture data is accidently set to -8000h if ch(a) and ch(b) are both <0.
   Otherwise the correct capture result is returned, ie. plain ch(a) data,
   not being affected by ch(b) (since addition is disabled).
   Workaround: Ensure that ch(a) and/or ch(b) are >=0 (or disabled).
 2) Overflow Bug - SNDCAPxCNT Bit1=1, Bit0=1 (addition enabled)
   In this mode, Capture data isn't clipped to MinMax(-8000h,+7FFFh),
   instead, it is ANDed with FFFFh, so the sign bit is lost if the
   addition result ch(a)+ch(b) is less/greater than -8000h/+7FFFh.
   Workaround: Reduce ch(a)/ch(b) volume or data to avoid overflows.
These bugs occur only for capture (speaker output remains intact), and they occur only when capturing ch(a) (capturing mixer-output works flawless).

ch(a)+ch(b) Channel Addition
The ch(a)+ch(b) addition unit has 2 outputs, with slightly different results:
 1) Addition Result for Capture(x) when using capture source=ch(a):
  Addition is performed always, no matter of SOUNDCNT.Bit12/13.
  And, no matter of ch(a) enable, result is plain ch(b) if ch(a) is disabled.
  Result is 16bit (plus fraction) with overflow error (see Capture Bugs).
 2) Addition Result for Mixer (towards speakers, and capture source=mixer):
  Ch(b) is muted if ch(a) is disabled.
  Ch(b) is muted if ch(b) SOUNDCNT.Bit12/13 is set to "Ch(b) not to mixer".
  Result is 17bit (plus fraction) without overflow error.
Addition mode can be used only if the <corresponding> capture unit is enabled, ie. if SNDCAPxCNT (Bit0 AND Bit7)=1. If so, addition affects both mixers (and so, may also affect the <other> capture unit if it reads from mixer).


DS Sound Block Diagrams

Left Mixer with Capture 0
(Right Mixer with Capture 1, respectively)
                       _____
  Ch0.L ------------->|     |  .------------------------------> to Capture 0
               ___    |     |  |                  ___
  Ch1.L ---o->|Sel|-->|     |  |       Ch0..Ch15 |   |
           |  |___|   |Left |--o---------------->|   |
  Ch2.L ---|--------->|Mixer|                    |Sel|   ______    ____
           |   ___    |     |                Ch1 |   |  |Master|  |Add |
  Ch3.L -o-|->|Sel|-->|     | .----------------->|   |->|Volume|->|Bias|-> L
         | |  |___|   |     | |                  |   |  |______|  |____|
  Ch4.L -|-|--------->|     | |              Ch3 |   |
  ...   -|-|--------->|     | | .--------------->|   |
  Ch15.L-|-|--------->|_____| | |   ___          |   |
         | '------------------o-|->|Add| Ch1+Ch3 |   |
         '----------------------o->|___|-------->|___|

Channel 0 and 1, Capture 0 with input from Left Mixer
(Channel 2 and 3, Capture 1 with input from Right Mixer, respectively)
  ____     _________     ___     ___      ___
 |FIFO|-->|Channel 0|-->|Vol|-->|Add|-o->|Pan|--> Ch0.L
 |____|   |_________|   |___|   |___| |  |___|--> Ch0.R
  ____     _________     ___      ^   |
 |FIFO|<--|Capture 0|<--|Sel|<----|---'
 |____|   |_ _____ _|   |___|<----|-------------- Left Mixer
  ____     _:Timer:_     ___     _|_      ___
 |FIFO|-->|Channel 1|-->|Vol|-->|Sel|--->|Pan|--> Ch1.L
 |____|   |_________|   |___|   |___|    |___|--> Ch1.R

Channel 4 (Channel 5..15, respectively)
  ____     _________     ___              ___
 |FIFO|-->|Channel 4|-->|Vol|----------->|Pan|--> Ch4.L
 |____|   |_________|   |___|            |___|--> Ch4.R

The FIFO isn't used in PSG/Noise modes (supported on channel 8..15).


DS Sound Notes

Sound delayed Start/Restart (timing glitch)
A sound will be started/restarted when changing its start bit from 0 to 1, however, the sound won't start immediately: PSG/Noise starts after 1 sample, PCM starts after 3 samples, and ADPCM starts after 11 samples (3 dummy samples as for PCM, plus 8 dummy samples for the ADPCM header).

Sound Stop (timing note)
In one-shot mode, the Busy bit gets cleared automatically at the BEGIN of the last sample period, nethertheless (despite of the cleared Busy bit) the last sample is kept output until the END of the last sample period (or, if the Hold flag is set, then the last sample is kept output infinitely, that is, until Hold gets cleared, or until the sound gets restarted).

Hold Flag (appears useless/bugged)
The Hold flag allows to keep the last sample being output infinitely after the end of one-shot sounds. This feature is probably intended to allow to play two continous one-shot sound blocks (without producing any scratch noise upon small delays between both blocks, which would occur if the output level would drop to zero).
However, the feature doesn't work as intended. As described above, PCM8/PCM16 sound starts are delayed by 3 samples. With Hold flag set, old output level is acually kept intact during the 1st sample, but the output level drops to zero during 2nd-3rd sample, before starting the new sound in 4th sample.

7bit Volume and Panning Values
  data.vol   = data*N/128
  pan.left   = data*(128-N)/128
  pan.right  = data*N/128
  master.vol = data*N/128/64
Register settings of 0..126,127 are interpreted as N=0..126,128.

Max Output Levels
When configured to max volume (and left-most or right-most panning), each channel can span the full 10bit output range (-200h..1FFh) on one speaker, as well as the full 16bit input range (-8000h..7FFFh) on one capture unit.
(It needs 2 channels to span the whole range on BOTH speakers/capture units.)
Together, all sixteen channels could thus reach levels up to -1E00h..21F0h (with default BIAS=200h) on one speaker, and -80000h..+7FFF0h on one capture unit. However, to avoid overflows, speaker outputs are clipped to MinMax(0,3FFh), and capture inputs to MinMax(-8000h..+7FFFh).

Channel/Mixer Bit-Widths
  Step                           Bits  Min        Max
  0 Incoming PCM16 Data          16.0  -8000h     +7FFFh
  1 Volume Divider (div 1..16)   16.4  -8000h     +7FFFh
  2 Volume Factor (mul N/128)    16.11 -8000h     +7FFFh
  3 Panning (mul N/128)          16.18 -8000h     +7FFFh
  4 Rounding Down (strip 10bit)  16.8  -8000h     +7FFFh
  5 Mixer (add channel 0..15)    20.8  -80000h    +7FFF0h
  6 Master Volume (mul N/128/64) 14.21 -2000h     +1FF0h
  7 Strip fraction               14.0  -2000h     +1FF0h
  8 Add Bias (0..3FFh, def=200h) 15.0  -2000h+0   +1FF0h+3FFh
  9 Clip (min/max 0h..3FFh)      10.0  0          +3FFh
Table shows integer.fractional bits, and min/max values (without fraction).

Capture Clipping/Rounding
Incoming ch(a) is NOT clipped, ch(a)+ch(b) may overflow (see Capture Bugs).
Incoming mixer data (20.8bits) is clipped to 16.8bits (MinMax -8000h..7FFFh).
For PCM8 capture format, the 16.8 bits are divided by 100h (=8.16 bits).
If the MSB of the fractional part is set, then data is rounded towards zero.
(Positive values are rounded down, negative values are rounded up.)
The fractional part is then discarded, and plain integer data is captured.

PSG Sound
The output volume equals to PCM16 values +7FFFh (HIGH) and -7FFFh (LOW).
PSG sound is always Infinite (the SOUNDxLEN Register, and the SOUNDxCNT Repeat Mode bits have no effect). The PSG hardware doesn't support sound length, sweep, or volume envelopes, however, these effects can be produced by software with little overload (or, more typically, with enormous overload, depending on the programming language used).

PSG Wave Duty (channel 8..13 in PSG mode)
Each duty cycle consists of eight HIGH or LOW samples, so the sound frequency is 1/8th of the selected sample rate. The duty cycle always starts at the begin of the LOW period when the sound gets (re-)started.
  0  12.5% "_______-_______-_______-"
  1  25.0% "______--______--______--"
  2  37.5% "_____---_____---_____---"
  3  50.0% "____----____----____----"
  4  62.5% "___-----___-----___-----"
  5  75.0% "__------__------__------"
  6  87.5% "_-------_-------_-------"
  7   0.0% "________________________"
The Wave Duty bits exist and are read/write-able on all channels (although they are actually used only in PSG mode on channels 8-13).

PSG Noise (channel 14..15 in PSG mode)
Noise randomly switches between HIGH and LOW samples, the output levels are calculated, at the selected sample rate, as such:
  X=X SHR 1, IF carry THEN Out=LOW, X=X XOR 6000h ELSE Out=HIGH
The initial value when (re-)starting the sound is X=7FFFh. The formula is more or less same as "15bit polynomial counter" used on 8bit Gameboy and GBA.

PCM8 and PCM16
Signed samples in range -80h..+7Fh (PCM8), or -8000h..+7FFFh (PCM16).
The output volume of PCM8=NNh is equal to PCM16=NN00h.

IMA-ADPCM Format
IMA-ADPCM is a Adaptive Differential Pulse Code Modulation (ADPCM) variant, designed by International Multimedia Association (IMA), the format is used, among others, in IMA-ADPCM compressed Windows .WAV files.
The NDS data consist of a 32bit header, followed by 4bit values (so each byte contains two values, the first value in the lower 4bits, the second in upper 4 bits). The 32bit header contains initial values:
  Bit0-15   Initial PCM16 Value (Pcm16bit = -7FFFh..+7FFF) (not -8000h)
  Bit16-22  Initial Table Index Value (Index = 0..88)
  Bit23-31  Not used (zero)
In theory, the 4bit values are decoded into PCM16 values, as such:
  Diff = ((Data4bit AND 7)*2+1)*AdpcmTable[Index]/8      ;see rounding-error
  IF (Data4bit AND 8)=0 THEN Pcm16bit = Max(Pcm16bit+Diff,+7FFFh)
  IF (Data4bit AND 8)=8 THEN Pcm16bit = Min(Pcm16bit-Diff,-7FFFh)
  Index = MinMax (Index+IndexTable[Data4bit AND 7],0,88)
In practice, the first line works like so (with rounding-error):
  Diff = AdpcmTable[Index]/8
  IF (data4bit AND 1) THEN Diff = Diff + AdpcmTable[Index]/4
  IF (data4bit AND 2) THEN Diff = Diff + AdpcmTable[Index]/2
  IF (data4bit AND 4) THEN Diff = Diff + AdpcmTable[Index]/1
And, a note on the second/third lines (with clipping-error):
  Max(+7FFFh) leaves -8000h unclipped (can happen if initial PCM16 was -8000h)
  Min(-7FFFh) clips -8000h to -7FFFh (possibly unlike windows .WAV files?)
Whereas, IndexTable[0..7] = -1,-1,-1,-1,2,4,6,8. And AdpcmTable [0..88] =
  0007h,0008h,0009h,000Ah,000Bh,000Ch,000Dh,000Eh,0010h,0011h,0013h,0015h
  0017h,0019h,001Ch,001Fh,0022h,0025h,0029h,002Dh,0032h,0037h,003Ch,0042h
  0049h,0050h,0058h,0061h,006Bh,0076h,0082h,008Fh,009Dh,00ADh,00BEh,00D1h
  00E6h,00FDh,0117h,0133h,0151h,0173h,0198h,01C1h,01EEh,0220h,0256h,0292h
  02D4h,031Ch,036Ch,03C3h,0424h,048Eh,0502h,0583h,0610h,06ABh,0756h,0812h
  08E0h,09C3h,0ABDh,0BD0h,0CFFh,0E4Ch,0FBAh,114Ch,1307h,14EEh,1706h,1954h
  1BDCh,1EA5h,21B6h,2515h,28CAh,2CDFh,315Bh,364Bh,3BB9h,41B2h,4844h,4F7Eh
  5771h,602Fh,69CEh,7462h,7FFFh
The closest way to reproduce the AdpcmTable with 32bit integer maths appears:
  X=000776d2h, FOR I=0 TO 88, Table[I]=X SHR 16, X=X+(X/10), NEXT I
  Table[3]=000Ah, Table[4]=000Bh, Table[88]=7FFFh, Table[89..127]=0000h
When using ADPCM and loops, set the loopstart position to the data part, rather than the header. At the loop end, the SAD value is reloaded to the loop start location, additionally index and pcm16 values are reloaded to the values that have originally appeared at that location. Do not change the ADPCM loop start position during playback.

Microphone Input
For Microphone (and Touchscreen) inputs, see
DS Touch Screen Controller (TSC)


DS Files - Sound (SDAT etc.)

Standard NDS Sound Files
Sound data is often stored in a SDAT file (with SSEQ, SSAR, SBNK, SWAR, STRM blocks inside of the SDAT files). Samples can be stored in SWAV files (or be contained in SWAR's inside of SDAT files).
DS Sound Files - SDAT (Sound Data Archive)
DS Sound Files - SSEQ (Sound Sequence)
DS Sound Files - SSAR (Sound Sequence Archive)
DS Sound Files - SBNK (Sound Bank)
DS Sound Files - SWAR (Sound Wave Archive)
DS Sound Files - SWAV (Sound Wave Data)
DS Sound Files - STRM (Sound Wave Stream)
Thanks: http://www.feshrine.net/hacking/doc/nds-sdat.php - 2007 by kiwi.ds

Other NDS Sound Files
DS Sound Files - HWAS (Multiblock Sound Wave Data)


DS Sound Files - SDAT (Sound Data Archive)

SDAT Header
  000h 4     ID "SDAT"           ;alike "CSAR" on 3DS
  004h 2     Byte Order    (FEFFh)
  006h 2     Version       (0100h)
  008h 4     Total Filesize
  00Ch 2     Header Size (usually 40h)
  00Eh 2     Number of Blocks (usually 4 = SYMB+INFO+FAT+FILE) (or 3=no SYMB)
  010h 4+4   SYMB Block (Offset from SDAT+0, Size) ;=0,0 if above is 3=no SYMB
  018h 4+4   INFO Block (Offset from SDAT+0, Size) ;\
  020h 4+4   FAT  Block (Offset from SDAT+0, Size) ; always present
  028h 4+4   FILE Block (Offset from SDAT+0, Size) ;/
  030h 10h   Padding to 20h-byte boundary (0)
The SYMB block exists in most SDAT files (except in some titles like Downhill Jam and Over the Hedge).

 _________________________________ SYMB Block _________________________________

Symbol Block (if present) (names for the corresponding items in INFO block)
  000h 4     ID "SYMB"
  004h 4     SYMB Block Size (rounded up to 4-byte boundary, unlike as in SDAT)
  008h 4     File List SSEQ    (Offset from SYMB+0) Sequences (songs)
  00Ch 4     Folder List SSAR  (Offset from SYMB+0) Sequence Archives (fx)
  010h 4     File List BANK    (Offset from SYMB+0) Banks
  014h 4     File List SWAR    (Offset from SYMB+0) Wave Archives (samples)
  018h 4     File List Player  (Offset from SYMB+0) Player (Group-related)
  01Ch 4     File List Group   (Offset from SYMB+0) Group (SSEQ+SSAR+BANK+SWAR)
  020h 4     File List Player2 (Offset from SYMB+0) Player2 (Stream-related)
  024h 4     File List STRM    (Offset from SYMB+0) Wave Stream
  028h 18h   Reserved (0)
  040h ..    File/Folder Lists (see below)
  ..   ..    File/Folder Name Strings (ASCII, terminated by 0)
  ..   ..    Padding to 4-byte boundary (0)
File List's are having following format:
  000h 4       Number of entries in this list (can be 0=None)
  004h N*4     File Name (Offset from SYMB+0)
Folder List (for SSAR):
  000h 4       Number of entries in this list (can be 0=None)
  004h N*(4+4) SSAR "Folder Name" and SSEQ "File List" (Offset's from SYMB+0)

 _________________________________ INFO Block _________________________________

Info Block
  000h 4     ID "INFO"
  004h 4     INFO Block Size (same as in SDAT header)
  008h 4     Info List SSEQ    (Offset from INFO+0) Sequences (songs)
  00Ch 4     Info List SSAR    (Offset from INFO+0) Sequence Archives (fx)
  010h 4     Info List BANK    (Offset from INFO+0) Banks
  014h 4     Info List SWAR    (Offset from INFO+0) Wave Archives (samples)
  018h 4     Info List Player  (Offset from INFO+0) Player (Group-related)
  01Ch 4     Info List Group   (Offset from INFO+0) Group (SSEQ+SSAR+BANK+SWAR)
  020h 4     Info List Player2 (Offset from INFO+0) Player2 (Stream-related)
  024h 4     Info List STRM    (Offset from INFO+0) Wave Stream
  028h 18h   Reserved (0)
  ..   ..    Info Lists (see below)
  ..   ..    Info Entries (see below)
  ..   ..    Padding to 4-byte boundary (0)
Info List's are having following format:
  000h 4     Number of entries in this list (can be 0=None)
  004h N*4   Info Entries (Offset from INFO+0)

SSEQ Info Entry (Sequences, eg. songs)
  000h 2   FAT fileID of SSEQ file      ;for accessing this file
  002h 2   Unknown
  004h 2   bnk         ;Associated BANK
  006h 1   vol         ;Volume
  007h 1   cpr
  008h 1   ppr
  009h 1   ply
  00Ah 2   Unknown (0)

SSAR Info Entry (Sequence Archives, eg. collections of sound effects)
  000h 2   FAT fileID of SSAR file
  002h 2   unknown
Note: bnk/vol/cpr/ppr/ply is stored in the SSAR file (instead of in Info). The actual sequences are also in SSAR? Or does the SSAR contain pointers to SSEQ files?

BANK Info Entry (Banks)
  000h 2   FAT fileID of SBNK file
  002h 2   unknown
  004h 2   1st SWAR   ;\
  006h 2   2nd SWAR   ; Associated Wave Archives (FFFFh=Unused entry)
  008h 2   3rd SWAR   ;
  00Ah 2   4th SWAR   ;/

SWAR Info Entry (Wave Archives, eg. collections of instruments or effects)
  000h 2   FAT fileID of SWAR file
  002h 2   unknown

Player Info Entry (whatever)
  000h 1   Unknown
  001h 3   Padding
  004h 4   Unknown

Group Info Entry (whatever, list of files that must be loaded to memory?)
  000h 4       Number of items in this group
  004h N*(4+4) Array (with ID+Index pairs)
ID values: 700h=SSEQ, 803h=SSAR, 601h=BANK, 402h=SWAR.
Index: Entry number in the corresponding SSEQ/SSAR/BANK/SWAR list.

Player2 Info Entry (whatever, Stream related?)
  000h 1   nCount             ;number of USED entries in below array
  001h 16  v[16]              ;unknown array (UNUSED entries are set to FFh
  011h 7   Reserved (0)

STRM Info Entry
  000h 2   FAT fileID of STRM file    ;for accessing the file
  002h 2   Unknown
  004h 1   vol            ;volume
  005h 1   pri            ;priority?
  006h 1   ply            ;play?
  007h 5   Reserved (0)

 ____________________________ FAT and FILE Blocks _____________________________

FAT Block
  000h 4         ID "FAT "
  004h 4         FAT Block Size (same as in SDAT header) (0Ch+N*10h)
  008h 4         Number of files
  00Ch N*(4+4+8) File Entries (Offset from SDAT+0, Size, Zero)
The 8-byte Zero entries can be used for storing data at runtime.

File Block
  000h 4         ID "FILE"
  004h 4         FILE Block Size (same as in SDAT header)
  008h 4         Number of files (same as in FAT block)
  00Ch 4         Reserved (0)
  010h ..        Files (SSEQ,SSAR,SBNK,SWAR,STRM) (at offsets specified in FAT)


DS Sound Files - SSEQ (Sound Sequence)

It is a converted MIDI sequence. Linked to a BANK for instruments.
SSEQ is usually found inside of SDAT files (but also exists as standalone file, eg. 3DS Circle Pad Pro test/calib, RomFS:\extrapad_bcwav_LZ.bin\*.sseq, and 3DS Picture Picker, RomFS:\sound\csnd.LZ\*).

SSEQ Header
  000h 4     ID "SSEQ"                                  ;\
  004h 2     Byte Order    (FEFFh)                      ;
  006h 2     Version       (0100h)                      ; Main header
  008h 4     Total Filesize                             ;
  00Ch 2     Header Size (usually 10h)                  ;
  00Eh 2     Number of Blocks (usually 1 = DATA)        ;/
  010h 4     ID "DATA"                                  ;\
  014h 4     Total Filesize, minus 10h                  ; Sub header
  018h 4     Offset to data (from SSEQ+0) (1Ch)         ;/
  01Ch ..    Arrays of sequence data..                  ;-

NB. For the details of the SSEQ file, please refer to loveemu's sseq2mid

Description
A SSEQ can have at maximum 16 tracks, notes in the range of 0..127 (middle C is 60). Each quartet note has a fixed tick length of 48. Tempo in the range of 1..240 BPM (default is 120). The SSEQ will not be played correctly if tempo higher than 240.

The SEQ player uses ARM7's Timer1 for timing. The ARM7's 4 Timers runs at 33MHz (approximately 2^25). The SEQ player sets Timer1 reload value to 2728, prescaler to F/64. So on about every 0.0052 sec (64*2728/33MHz) the SEQ Player will be notified (1 cycle). As a quartet note has fixed tick value of 48, the highest tempo that SEQ Player can handle is 240 BPM (60/(0.0052*48)).

During each cycle, the SEQ player adds the tempo value to a variable. Then it checks if the value exceeds 240. If it does, the SEQ player subtracts 240 from the variable, and process the SSEQ file. Using this method, the playback is not very precise but the difference is too small to be noticed.

Take an example with tempo = 160 BPM, the SSEQ file is processed twice in 3 notifications.
  cycle  variable action
  1       0       Add 160
  2       160     Add 160
  3       320     Subtract 240, process once, add 160
  4       240     Subtract 240, process once, add 160
  5       160     Add 160
  6       320     Subtract 240, process once, add 160
  7       240     Subtract 240, process once, add 160
  8       160     Add 160

Events
  ID      Parameter             Description
  00h-7Fh Velocity: 1 byte [0..127]
          Duration: Variable Length
                                NOTE-ON. Duration is expressed in tick.
                                48 for quartet note.
                                Usually it is NOT a multiple of 3.
  80h     Duration: Variable Length
                                REST. It tells the SSEQ-sequencer to wait for
                                a certain tick. Usually it is a multiple of 3.
  81h     Bank & Program Number:
          Variable Length
                                bits[0..7] is the program number,
                                bits[8..14] is the bank number.
                                Bank change is seldomly found,
                                so usually bank 0 is used.
  FEh     2 bytes Indicates which tracks are used.
          Bit0 for track 0, ... Bit15 for track 15.
          If the bit is set, the corresponding track is used.
                                Indication begin of multitrack. Must be in the
                                beginning of the first track to work. A series
                                of event 0x93 follows.
  93h     4 bytes 1st byte is track number [0..15]
          The other 3 bytes are the relative adress of track data.
          Add nDataOffset (usually 0x1C) to find out the absolute address.
                                SSEQ is similar to MIDI in that track data are
                                stored one after one track. Unlike mod music.
  94h     JUMP Address: 3 bytes
          (Add nDataOffset (usually 0x1C) to find out the absolute address.)
                                JUMP. A jump must be backward. So that the
                                song will loop forever.
  95h     CALL Address: 3 bytes
          (Add nDataOffset (usually 0x1C) to find out the absolute address.)
  A0h-BFh See loveemu's sseq2mid for more details.
                                Some arithmetic operations / comparions.
                                Affect how SSEQ is to be played.
  C0h     1 byte  PAN                (0..127, middle is 64, uh?)
  C1h     1 byte  VOLUME             (0..127)
  C2h     1 byte  MASTER VOLUME      (0..127)
  C3h     1 byte  TRANSPOSE (Channel Coarse Tuning) (0..64 = 64..128 in MIDI)
  C4h     1 byte  PITCH BEND
  C5h     1 byte  PITCH BEND RANGE
  C6h     1 byte  TRACK PRIORITY
  C7h     1 byte  MONO/POLY          (0=Poly, 1=Mono)
  C8h     1 byte  TIE (unknown)      (0=Off, 1=On)
  C9h     1 byte  PORTAMENTO CONTROL
  CAh     1 byte  MODULATION DEPTH   (0=Off, 1=On)
  CBh     1 byte  MODULATION SPEED
  CCh     1 byte  MODULATION TYPE    (0=Pitch, 1=Volume, 2=Pan)
  CDh     1 byte  MODULATION RANGE
  CEh     1 byte  PORTAMENTO ON/OFF
  CFh     1 byte  PORTAMENTO TIME
  D0h     1 byte  ATTACK RATE
  D1h     1 byte  DECAY RATE
  D2h     1 byte  SUSTAIN RATE
  D3h     1 byte  RELEASE RATE
  D4h     1 byte  LOOP START         (how many times to be looped)
  D5h     1 byte  EXPRESSION
  D6h     1 byte  PRINT VARIABLE     (unknown)
  E0h     2 byte  MODULATION DELAY
  E1h     2 byte  TEMPO
  E3h     2 byte  SWEEP PITCH
  FCh     -       LOOP END           (for LOOP START)
  FDh     -       RETURN from CALL command
  FFh     -       EOT: End Of Track


DS Sound Files - SSAR (Sound Sequence Archive)

It is a collection of SSEQ sequences (mainly for relative short sound effects) (longer sequences like music are usually stored in separate SSEQ files instead of in SSAR archives).

SSAR Header
  000h 4     ID "SSAR"                                  ;\
  004h 2     Byte Order    (FEFFh)                      ;
  006h 2     Version       (0100h)                      ; Main header
  008h 4     Total Filesize                             ;
  00Ch 2     Header Size (usually 10h)                  ;
  00Eh 2     Number of Blocks (usually 1 = DATA)        ;/
  010h 4     ID "DATA"                                  ;\
  014h 4     Total Filesize, minus 10h                  ;
  018h 4     Offset to data (from SSAR+0) (20h+N*0Ch)   ; Sub header
  01Ch 4     Number of records                          ;
  020h N*0Ch Records (12 bytes each)                    ;/
  ..   ..    data... unknown content? alike SSEQ?       ;-

SSAR Records
  000h 4   nOffset    ;relative offset of the archived SEQ file,
                           absolute offset = nOffset + SSAR::nDataOffset
  004h 2   bnk        ;bank
  006h 1   vol        ;volume
  007h 1   cpr        ;channel pressure
  008h 1   ppr        ;polyphonic pressure
  009h 1   ply        ;play
  00Ah 2   reserved (0)

SSAR Data (addressed via relative offset in above 0Ch-byte record)
  data... unknown content? alike SSEQ?

NB. Archived SSEQ files are not stored in sequence (order). So Rec[0].nOffset may point to 0x100 but Rec[1].nOffset points to 0x40.

NB. Archived SSEQ files cannot be readily extracted from SSAR file because data in one SSEQ may 'call' data in other SSEQ.


DS Sound Files - SBNK (Sound Bank)

This seems to assign ADSR patterns to each note of each SWAV instrument...?

"A bank is linked to up to 4 SWAR files which contain the samples. It defines the instruments which a SSEQ sequence can use. You may imagine SSEQ + SBNK + SWAR are similar to module music created by trackers." uh?

SBNK Header
  000h 4   ID "SBNK"                                    ;\
  004h 2   Byte Order    (FEFFh)                        ;
  006h 2   Version       (0100h)                        ; Main header
  008h 4   Total Filesize                               ;
  00Ch 2   Header Size (usually 10h)                    ;
  00Eh 2   Number of Blocks (usually 1 = DATA)          ;/
  010h 4   ID "DATA"                                    ;\
  014h 4   Total Filesize, minus 10h                    ;
  018h 20h Reserved (0) (for use at runtime)            ; Sub header
  038h 4   Number of Instruments (SWAV's)               ;
  03Ch N*4 Instrument Records (1+2+1 bytes per instr.)  ;/
  ...  ..  Instrument Data (depending of above records) ;-

Instrument Record
  000h 1   fRecord     ;can be either 0, 1..4, 16 or 17
  001h 2   nOffset     ;absolute offset of the data in file  ;uh, misaligned?
  003h 1   Reserved (0)

fRecord = 0, it is empty (unknown purpose, dummy? or maybe disable ADSR?)
nOffset will also = 0.

fRecord < 16, the record is a note/wave definition
"I have seen values 1, 2 and 3. But it seems the value does not affect the wave/note definition that follows. Instrument record size is 10 bytes."
  00h 10    SWAV, SWAR, Note, Attack, Decay, Sustain, Release, Pan

fRecord = 16, the record is a range of note/wave definitions
  00h      1   Lower note (0..127)          ;eg. 10 ;\notes 10..20
  01h      1   Upper note (0..127)          ;eg. 20 ;/
  02h+N*12 2   Unknown (usually 0001h)
  04h+N*12 10  SWAV, SWAR, Note, Attack, Decay, Sustain, Release, Pan

fRecord = 17, the record is a regional wave/note definition
  00h      1   End of 1st region (0..127)   ;eg. 25  = notes 0..25
  01h      1   End of 2nd region (0..127)   ;eg. 35  = notes 26..35
  02h      1   End of 3rd region (0..127)   ;eg. 45  = notes 36..45
  03h      1   End of 4th region (0..127)   ;eg. 55  = notes 46..55
  04h      1   End of 5th region (0..127)   ;eg. 65  = notes 56..65
  05h      1   End of 6th region (0..127)   ;eg. 127 = notes 66..last
  06h      1   End of 7th region (0..127)   ;eg. 0   = none
  07h      1   End of 8th region (0..127)   ;eg. 0   = none
  08h+N*12 2   Unknown (usually 0001h)
  08h+N*12 10  SWAV, SWAR, Note, Attack, Decay, Sustain, Release, Pan
REMARKS: Unknown bytes before wave/defnition definition = 5, not 1 in stage_04_bank.sbnk, stage_04.sdat, Rom No.1156, uh?

SWAV, SWAR, Note, Attack, Decay, Sustain, Release, Pan
  00h 2  SWAV Number   the swav used
  02h 2  SWAR Mumber   the swar used (see Info Block --> "BANK Info Entry")
  04h 1  Note Number   (0..127)
  05h 1  Attack Rate   (0..127, 127=fast)
  06h 1  Decay Rate    (0..127, 127=fast)
  07h 1  Sustain Level (0..127, 127=stay at max, no decay)
  08h 1  Release Rate  (0..127, 127=fast)
  09h 1  Pan           (0..127, 64=middle) (uh, what=left, what=right?)

Articulation Data
             .                   <-- max level (127)
            / \
           /   \
          /     '---------.      <-- sustain level (0..127)
         /                 \
        /                   \
  -----'---------------------'-- <-- min level (0)
      Attack Decay Sustain Release

  "The SEQ Player treats 0 as the 100% amplitude value and -92544 (723*128)
  as the 0% amplitude value. The starting ampltitude is 0% (-92544)." uh?

  "During the attack phase, in each cycle, the SSEQ Player calculates the new
  amplitude value: amplitude value = attack rate * amplitude value / 255. The
  attack phase stops when amplitude reaches 0." THAT IS... NON-LINEAR attack?

  "During the decay phase, in each cycle, the SSEQ Player calculates the new
  amplitude value: amplitude value = amplitude value - decay rate.
  Note the starting amplitude value is 0. The decay phase stops when
  amplitude reaches sustain level." THAT IS... LINEAR decay/release?


DS Sound Files - SWAR (Sound Wave Archive)

It is a collection of mono wave (SWAV) samples only (which can be in either PCM8, PCM16 or ADPCM compression).

SWAR Header
  000h 4     ID "SWAR"                                  ;\
  004h 2     Byte Order    (FEFFh)                      ;
  006h 2     Version       (0100h)                      ; Main header
  008h 4     Total Filesize (including SWAV's)          ;
  00Ch 2     Header Size (usually 10h)                  ;
  00Eh 2     Number of Blocks (usually 1 = DATA)        ;/
  010h 4     ID "DATA"                                  ;\
  014h 4     Total Filesize, minus 10h                  ;
  018h 20h   Reserved (0) (for use at runtime)          ; Sub header
  038h 4     Number of SWAV sample blocks               ;
  03Ch N*4   Offsets to Sample blocks (from SWAR+0)     ;/
  ..   ..    Sample blocks... starting with Type (0=PCM8, 1=PCM16, 2=IMA-ADPCM)
When extracting single sample block, one can convert them to SWAV files (by inserting an 18h-byte SWAV header).
The sample blocks are usually (always?) stored at increasing offsets (so one can determine the size by computing the distance to next offset; or to filesize for last entry) (alternately, the size can be computed by looking at the Sound Length entry of sample block).


DS Sound Files - SWAV (Sound Wave Data)

SWAV Header (present only in standalone SWAV files) (not in SWAR archives)
  000h 4     ID "SWAV"                                  ;\
  004h 2     Byte Order    (FEFFh)                      ;
  006h 2     Version       (0100h)                      ; Main header
  008h 4     Total Filesize                             ;
  00Ch 2     Header Size (usually 10h)                  ;
  00Eh 2     Number of Blocks (usually 1 = DATA)        ;/
  010h 4     ID "DATA"                                  ;\Sub header
  014h 4     Total Filesize, minus 10h                  ;/
  018h ..    Sample block (see below)
Note: System Flaw has a lot of SWAV files (instead of using SWAR archives).

Sample Block Format (present in SWAV files and SWAR archives)
  000h 1    WaveType (0=PCM8, 1=PCM16, 2=IMA-ADPCM)
  001h 1    Loop flag = TRUE|FALSE   ;uh?
  002h 2    Sampling Rate
  004h 2    Time (ARM7_CLOCK / nSampleRate)
                [ARM7_CLOCK: 33.513982MHz/2 = 1.6756991 E +7]
  006h 2    Loop Offset, in 4-byte units
  008h 4    Sound Length, in 4-byte units (exluding ADPCM header, if any)
  00Ch ...  Data... (samples) (with 32bit header in case of ADPCM)


DS Sound Files - STRM (Sound Wave Stream)

It is an individual mono/stereo wave file (PCM8, PCM16 or ADPCM) (eg. used in Ultimate Spiderman rom:\sound\sound_stream.sdat).

STRM Header
  000h 4     ID "STRM"                                          ;\
  004h 2     Byte Order    (FEFFh)                              ;
  006h 2     Version       (0100h)                              ; Main header
  008h 4     Total Filesize                                     ;
  00Ch 2     Header Size (usually 10h)                          ;
  00Eh 2     Number of Blocks (usually 2 = HEAD+DATA)           ;/
  010h 4     ID "HEAD"                                          ;\
  014h 4     Size of HEAD structure (uh, this is... 50h?)       ;
  018h 1     Type       (0=PCM8, 1=PCM16, 2=IMA-ADPCM)          ; Sub header
  019h 1     Loop flag  (?=TRUE|FALSE)  ;uh?                    ;
  01Ah 1     Channels   (?=What)        ;mono/stereo?           ;
  01Bh 1     Unknown    (always 0)                              ;
  01Ch 2     Sampling Rate (perhaps resampled from original)    ;
  01Eh 2     Time (1.0 / rate * ARM7_CLOCK / 32)                ;
               [ARM7_CLOCK: 33.513982MHz/2 = 1.6756991e7]       ;
  020h 4     Loop Offset (samples)                              ;
  024h 4     Number of Samples                                  ;
  028h 4     Wave Data Offset (always 68h)                      ;
  02Ch 4     Number of Blocks       (per what?)                 ;
  030h 4     Block Length           (per Channel)               ;
  034h 4     Samples Per Block      (per Channel)               ;
  038h 4     Last Block Length      (per Channel)               ;
  03Ch 4     Samples Per Last Block (per Channel)               ;
  040h 20h   Reserved (always 0)                                ;/
  060h 4     ID "DATA"                                          ;\Data header
  064h 4     Data Size (8+N ?)                                  ;/
  068h N     Wave Data blocks...                                ;-Sample data
Mono blocks are ordered: Block1, Block2, Block3, etc.
Stereo blocks are ordered: LeftBlock1, RightBlock1, LeftBlock2, etc.


DS Sound Files - HWAS (Multiblock Sound Wave Data)

Used in NDS Over the Hedge, rom:\vvobj\generated\gob\main.gfc and main.gob
Used in NDS Downhill Jam, rom:\vvobj\generated\gob\main.gfc and main.gob
(the Hedge/Downhill archives contain both .hwas and .swav files, plus other stuff).
Reportedly, Guitar Heroes On Tour series does also use .hwas files.
  000h 4    ID "sawh" (aka "hwas" spelled backwards)
  004h 4    Blocksize (2000h in Over the Hedge, 8000h in Guitar Heroes)
  008h 4    Samplerate in Hertz (always 19996)
  00Ch 4    Number of Channels (always 1=mono)
  010h 4    Loop Start Sample (always 0, offset from start of data section)
  014h 4    Filesize minus 200h (ie. excluding 200h-byte header)
  018h 4    Loop End Sample (end of music, offset from start of data section)
  01Ch 1E4h Zerofilled
 Data Section:
  200h ..   1st data block (adpcm_header[4], plus adpcm_data[blocksize])
  ...  ..   2nd data block (adpcm_header[4], plus adpcm_data[blocksize])
  ...  ..   etc.
  ...  ..   Last data block (adpcm_header[4], plus adpcm_data[remaining bytes])
  ...  ..   Padding to 200h-byte boundary
The .hwas format contains more or less the same data as Nintendo's .swav format:
DS Sound Files - SWAV (Sound Wave Data)
The main difference is that .swav has only one data block, and .hwas is split into several data blocks (each with their own 4-byte adpcm header).


DS System and Built-in Peripherals

DS DMA Transfers
DS Timers
DS Interrupts
DS Maths
DS Inter Process Communication (IPC)
DS Keypad
DS Absent Link Port
DS Real-Time Clock (RTC)
DS Serial Peripheral Interface Bus (SPI)
DS Touch Screen Controller (TSC)
DS Power Management Device
DS Power Control
DS Backwards-compatible GBA-Mode
DS Debug Registers (Emulator/Devkits)


DS DMA Transfers

The DS includes four DMA channels for each CPU (ie. eight channels in total), which are working more or less the same as on GBA:
GBA DMA Transfers
All NDS9 and NDS7 DMA Registers are R/W. The gamepak bit (Bit 27) has been removed (on the NDS9 the bit is used to expand the mode setting to 3bits).

NDS9 DMA
Word count of all channels is expanded to 21bits (max 1..1FFFFFh units, or 0=200000h units), and SAD/DAD registers for all channels support ranges of 0..0FFFFFFEh. The transfer modes (DMACNT Bit27-29) are:
  0  Start Immediately
  1  Start at V-Blank
  2  Start at H-Blank (paused during V-Blank)
  3  Synchronize to start of display
  4  Main memory display
  5  DS Cartridge Slot
  6  GBA Cartridge Slot
  7  Geometry Command FIFO

NDS7 DMA
Word Count, SAD, and DAD are R/W, aside from that they do have the same restrictions as on GBA (max 4000h or 10000h units, some addresses limited to 0..07FFFFFEh). DMACNT Bit27 is unused on NDS7. The transfer modes (DMACNT Bit28-29) are:
  0  Start Immediately
  1  Start at V-Blank
  2  DS Cartridge Slot
  3  DMA0/DMA2: Wireless interrupt, DMA1/DMA3: GBA Cartridge Slot

40000E0h - NDS9 only - DMA0FILL - DMA 0 Filldata (R/W)
40000E4h - NDS9 only - DMA1FILL - DMA 1 Filldata (R/W)
40000E8h - NDS9 only - DMA2FILL - DMA 2 Filldata (R/W)
40000ECh - NDS9 only - DMA3FILL - DMA 3 Filldata (R/W)
  Bit0-31 Filldata
The DMA Filldata registers contain 16 bytes of general purpose WRAM, intended to be used as fixed source addresses for DMA memfill operations.
This is useful because DMA cannot read from TCM, and reading from Main RAM would require to recurse cache & write buffer.
The DMA Filldata is used with Src=Fixed and SAD=40000Exh (which isn't optimal because it's doing repeated reads from SAD, and, for that reason, a memfill via STMIA opcodes can be faster than DMA; the DSi's new NDMA channels are providing a faster fill method with Src=Fill and SAD=Unused).

NDS7 Sound DMA
The NDS additionally includes 16 Sound DMA channels, plus 2 Sound Capture DMA channels (see Sound chapter). The priority of these channels is unknown.

NDS9 Cache, Writebuffer, DTCM, and ITCM
Cache and tightly coupled memory are connected directly to the NDS9 CPU, without using the system bus. So that, DMA cannot access DTCM/ITCM, and access to cached memory regions must be handled with care: Drain the writebuffer before DMA-reads, and invalidate the cache after DMA-writes. See,
ARM CP15 System Control Coprocessor
The CPU can be kept running during DMA, provided that it is accessing only TCM (or cached memory), otherwise the CPU is halted until DMA finishes.
Respectively, interrupts executed during DMA will usually halt the CPU (unless the IRQ handler uses only TCM and cache; the IRQ vector at FFFF00xxh must be cached, or relocated to ITCM at 000000xxh, and the IRQ handler may not access IE, IF, or other I/O ports).

NDS Sequential Main Memory DMA
Main RAM has different access time for sequential and non-sequential access. Normally DMA uses sequential access (except for the first word), however, if the source and destination addresses are both in Main RAM, then all accesses become non-sequential. In that case it would be faster to use two DMA transfers, one from Main RAM to a scratch buffer in WRAM, and one from WRAM to Main RAM.


DS Timers

Same as GBA, except F = 33.513982 MHz (for both NDS9 and NDS7).
GBA Timers
Both NDS9 and NDS7 have four Timers each, eight Timers in total.
The NDS sound controller is having its own frequency generators (unlike GBA, which needed to use Timers to drive channel A/B sounds).


DS Interrupts

4000208h - NDS9/NDS7 - IME - Interrupt Master Enable (R/W)
  0     Disable all interrupts  (0=Disable All, 1=See IE register)
  1-31  Not used

4000210h - NDS9/NDS7 - IE - 32bit - Interrupt Enable (R/W)
4000214h - NDS9/NDS7 - IF - 32bit - Interrupt Request Flags (R/W)
Bits in the IE register are 0=Disable, 1=Enable.
Reading IF returns 0=No request, 1=Interrupt Request.
Writing IF acts as 0=No change, 1=Acknowledge (clears that bit).
  0     LCD V-Blank
  1     LCD H-Blank
  2     LCD V-Counter Match
  3     Timer 0 Overflow
  4     Timer 1 Overflow
  5     Timer 2 Overflow
  6     Timer 3 Overflow
  7     NDS7 only: SIO/RCNT/RTC (Real Time Clock)
  8     DMA 0
  9     DMA 1
  10    DMA 2
  11    DMA 3
  12    Keypad
  13    GBA-Slot (external IRQ source) / DSi: None such
  14    Not used                       / DSi9: NDS-Slot Card change?
  15    Not used                       / DSi: dito for 2nd NDS-Slot?
  16    IPC Sync
  17    IPC Send FIFO Empty
  18    IPC Recv FIFO Not Empty
  19    NDS-Slot Game Card Data Transfer Completion
  20    NDS-Slot Game Card IREQ_MC
  21    NDS9 only: Geometry Command FIFO
  22    NDS7 only: Screens unfolding
  23    NDS7 only: SPI bus
  24    NDS7 only: Wifi    / DSi9: XpertTeak DSP
  25    Not used           / DSi9: Camera
  26    Not used           / DSi9: Undoc, IF.26 set on FFh-filling 40021Axh
  27    Not used           / DSi:  Maybe IREQ_MC for 2nd gamecard?
  28    Not used           / DSi: NewDMA0
  29    Not used           / DSi: NewDMA1
  30    Not used           / DSi: NewDMA2
  31    Not used           / DSi: NewDMA3
  ?     DSi7: any further new IRQs on ARM7 side... in bit13-15,21,25-26?
Raw TCM-only IRQs can be processed even during DMA ?
Trying to set all IE bits gives FFFFFFFFh (DSi7) or FFFFFF7Fh (DSi9).

4000218h - DSi7 - IE2 - DSi7 Extra Interrupt Enable Bits
400021Ch - DSi7 - IF2 - DSi7 Extra Interrupt Flags
  0     DSi7: GPIO18[0]   ;\
  1     DSi7: GPIO18[1]   ; maybe 1.8V signals?
  2     DSi7: GPIO18[2]   ;/
  3     DSi7: Unused (0)
  4     DSi7: GPIO33[0] unknown (related to "GPIO330" testpoint on mainboard?)
  5     DSi7: GPIO33[1] Headphone connect (HP#SP) (static state)
  6     DSi7: GPIO33[2] Powerbutton interrupt (short pulse upon key-down)
  7     DSi7: GPIO33[3] Sound Enable Output (ie. not a useful irq-input)
  8     DSi7: SD/MMC Controller   ;-Onboard eMMC and External SD Slot
  9     DSi7: SD Slot Data1 pin   ;-For SDIO hardware in External SD Slot
  10    DSi7: SDIO Controller     ;\Atheros Wifi Unit
  11    DSi7: SDIO Data1 pin      ;/
  12    DSi7: AES interrupt
  13    DSi7: I2C interrupt
  14    DSi7: Microphone Extended interrupt
  15-31 DSi7: Unused (0)
Trying to set all IE2 bits gives 00007FF7h (DSi7) or 00000000h (DSi9).

DTCM+3FFCh - NDS9 - IRQ Handler (hardcoded DTCM address)
380FFFCh - NDS7 - IRQ Handler (hardcoded RAM address)
  Bit 0-31  Pointer to IRQ Handler
NDS7 Handler must use ARM code, NDS9 Handler can be ARM/THUMB (Bit0=Thumb).

DTCM+3FF8h - NDS9 - IRQ Check Bits (hardcoded DTCM address)
380FFF8h - NDS7 - IRQ Check Bits (hardcoded RAM address)
  Bit 0-31  IRQ Flags (same format as IE/IF registers)
When processing & acknowleding interrupts via IF register, the user interrupt handler should also set the corresponding bits of the IRQ Check value (required for BIOS IntrWait and VBlankIntrWait SWI functions).

380FFC0h - DSi7 only - Extra IRQ Check Bits for IE2/IF2 (hardcoded RAM addr)
Same as the above 380FFF8h value, but for new IE2/IF2 registers, intended for use with IntrWait and VBlankIntrWait functions. However, that functions are BUGGED on DSi and won't actually work in practice (they do support only the new 380FFC0h bits, but do accidently ignore the old 380FFF8h bits).

--- Below for other (non-IRQ) exceptions ---

27FFD9Ch - RAM - NDS9 Debug Stacktop / Debug Vector (0=None)
380FFDCh - RAM - NDS7 Debug Stacktop / Debug Vector (0=None)
These addresses contain a 32bit pointer to the Debug Handler, and, memory below of the addresses is used as Debug Stack. The debug handler is called on undefined instruction exceptions, on data/prefetch aborts (caused by the protection unit), on FIQ (possibly caused by hardware debuggers). It is also called by accidental software-jumps to the reset vector, and by unused SWI numbers within range 0..1Fh.


DS Maths

4000280h - NDS9 - DIVCNT - Division Control (R/W)
  0-1   Division Mode    (0-2=See below) (3=Reserved; same as Mode 1)
  2-13  Not used
  14    Division by zero (0=Okay, 1=Division by zero error; 64bit Denom=0)
  15    Busy             (0=Ready, 1=Busy) (Execution time see below)
  16-31 Not used
Division Modes and Busy Execution Times
  Mode  Numer / Denom = Result, Remainder ; Cycles
  0     32bit / 32bit = 32bit , 32bit     ; 18 clks
  1     64bit / 32bit = 64bit , 32bit     ; 34 clks
  2     64bit / 64bit = 64bit , 64bit     ; 34 clks
Division is started when writing to any of the DIVCNT/NUMER/DENOM registers.

4000290h - NDS9 - DIV_NUMER - 64bit Division Numerator (R/W)
4000298h - NDS9 - DIV_DENOM - 64bit Division Denominator (R/W)
Signed 64bit values (or signed 32bit values in 32bit modes, the upper 32bits are then unused, with one exception: the DIV0 flag in DIVCNT is set only if the full 64bit DIV_DENOM value is zero, even in 32bit mode).

40002A0h - NDS9 - DIV_RESULT - 64bit Division Quotient (=Numer/Denom) (R)
40002A8h - NDS9 - DIVREM_RESULT - 64bit Remainder (=Numer MOD Denom) (R)
Signed 64bit values (in 32bit modes, the values are sign-expanded to 64bit).

Division Overflows
Overflows occur on "DIV0" and "-MAX/-1" (eg. -80000000h/-1 in 32bit mode):
  DIV0     -->  REMAIN=NUMER, RESULT=+/-1 (with sign opposite of NUMER)
  -MAX/-1  -->  RESULT=-MAX               (instead +MAX)
On overflows in 32bit/32bit=32bit mode: the upper 32bit of the sign-expanded 32bit result are inverted. This feature produces a correct 64bit (+MAX) result in case of the incorrect 32bit (-MAX) result. The feature also applies on DIV0 errors (which makes the sign-expanded 64bit result even more messed-up than the normal 32bit result).
The DIV0 flag in DIVCNT.14 indicates DENOM=0 errors (it does not indicate "-MAX/-1" errors). The DENOM=0 check relies on the full 64bit value (so, in 32bit mode, the flag works only if the unused upper 32bit of DENOM are zero).

40002B0h - NDS9 - SQRTCNT - Square Root Control (R/W)
  0     Mode (0=32bit input, 1=64bit input)
  1-14  Not used
  15    Busy (0=Ready, 1=Busy) (Execution time is 13 clks, in either Mode)
  16-31 Not used
Calculation is started when writing to any of the SQRTCNT/PARAM registers.

40002B4h - NDS9 - SQRT_RESULT - 32bit - Square Root Result (R)
40002B8h - NDS9 - SQRT_PARAM - 64bit - Square Root Parameter Input (R/W)
Unsigned 64bit parameter, and unsigned 32bit result.

IRQ Notes
Push all DIV/SQRT values (parameters and control registers) when using DIV/SQRT registers on interrupt level, and, after restoring them, be sure to wait until the busy flag goes off, before leaving the IRQ handler.

BIOS Notes
The NDS9 and NDS7 BIOSes additionally contain software based division and square root functions, which are NOT using above hardware registers (even the NDS9 functions are raw software).

Timing Notes
The Div/Sqrt timings are counted in 33.51MHz units. Although the calculations are quite fast, mind that reading/writing the result/parameter registers takes up additional clock cycles (especially due to the PENALTY cycle glitch for non-sequential accesses; parts of that problem can be eventually bypassed by using sequential STMIA/LDMIA opcodes) (nethertheless, in some cases, software may be actually faster than the hardware registers; eg. for small 8bit numbers; that of course NOT by using the BIOS software functions which are endless inefficient).


DS Inter Process Communication (IPC)

Allows to exchange status information between ARM7 and ARM9 CPUs.
The register can be accessed simultaneously by both CPUs (without violating access permissions, and without generating waitstates at either side).

4000180h - NDS9/NDS7 - IPCSYNC - IPC Synchronize Register (R/W)
  Bit   Dir  Expl.
  0-3   R    Data input from IPCSYNC Bit8-11 of remote CPU (00h..0Fh)
  4-7   -    Not used
  8-11  R/W  Data output to IPCSYNC Bit0-3 of remote CPU   (00h..0Fh)
  12    -    Not used
  13    W    Send IRQ to remote CPU      (0=None, 1=Send IRQ)
  14    R/W  Enable IRQ from remote CPU  (0=Disable, 1=Enable)
  15-31 -    Not used

4000184h - NDS9/NDS7 - IPCFIFOCNT - IPC Fifo Control Register (R/W)
  Bit   Dir  Expl.
  0     R    Send Fifo Empty Status      (0=Not Empty, 1=Empty)
  1     R    Send Fifo Full Status       (0=Not Full, 1=Full)
  2     R/W  Send Fifo Empty IRQ         (0=Disable, 1=Enable)
  3     W    Send Fifo Clear             (0=Nothing, 1=Flush Send Fifo)
  4-7   -    Not used
  8     R    Receive Fifo Empty          (0=Not Empty, 1=Empty)
  9     R    Receive Fifo Full           (0=Not Full, 1=Full)
  10    R/W  Receive Fifo Not Empty IRQ  (0=Disable, 1=Enable)
  11-13 -    Not used
  14    R/W  Error, Read Empty/Send Full (0=No Error, 1=Error/Acknowledge)
  15    R/W  Enable Send/Receive Fifo    (0=Disable, 1=Enable)
  16-31 -    Not used

4000188h - NDS9/NDS7 - IPCFIFOSEND - IPC Send Fifo (W)
  Bit0-31  Send Fifo Data (max 16 words; 64bytes)

4100000h - NDS9/NDS7 - IPCFIFORECV - IPC Receive Fifo (R)
  Bit0-31  Receive Fifo Data (max 16 words; 64bytes)

IPCFIFO Notes
When IPCFIFOCNT.15 is disabled: Writes to IPCFIFOSEND are ignored (no data is stored in the FIFO, the error bit doesn't get set though), and reads from IPCFIFORECV return the oldest FIFO word (as usually) (but without removing the word from the FIFO).
When the Receive FIFO is empty: Reading from IPCFIFORECV returns the most recently received word (if any), or ZERO (if there was no data, or if the FIFO was cleared via IPCFIFOCNT.3), and, in either case the error bit gets set.
The Fifo-IRQs are edge triggered, IF.17 gets set when the condition "(IPCFIFOCNT.2 AND IPCFIFOCNT.0)" changes from 0-to-1, and IF.18 gets set when "(IPCFIFOCNT.10 AND NOT IPCFIFOCNT.8)" changes from 0-to-1. The IRQ flags can be acknowledged even while that conditions are true.


DS Keypad

For the GBA-buttons: Same as GBA, both ARM7 and ARM9 have keyboard input registers, and each its own keypad IRQ control register.
GBA Keypad Input

For Touchscreen (and Microphone) inputs, see
DS Touch Screen Controller (TSC)

4000136h - NDS7 - EXTKEYIN - Key X/Y Input (R)
  0      Button X     (0=Pressed, 1=Released)
  1      Button Y     (0=Pressed, 1=Released)
  2      Unknown / set
  3      DEBUG button (0=Pressed, 1=Released/None such)
  4,5    Unknown / set
  6      Pen down     (0=Pressed, 1=Released/Disabled) (always 0 in DSi mode)
  7      Hinge/folded (0=Open, 1=Closed)
  8..15  Unknown / zero
The Hinge stuff is a magnetic sensor somewhere underneath of the Start/Select buttons (NDS) or between A/B/X/Y buttons (DSi), it will be triggered by the magnet field from the right speaker when the console is closed. The hinge generates an interrupt request (there seems to be no way to disable this, unlike as for all other IRQ sources), however, the interrupt execution can be disabled in IE register (as for other IRQ sources).
The Pen Down is the /PENIRQ signal from the Touch Screen Controller (TSC), if it is enabled in the TSC control register, then it will notify the program when the screen pressed, the program should then read data from the TSC (if there's no /PENIRQ then doing unneccassary TSC reads would just waste CPU power). However, the user may release the screen before the program performs the TSC read, so treat the screen as not pressed if you get invalid TSC values (even if /PENIRQ was LOW).
Not sure if the TSC /PENIRQ is actually triggering an IRQ in the NDS?
The Debug Button should be connected to R03 and GND (on original NDS, R03 is the large soldering point between the SL1 jumper and the VR1 potentiometer) (there is no R03 signal visible on the NDS-Lite board).
Interrupts are reportedly not supported for X,Y buttons.


DS Absent Link Port

The DS doesn't have a Serial Link Port Socket, however, internally, the NDS7 contains the complete set of Serial I/O Ports, as contained in the GBA:
GBA Communication Ports

In GBA mode, the ports are working as on real GBA (as when no cable is connected). In NDS mode, the ports are even containing some additional bits:

NDS7 SIO Bits (according to an early I/O map from Nintendo)
  NDS7 4000128h SIOCNT   Bit15 "CKUP"  New Bit in NORMAL/MULTI/UART mode (R/W)
  NDS7 4000128h SIOCNT   Bit14 "N/A"   Removed IRQ Bit in UART mode (?)
  NDS7 400012Ah SIOCNT_H Bit14 "TFEMP" New Bit (R/W)
  NDS7 400012Ah SIOCNT_H Bit15 "RFFUL" New Bit (always zero?)
  NDS7 400012Ch SIOSEL   Bit0  "SEL"   New Bit (always zero?)
  NDS7 4000140h JOYCNT   Bit7  "MOD"   New Bit (R/W)
The "CKUP" bit duplicates the internal clock transfer rate (selected in SIOCNT.1) (tested in normal mode) (probably works also in multi/uart mode?).

NDS7 DS-Lite 4001080h (W) (?)
DS-Lite Firmware writes FFFFh to this address (prior to accessing SIOCNT), so it's probably SIO or debugging related (might be as well a bug or so). Reading from the port always returns 0000h on both DS and DS-Lite.

NDS9 SIO Bits (according to an early I/O map from Nintendo)
  NDS9 4000120h SIODATA32 Bit0-31 Data            (always zero?)
  NDS9 4000128h SIOCNT    Bit2    "TRECV" New Bit (always zero?)
  NDS9 4000128h SIOCNT    Bit3    "TSEND" New Bit (always zero?)
  NDS9 400012Ch SIOSEL    Bit0    "SEL"   New Bit (always zero?)
Not sure if these ports really exist in the release-version, or if it's been prototype stuff?

RCNT
RCNT (4000134h) should be set to 80xxh (general purpose mode) before accessing EXTKEYIN (4000136h) or RTC (4000138h). No idea why (except when using RTC/SI-interrupt).

DS Serial Port
The SI line is labeled "INT" on the NDS mainboard, it is connected to Pin 1 of the RTC chip (ie. the /INT interrupt pin).
I have no idea where to find SO, SC, and SD. I've written a test proggy that pulsed all four RCNT bits - but all I could find was the SI signal. However, the BIOS contains some code that uses SIO normal mode transfers (for the debug version), so at least SI, SO, SC should exist...?
MAYBE that three signals are somehow replaced by EXTKEYIN bit0,1,3?


DS Real-Time Clock (RTC)

NDS
Seiko Instruments Inc. S-35180 (compatible with S-35190A)
Miniature 8pin RTC with 3-wire serial bus

DSi
Seiko S-35199A01 (12pin BGA, with some extra functions like FOUT and Alarm Date)

4000138h - NDS7 - Real Time Clock Register
  Bit  Expl.
  0    Data I/O   (0=Low, 1=High)
  1    Clock Out  (0=Low, 1=High)
  2    Select Out (0=Low, 1=High/Select)
  4    Data  Direction  (0=Read, 1=Write)
  5    Clock Direction  (should be 1=Write)
  6    Select Direction (should be 1=Write)
  3,8-11   Unused I/O Lines
  7,12-15  Direction for Bit3,8-11 (usually 0)
  16-31    Not used

Serial Transfer Flowchart
Chipselect and Command/Parameter Sequence:
  Init CS=LOW and /SCK=HIGH, and wait at least 1us
  Switch CS=HIGH, and wait at least 1us
  Send the Command byte (see bit-transfer below)
  Send/receive Parameter byte(s) associated with the command (see below)
  Switch CS to LOW
Bit transfer (repeat 8 times per cmd/param byte) (bits transferred LSB first):
  Output /SCK=LOW and SIO=databit (when writing), then wait at least 5us
  Output /SCK=HIGH, wait at least 5us, then read SIO=databit (when reading)
  In either direction, data is output on (or immediately after) falling edge.
Ideally, <both> commands and parameters should be transmitted LSB-first (unlike the original Seiko document, which recommends LSB-first for data, and MSB-first for commands) (actually, later Seiko datasheets are going so far to recommend MSB-first for everything, eg. to use bit-reversed Data=C8h for Year=13h).

Command Register
  Command Register
    Fwd  Rev
    0    7   Fixed Code (must be 0)
    1    6   Fixed Code (must be 1)
    2    5   Fixed Code (must be 1)
    3    4   Fixed Code (must be 0, or, DSi only: 1=Extended Command)
    4-6  3-1 Command
             Fwd Rev Parameter bytes (read/write access)
             0   0   1 byte, status register 1
             4   1   1 byte, status register 2
             2   2   7 bytes, date & time (year,month,day,day_of_week,hh,mm,ss)
             6   3   3 bytes, time (hh,mm,ss)
             1*  4*  1 byte, int1, frequency duty setting
             1*  4*  3 bytes, int1, alarm time 1 (day_of_week, hour, minute)
             5   5   3 bytes, int2, alarm time 2 (day_of_week, hour, minute)
             3   6   1 byte, clock adjustment register
             7   7   1 byte, free register
             Extended command (when above "fourth bit" was set, DSi only)
             Fwd Rev Parameter bytes (read/write access)
             0   0   3 byte, up counter (msw,mid,lsw) (read only)
             4   1   1 byte, FOUT register setting 1
             2   2   1 byte, FOUT register setting 2
             6   3   reserved
             1   4   3 bytes, alarm date 1 (year,month,day)
             5   5   3 bytes, alarm date 2 (year,month,day)
             3   6   reserved
             7   7   reserved
    7    0   Parameter Read/Write Access (0=Write, 1=Read)
* INT1: Type and number of parameters depend on INT1 setting in stat reg2.
The "Fwd" bit numbers and command values for LSB-first command transfers (ie. both commands and parameters use the same bit-order).
The "Rev" numbers/values are for MSB-first command transfers (ie. commands using opposite bit-order than parameters, as being suggested by Seiko).

Control and Status Registers
  Status Register 1
    0   W   Reset                (0=Normal, 1=Reset)
    1   R/W 12/24 hour mode      (0=12 hour, 1=24 hour)
    2-3 R/W General purpose bits
    4   R   Interrupt 1 Flag (1=Yes)                      ;auto-cleared on read
    5   R   Interrupt 2 Flag (1=Yes)                      ;auto-cleared on read
    6   R   Power Low Flag (0=Normal, 1=Power is/was low) ;auto-cleared on read
    7   R   Power Off Flag (0=Normal, 1=Power was off)    ;auto-cleared on read
    Power off indicates that the battery was removed or fully discharged,
    all registers are reset to 00h (or 01h), and must be re-initialized.
  Status Register 2
    0-3 R/W INT1 Mode/Enable
            0000b Disable
            0x01b Selected Frequency steady interrupt
            0x10b Per-minute edge interrupt
            0011b Per-minute steady interrupt 1 (duty 30.0 seconds)
            0100b Alarm 1 interrupt
            0111b Per-minute steady interrupt 2 (duty 0.0079 seconds)
            1xxxb 32kHz output
    4-5 R/W General purpose bits
    6   R/W INT2 Enable
            0b    Disable
            1b    Alarm 2 interrupt
    7   R/W Test Mode (0=Normal, 1=Test, don't use) (cleared on Reset)
  Clock Adjustment Register (to compensate oscillator inaccuracy)
    0-7 R/W Adjustment (00h=Normal, no adjustment)
  Free Register
    0-7 R/W General purpose bits

Date Registers
  Year Register
    0-7 R/W Year     (BCD 00h..99h = 2000..2099)
  Month Register
    0-4 R/W Month    (BCD 01h..12h = January..December)
    5-7 -   Not used (always zero)
  Day Register
    0-5 R/W Day      (BCD 01h..28h,29h,30h,31h, range depending on month/year)
    6-7 -   Not used (always zero)
  Day of Week Register (septenary counter)
    0-2 R/W Day of Week (00h..06h, custom assignment, usually 0=Monday?)
    3-7 -   Not used (always zero)

Time Registers
  Hour Register
    0-5 R/W Hour     (BCD 00h..23h in 24h mode, or 00h..11h in 12h mode)
    6   *   AM/PM    (0=AM before noon, 1=PM after noon)
            * 24h mode: AM/PM flag is read only (PM=1 if hour = 12h..23h)
            * 12h mode: AM/PM flag is read/write-able
            * 12h mode: Observe that 12 o'clock is defined as 00h (not 12h)
    7   -   Not used (always zero)
  Minute Register
    0-6 R/W Minute   (BCD 00h..59h)
    7   -   Not used (always zero)
  Second Register
    0-6 R/W Minute   (BCD 00h..59h)
    7   -   Not used (always zero)

Alarm 1 and Alarm 2 Registers
  Alarm1 and Alarm2 Day of Week Registers (INT1 and INT2 each)
    0-2 R/W Day of Week (00h..06h)
    3-6 -   Not used (always zero)
    7   R/W Compare Enable (0=Alarm every day, 1=Alarm only at specified day)
  Alarm1 and Alarm2 Hour Registers (INT1 and INT2 each)
    0-5 R/W Hour     (BCD 00h..23h in 24h mode, or 00h..11h in 12h mode)
    6   R/W AM/PM    (0=AM, 1=PM) (must be correct even in 24h mode?)
    7   R/W Compare Enable (0=Alarm every hour, 1=Alarm only at specified hour)
  Alarm1 and Alarm2 Minute Registers (INT1 and INT2 each)
    0-6 R/W Minute   (BCD 00h..59h)
    7   R/W Compare Enable (0=Alarm every min, 1=Alarm only at specified min)
  Selected Frequency Steady Interrupt Register (INT1 only) (when Stat2/Bit2=0)
    0   R/W Enable 1Hz Frequency  (0=Disable, 1=Enable)
    1   R/W Enable 2Hz Frequency  (0=Disable, 1=Enable)
    2   R/W Enable 4Hz Frequency  (0=Disable, 1=Enable)
    3   R/W Enable 8Hz Frequency  (0=Disable, 1=Enable)
    4   R/W Enable 16Hz Frequency (0=Disable, 1=Enable)
            The signals are ANDed when two or more frequencies are enabled,
            ie. the /INT signal gets LOW when either of the signals is LOW.
    5-7 R/W General purpose bits
Note: There is only one register shared as "Selected Frequency Steady Interrupt" (accessed as single byte parameter when Stat2/Bit2=0) and as "Alarm1 Minute" (accessed as 3rd byte of 3-byte parameter when Stat2/Bit2=1), changing either value will also change the other value.

Up Counter (DSi only)
  Up Counter Msw
    0-7 R   Up Counter bit16-23 (non-BCD, 00h..FFh)
  Up Counter Mid
    0-7 R   Up Counter bit8-15  (non-BCD, 00h..FFh)
  Up Counter Lsw
    0-7 R   Up Counter bit0-7   (non-BCD, 00h..FFh)
The 24bit Up Counter is incremented when seconds=00h (that is, once per minute; unless the Time is getting changed by write commands, which may cause some stuttering). The Up Counter starts at 000000h upon power-up, and, if the battery lasts that long: wraps from FFFFFFh to 000000h after about 30 years.

Alarm 1 and Alarm 2 Date Registers (DSi only)
  Alarm 1 and Alarm 2 Year Register
    0-7 R/W Year     (BCD 00h..99h = 2000..2099)
  Alarm 1 and Alarm 2 Month Register
    0-4 R/W Month    (BCD 01h..12h = January..December)
    5   -   Not used (always zero)
    6   R/W Year Compare Enable (0=Ignore, 1=Enable)
    7   R/W Month Compare Enable (0=Ignore, 1=Enable)
  Alarm 1 and Alarm 2 Day Register
    0-5 R/W Day      (BCD 01h..28h,29h,30h,31h, range depending on month/year)
    6   -   Not used (always zero)
    7   R/W Day Compare Enable (0=Ignore, 1=Enable)
XXX unspecified if above Alarm Date stuff is really R/W (or write only)

FOUT Register (DSi only)
  FOUT Register Setting 1
    0-7 R/W  Enable bits (bit0=256Hz, bit1=512Hz, ..., bit7=32768Hz)
  FOUT Register Setting 2
    0-7 R/W  Enable bits (bit0=1Hz,   bit1=2Hz, ...,   bit7=128Hz)
  The above sixteen FOUT signals are ANDed when two or more frequencies are
  enabled, ie. the FOUT signal gets LOW when either of the signals is LOW.
Note: The FOUT pin goes to the DSi's wifi daughterboard: FOUT must be set to 32768Hz (FOUT1=80h, FOUT2=00h), that setting is required for exchanging Atheros WMI commands/events, the firmware does take care of initializing that setting (eg. needed after battery removal, or after overwriting the FOUT registers by software).

Interrupt
There's only one /INT signal, shared for both INT1 and INT2.
In the NDS, it is connected to the SI-input of the SIO unit (and so, also shared with SIO interrupts). To enable the interrupt, RCNT should be set to 8144h (Bit14-15=General Purpose mode, Bit8=SI Interrupt Enable, Bit6,2=SI Output/High).
The Output/High settings seems to be used as pullup (giving faster reactions on low-to-high transitions) (nethertheless, in most cases it seems to be also working okay as Input, ie. with RCNT=8100h).
The RCNT interrupt is generated on high-to-low transitions on the SI line (but only if the IRQ is enabled in RCNT.8, and only if RCNT is set to general purpose mode) (note: changing RCNT.8 from off-to-on does NOT generate IRQs, even when SI is LOW).

Pin-Outs
  1 /INT      8 VDD
  2 XOUT      7 SIO
  3 XIN       6 /SCK
  4 GND       5 CS


DS Serial Peripheral Interface Bus (SPI)

Serial Peripheral Interface Bus
SPI Bus is a 4-wire (Data In, Data Out, Clock, and Chipselect) serial bus.
The NDS supports the following SPI devices (each with its own chipselect).
DS Firmware Serial Flash Memory
DS Touch Screen Controller (TSC)
DS Power Management Device

40001C0h - NDS7 - SPICNT - SPI Bus Control/Status Register
  0-1   Baudrate (0=4MHz/Firmware, 1=2MHz/Touchscr, 2=1MHz/Powerman., 3=512KHz)
  2     DSi: Baudrate MSB   (4=8MHz, 5..7=None/0Hz) (when SCFG_EXT7.bit9=1)
  2     NDS: Not used       (Zero)
  3-6   Not used            (Zero)
  7     Busy Flag           (0=Ready, 1=Busy) (presumably Read-only)
  8-9   Device Select       (0=Powerman., 1=Firmware, 2=Touchscr, 3=Reserved)
  10    Transfer Size       (0=8bit/Normal, 1=16bit/Bugged)
  11    Chipselect Hold     (0=Deselect after transfer, 1=Keep selected)
  12-13 Not used            (Zero)
  14    Interrupt Request   (0=Disable, 1=Enable)
  15    SPI Bus Enable      (0=Disable, 1=Enable)
The "Hold" flag should be cleared BEFORE transferring the LAST data unit, the chipselect will be then automatically cleared after the transfer, the program should issue a WaitByLoop(3) manually AFTER the LAST transfer.

40001C2h - NDS7 - SPIDATA - SPI Bus Data/Strobe Register (R/W)
The SPI transfer is started on writing to this register, so one must <write> a dummy value (should be zero) even when intending to <read> from SPI bus.
  0-7   Data
  8-15  Not used (always zero, even in bugged-16bit mode)
During transfer, the Busy flag in SPICNT is set, and the written SPIDATA value is transferred to the device (via output line), simultaneously data is received (via input line). Upon transfer completion, the Busy flag goes off (with optional IRQ), and the received value can be then read from SPIDATA, if desired.

Notes/Glitches
SPICNT Bits 12,13 appear to be unused (always zero), although the BIOS (attempts to) set Bit13=1, and Bit12=Bit11 when accessing the firmware.
The SPIDATA register is restricted to 8bit, so that only each 2nd byte will appear in SPIDATA when attempting to use the bugged-16bit mode.

Cartridge Backup Auxiliar SPI Bus
The NDS Cartridge Slot uses a separate SPI bus (with other I/O Ports), see
DS Cartridge Backup


DS Touch Screen Controller (TSC)

Texas Instruments TSC2046 (NDS)
Asahi Kasei Microsystems AK4148AVT (NDS-Lite)
The Touch Screen Controller (for lower LCD screen) is accessed via SPI bus,
DS Serial Peripheral Interface Bus (SPI)

Control Byte (transferred MSB first)
  0-1  Power Down Mode Select
  2    Reference Select (0=Differential, 1=Single-Ended)
  3    Conversion Mode  (0=12bit, max CLK=2MHz, 1=8bit, max CLK=3MHz)
  4-6  Channel Select   (0-7, see below)
  7    Start Bit (Must be set to access Control Byte)

Channel
  0 Temperature 0 (requires calibration, step 2.1mV per 1'C accuracy)
  1 Touchscreen Y-Position  (somewhat 0B0h..F20h, or FFFh=released)
  2 Battery Voltage         (not used, connected to GND in NDS, always 000h)
  3 Touchscreen Z1-Position (diagonal position for pressure measurement)
  4 Touchscreen Z2-Position (diagonal position for pressure measurement)
  5 Touchscreen X-Position  (somewhat 100h..ED0h, or 000h=released)
  6 AUX Input               (connected to Microphone in the NDS)
  7 Temperature 1 (difference to Temp 0, without calibration, 2'C accuracy)
All channels can be accessed in Single-Ended mode.
In differential mode, only channel 1,3,4,5 (X,Z1,Z2,Y) can be accessed.
On AK4148AVT, channel 6 (AUX) is split into two separate channels, IN1 and IN2, separated by Bit2 (Reference Select). IN1 is selected when Bit2=1, IN2 is selected when Bit2=0 (despite of the Bit2 settings, both IN1 and IN2 are using single ended more). On the NDS-Lite, IN1 connects to the mircrophone (as on original NDS), and the new IN2 input is simply wired to VDD3.3 (which is equal to the external VREF voltage, so IN2 is always FFFh).

Power Down Mode
  Mode /PENIRQ   VREF  ADC   Recommended use
  0    Enabled   Auto  Auto  Differential Mode (Touchscreen, Penirq)
  1    Disabled  Off   On    Single-Ended Mode (Temperature, Microphone)
  2    Enabled   On    Off   Don't use
  3    Disabled  On    On    Don't use
Allows to enable/disable the /PENIRQ output, the internal reference voltage (VREF), and the Analogue-Digital Converter.
For AK4148AVT, Power Down modes are slightly different (among others, /PENIRQ is enabled in Mode 0..2).

Reference Voltage (VREF)
VREF is used as reference voltage in single ended mode, at 12bit resolution one ADC step equals to VREF/4096. The TSC generates an internal VREF of 2.5V (+/-0.05V), however, the NDS uses as external VREF of 3.33V (sinks to 3.31V at low battery charge), the external VREF is always enabled, no matter if internal VREF is on or off. Power Down Mode 1 disables the internal VREF, which may reduce power consumption in single ended mode. After conversion, Power Down Mode 0 should be restored to re-enable the Penirq signal.

Sending the first Command after Chip-Select
Switch chipselect low, then output the command byte (MSB first).

Reply Data
The following reply data is received (via Input line) after the Command byte has been transferred: One dummy bit (zero), followed by the 8bit or 12bit conversion result (MSB first), followed by endless padding (zero).
Note: The returned ADC value may become unreliable if there are longer delays between sending the command, and receiving the reply byte(s).

Sending further Commands during/after receiving Reply Data
In general, the Output line should be LOW during the reply period, however, once when Data bit6 has been received (or anytime later), a new Command can be invoked (started by sending the HIGH-startbit, ie. Command bit7), simultaneously, the remaining reply-data bits (bit5..0) can be received.
In other words, the new command can be output after receiving 3 bits in 8bit mode (the dummy bit, and data bits 7..6), or after receiving 7 bits in 12bit mode (the dummy bit, and data bits 11..6).
In practice, the NDS SPI register always transfers 8 bits at once, so that one would usually receive 8 bits (rather than above 3 or 7 bits), before outputting a new command.

Touchscreen Position
Read the X and Y positions in 12bit differential mode, then convert the touchscreen values (adc) to screen/pixel positions (scr), as such:
  scr.x = (adc.x-adc.x1) * (scr.x2-scr.x1) / (adc.x2-adc.x1) + (scr.x1-1)
  scr.y = (adc.y-adc.y1) * (scr.y2-scr.y1) / (adc.y2-adc.y1) + (scr.y1-1)
The X1,Y1 and X2,Y2 calibration points are found in Firmware User Settings,
DS Firmware User Settings
scr.x1,y1,x2,y2 are originated at 1,1 (converted to 0,0 by above formula).

Touchscreen Pressure (not supported on DSi)
To calculate the pressure resistance, in respect to X/Y/Z positions and X/Y plate resistances, either of below formulas can be used,
  Rtouch = (Rx_plate*Xpos*(Z2pos/Z1pos-1))/4096
  Rtouch = (Rx_plate*Xpos*(4096/Z1pos-1)-Ry_plate*(1-Ypos))/4096
The second formula requires less CPU load (as it doesn't require to measure Z2), the downside is that one must know both X and Y plate resistance (or at least their ratio). The first formula doesn't require that ratio, and so Rx_plate can be set to any value, setting it to 4096 results in
  touchval = Xpos*(Z2pos/Z1pos-1)
Of course, in that case, touchval is just a number, not a resistance in Ohms.

Touchscreen Notes
It may be impossible to press locations close to the screen borders.
When pressing two or more locations the TSC values will be somewhere in the middle of these locations.
The TSC values may be garbage if the screen becomes newly pressed or released, to avoid invalid inputs: read TSC values at least two times, and ignore BOTH positions if ONE position was invalid.

Microphone / AUX Channel
Observe that the microphone amplifier is switched off after power up, see:
DS Power Management Device
DS Power Control

Temperature Calculation (not supported on DSi)
TP0 decreases by circa 2.1mV per degree Kelvin. The voltage difference between TP1 minus TP0 increases by circa 0.39mV (1/2573 V) per degree Kelvin. At VREF=3.33V, one 12bit ADC step equals to circa 0.8mV (VREF/4096).
Temperature can be calculated at best resolution when using the current TP0 value, and two calibration values (an ADC value, and the corresponding temperature in degrees kelvin):
  K = (CAL.TP0-ADC.TP0) * 0.4 + CAL.KELVIN
Alternately, temperature can be calculated at rather bad resolution, but without calibration, by using the difference between TP1 and TP0:
  K = (ADC.TP1-ADC.TP0) * 8568 / 4096
To convert Kelvin to other formats,
  Celsius:     C = (K-273.15)
  Fahrenheit:  F = (K-273.15)*9/5+32
  Reaumur:     R = (K-273.15)*4/5
  Rankine:     X = (K)*9/5
The Temperature Range for the TSC 2046 chip is -40'C..+85'C (for AK4181AVT only -20'C..+70'C). According to Nintendo, the DS should not be exposed to "extreme" heat or cold, the optimal battery charging temperature is specified as +10'C..+40'C.
The original firmware does not support temperature calibration, calibration is supported by nocash firmware (if present). See Extended Settings,
DS Firmware Extended Settings

Pin-Outs
         ________
  VCC  1|o       |16 DCLK
  X+   2|        |15 /CS
  Y+   3|  TSC   |14 DIN
  X-   4|  2046  |13 BUSY
  Y-   5|        |12 DOUT
  GND  6|        |11 /PENIRQ
  VBAT 7|        |10 IOVDD
  AUX  8|________|9  VREF

For AK4181AVT, same pins as above, except that IOVDD replaced by the new IN2 input, the pin is wired to VDD3.3 (so IN2 is always equal to VREF, which is wired to VDD3.3, too) (and AUX is renamed to IN1, and is kept used for MIC input).

DSi Touchscreen Controller (in NDS mode)
DSi in NDS mode does support only X, Y, and MIC (all other channels do return FFFh in 12bit mode, and FFh in 8bit mode, ie. no pressure, no temperature, and no GNDed battery sensor). On DSi, MIC does return data in both single-ended and differential mode (unlike as on real NDS).

DSi Touchscreen Controller (in DSi mode)
The DSi touchscreen controller supports a NDS backwards compatibility mode. But, in DSi mode, it is working entirely different (it's still accessed via SPI bus, but with some new MODE/INDEX values).
DSi Touchscreen/Sound Controller
The NDS Touchscreen controller did additionally allow to read Temperature and Touchscreen Pressure - unknown if the DSi is also supporting such stuff (via whatever DSi-specific registers).
The touchscreen hardware can be switched to NDS compatibility mode (for older games), but unknown how to do that.


DS Power Control

The DS contains several Power Managment functions, some accessed via I/O ports (described below), and some accessed via SPI bus:
DS Power Management Device

4000304h - NDS9 - POWCNT1 - Graphics Power Control Register (R/W)
  0     Enable Flag for both LCDs (0=Disable) (Prohibited, see notes)
  1     2D Graphics Engine A      (0=Disable) (Ports 008h-05Fh, Pal 5000000h)
  2     3D Rendering Engine       (0=Disable) (Ports 320h-3FFh)
  3     3D Geometry Engine        (0=Disable) (Ports 400h-6FFh)
  4-8   Not used
  9     2D Graphics Engine B      (0=Disable) (Ports 1008h-105Fh, Pal 5000400h)
  10-14 Not used
  15    Display Swap (0=Send Display A to Lower Screen, 1=To Upper Screen)
  16-31 Not used
Use SwapBuffers command once after enabling Rendering/Geometry Engine.
Improper use of Bit0 may damage the hardware?
When disabled, corresponding Ports become Read-only, corresponding (palette-) memory becomes read-only-zero-filled.

4000304h - NDS7 - POWCNT2 - Sound/Wifi Power Control Register (R/W)
  Bit   Expl.
  0     Sound Speakers (0=Disable, 1=Enable) (Initial setting = 1)
  1     Wifi           (0=Disable, 1=Enable) (Initial setting = 0)
  2-31  Not used
Note: Bit0 disables the internal Speaker only, headphones are not disabled.
Bit1 disables Port 4000206h, and Ports 4800000h-480FFFFh.

4000206h - NDS7 - WIFIWAITCNT - Wifi Waitstate Control
  Bit   Expl.
  0-1   WS0 nonsequential time (0-3 = 10, 8, 6, 18 cycles) ;\4800000h-4807FFFh
  2     WS0 sequential time    (0-1 = 6, 4 cycles)         ;/   (used for RAM)
  3-4   WS1 nonsequential time (0-3 = 10, 8, 6, 18 cycles) ;\4808000h-480FFFFh
  5     WS1 sequential time    (0-1 = 10, 4 cycles)        ;/   (used for I/O)
  6-15  Not used (zero)
This register is initialized by firmware on power-up (set to 0030h, other software shouldn't change that setting). The timings are per 16bit halfword access.
Note: WIFIWAITCNT can be accessed only when enabled in POWCNT2.

4000301h - NDS7 - HALTCNT - Low Power Mode Control (R/W)
In Halt mode, the CPU is paused as long as (IE AND IF)=0.
In Sleep mode, most of the hardware including sound and video are paused, this very-low-power mode could be used much like a screensaver.
  Bit   Expl.
  0-5   Not used (zero)
  6-7   Power Down Mode  (0=No function, 1=Enter GBA Mode, 2=Halt, 3=Sleep)
The HALTCNT register should not be accessed directly. Instead, the BIOS Halt, Sleep, CustomHalt, IntrWait, or VBlankIntrWait SWI functions should be used.
BIOS Halt Functions
ARM CP15 System Control Coprocessor
The NDS9 does not have a HALTCNT register, instead, the Halt function uses the co-processor opcode "mcr p15,0,r0,c7,c0,4" - this opcode locks up if interrupts are disabled via IME=0 (unlike NDS7 HALTCNT method which doesn't check IME).

4000300h - NDS7/NDS9 - POSTFLG - BYTE - Post Boot Flag (R/W)
The NDS7 and NDS9 post boot flags are usually set upon BIOS/Firmware boot completion, once when set the reset vector is redirected to the debug handler of Nintendo's hardware debugger. That allows the NDS7 debugger to capture accidental jumps to address 0, that appears to be a common problem with HLL-programmers, asm-coders know that (and why) they should not jump to 0.
  Bit   Expl.
  0     Post Boot Flag (0=Boot in progress, 1=Boot completed)
  1     NDS7: Not used (always zero), NDS9: Bit1 is read-writeable
  2-7   Not used (always zero)
There are some write-restrictions: The NDS7 register can be written to only from code executed in BIOS (done by NDS boot ROM, or by DSi firmware, whereas the DSi firmware is using the CpuSet SWI function to issue the POSTFLG write from within ROM). Bit0 of both NDS7 and NDS9 registers cannot be cleared (except by Reset) once when it is set. DSi games seem to run regardless of POSTFLG, whilst NDS games somewhat refuse to run when POSTFLG=0.

Memory Power Down Functions
DS Main Memory Control
DS Firmware Serial Flash Memory


DS Power Management Device

Power Management Device - Mitsumi 3152A (NDS) / Mitsumi 3205B (NDS-LITE)
The Power Management Device is accessed via SPI bus,
DS Serial Peripheral Interface Bus (SPI)
To access the device, write the Index Register, then read or write the data register, and release the chipselect line when finished.
  Index Register
  Bit0-6 Register Select          (0..3) (0..4 for DS-Lite) (0..7Fh for DSi)
  Bit7   Register Direction       (0=Write, 1=Read)
  Register 0 - Powermanagement Control (R/W)
  Bit0   Sound Amplifier Enable   (0=Disable, 1=Enable)
         (Old-DS:  Disabled: Sound is very silent, but still audible)
         (DS-Lite: Disabled: Sound is NOT audible)
         (DSi in NDS Mode: R/W, but effect is unknown yet)
         (DSi in DSi Mode: Not used, Bit0 is always 1)
  Bit1   Sound Amplifier Mute     (0=Normal, 1=Mute) (Old-DS Only, not DS-Lite)
         (Old-DS:  Muted: Sound is NOT audible (that works only if Bit0=1)
         (DS-Lite: Not used, Bit1 is always zero)
         (DSi in NDS Mode: R/W, but effect is unknown yet)
         (DSi in DSi Mode: R/W, but effect is unknown yet)
  Bit2   Lower Backlight          (0=Disable, 1=Enable)
  Bit3   Upper Backlight          (0=Disable, 1=Enable)
  Bit4   Power LED Blink Enable   (0=Always ON, 1=Blinking OFF/ON)
  Bit5   Power LED Blink Speed    (0=Slow, 1=Fast) (only if Blink enabled)
         (DSi: Power LED Blinking isn't supported, neither in NDS nor DSi mode)
  Bit6   DS System Power          (0=Normal, 1=Shut Down)
  Bit7   Not used                 (always 0)
  Register 1 - Battery Status (R)
  Bit0   Battery Power LED Status (0=Power Good/Green, 1=Power Low/Red)
         (DSi: Usually 0, not tested if it changes upon Power=Low)
  Bit1-7 Not used
  Register 2 - Microphone Amplifier Control (R/W)
  Bit0   Amplifier                (0=Disable, 1=Enable)
  Bit1-7 Not used                 (always 0)
  (DSi in NDS Mode: looks same as NDS, ie. only bit0 is R/W)
  (DSi in DSi Mode: Not used, always FFh)
  Register 3 - Microphone Amplifier Gain Control (R/W)
  Bit0-1 Gain                     (0..3=Gain 20, 40, 80, 160)
  Bit2-7 Not used                 (always 0)
  (DSi in NDS Mode: looks same as NDS, ie. only bit0-1 are R/W)
  (DSi in DSi Mode: Not used, always FFh)
  Register 4 - DS-Lite and DSi Only - Backlight Levels/Power Source (R/W)
  Bit0-1 Backlight Brightness (0..3=Low,Med,High,Max)   (R/W)
         (when bit2+3 are both set, then reading bit0-1 always returns 3)
  Bit2   Force Max Brightness when Bit3=1 (0=No, 1=Yes) (R/W)
  Bit3   External Power Present           (0=No, 1=Yes) (Read-Only)
  Bit4-7 Unknown (Always 4) (Read-Only)
  (DSi in NDS Mode: looks same as in DSi mode)
  (DSi in DSi Mode: Bit0-1 are R/W, but ignored, bit2-3 are always 0)
  Register 10h - DSi Only - Backlight Mirrors & Reset (R/W)
  Bit0   Reset (0=No, 1=Reboot DSi) (same/similar as BPTWL reset feature?)
  Bit1   Unknown (R/W) (note: whatever it is, it isn't warmboot flag)
  Bit2-3 Mirror of Register 0, bit2-3 (backlight enable bits) (R/W)
  Bit4-7 Not used (always 0)
  Bit5   Not used (always 0) - but DSi bootrom sets that bit on boot error?
  (This register works in NDS mode and DSi mode, though it's mainly intended
  for NDS mode, eg. DS Download Play uses the Reset bit to return to DSi menu)
  (note: writing bit2 seems to affect BOTH bit1 and bit2 in register 0)
  Register 1Fh and 20h - DSi Only (?)
  DSi bootrom sets register 1Fh and 20h bit0-4 to value 1Fh on boot error,
  unknown purpose, seems to have no effect, maybe prototype backlight level?
On Old-DS, registers 4..7Fh are mirrors of 0..3. On DS-Lite, registers 5,6,7 are mirrors of 4, register 8..7Fh are mirrors of 0-7.
On DSi (in DS mode), index 0,1,2,3,4,10h are used (reads as 0Fh,00h,00h,01h,41h,0Fh - regardless of backlight level, and power source), index 5..0Fh and 11h..7Fh return 00h (ie. unlike DS and DS-Lite, there are no mirrors; aside from the mirrored bits in register 10h).

Backlight Dimming / Backlight caused Shut-Down(s)
The above bits are essentially used to switch Backlights on or off. However, there a number of strange effects. Backlight dimming is possible by pulse width modulation, ie. by using a timer interrupt to issue pulse widths of N% ON, and 100-N% OFF. Too long pulses are certainly resulting in flickering. Too short pulses are ignored, the backlights will remain OFF, even if the ON and OFF pulses are having the same length. Much too short pulses cause the power supply to shut-down; after changing the backlight state, further changes must not occur within the next (circa) 2500 clock cycles. The mainboard can be operated without screens & backlights connected, however, if so, the power supply will shut-down as soon as backlights are enabled.
Pulse width modulated dimming does also work on the DS-Lite, allowing to use smoother fade in/out effects as when using the five "hardware" levels (Off,Low,Med,High,Max).


DS Main Memory Control

Main Memory
The DS Main Memory is 2Mx16bit (4MByte), 1.8V Pseudo SRAM (PSRAM); all Dynamic RAM refresh is handled internally, the chip doesn't require any external refresh signals, and alltogether behaves like Static RAM. Non-sequential access time is 70ns, sequential (burst) access time is 12ns.

Main Memory Control
The memory chips contain built-in Control functions, which can be accessed via Port 27FFFFEh and/or by EXMEMCNT Bit 14. Nintendo is using at least two different types of memory chips in DS consoles, Fujitsu 82DBS02163C-70L, and ST M69AB048BL70ZA8, both appear to have different control mechanisms, other chips (with 8MB size) are used in the semi-professional DS hardware debuggers, and further chips may be used in future, so using the memory control functions may lead into compatibitly problems.

Power Consumption / Power Control
Power Consumption during operation (read/write access) is somewhat 30mA, in standby mode (no read/write access) consumption is reduced to 100uA.
Furthermore, a number of power-down modes are supported: In "Deep" Power Down mode the refresh is fully disabled, consumption is 10uA (and all data will be lost), in "Partial" Power Down modes only fragment of memory is refreshed, for smallest fragments, consumption goes to down to circa 50uA. The chip cannot be accessed while it is in Deep or Partial Power Down mode.

Fujitsu 82DBS02163C-70L
The Configuration Register (CR) can be written to by the following sequence:
  LDRH R0,[27FFFFEh]      ;read one value
  STRH R0,[27FFFFEh]      ;write should be same value as above
  STRH R0,[27FFFFEh]      ;write should be same value as above
  STRH R0,[27FFFFEh]      ;write any value
  STRH R0,[27FFFFEh]      ;write any value
  LDRH R0,[2400000h+CR*2] ;read, address-bits are defining new CR value
Do not access any other Main Memory addresses during above sequence (ie. disable interrupts, and do not execute the sequence by code located in Main Memory). The CR value is write-only. The CR bits are:
  Bit    Expl.
  0-6    Reserved         (Must be 7Fh)
  7      Write Control
           0=WE Single Clock Pulse Control without Write Suspend Function
           1=WE Level Control with Write Suspend Function)
          Burst Read/Single Write is not supported at WE Single Clock Mode.
  8      Reserved         (Must be 1)
  9      Valid Clock Edge (0=Falling Edge, 1=Rising Edge)
  10     Single Write     (0=Burst Read/Burst Write, 1=Burst Read/Single Write)
  11     Burst Sequence   (0=Reserved, 1=Sequential)
  12-14  Read Latency     (1=3 clocks, 2=4 clocks, 3=5 clocks, other=Reserved)
  15     Mode
           0=Synchronous:  Burst Read, Burst Write
           1=Asynchronous: Page Read, Normal Write
          In Mode 1 (Async), only the Partial Size bits are used,
          all other bits, CR bits 0..18, must be "1".
  16-18  Burst Length     (2=8 Words, 3=16Words, 7=Continous, other=Reserved)
  19-20  Partial Size     (0=1MB, 1=512KB, 2=Reserved, 3=Deep/0 bytes)
The Power Down mode is entered by setting CE2=LOW, this can be probably done by setting EXMEMCNT Bit14 to zero.

ST Microelectronics M69AB048BL70ZA8
The chip name decodes as PSRAM (M96), Asynchronous (A), 1.8V Burst (B), 2Mx16 (048), Two Chip Enables (B), Low Leakage (L), 70ns (70), Package (ZA), -30..+85'C (8).
There are three data sheets for different PSRAM chips available at www.st.com (unfortunately none for M69AB048BL70ZA8), each using different memory control mechanisms.

NDS9 BIOS
The NDS9 BIOS contains the following Main Memory initialization code, that method doesn't match up with any ST (nor Fujitsu) data sheets that I've seen. At its best, it looks like a strange (and presumably non-functional) mix-up of different ST control methods.
  STRH 2000h,[4000204h]    ;EXMEMCNT, enable RAM, async mode
  LDRH R0,[27FFFFEh]
  STRH R0,[27FFFFEh]
  STRH R0,[27FFFFEh]
  STRH FFDFh,[27FFFFEh]
  STRH E732h,[27FFFFEh]
  LDRH R0,[27E57FEh]
  STRH 6000h,[4000204h]    ;EXMEMCNT, enable RAM, normal mode


DS Backwards-compatible GBA-Mode

When booting a 32pin GBA cartridge, the NDS is automatically switched into GBA mode, in that mode all NDS related features are disabled, and the console behaves (almost) like a GBA.

GBA Features that are NOT supported on NDS in GBA Mode.
Unlike real GBA, the NDS does not support 8bit DMG/CGB cartridges.
The undocumented Internal Memory Control register (Port 800h) isn't supported, so the NDS doesn't allow to use 'overclocked' RAM.
The NDS doesn't have a link-port, so GBA games can be played only in single player mode, link-port accessories cannot be used, and the NDS cannot run GBA code via multiboot.

GBA Features that are slightly different on NDS in GBA Mode.
The CPU, Timers, and Sound Frequencies are probably clocked at 16.76MHz; 33.51MHz/2; a bit slower than the original GBA's 16.78MHz clock?
In the BIOS, a single byte in a formerly 00h-filled area has been changed from 00h to 01h, resulting in SWI 0Dh returning a different BIOS checksum.
The GBA picture can be shown on upper or lower screen (selectable in boot-menu), the backlight for the selected screen is always on, resulting in different colors & much better visibility than original GBA. Unlike GBA-SP, the NDS doesn't have a backlight-button.

Screen Border in GBA mode
The GBA screen is centered in the middle of the NDS screen. The surrounding pixels are defined by 32K-color bitmap data in VRAM Block A and B. Each frame, the GBA picture is captured into one block, and is displayed in the next frame (while capturing new data to the other block).
To get a flicker-free border, both blocks should be initialized to contain the same image before entering GBA mode (usually both are zero-filled, resulting in a plain black border).
Note: When using two different borders, the flickering will be irregular - so there appears to be a frame inserted or skipped once every some seconds in GBA mode?!

Switching from NDS Mode to GBA Mode
  --- NDS9: ---
  ZEROFILL VRAM A,B     ;init black screen border (or other color/image)
  POWCNT=8003h          ;enable 2D engine A on upper screen (0003h=lower)
  EXMEMCNT=...          ;set Async Main Memory mode (clear bit14)
  IME=0                 ;disable interrupts
  SWI 06h               ;halt with interrupts disabled (lockdown)
  --- NDS7: ---
  POWERMAN.REG0=09h     ;enable sound amplifier & upper backlight (05h=lower)
  IME=0                 ;disable interrupts
  wait for VCOUNT=200   ;wait until VBlank
  SWI 1Fh with R2=40h   ;enter GBA mode, by CustomHalt(40h)
After that, the GBA BIOS will be booted, the GBA Intro will be displayed, and the GBA cartridge (if any) will be started.


DS Debug Registers (Emulator/Devkits)

No$gba Emulator Pseudo I/O Ports (no$gba) (GBA,NDS9,NDS7)
  4FFFA00h..A0Fh R Emulation ID (16 bytes, eg. "no$gba v2.7", padded with 20h)
  4FFFA10h       W String Out (raw)
  4FFFA14h       W String Out (with %param's)
  4FFFA18h       W String Out (with %param's, plus linefeed)
  4FFFA1Ch       W Char Out (nocash)
  4FFFA20h..A27h R Clock Cycles (64bit)
  4FFFA28h..A3Fh - N/A
Note: Above ports can be disabled via the "Debug I/O" option in no$gba setup.

Ensata Emulator Pseudo I/O Ports (NDS9)
  4000640h (32bit) ;aka CLIPMTX_RESULT (mis-used to invoke detection)
  4000006h (16bit) ;aka VCOUNT (mis-used to get detection result)
  4FFF010h (32bit) ;use to initialize/unlock/reset something
  4FFF000h (8bit)  ;debug message character output (used when Ensata detected)
The Ensata detection works by mis-using CLIPMTX_RESULT and VCOUNT registers:
  [4000640h]=2468ACE0h      ;CLIPMTX_RESULT (on real hardware it's read-only)
  if ([4000006h] AND 1FFh)=10Eh ;VCOUNT (on real hardware it's 000h..106h)
    [4FFF010h]=13579BDFh        ;\initialize/reset something
    [4FFF010h]=FDB97531h        ;/
    Ensata=true
  else
    Ensata=false
  endif
Once when a commercial game has detected Ensata, it stops communicating with the ARM7, and instead it does seem to want to communicate with the Ensata executable (which has little to do with real NDS hardware). Ie. aside from "unlocking" port 4FFF000h, it does also "lock" access to the ARM7 hardware (like sound, touchscreen, RTC, etc).

ISD (Intelligent Systems Debugger or so) I/O Ports
The ISD ports seem to be real (non-emulated) debugging ports, mapped to the GBA Slot region at 8000000h-9FFFFFFh, and used to output text messages, and possible also other debugging stuff.
There are appear to be two variants: nitroemu and cgbemu (the latter appears to be dating back to old 8bit CGB hardware; which was apparently still used for the NDS two hardware generations later).

NDS Devkit
In Nintendo's devkit, debug messages are handled in file "os_printf.c", this file detects the available hardware/software based debug I/O ports, and redirects the [OS_PutString] vector to the corresponding string_out function (eg. to OS_PutStringAris for writing a 00h-terminated string to port 4FFF000h). With some minimal efforts, this could be redirected to the corresponding no$gba debug I/O ports.


DS Cartridges, Encryption, Firmware

Cartridges
DS Cartridge Header
DS Cartridge Secure Area
DS Cartridge Icon/Title
DS Cartridge Protocol
DS Cartridge Backup
DS Cartridge NAND
DS Cartridge I/O Ports
DS Cartridge NitroROM and NitroARC File Systems
DS Cartridge Unknown Commands
DS Cartridge PassMe/PassThrough
DS Cartridge GBA Slot

Cartridge File Formats
DS File Formats

Add-Ons
DS Cart Rumble Pak
DS Cart Slider with Rumble
DS Cart Expansion RAM
DS Cart Infrared/Pedometers
DS Cart Unknown Extras

Special Cartridges
DS Cart Cheat Action Replay DS
DS Cart Cheat Codebreaker DS
DS Cart DLDI Driver

Encryption
DS Encryption by Gamecode/Idcode (KEY1)
DS Encryption by Random Seed (KEY2)

Firmware / Wifi Flash
DS Firmware Serial Flash Memory
DS Firmware Header
DS Firmware Wifi Calibration Data
DS Firmware Wifi Internet Access Points
DS Firmware User Settings
DS Firmware Extended Settings


DS Cartridge Header

Header Overview (loaded from ROM Addr 0 to Main RAM 27FFE00h on Power-up)
  Address Bytes Expl.
  000h    12    Game Title  (Uppercase ASCII, padded with 00h)
  00Ch    4     Gamecode    (Uppercase ASCII, NTR-<code>)        (0=homebrew)
  010h    2     Makercode   (Uppercase ASCII, eg. "01"=Nintendo) (0=homebrew)
  012h    1     Unitcode    (00h=NDS, 02h=NDS+DSi, 03h=DSi) (bit1=DSi)
  013h    1     Encryption Seed Select (00..07h, usually 00h)
  014h    1     Devicecapacity         (Chipsize = 128KB SHL nn) (eg. 7 = 16MB)
  015h    7     Reserved    (zero filled)
  01Ch    1     Reserved    (zero)                      (except, used on DSi)
  01Dh    1     NDS Region  (00h=Normal, 80h=China, 40h=Korea) (other on DSi)
  01Eh    1     ROM Version (usually 00h)
  01Fh    1     Autostart (Bit2: Skip "Press Button" after Health and Safety)
                (Also skips bootmenu, even in Manual mode & even Start pressed)
  020h    4     ARM9 rom_offset    (4000h and up, align 1000h)
  024h    4     ARM9 entry_address (2000000h..23BFE00h)
  028h    4     ARM9 ram_address   (2000000h..23BFE00h)
  02Ch    4     ARM9 size          (max 3BFE00h) (3839.5KB)
  030h    4     ARM7 rom_offset    (8000h and up)
  034h    4     ARM7 entry_address (2000000h..23BFE00h, or 37F8000h..3807E00h)
  038h    4     ARM7 ram_address   (2000000h..23BFE00h, or 37F8000h..3807E00h)
  03Ch    4     ARM7 size          (max 3BFE00h, or FE00h) (3839.5KB, 63.5KB)
  040h    4     File Name Table (FNT) offset
  044h    4     File Name Table (FNT) size
  048h    4     File Allocation Table (FAT) offset
  04Ch    4     File Allocation Table (FAT) size
  050h    4     File ARM9 overlay_offset
  054h    4     File ARM9 overlay_size
  058h    4     File ARM7 overlay_offset
  05Ch    4     File ARM7 overlay_size
  060h    4     Port 40001A4h setting for normal commands (usually 00586000h)
  064h    4     Port 40001A4h setting for KEY1 commands   (usually 001808F8h)
  068h    4     Icon/Title offset (0=None) (8000h and up)
  06Ch    2     Secure Area Checksum, CRC-16 of [[020h]..00007FFFh]
  06Eh    2     Secure Area Delay (in 131kHz units) (051Eh=10ms or 0D7Eh=26ms)
  070h    4     ARM9 Auto Load List Hook RAM Address (?) ;\endaddr of auto-load
  074h    4     ARM7 Auto Load List Hook RAM Address (?) ;/functions
  078h    8     Secure Area Disable (by encrypted "NmMdOnly") (usually zero)
  080h    4     Total Used ROM size (remaining/unused bytes usually FFh-padded)
  084h    4     ROM Header Size (4000h)
  088h    4     Unknown, some rom_offset, or zero? (DSi: slightly different)
  08Ch    8     Reserved (zero filled; except, [88h..93h] used on DSi)
  094h    2     NAND end of ROM area  ;\in 20000h-byte units (DSi: 80000h-byte)
  096h    2     NAND start of RW area ;/usually both same address (0=None)
  098h    18h   Reserved (zero filled)
  0B0h    10h   Reserved (zero filled; or "DoNotZeroFillMem"=unlaunch fastboot)
  0C0h    9Ch   Nintendo Logo (compressed bitmap, same as in GBA Headers)
  15Ch    2     Nintendo Logo Checksum, CRC-16 of [0C0h-15Bh], fixed CF56h
  15Eh    2     Header Checksum, CRC-16 of [000h-15Dh]
  160h    4     Debug rom_offset   (0=none) (8000h and up)       ;only if debug
  164h    4     Debug size         (0=none) (max 3BFE00h)        ;version with
  168h    4     Debug ram_address  (0=none) (2400000h..27BFE00h) ;SIO and 8MB
  16Ch    4     Reserved (zero filled) (transferred, and stored, but not used)
  170h    90h   Reserved (zero filled) (transferred, but not stored in RAM)
  200h    E00h  Reserved (zero filled) (usually not transferred)
DSi Cartridges are using an extended cartridge header,
DSi Cartridge Header
Some of that new/changed DSi header entries are important even in NDS mode:
- On DSi, ARM9/ARM7 areas are restricted to 2.75MB (instead 3.8MB on real NDS)
- New NDS titles must have RSA signatures (and old titles must be in whitelist)

For more info about CRC-16, see description of GetCRC16 BIOS function,
BIOS Misc Functions
For the Logo checksum, the BIOS verifies only [15Ch]=CF56h, it does NOT verify the actual data at [0C0h-15Bh] (nor it's checksum), however, the data is verified by the firmware.

Secure Area Delay
The Secure Area Delay at header[06Eh] is counted in 130.912kHz units (which can be clocked via one of the hardware timers with prescaler=F/256 and reload=(10000h-((X AND 3FFFh)+2)); for some weird reason, in case of Header checksum it's ANDed with 1FFFh instead of 3FFFh). Commonly used values are X=051Eh (10ms), and X=0D7Eh (26ms).
The delay is used for all Blowfish encrypted commands, the actual usage/purpose differs depending on bit31 of the ROM Chip ID:
When ChipID.Bit31=0 (commands are sent ONCE): The delay is issued BEFORE sending the command:
  Delay,Cmd
Older/newer games are using delays of 10ms/26ms (although all known existing cartridges with Bit31=0 would actually work WITHOUT delays).
When ChipID.Bit31=1 (commands are repeated MULTIPLE times): The delay is issued AFTER sending the command for the FIRST time:
  Cmd,Delay,Cmd                                ;for 2x repeat
  Cmd,Delay,Cmd,Cmd,Cmd,Cmd,Cmd,Cmd,Cmd,Cmd    ;for 9x repeat
Known games are using delays of 26ms (although all known existing cartridges (=Cooking Coach) with Bit31=1 would actually work with shorter delays of ca. 7ms (but, better use 8ms for safety)).

NDS Gamecodes
This is the same code as the NTR-UTTD (NDS) or TWL-UTTD (DSi) code which is printed on the package and sticker on (commercial) cartridges (excluding the leading "NTR-" or "TWL-" part).
  U  Unique Code          (usually "A", "B", "C", or special meaning)
  TT Short Title          (eg. "PM" for Pac Man)
  D  Destination/Language (usually "J" or "E" or "P" or specific language)
The first character (U) is usually "A" or "B", in detail:
  A NDS common games
  B NDS common games
  C NDS common games
  D DSi-exclusive games
  H DSiWare (system utilities and browser) (eg. HNGP=browser)
  I NDS and DSi-enhanced games with built-in Infrared port
  K DSiWare (dsiware games and flipnote) (eg. KGUV=flipnote)
  N NDS nintendo channel demo's japan (NTR-NTRJ-JPN)
  T NDS many games
  U NDS and DSi uncommon extra hardware (eg. NAND, ram, microSD, TV, azimuth)
  V DSi-enhanced games
  Y NDS many games
The second/third characters (TT) are:
  Usually an abbreviation of the game title (eg. "PM" for "Pac Man") (unless
  that gamecode was already used for another game, then TT is just random)
The fourth character (D) indicates Destination/Language:
  A Asian    E English/USA  I Italian   M Swedish  Q Danish   U Australian
  B N/A      F French       J Japanese  N Nor      R Russian  V EUR+AUS
  C Chinese  G N/A          K Korean    O Int      S Spanish  W..Z Europe #3..5
  D German   H Dutch        L USA #2    P Europe   T USA+AUS


DS Cartridge Secure Area

The Secure Area is located in ROM at 4000h..7FFFh, it can contain normal program code and data, however, it can be used only for ARM9 boot code, it cannot be used for ARM7 boot code, icon/title, filesystem, or other data.

Secure Area Size
The Secure Area exists if the ARM9 boot code ROM source address (src) is located within 4000h..7FFFh, if so, it will be loaded (by BIOS via KEY1 encrypted commands) in 4K portions, starting at src, aligned by 1000h, up to address 7FFFh. The secure area size if thus 8000h-src, regardless of the ARM9 boot code size entry in header.
Note: The BIOS silently skips any NDS9 bootcode at src<4000h.
Cartridges with src>=8000h do not have a secure area.

Secure Area ID
The first 8 bytes of the secure area are containing the Secure Area ID, the ID is required (verified by BIOS boot code), the ID value changes during boot process:
  Value                Expl.
  "encryObj"           raw ID before encryption (raw ROM-image)
  (encrypted)          encrypted ID after encryption (encrypted ROM-image)
  "encryObj"           raw ID after decryption (verified by BIOS boot code)
  E7FFDEFFh,E7FFDEFFh  destroyed ID (overwritten by BIOS after verify)
If the decrypted ID does match, then the BIOS overwrites the first 8 bytes by E7FFDEFFh-values (ie. only the ID is destroyed). If the ID doesn't match, then the first 800h bytes (2K) are overwritten by E7FFDEFFh-values.

Secure Area First 2K Encryption/Content
The first 2K of the Secure Area (if it exists) are KEY1 encrypted. In official games, this 2K region contains data like so (in decrypted form):
  000h..007h  Secure Area ID (see above)
  008h..00Dh  Fixed (FFh,DEh,FFh,E7h,FFh,DEh)
  00Eh..00Fh  CRC16 across following 7E0h bytes, ie. [010h..7FFh]
  010h..7FDh  Unknown/random values, mixed with some THUMB SWI calls
  7FEh..7FFh  Fixed (00h,00h)
Of which, only the ID in the first 8 bytes is verified. Neither BIOS nor (current) firmare versions are verifying the data at 008h..7FFh, so the 7F8h bytes may be also used for normal program code/data.

Avoiding Secure Area Encryption
WLAN files are reportedly same format as cartridges, but without Secure Area, so games with Secure Area cannot be booted via WLAN. No$gba can encrypt and decrypt Secure Areas only if the NDS BIOS-images are present. And, Nintendo's devkit doesn't seem to support Secure Area encryption of unreleased games.
So, unencrypted cartridges are more flexible in use. Ways to avoid encryption (which still work on real hardware) are:
1) Set NDS9 ROM offset to 4000h, and leave the first 800h bytes of the Secure Area 00h-filled, which can be (and will be) safely destroyed during loading; due to the missing "encryObj" ID; that method is used by Nintendo's devkit.
2) Set NDS9 ROM offset to 8000h or higher (cartridge has no Secure Area at all).
3) Set NDS9 ROM offset, RAM address, and size to zero, set NDS7 ROM offset to 200h, and point both NDS9 and NDS7 entrypoints to the loaded NDS7 region. That method avoids waste of unused memory at 200h..3FFFh, and it should be compatible with the NDS console, however, it is not comaptible with commercial cartridges - which do silently redirect address below 4000h to "addr=8000h+(addr AND 1FFh)". Still, it should work with inofficial flashcards, which do not do that redirection. No$gba emulates the redirection for regular official cartridges, but it disables redirection for homebrew carts if NDS7 rom offset<8000h, and NDS7 size>0.
[One possible problem: Newer "anti-passme" firmware versions reportedly check that the entrypoint isn't set to 80000C0h, that firmwares might also reject NDS9 entrypoints within the NDS7 bootcode region?]


DS Cartridge Icon/Title

The ROM offset of the Icon/Title is defined in CartHdr[68h]. The size was originally implied by the size of the original Icon/Title structure rounded to 200h-byte sector boundary (ie. A00h bytes for Version 1 or 2), however, later DSi carts (with CartHdr[1Ch].bit0=1) are having a size entry at CartHdr[208h] (usually 23C0h).
If present (ie. if CartHdr[68h]=nonzero), then Icon/Title are displayed in the bootmenu.
  0000h 2     Version (0001h, 0002h, 0003h, or 0103h)
  0002h 2     CRC16 across entries 0020h..083Fh (all versions)
  0004h 2     CRC16 across entries 0020h..093Fh (Version 0002h and up)
  0006h 2     CRC16 across entries 0020h..0A3Fh (Version 0003h and up)
  0008h 2     CRC16 across entries 1240h..23BFh (Version 0103h and up)
  000Ah 16h   Reserved (zero-filled)
  0020h 200h  Icon Bitmap  (32x32 pix) (4x4 tiles, 4bit depth) (4x8 bytes/tile)
  0220h 20h   Icon Palette (16 colors, 16bit, range 0000h-7FFFh)
              (Color 0 is transparent, so the 1st palette entry is ignored)
  0240h 100h  Title 0 Japanese  (128 characters, 16bit Unicode)
  0340h 100h  Title 1 English   ("")
  0440h 100h  Title 2 French    ("")
  0540h 100h  Title 3 German    ("")
  0640h 100h  Title 4 Italian   ("")
  0740h 100h  Title 5 Spanish   ("")
  0840h 100h  Title 6 Chinese   ("")                 (Version 0002h and up)
  0940h 100h  Title 7 Korean    ("")                 (Version 0003h and up)
  0A40h 800h  Zerofilled (probably reserved for Title 8..15)
Below for animated DSi icons only (Version 0103h and up):
  1240h 1000h Icon Animation Bitmap 0..7 (200h bytes each, format as above)
  2240h 100h  Icon Animation Palette 0..7 (20h bytes each, format as above)
  2340h 80h   Icon Animation Sequence (16bit tokens)
Unused/padding bytes:
  0840h 1C0h  Unused/padding (FFh-filled) in Version 0001h
  0940h C0h   Unused/padding (FFh-filled) in Version 0002h
  23C0h 40h   Unused/padding (FFh-filled) in Version 0103h

Versions
  0001h = Original
  0002h = With Chinese Title
  0003h = With Chinese+Korean Titles
  0103h = With Chinese+Korean Titles and animated DSi icon

Title Strings
Usually, for non-multilanguage games, the same (english) title is stored in all title entries. The title may consist of ASCII characters 0020h-007Fh, character 000Ah (linefeed), and should be terminated/padded by 0000h.
The whole text should not exceed the dimensions of the DS cart field in the bootmenu (the maximum number of characters differs due to proportional font).
The title is usually split into a primary title, optional sub-title, and manufacturer, each separated by 000Ah character(s). For example: "America", 000Ah, "The Axis of War", 000Ah, "Cynicware", 0000h.

Icon Animation Sequence (DSi)
The sequence is represented by 16bit tokens, in the following format:
  15    Flip Vertically   (0=No, 1=Yes)
  14    Flip Horizontally (0=No, 1=Yes)
  13-11 Palette Index     (0..7)
  10-8  Bitmap Index      (0..7)
  7-0   Frame Duration    (01h..FFh) (in 60Hz units)
Value 0000h indicates the end of the sequence. If the first token is 0000h, then the non-animated default image is shown.
Uh, actually, a non-animated icon uses values 01h,00h,00h,01h, followed by 7Ch zerofilled bytes (ie. 0001h, 0100h, 3Eh x 0000h)?

FAT16:\title\000300tt\4ggggggg\data\banner.sav ;if carthdr[1BFh].bit2=1
Some DSi games are having a separate "banner.sav" file stored in the eMMC filesystem, enabled via carthdr[1BFh].bit2 (allowing to indicate the game progress by overriding the default icon). The banner files are 4000h bytes in size, the animation data is same as above, but without title strings and without non-animated icon.
  0000h 2     Version (0103h)
  0002h 6     Reserved (zero-filled)
  0008h 2     CRC16 across entries 0020h..119Fh (with initial value FFFFh)
  000Ah 16h   Reserved (zero-filled)
  0020h 1000h Icon Animation Bitmap 0..7 (200h bytes each)  ;\same format as
  1020h 100h  Icon Animation Palette 0..7 (20h bytes each)  ; in Icon/Title
  1120h 80h   Icon Animation Sequence (16bit tokens)        ;/
  11A0h 2E60h Garbage (random values, maybe due to eMMC decryption)
The feature is used by some Brain Age Express games (for example, Brain Age Express Sudoku: 'title\00030004\4b4e3945\data\banner.sav').
The feature does probably work only for DSiware titles (unless there are any DSi carts with SD/MMC access enabled; or unless there is a feature for storing similar data in cartridge memory).


DS Cartridge Protocol

Communication with Cartridge ROM relies on sending 8 byte commands to the cartridge, after the sending the command, a data stream can be received from the cartridge (the length of the data stream isn't fixed, below descriptions show the default length in brackets, but one may receive more, or less bytes, if desired).

Cartridge Memory Map
  0000000h-0000FFFh Header (unencrypted)
  0001000h-0003FFFh Not read-able (zero filled in ROM-images)
  0004000h-0007FFFh Secure Area, 16KBytes (first 2Kbytes with extra encryption)
  0008000h-...      Main Data Area
DSi cartridges are split into a NDS area (as above), and a new DSi area:
  XX00000h XX02FFFh DSi Not read-able (XX00000h=first megabyte after NDS area)
  XX03000h-XX06FFFh DSi ARM9i Secure Area (usually with modcrypt encryption)
  XX07000h-...      DSi Main Data Area
Cartridge memory must be copied to RAM (the CPU cannot execute code in ROM).

Command Summary, Cmd/Reply-Encryption Type, Default Length
  Command/Params    Expl.                             Cmd  Reply Len
  -- Unencrypted Load --
  9F00000000000000h Dummy (read HIGH-Z bytes)         RAW  RAW   2000h
  0000000000000000h Get Cartridge Header              RAW  RAW   200h DSi:1000h
  00aaaaaaaa000000h Get Cartridge Header (1T-ROM,NAND)RAW  RAW   200h
  9000000000000000h 1st Get ROM Chip ID               RAW  RAW   4
  A000000000000000h Get 3DS encryption type (3DS)     RAW  RAW   4
  00aaaaaaaa000000h Unencrypted Data (debug ver only) RAW  RAW   200h
  3Ciiijjjxkkkkkxxh Activate KEY1 Encryption (NDS)    RAW  RAW   0
  3Diiijjjxkkkkkxxh Activate KEY1 Encryption (DSi)    RAW  RAW   0
  3E00000000000000h Activate 16-byte commands (3DS)   RAW  RAW   0
  -- Secure Area Load --
  4llllmmmnnnkkkkkh Activate KEY2 Encryption Mode     KEY1 FIX   910h+0
  1lllliiijjjkkkkkh 2nd Get ROM Chip ID               KEY1 KEY2  910h+4
  xxxxxxxxxxxxxxxxh Invalid - Get KEY2 Stream XOR 00h KEY1 KEY2  910h+...
  2bbbbiiijjjkkkkkh Get Secure Area Block (4Kbytes)   KEY1 KEY2  910h+10A8h
  6lllliiijjjkkkkkh Optional KEY2 Disable             KEY1 KEY2  910h+?
  Alllliiijjjkkkkkh Enter Main Data Mode              KEY1 KEY2  910h+0
  -- Main Data Load --
  B7aaaaaaaa000000h Encrypted Data Read               KEY2 KEY2  200h
  B800000000000000h 3rd Get ROM Chip ID               KEY2 KEY2  4
  xxxxxxxxxxxxxxxxh Invalid - Get KEY2 Stream XOR 00h KEY2 KEY2  ...
  B500000000000000h Whatever NAND related? (DSi?)     KEY2 KEY2  0
  D600000000000000h Whatever NAND related? (DSi?)     KEY2 KEY2  4
The parameter digits contained in above commands are:
  aaaaaaaa     32bit ROM address (command B7 can access only 8000h and up)
  bbbb         Secure Area Block number (0004h..0007h for addr 4000h..7000h)
  x,xx         Random, not used in further commands (DSi: always zero)
  iii,jjj,llll Random, must be SAME value in further commands
  kkkkk        Random, must be INCREMENTED after FURTHER commands
  mmm,nnn      Random, used as KEY2-encryption seed

 ____________ Unencrypted Commands (First Part of Boot Procedure) _____________

Cartridge Reset
The /RES Pin switches the cartridge into unencrypted mode. After reset, the first two commands (9Fh and 00h) are transferred at 4MB/s CLK rate.

9F00000000000000h (2000h) - Dummy
Dummy command send after reset, returns endless stream of HIGH-Z bytes (ie. usually receiving FFh, immediately after sending the command, the first 1-2 received bytes may be equal to the last command byte).

0000000000000000h (200h) (DSi:1000h) - Get Header (from address 00000000h)
00aaaaaaaa000000h (200h) - DSi Get Header Snippet (from address aaaaaaaah)
Returns RAW unencrypted cartridge header, usually repeated every 1000h bytes. Some carts allow to read the header with a single 200h-byte or 1000h-byte read, others require eight separate 200h-byte reads.
  NDS/MROM   --> Read 200h bytes from address 000h
  NDS/1T-ROM --> Read 200h bytes from address 000h
  NDS/NAND   --> Read 200h bytes from address 000h
  DSi/MROM   --> Read 1000h bytes from address 000h
  DSi/1T-ROM --> Read 8x200h bytes from address 000h,200h,400h,..,E00h
  DSi/NAND   --> Read 8x200h bytes from address 000h,200h,400h,..,E00h
Note: DSi/1T-ROM usually allows to read 1000h bytes or 8x200h, but DSi/NAND works only when reading 8x200h bytes.
The Gamecode header entry is used later on to initialize the encryption. Also, the ROM Control entries define the length of the KEY1 dummy periods (typically 910h clocks), and the CLK transfer rate for further commands (typically faster than the initial 4MB/s after power up).

9000000000000000h (4) - 1st Get ROM Chip ID
Returns RAW unencrypted Chip ID (eg. C2h,0Fh,00h,00h), repeated every 4 bytes.
  1st byte - Manufacturer (eg. C2h=Macronix) (roughly based on JEDEC IDs)
  2nd byte - Chip size (00h..7Fh: (N+1)Mbytes, F0h..FFh: (100h-N)*256Mbytes?)
  3rd byte - Flags (see below)
  4th byte - Flags (see below)
The Flag Bits in 3th byte can be
  0   Uses Infrared (but via SPI, unrelated to ROM) (also Jam with the Band)
  1   Unknown (set in some 3DS carts)
  2-6 Zero
  7   Unknown (set in Kingdom Hearts - Re-Coded)
The Flag Bits in 4th byte can be
  0-2 Zero
  3   NAND flag (0=ROM, 1=NAND)
  4   3DS Flag  (0=NDS/DSi, 1=3DS)
  5   Unknown   (0=Normal, 1=Support cmd B5h/D6h)
  6   DSi flag  (0=NDS/3DS, 1=DSi) (but also set in NDS Walk with Me)
  7   Cart Protocol Variant (0=old/smaller MROM, 1=new/bigger 1T-ROM or NAND)
Existing/known ROM IDs are:
  C2h,07h,00h,00h NDS Macronix 8MB ROM  (eg. DS Vision, with microSD slot)
  AEh,0Fh,00h,00h NDS Noname   16MB ROM (eg. Meine Tierarztpraxis)
  C2h,0Fh,00h,00h NDS Macronix 16MB ROM (eg. Metroid Demo)
  C2h,1Fh,00h,00h NDS Macronix 32MB ROM (eg. Over the Hedge)
  C2h,1Fh,00h,40h DSi Macronix 32MB ROM (eg. Art Academy, TWL-VAAV, SystemFlaw)
  80h,3Fh,01h,E0h NDS SanDisk  64MB ROM+Infrared (eg. Walk with Me, NTR-IMWP)
  AEh,3Fh,00h,E0h DSi Noname   64MB ROM (eg. de Blob 2, TWL-VD2V)
  C2h,3Fh,00h,00h NDS Macronix 64MB ROM (eg. Ultimate Spiderman)
  C2h,3Fh,00h,40h DSi Macronix 64MB ROM (eg. Crime Lab, NTR-VAOP)
  80h,7Fh,00h,80h NDS SanDisk  128MB ROM (DS Zelda, NTR-AZEP-0)
  80h,7Fh,01h,E0h ?   SanDisk? 128MB ROM+Infrared (P-letter SoulSilver, IPGE)
  C2h,7Fh,00h,80h NDS Macronix 128MB ROM (eg. Spirit Tracks, NTR-BKIP)
  C2h,7Fh,00h,C0h DSi Macronix 128MB ROM (eg. Cooking Coach, TWL-VCKE)
  ECh,7Fh,00h,88h NDS Samsung  128MB NAND (eg. Warioware D.I.Y., NTR-UORE)
  ECh,7Fh,01h,88h NDS Samsung  128MB NAND (eg. Jam with the Band, NTR-UXBP)
  ECh,7Fh,00h,E8h DSi Samsung  128MB NAND (eg. Face Training, TWL-USKV)
  80h,FFh,80h,E0h NDS SanDisk? 256MB ROM (Kingdom Hearts - Re-Coded, NTR-BK9P)
  C2h,FFh,01h,C0h DSi Macronix 256MB ROM+Infrared (eg. P-Letter White)
  C2h,FFh,00h,80h NDS Macronix 256MB ROM (eg. Band Hero, NTR-BGHP)
  C2h,FEh,01h,C0h DSi Macronix 512MB ROM+Infrared (eg. P-Letter White 2)
  C2h,FEh,00h,90h 3DS Macronix probably 512MB? ROM (eg. Sims 3)
  45h,FAh,00h,90h 3DS SanDisk? maybe... 1GB?   ROM (eg. Starfox)
  C2h,F8h,00h,90h 3DS Macronix maybe... 2GB?   ROM (eg. Kid Icarus)
  C2h,7Fh,00h,90h 3DS Macronix 128MB ROM CTR-P-AENJ MMinna no Ennichi
  C2h,FFh,00h,90h 3DS Macronix 256MB ROM CTR-P-AFSJ Pro Yakyuu Famista 2011
  C2h,FEh,00h,90h 3DS Macronix 512MB ROM CTR-P-AFAJ Real 3D Bass FishingFishOn
  C2h,FAh,00h,90h 3DS Macronix 1GB ROM CTR-P-ASUJ Hana to Ikimono Rittai Zukan
  C2h,FAh,02h,90h 3DS Macronix 1GB ROM CTR-P-AGGW Luigis Mansion 2 ASiA CHT
  C2h,F8h,00h,90h 3DS Macronix 2GB ROM CTR-P-ACFJ Castlevania - Lords of Shadow
  C2h,F8h,02h,90h 3DS Macronix 2GB ROM CTR-P-AH4J Monster Hunter 4
  AEh,FAh,00h,90h 3DS Noname?  1GB ROM CTR-P-AGKJ Gyakuten Saiban 5
  AEh,FAh,00h,98h 3DS Noname?  1GB NAND CTR-P-EGDJ Tobidase Doubutsu no Mori
  45h,FAh,00h,90h 3DS SanDisk? 1GB ROM CTR-P-AFLJ Fantasy Life
  45h,F8h,00h,90h 3DS SanDisk? 2GB ROM CTR-P-AVHJ Senran Kagura Burst - Guren
  C2h,F0h,00h,90h 3DS Macronix 4GB ROM CTR-P-ABRJ Biohazard Revelations
  ?,?,?,?         NDS ?        ? (eg. Japanese TV Tuner, NTR-UNSJ)
  00h,00h,00h,00h Cart Reset Busy (Face Training needs 20ms delay after reset)
  FFh,FFh,FFh,FFh None (no cartridge inserted)
The official JEDEC ID for Samsung would be "CEh", but for some reason, Samsung's NDS chip does spit out "ECh" as Maker ID. SanDisk has two IDs (80h on NDS/DSi, and 45h on 3DS).

3Ciiijjjxkkkkkxxh (0) - Activate KEY1 Encryption Mode
The 3Ch command returns endless stream of HIGH-Z bytes, all following commands, and their return values, are encrypted. The random parameters iii,jjj,kkkkk must be re-used in further commands; the 20bit kkkkk value is to be incremented by one after each <further> command (it is <not> incremented after the 3Ch command).

3Diiijjjxkkkkkxxh (0) - Activate KEY1 Encryption Mode and Unlock DSi Mode
Same as command 3Ch (but with different initial 1048h-byte encryption values), and works only on DSi carts. Command 3Dh is unlocking two features on DSi carts:
  1) Command 2bbbbiiijjjkkkkkh loads ARM9i secure area (instead of ARM9 area)
  2) Command B7aaaaaaaa000000h allows to read the 'whole' cartridge space
Without command 3Dh, DSi carts will allow to read only the first some megabytes (for example, the first 11 Mbyte of the System Flaw cartridge), and the remaining memory returns mirrors of "addr=8000h+(addr AND 1FFh)").
Note: After reset, the cartridge protocol allows to send only either one of the 3Ch/3Dh commands (DSi consoles can control the cartridge reset pin, so they can first send 3Ch and read the normal secure area, then issue a reset and 3Dh and read the DSi secure area) (on a NDS one could do the same by ejecting/inserting the cartridge instead of toggling the reset pin).

 ____________ KEY1 Encrypted Commands (2nd Part of Boot procedure) ____________

4llllmmmnnnkkkkkh (910h) - Activate KEY2 Encryption Mode
KEY1 encrypted command, parameter mmmnnn is used to initialize the KEY2 encryption stream. Returns 910h dummy bytes (which are still subject to old KEY2 settings; at pre-initialization time, this is fixed: HIGH-Z, C5h, 3Ah, 81h, etc.). The new KEY2 seeds are then applied, and the first KEY2 byte is then precomputed. The 910h dummy stream is followed by that precomputed byte value endless repeated (this is the same value as that "underneath" of the first HIGH-Z dummy-byte of the next command).
Secure1000h: Returns repeated FFh bytes (instead of the leading C5h, 3Ah, 81h, etc. stuff).
Secure1000h: Returns repeated FFh bytes (instead of the repeated precomputed value).

1lllliiijjjkkkkkh (914h) - 2nd Get ROM Chip ID / Get KEY2 Stream
KEY1 encrypted command. Returns 910h dummy bytes, followed by KEY2 encrypted Chip ID repeated every 4 bytes, which must be identical as for the 1st Get ID command. The BIOS randomly executes this command once or twice. Changing the first command byte to any other value returns an endless KEY2 encrypted stream of 00h bytes, that is the easiest way to retrieve encryption values and to bypass the copyprotection.

2bbbbiiijjjkkkkkh (19B8h) - Get Secure Area Block
KEY1 encrypted command. Used to read a secure area block (bbbb in range 0004h..0007h for addr 4000h..7000h) (or, after sending command 3Dh on a DSi: bbbb in range 0004h..0007h for addr XX03000h..XX06000h).
Each block is 4K, so it requires four Get Secure Area commands to receive the whole Secure Area (ROM locations 4000h-7FFFh), the BIOS is reading these blocks in random order.
Normally (if the upper bit of the Chip ID is set): Returns 910h dummy bytes, followed by 200h KEY2 encrypted Secure Area bytes, followed by 18h KEY2 encrypted 00h bytes, then the next 200h KEY2 encrypted Secure Area bytes, again followed by 18h KEY2 encrypted 00h bytes, and so on. That stream is repeated every 10C0h bytes (8x200h data bytes, plus 8x18h zero bytes).
Alternately (if the upper bit of the Chip ID is zero): Returns 910h dummy bytes, followed by 1000h KEY2 encrypted Secure Area bytes, presumably followed by 18h bytes, too.
Aside from above KEY2 encryption (which is done by hardware), the first 2K of the NDS Secure Area is additionally KEY1 encrypted; which must be resolved after transfer by software (and the DSi Secure Area is usually modcrypted, as specified in the cartridge header).

6lllliiijjjkkkkkh (0) - Optional KEY2 Disable
KEY1 encrypted command. Returns 910h dummy bytes (which are still KEY2 affected), followed by endless stream of RAW 00h bytes. KEY2 encryption is disabled for all following commands.
This command is send only if firmware[18h] matches encrypted string "enPngOFF", and ONLY if firmware get_crypt_keys had completed BEFORE completion of secure area loading, this timing issue may cause unstable results.

Alllliiijjjkkkkkh (910h) - Enter Main Data Mode
KEY1 encrypted command. Returns 910h dummy bytes, followed by endless KEY2 encrypted stream of 00h bytes. All following commands are KEY2 encrypted.

 ________________ KEY2 Encrypted Commands (Main Data Transfer) ________________

B7aaaaaaaa000000h (200h) - Get Data
KEY2 encrypted command. The desired ROM address is specifed, MSB first, in parameter bytes (a). Returned data is KEY2 encrypted.
There is no alignment restriction for the address. However, the datastream wraps to the begin of the current 4K block when address+length crosses a 4K boundary (1000h bytes). Special case: SanDisk ROMs are forcefully 200h-byte aligned, and can merely read max 200h bytes (padded with unencrypted FFh bytes when trying to read more data).
The command can be used only for addresses 8000h and up. Addresses 0..7FFFh are silently redirected to address "8000h+(addr AND 1FFh)". DSi cartridges will also reject XX00000h..XX06FFFh in the same fashion (and also XX07000h and up if the DSi cartridge isn't unlocked via command 3Dh).
Addresses that do exceed the ROM size do mirror to the valid address range (that includes mirroring non-loadable regions like 0..7FFFh to "8000h+(addr AND 1FFh)"; some newer games are using this behaviour for some kind of anti-piracy checks).

B800000000000000h (4) - 3rd Get ROM Chip ID
KEY2 encrypted command. Returns KEY2 encrypted Chip ID repeated every 4 bytes.

xxxxxxxxxxxxxxxxh - Invalid Command
Any other command (anything else than above B7h and B8h) in KEY2 command mode causes communcation failures. The invalid command returns an endless KEY2 encrypted stream of 00h bytes. After the invalid command, the KEY2 stream is NOT advanced for further command bytes, further commands seems to return KEY2 encrypted 00h bytes, of which, the first returned byte appears to be HIGH-Z.
Ie. the cartridge seems to have switched back to a state similar to the KEY1-phase, although it doesn't seem to be possible to send KEY1 commands.

 ___________________________________ Notes ___________________________________

KEY1 Command Encryption / 910h Dummy Bytes
All KEY1 encrypted commands are followed by 910h dummy byte transfers, these 910h clock cycles are probably used to decrypt the command at the cartridge side; communication will fail when transferring less than 910h bytes.
The return values for the dummy transfer are: A single HIGH-Z byte, followed by 90Fh KEY2-encrypted 00h bytes. The KEY2 encryption stream is advanced for all 910h bytes, including for the HIGH-Z byte.
Note: Current cartridges are using 910h bytes, however, other carts might use other amounts of dummy bytes, the 910h value can be calculated based on ROM Control entries in cartridge header. For the KEY1 formulas, see:
DS Encryption by Gamecode/Idcode (KEY1)

KEY2 Command/Data Encryption
DS Encryption by Random Seed (KEY2)

Cart Protocol Variants (Chip ID.Bit31)
There are two protocol variants for NDS carts, indicated by Bit31 of the ROM Chip ID (aka bit7 of the 4th ID byte):
  1) Chip ID.Bit31=0  Used by older/smaller carts with up to 64MB ROM
  2) Chip ID.Bit31=1  Used by newer/bigger carts with 64MB or more ROM
The first variant (for older carts) is described above. The second second variant includes some differences for KEY1 encrypted commands:
GAPS: The commands have the same 910h-cycle gaps, but without outputting CLK pulses during those gaps (ie. used with ROMCTRL.Bit28=0) (the absence of the CLKs implies that there is no dummy data transferred during gaps, and accordingly, that the KEY2 stream isn't advanced during the 910h gap cycles).
REPEATED COMMANDS and SECURE AREA DELAY: All KEY1 encrypted commands must be sent TWICE (or even NINE times). First, send the command with 0-byte Data transfer length. Second, issue the Secure Area Delay (required; use the delay specified in cart header[06Eh]).
Third, send the command once again with 0-byte or 4-byte data transfer length (usually 0 bytes, or 4-bytes for Chip ID command), or sent it eight times with 200h-byte data transfer length (for the 1000h-byte secure area load command).
For those repeats, always resend exactly the same command (namely, kkkkk is NOT incremented during repeats, and there is no extra index needed to select 200h-byte portions within 1000h-byte blocks; the cartridge is automatically outputting the eight portions one after another).


DS Cartridge Backup

SPI Bus Backup Memory
  Type   Total Size  Page Size  Chip/Example      Game/Example
  EEPROM 0.5K bytes   16 bytes  ST M95040-W       (eg. Metroid Demo)
  EEPROM   8K bytes   32 bytes  ST M95640-W       (eg. Super Mario DS)
  EEPROM  64K bytes  128 bytes  ST M95512-W       (eg. Downhill Jam)
  EEPROM 128K bytes    ? bytes  ?                 (eg. Explorers of Sky)
  FLASH  256K bytes  256 bytes  ST M45PE20        (eg. Skateland)
  FLASH  256K bytes             Sanyo LE25FW203T  (eg. Mariokart)
  FLASH  512K bytes  256 bytes  ST M25PE40?       (eg. which/any games?)
  FLASH  512K bytes             ST 45PE40V6       (eg. DS Zelda, NTR-AZEP-0)
  FLASH 1024K bytes             ST 45PE80V6       (eg. Spirit Tracks, NTR-BKIP)
  FLASH 8192K bytes             MX25L6445EZNI-10G (Art Academy only, TWL-VAAV)
  FRAM     8K bytes   No limit  ?                 (eg. which/any games?)
  FRAM    32K bytes   No limit  Ramtron FM25L256? (eg. which/any games?)

Lifetime Stats (might vary per manufacturer)
  Type      Max Writes per Page    Data Retention
  EEPROM    100,000                40 years
  FLASH     100,000                20 years
  FRAM      No limit               10 years

SPI Bus Backup Memory is accessed via Ports 40001A0h and 40001A2h, see
DS Cartridge I/O Ports

Commands
For all EEPROM and FRAM types:
  06h WREN  Write Enable                Cmd, no parameters
  04h WRDI  Write Disable               Cmd, no parameters
  05h RDSR  Read Status Register        Cmd, read repeated status value(s)
  01h WRSR  Write Status Register       Cmd, write one-byte value
  9Fh RDID  Read JEDEC ID (not supported on EEPROM/FLASH, returns FFh-bytes)
For 0.5K EEPROM (8+1bit Address):
  03h RDLO  Read from Memory 000h-0FFh  Cmd, addr lsb, read byte(s)
  0Bh RDHI  Read from Memory 100h-1FFh  Cmd, addr lsb, read byte(s)
  02h WRLO  Write to Memory 000h-0FFh   Cmd, addr lsb, write 1..MAX byte(s)
  0Ah WRHI  Write to Memory 100h-1FFh   Cmd, addr lsb, write 1..MAX byte(s)
For 8K..64K EEPROM and for FRAM (16bit Address):
  03h RD    Read from Memory            Cmd, addr msb,lsb, read byte(s)
  02h WR    Write to Memory             Cmd, addr msb,lsb, write 1..MAX byte(s)
For 128K EEPROM (24bit Address):
  As above, but with 24bit addr msb,mid,lsb ?
Note: MAX = Page Size (see above chip list) (no limit for FRAM).

For FLASH backup, commands should be same as for Firmware FLASH memory:
DS Firmware Serial Flash Memory
A few NDS/DSi carts are sharing the SPI bus for FLASH and Infrared, this requires a 00h-prefix byte for FLASH access, with slower 1MHz SPI clock and delays, see:
DS Cart Infrared/Pedometers

Status Register
  0   WIP  Write in Progress (1=Busy) (Read only) (always 0 for FRAM chips)
  1   WEL  Write Enable Latch (1=Enable) (Read only, except by WREN,WRDI)
  2-3 WP   Write Protect (0=None, 1=Upper quarter, 2=Upper Half, 3=All memory)
For 0.5K EEPROM:
  4-7 ONEs Not used (all four bits are always set to "1" each)
For 8K..64K EEPROM and for FRAM:
  4-6 ZERO Not used (all three bits are always set to "0" each)
  7   SRWD Status Register Write Disable (0=Normal, 1=Lock) (Only if /W=LOW)
WEL gets reset on Power-up, WRDI, WRSR, WRITE/LO/HI, and on /W=LOW.
The WRSR command allows to change ONLY the two WP bits, and the SRWD bit (if any), these bits are non-volatile (remain intact during power-down), respectively, the WIP bit must be checked to sense WRSR completion.

Detection (by examining hardware responses)
The overall memory type and bus-width can be detected by RDSR/RDID commands:
  RDSR  RDID          Type         (bus-width)
  FFh,  FFh,FFh,FFh   None         (none)
  F0h,  FFh,FFh,FFh   EEPROM       (with 8+1bit address bus)
  00h,  FFh,FFh,FFh   EEPROM/FRAM  (with 16bit address bus)
  ?     ?,?,?         EEPROM       (with 24bit address bus)
  00h,  xxh,xxh,xxh   FLASH        (usually with 24bit address bus)
And, the RD commands can be used to detect the memory size/mirrors (though that won't work if the memory is empty).

Detection (in emulators)
Nintendo is using different functions for sending cmd+addr and data. The bus-width can be detected by counting the bytes transferred with same program counter after chip selection. One could also try to examine code/data in the ROM-image (but that may envolve self-decompressing code and other obstacles).
Special cases:
Over the Hedge does initially try to access 8Kbyte EEPROM, but does actually use 0.5Kbyte EEPROM (as workaround: re-detect the bus-width on each transfer).
Rune Factory - A Fantasy Harvest Moon seems to be also difficult to detect (as workaround: force 64Kbyte EEPROM on gamecode ARFx).
FLASH has same 24bit bus-width as 128Kbyte EEPROM, but isn't compatible on writing. EEPROM does use 02h=Write+Erase. FLASH does use 0Ah=Write+Erase (or D8h/DBh=Erase and 02h=Write separatly).

Pin-Outs for EEPROM and FRAM chips
  Pin Name Expl.
  1  /S    Chip Select
  2  Q     Data Out
  3  /W    Write-Protect (not used in NDS, wired to VCC)
  4  VSS   Ground
  5  D     Data In
  6  C     Clock
  7  /HOLD Transfer-pause (not used in NDS, wired to VCC)
  8  VCC   Supply 2.5 to 5.5V for M95xx0-W

FRAM (Ferroelectric Nonvolatile RAM) is fully backwards compatible with normal EEPROMs, but comes up with faster write/erase time (no delays), and with lower power consumption, and unlimited number of write/erase cycles. Unlike as for normal RAM, as far as I understand, the data remains intact without needing any battery.

Other special save memory
  DS Vision (NDS cart with microSD slot... and maybe ALSO with EEPROM?)
  NAND carts can store data in a read/write-able portion of the "ROM" chip
  Typing Adventure does have SPI FLASH (but not directly wired to SPI bus)

DSi Internal eMMC and External SD Card
DSi cartridges are usually (maybe always) having SD/MMC access disabled, so they must stick using EEPROM/FLASH chips inside of the cartridges (which is required for NDS compatibility anyways).
However, DSiware games (downloaded from DSi Shop) are allowed to save data on eMMC, using "private.sav" or "public.sav" files in their data folder. The size of that files is preset in cartridge header.


DS Cartridge NAND

SLC-NAND is used in at least three NDS/DSi games. The ROM Chip ID has bit3 in 4th byte set.
  ECh,7Fh,00h,88h NDS Samsung  128MB NAND (eg. Warioware D.I.Y., NTR-UORE)
  ECh,7Fh,01h,88h NDS Samsung  128MB NAND (eg. Jam with the Band, NTR-UXBP)
  ECh,7Fh,00h,E8h DSi Samsung  128MB NAND (eg. Face Training, TWL-USKV)
In the cart header, the 1st byte of the Gamecode is "U" (that "U" is also used for a few other carts with "uncommon" hardware), and header entries [094h,096h] indicate the end of the ROM region and start of RW region (in 128Kbyte units for NDS, or 512Kbyte units for DSi; exception: the oldest NAND title (japanese version of Jam with the Band) did have [094h,096h] set to all zeroes). The chips are all 128MByte (122MByte usable), with memory map as so:
  00000000h  ROM region (one large region)                                  (R)
  0xxx0000h  RW region (split into several 128KByte blocks)               (R/W)
  07A00000h  Reserved region                                                (R)
The RW space is 8MB for Jam with the Band, 16MB for WarioWare DIY, and 82MB in Face Training. Unknown if some of the cart memory is reserved for broken sector handling.

DS Cartridges with NAND memory
NAND memory contains both the game and save memory (normal NDS games contain separate ROM and SPI FLASH/EEPROM chips for that purposes). The advantage is that NAND allows more storage than the usual FLASH chips. Nintendo also claims SLC-NAND to be very fast, but that's only half true (it's much slower than MROM, but might be slightly faster than SPI FLASH).

Command Summary
For whatever reason, random access is slightly restricted: One must use command 8Bh/B2h to select ROM region or a 128KByte RW window before reading/writing the selected area. Writing is done in 2Kbyte units (4x200h bytes).
 In ROM access mode:
  9400000000000000h Len=200h  NAND Read ID
  B2aaaaaaaa000000h Len=0     NAND Select 128Kbyte RW access mode
  B300000000000000h Len=04h   Unknown (returns 00000000h)
  BB00000000000000h Len=200h  Unknown (returns 1X 04 09 20 04, plus zeroes)
 In RW access mode (on DSi carts, this works ONLY in DSi mode):
  81aaaaaaaa000000h Len=200h  NAND Write to Write Buffer (must be issued 4x)
  8200000000000000h Len=0     NAND Forward Write Buffer to NAND
  8400000000000000h Len=0     NAND Discard Write Buffer
  8500000000000000h Len=0     NAND Write Enable
  8600000000000000h Len=0     Unknown
  8700000000000000h Len=0     NAND Write Disable
  8B00000000000000h Len=0     NAND Select ROM access mode
 In either mode:
  0B00000000000000h Len=200h  Returns cart header[000h..1FFh]
  0C00000000000000h Len=200h  Returns corrupted cart header[1F8h..3F7h] ??
  58h..5Fh          Len=0     Unknown (looks same/similar as in 1T-ROM carts)
  60h..68h          Len=800h  Unknown (looks same/similar as in 1T-ROM carts)
  B000000000000000h Len=04h   Unknown (returns 01010101h)
  B500000000000000h Len=0     Unknown (looks same/similar as in SanDisk carts)
  B7aaaaaaaa000000h Len=200h  NAND Read from ROM or RW area
  B800000000000000h Len=04h   Read Chip ID
  D600000000000000h Len=04h   NAND Read Status
 Further command(s) spotted in Face Training disassembly:
  8800000000000000h Len=0     Unknown (is in disassembly, but fails on HW?)

81aaaaaaaa000000h - NAND Write to Write Buffer + Data[200h]
The command must be issued 4 times with the same address (seems to use the address from the first command), a full write is 800h bytes (4x200h), the chip won't respond to other commands until all 4 commands are sent. Unknown what happens when trying to send more than 4 commands.
This command doesn't directly write to NAND, instead it stores the incoming data in a 800h-byte write buffer (latter committed using command 82h).
The provided address needs to be within the access window specified by command B2h.

8200000000000000h - NAND Forward Write Buffer to NAND
The data in the 800h-byte write buffer is written to the actual NAND, and the write-enable bit in the status register is cleared.

8400000000000000h - NAND Discard Write Buffer
The data in the write buffer is discarded (a subsequent command 82h would have no effect).
Games seem to always use this after command 82h, so maybe it's required even after a write.

8500000000000000h - NAND Write Enable
The write-enable bit in the status register is set.
Only works in RW access mode.

8B00000000000000h - NAND Select ROM access mode
Switch to ROM access mode.

B2aaaaaaaa000000h - NAND Select 128Kbyte RW access mode
The provided address defines an accessible 128K window in RW address space, reads and writes may only take place within that window, the lower 17 bits of the address are ignored.
Addresses below start of RW area are ignored (the cart stays in ROM mode, and the cart does then reportedly get stuck permanently busy).
Addresses that go past the end of the RW address space will just read all FF's.

B7aaaaaaaa000000h - NAND Read from ROM or RW area + Data[200h]
This command is used for reading data under both ROM and RW modes.
In ROM mode: returns data from the ROM space, pretty much like the 'regular' B7 command, trying to read from RW space in this mode will return all FF's.
In RW mode: returns data from the RW space, the provided address needs to be within the access window specified by command B2h.

D600000000000000h - NAND Read Status + Data[4]
Status register bits:
  0-1   Unknown (usually zero)
  2-3   Unknown (usually zero, but tested by DSi Launcher, not NAND related?)
  4     NAND write enable
  5     NAND status (0=busy, 1=ready)
  6     Unknown (usually zero, but set by DeSmuME)
  7     Unknown (possible error flag?)
  8-15  Same as bit0-7
  16-23 Same as bit0-7
  24-31 Same as bit0-7
Value on startup is 20h (aka 20202020h when reading 4 bytes).

BB00000000000000h Len=200h Unknown (returns 1X 04 09 20 04, plus zeroes)
  Values in Jam with the Band (nocash dump): 17 04 09 20 04, plus 1FBh zeroes
  Values in Face Training (nocash dump):     10 04 09 20 04, plus 1FBh zeroes

9400000000000000h - NAND Read ID + Data[200h]
Returns NAND ID data of sorts.
 Values in Jam with the Band (arisotura dump):
  000h  EC F1 00 95 40 00 00 00 00 00 00 00 00 00 00 00  ....@...........
  010h  00 00 00 00 00 00 00 00 EC 00 9E A1 51 65 34 35  ............Qe45
  020h  30 35 30 31 19 19 02 0A 00 00 00 00 00 00 00 00  0501............
  030h  FF FF FF .. (1D0h bytes) (why not 00h's ???)     ................
 Values in Jam with the Band (nocash dump):
  000h  EC F1 00 95 40 00 00 00 00 00 00 00 00 00 00 00  ....@...........
  010h  00 00 00 00 00 00 00 00 EC 00 3B 5A 32 9B 32 30  ..........;Z2.20
  020h  35 35 30 30 19 19 02 0A 00 00 00 00 00 00 00 00  5500............
  030h  00 00 00 .. (1D0h bytes)                         ................
 Values in Face Training (nocash dump):
  000h  EC F1 00 95 40 00 00 00 00 00 00 00 00 00 00 00  ....@...........
  010h  00 00 00 00 00 00 00 00 EC 00 5A 36 5C 14 35 35  ..........Z6\.55
  020h  32 36 30 36 04 04 08 0A 00 00 00 00 00 00 00 00  2606............
  030h  00 00 00 .. (1D0h bytes)                         ................
For Jam with Band, the 16 bytes at 018h are also found in the last 800h bytes of the RW space (see below). The bytes with value ECh might be related to the Maker ID in Chip ID.

Last 128Kbyte in RW region (at 079E0000h..079FFFFFh)
The last 128Kbyte of RW area is normal write-able memory in Face Training without special content. However, in Jam with the Band, the last 128KByte are readonly, they can be read like normal RW blocks (select via command B2h, then read via B7h), but writing isn't supported (although NAND Status bit5 gets cleared for a moment upon write attempts to this 128Kbyte area; unlike as for when trying to write 7A00000h and up).
 Values in Jam with the Band (arisotura dump):
  079E0000h  FF FF FF .. (1F800h bytes)                      ................
  079FF800h  EC 00 9E A1 51 65 34 35 30 35 30 31 19 19 02 0A ....Qe450501....
  079FF810h  00 00 00 00 6D D6 DA 9B B0 24 22 88 79 3B BF EA ....m....$".y;..
  079FF820h  E6 AC 5E FA 69 12 0D 52 5D 5B F5 80 FF FF FF FF ..^.i..R][......
  079FF830h  FF FF FF .. (7D0h bytes)                        ................
 Values in Jam with the Band (nocash dump):
  079E0000h  FF FF FF .. (1F800h bytes)                      ................
  079FF800h  EC 00 3B 5A 32 9B 32 30 35 35 30 30 19 19 02 0A ..;Z2.205500....
  079FF810h  00 00 00 00 DD 58 84 07 F9 72 19 04 96 8C FF 67 .....X...r.....g
  079FF820h  7F 66 B9 E5 FD F7 3F 1A AE 60 60 00 FF FF FF FF .f....?..``.....
  079FF830h  FF FF FF .. (7D0h bytes)                        ................
Jam with the Band checks the bytes at 079FF800h (unknown what it does with them, or what it does when they are missing).

Reserved Area (at 07A00000h and up) (including 08000000h and up)
This memory isn't intended to be used, in Jam with the Band it just returns FFh's. However, in Face Training it does return some interesting internal data (in RW mode):
The DSi Blowfish key (with the gamecode pre-applied), some NDS ARM code (for the secure area or so), and most interestingly some more ARM+THUMB code (apparently containing the firmware running on an ARM CPU inside of the game cartridge itself).
Unfortunately, that internal memory is returned as "raw" data with faulty bits, and it seems to be required to apply error correction to convert it to actual intact data (the "raw" stuff consists of 1E8h-byte data snippets, usually followed by 8-byte ECC info, or sometimes 16-byte or 20-byte ECC, or no ECC at all). There are several "backup" copies of the blowfish/firmware blocks.

Write Example
  B2aaaaaaaa000000h - Select 128Kbyte RW access mode (unlesss already)
  8500000000000000h - NAND Write Enable
  81aaaaaaaa000000h - NAND Write to Write Buffer        + Data[200h]
  81aaaaaaaa000000h - NAND Write to Write Buffer        + Data[200h]
  81aaaaaaaa000000h - NAND Write to Write Buffer        + Data[200h]
  81aaaaaaaa000000h - NAND Write to Write Buffer        + Data[200h]
  8200000000000000h - NAND Forward Write Buffer to NAND
  D600000000000000h - NAND Read Status                  + Data[4]
  (...repeat reading status until bit5=1=ready...)
  8400000000000000h - NAND Discard SRAM write
  8B00000000000000h - NAND Select ROM access mode (if desired)

Chipsets
Warioware D.I.Y., NTR-UORE:
  PCB "DI X-7 C17-01"
  Chip "SAMSUNG 004, KLC2811ANB-P204, NTR-UORE-0"
Jam with the Band, NTR-UXBP:
  PCB (Unknown)
  Chip "SAMSUNG 013, KLC2811UOC-P30A, NTR-UXBP-0, WKA069J2"
Face Training, TWL-USKV:
  PCB "DI X-8 C17-01"
  U1 "SAMSUNG 031, KLC2811UOC-P309, TWL-USKV-0, WKE114(80?)"
  (this chip must be slightly different, for DSi mode support)
There are also a bunch of 3DS games with similar chips (with the RW area being called "CARD2" area on 3DS, and, the 3DS is using 16-byte commands, so the protocol is different).

Notes
Unlike ROM carts, the NAND cart does crash upon invalid commands (and stops to respond to further commands). That is, upon invalid command numbers, upon ROM mode commands in RW mode (or vice-versa), upon any data lengths other than listed above.


DS Cartridge I/O Ports

The Gamecard bus registers can be mapped to NDS7 or NDS9 via EXMEMCNT, see
DS Memory Control

40001A0h - NDS7/NDS9 - AUXSPICNT - Gamecard ROM and SPI Control (R/W)
  0-1   SPI Baudrate        (0=4MHz/Default, 1=2MHz, 2=1MHz, 3=512KHz)
  2-5   Not used            (always zero)
  6     SPI Hold Chipselect (0=Deselect after transfer, 1=Keep selected)
  7     SPI Busy            (0=Ready, 1=Busy) (presumably Read-only)
  8-12  Not used            (always zero)
  13    NDS Slot Mode       (0=Parallel/ROM, 1=Serial/SPI-Backup)
  14    Transfer Ready IRQ  (0=Disable, 1=Enable) (for ROM, not for AUXSPI)
  15    NDS Slot Enable     (0=Disable, 1=Enable) (for both ROM and AUXSPI)
The "Hold" flag should be cleared BEFORE transferring the LAST data unit, the chipselect will be then automatically cleared after the transfer, the program should issue a WaitByLoop(12) on NDS7 (or longer on NDS9) manually AFTER the LAST transfer.

40001A2h - NDS7/NDS9 - AUXSPIDATA - Gamecard SPI Bus Data/Strobe (R/W)
The SPI transfer is started on writing to this register, so one must <write> a dummy value (should be zero) even when intending to <read> from SPI bus.
  0-7  Data
  8-15 Not used (always zero)
During transfer, the Busy flag in AUXSPICNT is set, and the written DATA value is transferred to the device (via output line), simultaneously data is received (via input line). Upon transfer completion, the Busy flag goes off, and the received value can be then read from AUXSPIDATA, if desired.

40001A4h - NDS7/NDS9 - ROMCTRL - Gamecard Bus ROMCTRL (R/W)
  0-12  KEY1 gap1 length  (0-1FFFh) (forced min 08F8h by BIOS) (leading gap)
  13    KEY2 encrypt data (0=Disable, 1=Enable KEY2 Encryption for Data)
  14     "SE" Unknown? (usually same as Bit13) (does NOT affect timing?)
  15    KEY2 Apply Seed   (0=No change, 1=Apply Encryption Seed) (Write only)
  16-21 KEY1 gap2 length  (0-3Fh)   (forced min 18h by BIOS) (200h-byte gap)
  22    KEY2 encrypt cmd  (0=Disable, 1=Enable KEY2 Encryption for Commands)
  23    Data-Word Status  (0=Busy, 1=Ready/DRQ) (Read-only)
  24-26 Data Block size   (0=None, 1..6=100h SHL (1..6) bytes, 7=4 bytes)
  27    Transfer CLK rate (0=6.7MHz=33.51MHz/5, 1=4.2MHz=33.51MHz/8)
  28    KEY1 Gap CLKs (0=Hold CLK High during gaps, 1=Output Dummy CLK Pulses)
  29    RESB Release Reset  (0=Reset, 1=Release) (cannot be cleared once set)
  30    Data Direction "WR" (0=Normal/read, 1=Write, for FLASH/NAND carts)
  31    Block Start/Status  (0=Ready, 1=Start/Busy) (IRQ See 40001A0h/Bit14)
The cartridge header is booted at 4.2MHz CLK rate, and following transfers are then using ROMCTRL settings specified in cartridge header entries [060h] and [064h], which are usually using 6.7MHz CLK rate for the main data transfer phase (whereof, older MROM carts can actually transfer 6.7Mbyte/s, but newer 1T-ROM carts default to reading 200h-byte blocks with gap1=657h, thus reaching only 1.6Mbyte/s).
Transfer length of null, four, and 200h..4000h bytes are supported by the console, however, retail cartridges cannot cross 1000h-byte boundaries (and, SanDisk ROM chips and Samsung NAND chips cannot transfer more than 200h bytes).
Default cart header entries
  hdr[60h]   hdr[64h]   hdr[6Eh]
  00586000h  001808F8h  051Eh     ;older/faster MROM
  00416657h  081808F8h  0D7Eh     ;newer/slower 1T-ROM
  00416657h  081808F8h  0D7Eh     ;newer/slower NAND
Older/Faster MROM
The romctrl values in cartheader[60h,64h] are okay, but the secure delay in [6Eh] is nonsense (should be zero).
Misdeclared MROM
Some carts like SystemFlaw and BiggestLoser are actually containing MROM chips despite of having 1T-ROM values in cart header (gap1=657h is making loading insane slow, gap2=01h causes errors on 1000h-byte blocks, and secure.clk=4.2MHz is slowing down secure area loading, combined with even slower secure area delay despite of not needing any delay for MROM).
As the cart header entries are wrong, some other detection is needed: This can be probably done by checking ChipID.bit31 (or otherwise by testing if 1000h-block reading works with gap1=01h, if so, then it's 1T-ROM).
Newer/Slower 1T-ROM
Actual 1T-ROM carts can be very slow, especially when using the insane cart header values and default firmware blocksize of 200h bytes which drops loading speed from 6.7Mbytes/s to 1.6Mbyte/s (as workaround, use gap1=180h, blocksize=1000h, also secure area delay should be 400h, not D7Eh) (tested/working for CookingCoach, unknown if that timings work for all other carts).
Superslow Writeable NAND
This is having the same official insane delays as 1T-ROM, but with less tolerance for faster timings (fastest working values are gap1=380h, blocksize=200h, secure delay 400h, plus 20ms delay after releasing reset).
Cart Reset
Reset flag in bit29 can be set once only (to release reset), the only way to clear the bit is power-off. However, there are some ways to issue resets:
1) On NDS: Manually eject/insert the cart (that won't affect bit29, but the cart will reset itself anyways upon power loss) (eject on DSi will power-off the cart slot).
2) If one of the two ROMCTRL registers (on ARM7 and ARM9) is still zero: Temporarily toggle ARM7/ARM9 cart access via EXMEMCNT on ARM9 side.
3) On DSi: If the 2nd cart slot ROMCTRL register (40021A4h) is still zero: Temporarily swap 1ns/2nd cart slot via SCFG_MC.bit15 on ARM7 side.
4) On DSi: Use SCFG_MC to toggle cart power off/on; this will actually reset bit29, the DSi firmware is actually using that method, but it's very slow (takes about 300ms, for the power-off wait, plus (unneccassary) hardcoded power-on delays).

40001A8h - NDS7/NDS9 - Gamecard bus 8-byte Command Out
The separate commands are described in the Cartridge Protocol chapter, however, once when the BIOS boot procedure has completed, one would usually only need command "B7aaaaaaaa000000h", for reading data (usually 200h bytes) from address aaaaaaaah (which should be usually aligned by 200h).
  0-7   1st Command Byte (at 40001A8h) (eg. B7h) (MSB)
  8-15  2nd Command Byte (at 40001A9h) (eg. addr bit 24-31)
  16-23 3rd Command Byte (at 40001AAh) (eg. addr bit 16-23)
  24-31 4th Command Byte (at 40001ABh) (eg. addr bit 8-15) (when aligned=even)
  32-39 5th Command Byte (at 40001ACh) (eg. addr bit 0-7)  (when aligned=00h)
  40-47 6th Command Byte (at 40001ADh) (eg. 00h)
  48-57 7th Command Byte (at 40001AEh) (eg. 00h)
  56-63 8th Command Byte (at 40001AFh) (eg. 00h) (LSB)
Observe that the command/parameter MSB is located at the smallest memory location (40001A8h), ie. compared with the CPU, the byte-order is reversed.

4100010h - NDS7/NDS9 - Gamecard bus 4-byte Data In (R) (or W)
  0-7   1st received Data Byte (at 4100010h)
  8-15  2nd received Data Byte (at 4100011h)
  16-23 3rd received Data Byte (at 4100012h)
  24-31 4th received Data Byte (at 4100013h)
After sending a command, data can be read from this register manually (when the DRQ bit is set), or by DMA (with DMASAD=4100010h, Fixed Source Address, Length=1, Size=32bit, Repeat=On, Mode=DS Gamecard).

40001B0h - 32bit - NDS7/NDS9 - Encryption Seed 0 Lower 32bit (W)
40001B4h - 32bit - NDS7/NDS9 - Encryption Seed 1 Lower 32bit (W)
40001B8h - 16bit - NDS7/NDS9 - Encryption Seed 0 Upper 7bit (bit7-15 unused)
40001BAh - 16bit - NDS7/NDS9 - Encryption Seed 1 Upper 7bit (bit7-15 unused)
These registers are used by the NDS7 BIOS to initialize KEY2 encryption (and there's normally no need to change that initial settings). Writes to the Seed registers do not have direct effect on the internal encryption registers, until the Seed gets applied by writing "1" to ROMCTRL.Bit15.
 For more info:
DS Encryption by Random Seed (KEY2)
Note: There are <separate> Seed registers for both NDS7 and NDS9, which can be applied by ROMCTRL on NDS7 and NDS9 respectively (however, once when applied to the internal registers, the new internal setting is used for <both> CPUs).


DS Cartridge NitroROM and NitroARC File Systems

The DS hardware, BIOS, and Firmware do NOT contain any built-in filesystem functions. The ARM9/ARM7 boot code (together max 3903KB), and Icon/Title information are automatically loaded on power-up.
Programs that require to load additional data from cartridge ROM may do that either by implementing whatever functions to translate filenames to ROM addresses, or by reading from ROM directly.

NitroROM
The NitroROM Filesystem is used by many NDS games (at least those that have been developed with Nintendo's tools). It's used for ROM Cartridges, and, on the DSi, it's also used for DSiWare games (in the latter case, NitroROM acts as a 2nd virtual filesystem inside of the DSi's FAT16 filesystem).
  FNT = cart_hdr[040h]     ;\origin as defined in ROM cartridge header
  FAT = cart_hdr[048h]     ;/
  IMG = 00000000h          ;-origin at begin of ROM
Aside from using filenames, NitroROM files can be alternately accessed via Overlay IDs (see later on below).

NitroARC (Nitro Archive)
NARC Files are often found inside of NitroROM Filesystems (ie. NARC is a second virtual filesystem, nested inside of the actual filesystem). The NARC Format is very similar to the NitroROM Format, but with additional Chunk Headers (instead of the Cartridge ROM Header).
  ...  ...  Optional Header (eg. compression header, or RSA signature)
  000h 4    Chunk Name "NARC" (Nitro Archive)                   ;\
  004h 2    Byte Order (FFFEh) (unlike usually, not FEFFh)      ;
  006h 2    Version (0100h)                                     ; NARC
  008h 4    File Size (from "NARC" ID to end of file)           ; Header
  00Ch 2    Chunk Size (0010h)                                  ;
  00Eh 2    Number of following chunks (0003h)                  ;/
  010h 4    Chunk Name "BTAF" (File Allocation Table Block)     ;\
  014h 4    Chunk Size (including above chunk name)             ; File
  018h 2    Number of Files                                     ; Allocation
  01Ah 2    Reserved (0000h)                                    ; Table
  01Ch ...  FAT (see below)                                     ;/
  ...  4    Chunk Name "BTNF" (File Name Table Block)           ;\
  ...  4    Chunk Size (including above chunk name)             ; File Name
  ...  ...  FNT (see below)                                     ; Table
  ...  ..   Padding for 4-byte alignment (FFh-filled, if any)   ;/
  ...  4    Chunk Name "GMIF" (File Image Block)                ;\
  ...  4    Chunk Size (including above chunk name)             ; File Data
  ...  ...  IMG (File Data)                                     ;/

NARCless variant
There are a few NARC archives with crippled header, without "NARC" string (eg. rom:\dwc\utility.bin in Over the Hedge, Downhill Jam, and Tony Hawk's Skateland).
  000h 4   FNT Filename Table Offset (always at 10h)
  004h 4   FNT Filename Table Size
  008h 4   FAT Allocaton Table Offset (at above Offset+Size+Padding)
  00Ch 4   FAT Allocaton Table Size
  010h ..  FNT Filename Table Data
  ...  ..  FAT Allocaton Table Data
  ...  ..  IMG File Data
The offsets in FAT are relative to IMG=0 (as if IMG would start at begin of file).

File Allocation Table (FAT) (base/size defined in cart header)
Contains ROM addresses for up to 61440 files (File IDs 0000h and up).
  Addr Size Expl.
  00h  4    Start address (originated at IMG base) (0=Unused Entry)
  04h  4    End address   (Start+Len)              (0=Unused Entry)
For NitroROM, addresses must be after Secure Area (at 8000h and up).
For NitroARC, addresses can be anywhere in the IMG area (at 0 and up).
Directories are fully defined in FNT area, and do not require FAT entries.

File Name Table (FNT) (base/size defined in cart header)
Consists of the FNT Directory Table, followed by one or more FNT Sub-Tables.
To interprete the directory tree: Start at the 1st Main-Table entry, which is referencing to a Sub-Table, any directories in the Sub-Table are referencing to Main-Table entries, which are referencing to further Sub-Tables, and so on.

FNT Directory Main-Table (base=FNT+0, size=[FNT+06h]*8)
Consists of a list of up to 4096 directories (Directory IDs F000h and up).
  Addr Size Expl.
  00h  4    Offset to Sub-table             (originated at FNT base)
  04h  2    ID of first file in Sub-table   (0000h..EFFFh)
For first entry (ID F000h, root directory):
  06h  2    Total Number of directories     (1..4096)
Further entries (ID F001h..FFFFh, sub-directories):
  06h  2    ID of parent directory (F000h..FFFEh)

FNT Sub-tables (base=FNT+offset, ends at Type/Length=00h)
Contains ASCII names for all files and sub-directories within a directory.
  Addr Size Expl.
  00h  1    Type/Length
              01h..7Fh File Entry          (Length=1..127, without ID field)
              81h..FFh Sub-Directory Entry (Length=1..127, plus ID field)
              00h      End of Sub-Table
              80h      Reserved
  01h  LEN  File or Sub-Directory Name, case-sensitive, without any ending
              zero, ASCII 20h..7Eh, except for characters \/?"<>*:;|
Below for Sub-Directory Entries only:
  LEN+1 2    Sub-Directory ID (F001h..FFFFh) ;see FNT+(ID AND FFFh)*8
File Entries do not have above ID field. Instead, File IDs are assigned in incrementing order (starting at the "First ID" value specified in the Directory Table).

ARM9 and ARM7 Overlay Tables (OVT) (base/size defined in cart header)
Somehow related to Nintendo's compiler, allows to assign compiler Overlay IDs to filesystem File IDs, and to define additional information such like load addresses.
  Addr Size Expl.
  00h  4    Overlay ID
  04h  4    RAM Address ;Point at which to load
  08h  4    RAM Size    ;Amount to load
  0Ch  4    BSS Size    ;Size of BSS data region
  10h  4    Static initialiser start address
  14h  4    Static initialiser end address
  18h  4    File ID  (0000h..EFFFh)
  1Ch  4    Reserved (zero)

Cartridge Header
The base/size of FAT, FNT, OVT areas is defined in cartridge header,
DS Cartridge Header


DS Cartridge Unknown Commands

The Main Data transfer mode is normally using only two commands (B7h/B8h), however most cartridges do support one or more undocumented commands (as opposed to invalid commands, which will cause the cart to stop responding).
  Title                    Chip ID   Commands...
  Metroid First Hunt       00000FC2  B7 B8 D8
  Meine Tierarztpraxis     00000FAE  B7 B8 D8
  Meine Tierpension        00000FC2  B7 B8 D8
  Nanostray                00000FC2  B7 B8 D8
  Over the Hedge           00001FC2  B7 B8 D8
  Tony Hawk's Skateland    00003FC2  B7 B8
  Tony Hawk's Downhill Jam 00003FC2  B7 B8
  Ultimate Spiderman       00003FC2  B7 B8
  System Flaw (DSi)        40001FC2  B7 B8 F1
  Biggest Loser (DSi)      40001FC2  B7 B8 F1
  Cooking Coach (DSi)      C0007FC2  58..5F 60..68 B7 B8
  Walk with Me             E0013F80  69..6C B5 B7 B8 D6
  Face Training (DSI NAND) E8007FEC  0x 5x 6x 8x 94 Bx D6 (see NAND chapter)
The presence of those commands was tested on DSi (where one can reset the cart by software to recover from invalid commands), with all parameter bits set to zero.
That testing is more difficult on NAND carts because the commands do only work when transferring the correct number of data bytes (0, 4, 200h, or 800h bytes), and only when being in the correct mode (ROM or RW mode; whereof, on DSi carts, the RW mode works ONLY in DSi mode).

 ______________________________ Command 58h..68h ______________________________

5800000000000000h-5F00000000000000h (..) - Get HighZ
Unknown purpose, returns HighZ.

6000000000000000h-6800000000000000h (..) - Get Zeroes
Unknown purpose, returns at least 4000h encrypted 00h bytes.

 ______________________________ Command 69h..6Ch ______________________________

6900000000000000h-6C00000000000000h (..) - Get Zeroes
Unknown purpose, returns at least 4000h encrypted 00h bytes.

 ______________________________ Command B5h/D6h _______________________________

B500000000000000h (0) - Start/Stop/Reset/Ack something?
Unknown. Returns only HighZ.

D600000000000000h (4) - Get Status Byte (also used on NAND carts)
Returns a status byte (repeated in first four bytes, then followed by HighZ bytes).

Command B5h/D6h are supported in carts that have bit5 set in 4th byte of Chip ID (eg. in Walk with Me). Command D6h (and maybe also B5h) works both on power up (before secure area), and in main data phase (after secure area). The DSi Launcher contains following code to deal with such carts:
 if chip_id AND 20000000h
   get_nand_status(cmd_D6h)
   if (nand_status AND 0Ch)<>0                    ;whatever bits
     whatever(cmd_B5h)                            ;whatever command
    loop:
     get_nand_status(cmd_D6h)
     if (nand_status AND 20h)=0 then goto loop    ;wait for ready flag

 ________________________________ Command D8h _________________________________

D800000000000000h (..) - Get Zeroes
Unknown purpose, returns at least 4000h encrypted 00h bytes.

 ________________________________ Command F1h _________________________________

F100000000000000h (1000h) - Get Serial/Manufacturer Info or so
Returns 1000h bytes of data (repeated each 1000h bytes), the data is mostly FFh-filled, with some kind of Serial Number or Manufacturer Info at offset E00h. Unknown what those values are good for, and if they contain unique IDs.
This command works in main data phase only (returns only FFh/HighZ on power up before secure area loading).
System Flaw cmd F1 response:
  0000..0DFF  FF-filled
  0E00        1E 40 05 5A FF FF 0D 01  32 68 38 7A 23 3F FF FF
  0E10        03 0B 00 00 03 09 FF FF  FF FF FF FF FF FF FF FF
  0E20        1E 40 05 03 0B 00 00 03  09 00 00 FF FF FF FF FF
  0E30        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E40        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E50        FF FF FF FF FF 5A FF 5E  FF FF FF FF FF FF 5A FF
  0E60        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E70        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E80..0FFF  FF-filled
  1000..3FFF  mirrors of 0000-0FFF
Biggest Loser cmd F1 response:
  0000..0DFF  FF-filled
  0E00        11 16 08 5A FF FF 0D 0B  39 7C 40 8E 2A 53 FF FF
  0E10        03 0A 07 05 05 04 00 00  07 00 7F FF 00 FF FF FF
  0E20        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E30        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E40        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E50        FF FF FF FF FF 5A FF 5E  FF FF FF FF FF FF 5A FF
  0E60        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E70        FF FF FF FF FF FF FF FF  FF FF FF FF FF FF FF FF
  0E80..0FFF  FF-filled
  1000..3FFF  mirrors of 0000-0FFF


DS Cartridge PassMe/PassThrough

PassMe is an adapter connected between the DS and an original NDS cartridge, used to boot unencrypted code from a flash cartridge in the GBA slot, it replaces the following entries in the original NDS cartridge header:
  Addr  Siz Patch
  004h  4   E59FF018h  ;opcode LDR PC,[027FFE24h] at 27FFE04h
  01Fh  1   04h        ;set autostart bit
  022h  1   01h        ;set ARM9 rom offset to nn01nnnnh (above secure area)
  024h  4   027FFE04h  ;patch ARM9 entry address to endless loop
  034h  4   080000C0h  ;patch ARM7 entry address in GBA slot
  15Eh  2   nnnnh      ;adjust header crc16
After having verified the encrypted chip IDs (from the original cartridge), the console thinks that it has successfully loaded a NDS cartridge, and then jumps to the (patched) entrypoints.

GBA Flashcard Format
Although the original PassMe requires only the entrypoint, PassMe programs should additionally contain one (or both) of the ID values below, allowing firmware patches to identify & start PassMe games without real PassMe hardware.
  0A0h  GBA-style Title    ("DSBooter")
  0ACh  GBA-style Gamecode ("PASS")
  0C0h  ARM7 Entrypoint    (32bit ARM code)
Of course, that applies only to early homebrew programs, newer games should use normal NDS cartridge headers.

ARM9 Entrypoint
The GBA-slot access rights in the EXMEMCNT register are initially assigned to the ARM7 CPU, so the ARM9 cannot boot from the flashcard, instead it is switched into an endless loop in Main RAM (which contains a copy of the cartridge header at 27FFE00h and up). The ARM7 must thus copy ARM9 code to Main RAM, and then set the ARM9 entry address by writing to [027FFE24h].


DS Cartridge GBA Slot

Aside from the 17-pin NDS slot, the DS also includes a 32-pin GBA slot. This slot is used for GBA backwards compatibility mode. Additionally, in DS mode, it can be as expansion port, or for importing data from GBA games.
  NDS:     Normal 32pin slot
  DS Lite: Short 32pin slot (GBA cards stick out)
  DSi:     N/A (dropped support for GBA carts, and for DS-expansions)
In DS mode, ROM, SRAM, FLASH backup, and whatever peripherals contained in older GBA cartridges can be accessed (almost) identically as in GBA mode,
GBA Cartridges

Addressing
In DS mode, only one ROM-region is present at 8000000h-9FFFFFFh (ie. without the GBA's mirrored WS1 and WS2 regions at A000000h-DFFFFFFh). The expansion region (for SRAM/FLASH/etc) has been moved from E000000h-E00FFFFh (GBA-mode) to A000000h-A00FFFFh (DS-mode).

Timings
GBA timings are specified as "waitstates" (excluding 1 access cycle), NDS timings are specified as (total) "access time". And, the NDS bus-clock is twice as fast as for GBA. So, for "N" GBA waitstates, the NDS access time should be "(N+1)*2". Timings are controlled via NDS EXMEMCNT instead GBA WAITCNT,
DS Memory Control - Cartridges and Main RAM

GBA EEPROM Timings
EEPROMs in GBA carts can be accessed via DMA in DS mode, although the timings are a bit too fast. The access time should be 18 clks for 1st/2nd access, but the NDS supports only 4 or 6 clks for 2nd access; of which, 6 clks seems to work stable (and 4 clks doesn't work, it seems to ignore writes and returns garnage on reading).


DS Cart Rumble Pak

DS Rumble Option Pak
The Rumble Pak comes bundled with Metroid Prime Pinball. It contains a small actuator made by ALPS to make it rumble. The original device (NTR-008) is sized like a normal GBA cartridge, and there's also shorter variant for the DS-Lite (USG-006).
The rumble pak is pretty simple internally, it only wires up to a few pins on the GBA Cartridge Port:
  VCC, GND, /WR, AD1, and IRQ (grounded)
AD1 runs into a little 8 pin chip, which is probably just a latch on the rising edge of /WR. A line runs from this chip to a transistor that is directly connected to the actuator. The only other chip on the board is a 5 pin jobber, probably a power component.
For detection, AD1 seems to be pulled low when reading from it, the other AD lines are open bus (containing the halfword address), so one can do:
  for i=0 to 0FFFh
    if halfword[8000000h+i*2]<>(i and FFFDh) then <not_a_ds_rumble_pak>
  next i
The actuator doesn't have an on/off setting like a motor, it rumbles when you switch it between the two settings. Switch frequently for a fast rumble, and fairly slowly for more of a 'tick' effect. That should be done via timer irq:
  rumble_state = rumble_state xor 0002h
  halfword[8000000h]=rumble_state
Unknown if one of the two states has higher power-consumption than the other, ie. if it's a "pull/release" mechanism, if so, then disabling rumble should be done by using the "release" state, which would be AD1=0, or AD1=1...?
Note: The v3 firmware can detect the Rumble Pak as an option pak, but it does not provide an enable/disable rumble option in the alarm menu.

Other DS Rumble device
There's also another DS add-on with rumble. That device uses AD8 (instead AD1) to control rumble, and, it's using a classic motor (ie. it's rumbling while and as long as the latched AD8 value is "1").
DS Cart Slider with Rumble

GBA Rumble Carts
There are also a few GBA games that contain built-in Rumble, and which could be used by NDS games as well. To be user friendly, best support both types.
GBA Cart Rumble


DS Cart Slider with Rumble

Add-on device for the japanese title Magukiddo. The optical sensor is attached underneath of the console (connected to the GBA slot).
The sensor is an Agilent ADNS-2030 Low Power Optical Mouse Sensor (16pin DIP chip with built-in optical sensor, and external LED light source) with two-wire serial bus (CLK and DTA).

ADNS-2030 Registers (write 1 byte index, then read/write 1 byte data)
Index (Bit7=Direction; 0=Read, 1=Write):
  00h Product_ID (R) (03h)
  01h Revision_ID (R) (10h=Rev. 1.0) (20h=Used in DS-option-pak)
  02h Motion/Status Flags (R)
  03h Delta_X (R) (signed 8bit) (automatically reset to 00h after reading)
  04h Delta_Y (R) (signed 8bit) (automatically reset to 00h after reading)
  05h SQUAL (R) (surface quality) (unsigned 8bit)
  06h Average_Pixel (R) (unsigned 6bit, upper 2bit unused)
  07h Maximum_Pixel (R) (unsigned 6bit, upper 2bit unused)
  08h Reserved
  09h Reserved
  0Ah Configuration_bits (R/W)
  0Bh Reserved
  0Ch Data_Out_Lower (R)
  0Dh Data_Out_Upper (R)
  0Eh Shutter_Lower (R)
  0Fh Shutter_Upper (R)
  10h Frame_Period_Lower (R/W)
  11h Frame_Period_Upper (R/W)
Motion/Status Flags:
  7 Motion since last report or PD (0=None, 1=Motion occurred)
  6 Reserved
  5 LED Fault detected (0=No fault,  1=Fault detected)
  4 Delta Y Overflow (0=No overflow, 1=Overflow occured)
  3 Delta X Overflow (0=No overflow, 1=Overflow occured)
  2 Reserved
  1 Reserved
  0 Resolution in counts per inch (0=400, 1=800)
Configuration_bits:
  7 Reset Power up defaults (W) (0=No, 1=Reset)
  6 LED Shutter Mode (0=LED always on, 1=LED only on when shutter is open)
  5 Self Test (W) (0=No, 1=Perform all self tests)
  4 Resolution in counts per inch (0=400, 1=800)
  3 Dump 16x16 Pixel bitmap (0=No, 1=Dump via Data_Out ports)
  2 Reserved
  1 Reserved
  0 Sleep Mode (0=Normal/Sleep after 1 second, 1=Always awake)
                          _______
                         |74273  |
  /WR -----------------> |CLK    |                       _____
  AD1/SIO CLK ---------> |D1   Q1|--------------> CLK   |74125|
  AD2 power control ---> |D2   Q2|--->     ____         |     |
  AD3/SIO DIR ---------> |D3   Q3|------o-|7400\________|/EN  |
  AD8 rumble on/off ---> |D?   Q?|--->  '-|____/        |     |
  AD0/SIO DTA ----o----> |D5   Q5|----------------------|A   Y|--o--DTA
                  |      |_______|                      |- - -|  |
          ____    '-------------------------------------|Y   A|--'
  /RD ---|7400\______ ____                              |     |
  /RD ---|____/      |7400\_____________________________|/EN  |
  A19 _______________|____/                             |_____|

7400 Quad NAND Gate, 74273 8bit Latch

AD0 Optical Sensor Serial Data (0=Low, 1=High)
AD1 Optical Sensor Serial Clock (0=Low, 1=High)
AD2 Optical Sensor Power (0=Off, 1=On)
AD3 Optical Sensor Serial Direction (0=Read, 1=Write)
AD8 Rumble Motor (0=Off, 1=On)

Thanks: Daniel Palmer


DS Cart Expansion RAM

DS Memory Expansions
There are several RAM expansions for the NDS. The RAM cartridge connects to the GBA slot; can can be then accessed from cartridges in the DS slot.
  Opera         (8MB RAM) (official RAM expansion for Opera browser)
  EZ3/4/3-in-1  (8-16MB RAM, plus FLASH, plus rumble)
  Supercard     (32MB)
  M3            (32MB)
  G6            (32MB)
The recommended access time (waitstates) for all memory types is unknown. Unknown which programs do use these expansions for which purposes (aside from the Opera browser).
Thanks to Rick "Lick" Wong for info on detection and unlocking.

Opera / DS Memory Expansion Pak (NTR-011 or USG-007)
  base=9000000h, size=800000h (8MB)
  unlock=1, lock=0
  STRH [8240000h],lock/unlock

EZ
  base=8400000h, size=VAR (8MB..16MB)
  locking/unlocking/detection see below

Supercard
  base=8000000h, size=1FFFFFEh (32MB minus last two bytes?)
  unlock=5 (RAM_RW), lock=3 (MEDIA)
  STRH [9FFFFFEh],A55Ah
  STRH [9FFFFFEh],A55Ah
  STRH [9FFFFFEh],lock/unlock
  STRH [9FFFFFEh],lock/unlock

M3
  base=8000000h, size=2000000h (32MB)
  unlock=00400006h, lock=00400003h
  LDRH Rd,[8E00002h]
  LDRH Rd,[800000Eh]
  LDRH Rd,[8801FFCh]
  LDRH Rd,[800104Ah]
  LDRH Rd,[8800612h]
  LDRH Rd,[8000000h]
  LDRH Rd,[8801B66h]
  LDRH Rd,[8000000h+(lock/unlock)*2]
  LDRH Rd,[800080Eh]
  LDRH Rd,[8000000h]
  LDRH Rd,[80001E4h]
  LDRH Rd,[80001E4h]
  LDRH Rd,[8000188h]
  LDRH Rd,[8000188h]

G6
  base=8000000h, size=2000000h (32MB)
  unlock=6, lock=3
  LDRH Rd,[9000000h]
  LDRH Rd,[9FFFFE0h]
  LDRH Rd,[9FFFFECh]
  LDRH Rd,[9FFFFECh]
  LDRH Rd,[9FFFFECh]
  LDRH Rd,[9FFFFFCh]
  LDRH Rd,[9FFFFFCh]
  LDRH Rd,[9FFFFFCh]
  LDRH Rd,[9FFFF4Ah]
  LDRH Rd,[9FFFF4Ah]
  LDRH Rd,[9FFFF4Ah]
  LDRH Rd,[9200000h+(lock/unlock)*2]
  LDRH Rd,[9FFFFF0h]
  LDRH Rd,[9FFFFE8h]

Detection
For EZ, detection works as so:
 ez_ram_test:   ;Based on DSLinux Amadeus' detection
  ez_subfunc(9880000h,8000h) ;-SetRompage (OS mode)
  ez_subfunc(9C40000h,1500h) ;-OpenNorWrite
  [08400000h]=1234h          ;\
  if [08400000h]=1234h       ; test writability at 8400000h
    [8000000h]=4321h         ; and non-writability at 8000000h
    if [8000000h]<>4321h     ;
      return true            ;/
  ez_subfunc(9C40000h,D200h) ;CloseNorWrite
  ez_subfunc(9880000h,0160h) ;SetRompage (0160h)
  ez_subfunc(9C40000h,1500h) ;OpenNorWrite
  [8400000h]=1234h           ;\
  if [8400000h]=1234h        ; test writability at 8400000h
    return true              ;/
  return false               ;-failed
 ez_subfunc(addr,data):
  STRH [9FE0000h],D200h
  STRH [8000000h],1500h
  STRH [8020000h],D200h
  STRH [8040000h],1500h
  STRH [addr],data
  STRH [9FC0000h],1500h
For all other types (everything except EZ), simply verify that you can write (when unlocked), and that you can't (when locked).


DS Cart Infrared/Pedometers

NDS/DSi Cartridges with IR port
DS Cart Infrared Cartridge SPI Commands
DS Cart Infrared Cartridge Memory Map

Activity Meter
Pedometer with two-color LED and button. The step counter results can be transferred to NDS via IrDA.
DS Cart Infrared Activity Meter IR Commands
DS Cart Infrared Activity Meter Memory Map

P-Walker
Pedometer with LCD, speaker, and three buttons. There is no intended way to run custom program code (though it can be tweaked to do so via CPU Memory Write command).
DS Cart Infrared P-Walker IR Commands
DS Cart Infrared P-Walker Memory Map
DS Cart Infrared P-Walker Ports LCD Controller
DS Cart Infrared P-Walker Ports Accelerometer BMA150
The purpose is more or less unknown: Apart from communicating with the NDS, the IrDA can be also used communicate with other P-Walkers (maybe for trading/fighting?). The GUI supports Teams, Routes, Events, Items (maybe for some built-in interactice game engine?).

Component Lists
DS Cart Infrared Component Lists

H8/38602 CPU series with H8/300H instruction set
The NDS cartridges and Activity Meter and P-Walker contain Renesas H8/3860X CPUs with H8/300H instruction set and on-chip firmware. In the cartridge it's merely used for forwading IR messages via SPI bus, in the pedometer it's handling step sensors, step counting, EEPROM logging, buttons, LED/LCD, RTC/time, IR messages, etc.
H8/386 SFRs
H8/386 Exception Vectors
H8/300H Operands
H8/300H Opcodes

References
  H8/300H Series Programming Manual (Hitachi, 257 pages)  ;-Opcodes
  H8/38602R Group Hardware Manual (Renesas, 554 pages)    ;-SFR's
  The addition of H8/38606 Group (Renesas, 6 pages)       ;-FLASH/ROM/RAM
For P-Walker:
  BMA150 Triaxial digital acceleration sensor Data sheet (Bosch, 56 pages)
  SSD1850 Advance Information (Solomon System, 56 pages)  ;-LCD driver
  http://dmitry.gr/?r=05.Projects&proj=28.%20pokewalker   ;-Disassembly/Story
  http://forums.nesdev.org/viewtopic.php?f=23&t=21140#p265388  ;-Forum


DS Cart Infrared Cartridge SPI Commands

There are two NDS cart firmware versions with minor differences:
  OLD was used in Walk with Me (maybe also Active Health?)
  NEW was used in the P-Letter game series
The IR-port is accessed via SPI bus commands; that bus is also shared for accessing FLASH/EEPROM memory (via 00h-prefix).

Infrared NDS cartridge SPI command summary
  04h,04h                  Initial dummy in walk with me (bugged read or wrdi?)
  00h,cmd,params[...]      Savedata access
  01h,00h,00h              Infrared RX (none, len=0, plus dummy data=0)
  01h,len,data[len]        Infrared RX (OLD: max 84h bytes, NEW: max B8h bytes)
  02h,data[...]            Infrared TX (OLD: max 84h bytes, NEW: max B8h bytes)
  02h,F2h,data[...]        OLD: ignored (refuses to TX data starting with F2h)
  03h,msb,lsb,data         Memory Write 8bit   ;\MOV.B
  04h,msb,lsb,data         Memory Read 8bit    ;/
  05h,msb,lsb,data,data    Memory Write 16bit  ;\MOV.W (fails on 8bit SFRs?)
  06h,msb,lsb,data,data    Memory Read 16bit   ;/
  07h,00h,num,num,num,...  Blah, returns num params from previous spi command
  08h..FFh                 OLD: Ignored (keeps awaiting a SPI command byte)
  08h,ver                  NEW: Returns version (ver=AAh)
  09h..FFh                 OLD: Ignored (returns zeropadding)

SPI Transfers
The SPI transfers are working at max 1MHz transfer clock, and they do require a delay after each byte:
Waiting 800h clks at 33MHz seems to work okay (eg. MOV r0,200h // SWI 03h on ARM7). The NEW ROM version disables IR polling when doing the SPI transfers for RX/TX data blocks (so it may work with shorter delays between the data[...] bytes).
The savedata access is directly passed to the FLASH/EEPROM chip and does work at 4MHz without delays (except, the leading 00h prefix must be transferred at 1MHz plus delay, and another delay is needed when releasing chipselect after last byte).
Note: The NDS cart slot IRQ pin is GNDed in Walk with Me (ie. there is no IRQ for SPI/IR status).
SPI access does require cart power on and reset (via DSi SCFG registers), but doesn't require any ROM commands like secure area loading. Confusingly, the ROM Chip ID seems to have an IR flag in bit0 of 3rd byte (although the ROM chip isn't wired to IR hardware at all).

IR Transfers
The IR transfers are using a fixed baudrate: 115200 baud, 8n1, one-directional (RX gets disabled during TX). The RX/TX commands are transferring "packets" (with each "packet" being terminated by a "pause" in the IR transmission; that "packet+pause" mechanism is making it impossible to use streaming for transferring larger blocks that exceed the buffer size of max 84h or B8h bytes).
The RX command will return empty data with len=00h until a WHOLE packet has been received via IR.
The TX command won't start the IR transfer until the WHOLE packet has been written via SPI, with packet end indicated by releasing chip select.
There is no way to detect TX transfer end (other than computing the expected tranfer time and using an ARM timer).
However, Nintendo is sending a Reply for most TX commands, so one can simply wait for RX packets to determine TX completion (if neither Reply nor Checksum Error are received then one will still need timeout handling).

Memory Read/Write
These commands are normally not used. The memory commands do forcefully abort IR transfers, so they can't be used for polling IR transfer status.
However, they can be used for dumping the firmware ROM, and they could be used to upload/execute custom code in RAM, which may allow to overcome some of the above IR transfer restrictions (other baudrates, fewer delays, better streaming, not ignoring byte F2h, etc).

IR Cart Detection
NDS/DSi Carts with IR support are having special game code with "I" in first letter (NTR-Ixxx or TWL-Ixxx). There are reportedly pirate/bootleg versions of the P-Letter games without IR hardware, unknown if they do nethertheless have the "I" in the gamecode.
Emulators can detect the leading 00h prefix for Savedata access, although that detection may go wrong if preceeded by IR access. Emulators can additionally detect the slow 1MHz SPI clock used for IR access (and for 00h prefix).


DS Cart Infrared Cartridge Memory Map

IR Cartridge SFR Usage
  [0FFD6h].0  Port 3 Data bit0 OUT  IrDA PWDOWN (1=disable IrDA RX)
  [0FFD6h].1  Port 3 Data bit1 IN   IrDA RXD  ;\via serial IrDA registers
  [0FFD6h].2  Port 3 Data bit2 OUT  IrDA TXD  ;/
  [0FFDBh].3  Port 8 Data bit3 OUT  Savedata chipselect (0=select) (cmd 00h)
  [0FFDBh].2  Port 8 Data bit2 OUT  LED color    ;\used in UNUSED functions,
  [0FFDBh].3  Port 8 Data bit3 OUT  LED color    ; in OLD ROM only, and
  [0FFDEh].0  Port B Data bit0 IN   Button input ;/conflicting with Savedata
  IrDA  IR Transfers
  SPI   NDS Console (and cmd 00h forwarding to Savedata)

IR Cartridge (OLD Version)
  FB80h 200h  undocumented and unused RAM, is R/W in my 38600R (!)
  FD80h 2     unused           ;-unused
  FD82h 2     ir_callback      ;\main callbacks for ir/spi polling
  FD84h 2     spi_callback     ;/
  FD86h 2     ir_timestamp     ;-last ir access (for timeout)?
  FD88h 2     spi_timestamp    ;-last spi access (for debug or so)?
  FD8Ah 1     initial_blah     ;-initial state of Port 8.bit3 (not really used)
  FD8Bh 1     ir_rxbuf_wrptr   ;-ir_rxbuf_wrptr (for incoming IR data)?
  FD8Ch 1     ir_rxbuf_rdptr   ;-ir_rxbuf_rdptr (for forwarding to spi)?
  FD8Dh 84h   spi_rx_buf       ;-spi_rx_buf  ;(also ir TX buf)
  FE11h 84h   infrared_rx_buf  ;-infrared_rx_buf
  FE95h 1     spi_index        ;-spi_index
  FE96h 1     ir_tx_index      ;-ir_tx_index   (from spi buf to TX infrared)
  FE97h 1     ir_timeout_flag  ;-ir_timeout_flag   (or packet end or so?)
  FE98h 2     button_num_changes   ;\
  FE9Ah 2     button_num_pushes    ; used only in
  FE9Ch 1     button_new_state     ; UNUSED functions
  FE9Dh 1     button_old_state     ;
  FE9Eh 1     button_newly_pushed  ;
  FE9Fh 1     button_offhold       ;/
  FEA0h E0h   stack_area (stacktop at FF80h)

IR Cartridge (NEW Version)
  FB80h 200h  undocumented and unused RAM, is R/W in my 38600R (!)
  FD80h 2     unused           ;-unused
  FD82h 2     ir_callback      ;\main callbacks for ir/spi polling
  FD84h 2     spi_callback     ;/
  FD86h 2     ir_timestamp     ;-last ir access (for timeout)?
  FD88h 1     ir_rxbuf_wrptr   ;-ir_rxbuf_wrptr (for incoming IR data)?
  FD89h 1     ir_rxbuf_rdptr   ;-blah, always set to 0, never used
  FD8Ah 1     spi_index        ;-spi_index
  FD8Bh 1     ir_tx_index      ;-ir_tx_index   (from spi buf to TX infrared)
  FD8Ch B8h   spi_rx_buf       ;-spi_rx_buf  ;(also ir TX buf)
  FE44h B8h+1 infrared_rx_buf  ;-infrared_rx_buf (plus space for appending 00h)
  FEFDh 1     ir_timeout_flag  ;-ir_timeout_flag   (or packet end or so?)
  FEFEh 82h   stack_area (stacktop at FF80h)



DS Cart Infrared Activity Meter IR Commands

Packet Encryption/Checksumming
Nintendo wants all IR packet bytes to be "encrypted" (XORed by AAh), that encryption/decryption must be done on ARM side. The checksums are calculated as so (on decrypted packets):
  sum=0, packet[2,3]=00h,00h                    ;-initial chksum
  for i=0 to size-1
    if (i and 1)=0 then sum=sum+packet[i]*100h  ;\add in big-endian fashion
    if (i and 1)=1 then sum=sum+packet[i]       ;/
  sum=(sum/10000h)+(sum AND FFFFh)              ;\final adjust
  sum=(sum/10000h)+(sum)                        ;/
  packet[2,3]=sum,sum/100h                      ;-store in little-endian
The packets are transferred at 115200 baud, 8n1. End of Packet is indicated by a pause in the IR transmission (that does also indicate the packet size).
Before sending a command packet, one should always wait for incoming data from the Activity Meter (ie. for the FCh byte, or for Reply/ChecksumError responses for previous command).

Activity Meter IR commands (from NDS):
  08,xx,cc,cc,msb,lsb,data[..]  CPU Memory Write    (len=3Eh max)  ;Reply=08
  0A,xx,cc,cc,msb,lsb,len       CPU Memory Read     (len=40h max)  ;Reply=0A
  0A,xx,cc,cc,FB,9C,len         CPU Memory Read FB9Ch with ClrFlag ;Reply=0A
  20,xx,cc,cc,msb,lsb,data[..]  Serial EEPROM Write (len=3Eh max)  ;Reply=20
  22,xx,cc,cc,msb,lsb,len       Serial EEPROM Read  (len=40h max)  ;Reply=22
  24,00,cc,cc,ss,ss,ss,ss       Update Ringbuf_mm    ;\            ;Reply=24
  24,01,cc,cc,ss,ss,ss,ss       Update Ringbuf_hh    ; and set     ;Reply=24
  24,02,cc,cc,ss,ss,ss,ss       Update Ringbuf_dd    ; 32bit       ;Reply=24
  24,03,cc,cc,ss,mm,hh          Set RTC hh:mm:ss     ; seconds     ;Reply=24
  24,04,cc,cc,ss,ss,ss,ss       Raw Set ssssssss ?   ;/            ;Reply=24
  24,xx,cc,cc,ss,ss,ss,ss       Invalid (same as 24,04)            ;Reply=24
  26,xx,cc,cc                   Deadlock   ;\both same (maybe      ;Reply=26
  28,xx,cc,cc                   Deadlock   ;/Watchdog/reboot?)     ;Reply=26
  2A,xx,cc,cc,00,nn             Stepback Ringbuf_hh  ;\go back nn  ;Reply=2A
  2A,xx,cc,cc,01,nn             Stepback Ringbuf_mm  ; entries,    ;Reply=2A
  2A,xx,cc,cc,02,nn             Stepback Ringbuf_dd  ;/see [FCDAh] ;Reply=2A
  2A,xx,cc,cc,xx,..             Invalid                            ;Reply=2A
  2C,cs,cc,cc                   Toggle one LED on/off              ;Reply=2C
  F4,xx,cc,cc                   Disconnect                         ;Reply=None
  F6,xx,cc,cc                   Force "Bad Chksum" reply           ;Reply=FC
  FA,xx,cc,cc                   Connect                            ;Reply=F8
  FE,...                        Noise      ;\ignored, noise        ;Reply=None
  FF,...                        Noise      ;/                      ;Reply=None
  xx,xx,cc,cc                   Invalid    ;-ignored, invalid cmd  ;Reply=None
  xx,xx,xx,xx                   Bad Chksum                         ;Reply=FC

Activity Meter IR replies (to NDS):
  08,sq,cc,cc           Reply to Cmd 08 (CPU Memory Write reply)
  0A,sq,cc,cc,data[..]  Reply to Cmd 0A (CPU Memory Read reply)
  20,sq,cc,cc           Reply to Cmd 20 (Serial EEPROM Write reply)
  22,sq,cc,cc,data[..]  Reply to Cmd 22 (Serial EEPROM Read reply)
  26,xx,cc,cc           Reply to Cmd 26 and 28 (Deadlock reply)
  24,xx,cc,cc           Reply to Cmd 24 (Update, or Set RTC time)
  2A,xx,cc,cc           Reply to Cmd 2A (Stepback, with result at [FCDAh])
  2C,cs,cc,cc           Reply to Cmd 2C (LED reply)
  80,FF,cc,cc           Factory Reset and Hardware Test completed (or failed)
  F8,00,cc,cc           Reply to Cmd FA (Connect reply)
  FC,xx,cc,cc           Reply to Cmd's with Bad Chksum (and Cmd F6)
  FC                    Advertising Msg (after pressing button) (single byte)

Notes
  cc,cc        Checksum (LITTLE-ENDIAN)
  msb,lsb      Memory Address (big-endian)
  ss,ss,ss,ss  Seconds since 2001 (big-endian)
  ss,mm,hh     RTC time HH:MM:SS (BCD) (caution: smashes seconds since 2001)
  sq           Increasing sequence number in Memory Access replies
  cs           LED color/state (c=color red/green, s=state on/off)
  xx           Whatever (don't care?)
There aren't any specific commands for reading things like step counters, one must instead use the Memory Read/Write commands with hardcoded RAM or EEPROM address, see:
DS Cart Infrared Activity Meter Memory Map
The command/reply are intended to be transferred from/to NDS accordingly, but things could go wrong if there are multiple consoles or activity meters (all trying to process the same message, or even mistreating replies as commands).
The infrared range (distance/angle) is unknown. Dumping the whole 64K CPU memory space worked without checksum errors at about 5-10cm distance (and that worked without even using the Connect command).


DS Cart Infrared Activity Meter Memory Map

The most important RAM locations are FCE8h=Total steps, and FB9Ch=Unique ID (when using multiple Activity Meters), FCF0h=Daily Goal (to change LED color after N steps). Nintendo is reading/writing a few more RAM locations. And, there are ring buffers with steps per minute/hour/day in EEPROM.

Activity Meter SFR Usage
  [0FFD4h].0  Port 1 Data bit0 IN   Factory Test (0=Test, 1=Normal)
  [0FFD4h].2  Port 1 Data bit2 OUT  Set for sum of eight A/D conversions
  [0FFD6h].0  Port 3 Data bit0 OUT  IrDA PWDOWN (1=disable IrDA RX)
  [0FFD6h].1  Port 3 Data bit1 IN   IrDA RXD  ;\via serial IrDA registers
  [0FFD6h].2  Port 3 Data bit2 OUT  IrDA TXD  ;/
  [0FFDBh].2  Port 8 Data bit2 OUT  LED color?
  [0FFDBh].3  Port 8 Data bit3 OUT  LED color?
  [0FFDCh].0  Port 9 Data bit0 OUT  SPI EEPROM chipselect (0=select)
  [0FFDEh].0  Port B Data bit0 IN   Button input
  IrDA  IR Transfers
  SPI   SPI 8Kbyte EEPROM
  A/D   Used to read two single-axis sensors (for step counting)?
  A/D   Also used to read sum of eight A/D conversions (for wakeup from sleep)?
The SPI EEPROM uses same commands as NDS cart savedata:
DS Cartridge Backup

Activity Meter RAM (1Kbyte, FB80h-FF7Fh)
  FB80h 1   Button flags (bit7=curr.state, bit6=newly.pressed, bit5=old.state)
  FB81h 1   ... cleared if memread src was unique_id (and other cases)
  FB82h 1   ... sys/power mode ?
  FB83h 1   ... adc_mode, or power_saving?
  FB84h 1   ... clock change request
  FB85h 1   ... led_extra_mask (never CLEARED, except on boot, or maybe via IR)
  FB86h 1   adc_array_index (index in ADC array X/Y, wraps in range 00h..3Fh)
  FB87h 1   ... entrysize of current data in ringbuf (per newest TAG) or so?
  FB88h 1   SPI overrun error (probably nonsense, SPI clk can't outrun itself)
  FB89h 1   Unused
  FB8Ah 1   num_steps_curr_minute (00h..FCh) (no conflict with tag FDh,FEh,FFh)
  FB8Bh 1   rtc_event_flags (bit0=minute, bit1=hour, bit2=day, bit3=also.hour)
  FB8Ch 1   ... timing offhold for various stuff
  FB8Dh 1   some_shift_amount         ;READ via IR
  FB8Eh 1   Daily goal reached flag (aka LED color) (bit0=reached, bit1=???)
  FB8Fh 1   ... timing for LED step pulses?
  FB90h 1   ... timing for LED step pulses?
  FB91h 1   ... flag for LED step pulse state?
  FB92h 1   Hour when new day starts (BCD, usually/always 03h)   ;READ via IR
  FB93h 1   ... some flag for inactivity low-power mode ?
  FB94h 1   LED animation number (1..5, or 0=none) (factory test result)
  FB95h 1   Unused
  FB96h 1   New day flag
  FB97h 1   Fixed LED mask (this is a "fixed" setting from EEPROM)
  FB98h 1   Compare_ctrl_0  ;\for "Compare Control" HW registers (89h,89h)
  FB99h 1   Compare_ctrl_1  ;/
  FB9Ah 1   New Goal flag (apply [FCF4h] as new goal, starting on next day?)
  FB9Bh 1   Unused
  FB9Ch 28h Unique ID ;READ via IR (initally set by NDS via RAM+EEPROM writes?)
  FBC4h 2   adc_current_x
  FBC6h 2   adc_current_y
  FBC8h 80h adc_array_x (40h x 16bit)
  FC48h 80h adc_array_y (40h x 16bit)
  FCC8h 2   adc_scale_factor_x  ;\scale factors
  FCCAh 2   adc_scale_factor_y  ;/
  FCCCh 2   adc_scale_unused_z  ;\semi-unused (written, but never read)
  FCCEh 2   adc_scale_unused_t  ;/
  FCD0h 2   ringbuf_mm_index (0020h..16A0h)   ;READ via IR
  FCD2h 2   ringbuf_hh_index (16A1h..1C42h)   ;READ via IR
  FBD4h 2   Unused
  FCD6h 2   ringbuf_dd_index (1C43h..1CDEh)   ;READ via IR
  FCD8h 2   num_steps_curr_hour    (16bit step counter for current hour)
  FCDAh 2   ringbuf_stepback_index (result from cmd_2Ah, to be read by cmd_0Ah)
  FCDCh 2   adc_inactivity_timer   (time since last pedometer step)
  FCDEh 2   SPI overrun error counter (related to flag at FB88h)
  FCE0h 2   Unused
  FCE2h 2   adc_current_sum (sum of eight A/D conversions)
  FCE4h 4   seconds_counter (seconds since 1st Jan 2001?, initially 0D2B0B80h)
  FCE8h 4   num_steps_lifelong (lifelong TOTAL steps)
  FCECh 4   num_steps_today    (step counter, for current day)
  FCF0h 4   Daily_goal         (WRITTEN via IR, NDS cart default=3000 decimal)
  FCF4h 4   new_goal_steps     (somewhat reload value for daily goal?)
  FCF8h 18h Unused
  FD10h 2   main_callback (main_adc_button_callback, or ir_callback)
  FD12h 40h ir_tx_data    (buffer for Memory & EEPROM reads)
  FD52h 2   clk_callback  (clk_whatever_callback, or 0=none)
  FD54h 2   ir_callback   (ir_active_callback, or ir_dummy_callback)
  FD56h 2   ir_timestamp_last_byte (for sensing SHORT GAPs, aka end-of-packet)
  FD58h 2   RX chksum from hdr[2..3]
  FD5Ah 2   RX chksum from calculation
  FD5Ch 2   ir_timestamp_last_xfer (for sensing LONG GAPs, aka sleep mode)
  FD5Eh 1   Unused
  FD5Fh 1   ir_rx_len
  FD60h 1   ... semi-unused (set to 00h?) (but never read)
  FD61h 44h ir_rxtx_buf, hdr[4]+data[40h]
  FDA5h 1   ir_tx_hdr_len    ;\memorized TX len+hdr[4]
  FDA6h 4   ir_tx_hdr_copy   ;/(never actually used)
  FDAAh 1   bad_chksum_count, give up sending bad_chksum replies after 3 errors
  FDABh 1   bad_chksum_flag, request reply_FCh (bad_chksum)
  FDACh 80h ... array (40h x 16bit)          ;\
  FE2Ch 80h ... array (40h x 16bit)          ; analog sine/cosine
  FEACh 4   ... dword                        ; stuff for converting
  FEB0h 4   ... dword                        ; adc to step counter?
  FEB4h 1   ... byte                         ;
  FEB5h 1   ... byte                         ;/
  FEB6h 2   Incremented in main_adc_button_callback (but not used elsewhere)
  FEB8h 1   Unused                   ;\maybe meant to be 4-byte tx hdr,
  FEB9h 1   TX sequence number       ; but only hdr[1] used (as increasing
  FEBAh 2   Unused                   ;/seq.no for memory read/write replies)
  FEBCh 4   ... array (2 x 16bit)
  FEC0h 4   ... array (2 x 16bit)
  FEC4h 4   ... array (2 x 16bit)
  FEC8h 4   ... array (2 x 16bit)
  FECEh B2h CPU Stack area, initial SP=FF80h

Activity Meter EEPROM (8Kbytes, serial SPI bus)
  EEPROM:0000h 9     ID "nintendo",00h (9 bytes)
  EEPROM:0009h 17h   Unused (FFh-filled)
  EEPROM:0020h 1681h Ringbuf_mm ;steps per MINUTE for 4 days ;(24*60*4-1)*8bit
  EEPROM:16A1h 5A2h  Ringbuf_hh ;steps per HOUR for 30 days  ;(24*30+1)*16bit
  EEPROM:1C43h 9Ch   Ringbuf_dd ;steps per DAY for 52 days   ;(52)*24bit
  EEPROM:1CDFh 1     Unused (FFh) (padding ringbuf's to 20h-byte-boundary)
  EEPROM:1CE0h 200h  Unused (FFh-filled)
  EEPROM:1EE0h 8+1   ADC_scale_values (4x16bit) ;RAM:FCC8h ;\
  EEPROM:1EE9h 2+1   ADC sum_limit              ;RAM:stack ; these EEPROM
  EEPROM:1EECh 3     Unused                                ; settings
  EEPROM:1EEFh 4+1   Num_steps_lifelong         ;RAM:FCE8h ; have 1-byte
  EEPROM:1EF4h 1+1   Fixed LED Mask             ;RAM:FB97h ; checksums
  EEPROM:1EF6h 2     Unused                                ; appended, and
  EEPROM:1EF8h 1+1   Some_shift_amount          ;RAM:FB8Dh ; backups at
  EEPROM:1EFAh 4+1   Daily_goal                 ;RAM:FCF0h ; 1F40h-1F9Fh
  EEPROM:1EFFh 4+1   New_goal_steps             ;RAM:FCF4h ;
  EEPROM:1F04h 28h+1 Unique ID                  ;RAM:FB9Ch ;
  EEPROM:1F2Dh 13h   Unused (00h-filled)                   ;/
  EEPROM:1F40h 60h   Backup copies of above data at 1EE0h..1F3Fh ;-backups
  EEPROM:1FA0h 2     Error code     (initially FFFFh)
  EEPROM:1FA2h 1     Reboot counter (initially 00h or 01h ?)
  EEPROM:1FA3h 5Dh   Unused (FFh-filled)
The MM/HH/DD ring buffers are steps per minute/hour/day accordingly, mixed with special tags:
  00xxh          Zero steps for N minutes (N=max FCh)       ;\in ringbuf_mm
  xxh            N steps per minute (N=01h..FCh)            ;/
  xxxxh          N steps per hour (N=0000h..FFFFh)          ;-in ringbuf_hh
  xxxxxxh        N steps per day (N=000000h..FFFFFFh)       ;-in ringbuf_dd
  FDxxxxxxxxxxh  Timestamp, reversed-BCD-digit-order, seconds since 2001 or so?
  FEh            Newest entry marker?
  FFh            Unused entry marker?
The firmware contains code for searching tags FDh/FEh/FFh forwards and backwards, that works well with BCD values and 8bit counters, but unknown it can work with the 16bit/24bit counters. The BCD digits are stored backwards (eg. 12345 = FD5432100000h). Rinbuf pointers can be read from RAM locations FCD0h, FCD2h, FCD6h, and FCDAh).


DS Cart Infrared P-Walker IR Commands

Commands are usually send from NDS (or from other Walkers)
  EEPROM Commands  (Cmd 02,04,0C,0E,82)     ;\From NDS or Walker
  Connect Commands (Cmd F8,FA,FC)           ;/
  Peer Commands    (Cmd 10...1C)            ;-From Walker
  Unused Commands  (Cmd's with * marking)   ;-From Prototype tests?
  Other Commands   (Cmd's other than above) ;-From NDS

Incoming Commands from NDS (or incoming commands/replies from another Walker)
  00,hi,..,lzss(..)     EEPROM Write [hi00h..hi7Fh] Compressed   ;Reply=04
  80,hi,..,lzss(..)     EEPROM Write [hi80h..hiFFh] Compressed   ;Reply=04
  02,hi,..,data(..)     EEPROM Write [hi00h..hi7Fh] Raw          ;Reply=04
  82,hi,..,data(..)     EEPROM Write [hi80h..hiFFh] Raw          ;Reply=04
  04,xx,..              EEPROM Write Reply                     ;SendMoreCmd(s)
  06,hi,..,lo,data(nn)* CPU Memory Write [hilo+(0..nn-1)]        ;Reply=06
  0A,hi,..,lo,data(nn)* EEPROM Write Random Len [hilo+(0..nn-1)] ;Reply=04
  0C,xx,..,hi,lo,nn     EEPROM Read Request [hilo+(0..nn-1)]     ;Reply=0E
  0E,xx,..,data(nn)     EEPROM Read Reply                      ;SendMoreCmd(s)
  10,xx,..,data(68h)    Peer Step 1 Request                      ;Reply=12
  12,xx,..,data(68h)    Peer Step 1 Reply                      ;SendMoreCmd(s)
  14,xx,..,data(38h)    Peer Step 2 Request                      ;Reply=16
  16,xx,..              Peer Step 2 Reply                ;Reply=16 or None
  1C,xx,..              Peer Refuse                      ;Reply=None+Disconnect
  20,xx,..              Identity Read Request                    ;Reply=22
  24,xx,..            * Ping Request                             ;Reply=26
  2A,xx,..,none?        Unique ID Read Request                   ;Reply=2A
  2C,xx,..,none?      * Unique ID Read Request slightly other    ;Reply=2A
  32,xx,..,data(28h?) * Identity Write Request 1                 ;Reply=34
  36,xx,..            * Connection Error 1                       ;Reply=None
  38,xx,..            * Walk Start Silent                        ;Reply=38
  40,xx,..,data(28h?) * Identity Write Request 2                 ;Reply=42
  44,xx,..            * Connection Error 2                       ;Reply=None
  4E,xx,..              Walk End Request                         ;Reply=50
  52,xx,..,data(28h?)?? Identity Write Request 3                 ;Reply=54
  56,xx,..            * Connection Error 3                       ;Reply=None
  5A,xx,..              Walk Start Nonsilent                     ;Reply=5A
  60,xx,..,data(28h?) * Identity Write Request 4                 ;Reply=62
  64,xx,..            * Connection Error 4                       ;Reply=None
  66,xx,..            * Walk End Request OTHER                   ;Reply=68
  9C,xx,..            * Error Whatever                   ;Reply=9C+Disconnect
  9E,xx,..            * Error Weird Participate          ;Reply=9E+Disconnect
  A0,xx,..            * Weird Participate 1                  ;Reply=A0 or 9E
  A2,xx,..            * Weird Participate 2                  ;Reply=A2 or 9E
  A4,xx,..            * Weird Participate 3                  ;Reply=A4 or 9E
  A6,xx,..            * Weird Participate 4                  ;Reply=A6 or 9E
  A8,xx,..            * Weird Participate 5                  ;Reply=A8 or 9E
  AA,xx,..            * Weird Participate 6                  ;Reply=AA or 9E
  AC,xx,..            * Weird Participate 7                  ;Reply=AC or 9E
  AE,xx,..            * Weird Participate 8                  ;Reply=AE or 9E
  B8,xx,..            * Award Stamp Heart                        ;Reply=D8
  BA,xx,..            * Award Stamp Spade                        ;Reply=DA
  BC,xx,..            * Award Stamp Diamond                      ;Reply=DC
  BE,xx,..            * Award Stamp Club                         ;Reply=DE
  C0,xx,..            * Award Special Map                        ;Reply=C0
  C2,xx,..            * Award Event P-Letter                     ;Reply=C2
  C4,xx,..            * Award Event Item                         ;Reply=C4
  C6,xx,..            * Award Event Route                        ;Reply=C6
  D0,xx,..            * Award All Stamps and Special Map         ;Reply=C0
  D2,xx,..            * Award All Stamps and Event P-Letter      ;Reply=C2
  D4,xx,..            * Award All Stamps and Event Item          ;Reply=C4
  D6,xx,..            * Award All Stamps and Event Route         ;Reply=C6
  D8,xx,..            * Connection Error 5                       ;Reply=None
  F0,xx,..,data(71h) ?? Enroll Data (28h+40h+8+1 bytes)          ;Reply=F0
  F4,xx,..            * Disconnect                       ;Reply=None+Disconnect
  F8,02,..              Connection Reply from Walker             ;SendCmd=1002
  FA,01,..              Connection Request from NDS              ;Reply=F802
  FA,02,..              Connection Request from Walker           ;Reply=F802
  FA,xx,..              Connection Request invalid       ;Reply=None+Disconnect
  FC                    Connection Beacon from Walker            ;SendCmd=FA
  FE,01,..,data(8)    * EEPROM Write [0008h..000Fh]              ;Reply=FE
  xx                  * Ignored (single byte other than FC)      ;Reply=None
  xx,xx,..            * Invalid Cmd                              ;Reply=None
  xx,xx,xxxx          * Ignored (wrong 4-byte ID for Cmd 00-F7)  ;Reply=None
  xx,xx,xxxx          * Bad Checksum (disconnect if too often)   ;Reply=None

Outgoing Replies to NDS (or outgoing commands/replies to another Walker)
  02,hi,..,data(nn)     EEPROM Write ...                         ;Cmd=Peer
  82,hi,..,data(nn)     EEPROM Write ...                         ;Cmd=Peer
  04,hi,..              EEPROM Write Reply                  ;Cmd=00/02/0A/80/82
  06,hi,..            * CPU Memory Write Reply                   ;Cmd=06h
  0C,02,..,hi,lo,nn     EEPROM Read Request  ;Peer, EEPROM Read  ;Cmd=0Eh
  0E,02,..,data(nn)     EEPROM Read Reply                        ;Cmd=0Ch
  10,02,..,data(68h)    Peer Step 1 Request (after Connect Reply);Cmd=F8h
  12,02,..,data(68h)    Peer Step 1 Reply                        ;Cmd=10h
  14,02,..,data(38h)    Peer Step 2 Request                      ;Cmd=0Eh
  16,02,..              Peer Step 2 Reply                        ;Cmd=14h/16h
  1C,02,..              Peer Refuse                              ;Cmd=10h/12h
  22,02,..,data(68h)    Identitiy Read Reply                     ;Cmd=20h
  26,02,..            * Ping Reply                               ;Cmd=24h
  2A,02,..,data(28h)    Unique ID Reply                          ;Cmd=2Ah/2Ch
  34,02,..            * Identitiy Write 1 Reply                  ;Cmd=32h
  38,02,..            * Walk Start silent Reply                  ;Cmd=38h
  42,02,..            * Identitiy Write 2 Reply                  ;Cmd=40h
  50,02,..              Walk End Reply                           ;Cmd=4Eh
  54,02,..           ?? Identitiy Write 3 Reply                  ;Cmd=52h
  5A,02,..              Walk Start nonsilent Reply               ;Cmd=5Ah
  62,02,..            * Identitiy Write 4 Reply                  ;Cmd=60h
  68,02,..            * Walk End OTHER Reply                     ;Cmd=66h
  9C,02,..            * Weird Whatever Reply-to-Reply?           ;Cmd=9Ch
  9E,02,..,data(11h)  * Weird Participated Reply                 ;Cmd=A0h..AEh
  9E,02,..            * Weird Participated Reply-to-Reply?       ;Cmd=9Eh
  A0,02,..,data(11h)  * Weird Participated Reply 1               ;Cmd=A0h
  A2,02,..,data(11h)  * Weird Participated Reply 2               ;Cmd=A2h
  A4,02,..,data(11h)  * Weird Participated Reply 3               ;Cmd=A4h
  A6,02,..,data(11h)  * Weird Participated Reply 4               ;Cmd=A6h
  A8,02,..,data(11h)  * Weird Participated Reply 5               ;Cmd=A8h
  AA,02,..,data(11h)  * Weird Participated Reply 6               ;Cmd=AAh
  AC,02,..,data(11h)  * Weird Participated Reply 7               ;Cmd=ACh
  AE,02,..,data(11h)  * Weird Participated Reply 8               ;Cmd=AEh
  C0,02,..            * Award Special Map Reply                  ;Cmd=C0h/D0h
  C2,02,..            * Award Event P-Letter Reply               ;Cmd=C2h/D2h
  C4,02,..            * Award Event Item Reply                   ;Cmd=C4h/D4h
  C6,02,..            * Award Event Route Reply                  ;Cmd=C6h/D6h
  C8,02,..            * Award Stamp Heart Reply                  ;Cmd=B8h
  CA,02,..            * Award Stamp Spade Reply                  ;Cmd=BAh
  CC,02,..            * Award Stamp Diamond Reply                ;Cmd=BCh
  CE,02,..            * Award Stamp Club Reply                   ;Cmd=BEh
  F0,02,..,data(28h) ?? Enroll Reply                             ;Cmd=F0h
  F8,02,..              Connect Reply                            ;Cmd=FAh
  FA,02,..              Connect Request from walker              ;Cmd=FCh
  FC                    Connection Beacon                        ;Button?
  FE,02,..            * EEPROM Write [0008h..000Fh] Reply        ;Cmd=FEh
  -?-                   Checksum Error... has no reply? or maybe sends Beacons?

Notes
  ..    short for 16bit Checksum at hdr[2..3] and 32bit Session ID at hdr[4..7]
  xx    somewhat don't care (usually 01h=From NDS, or 02h=From Walker)
All 16bit checksum and the IR "encryption" (XOR by AAh), seem to be same as for Activity Meter (see there, except use initial sum=2, not sum=0).
The Connect Request & Reply commands are sending a "random" SessionID each, all following commands/replies (except F8h and up) must use
  SessionID = ConnectRequestRandomID XOR ConnectReplyRandomID.
The Compressed EEPROM commands are writing decompressed 80h-bytes of data to EEPROM (ie. the compression is only used to speedup the IR transfer, not to save memory). The compression format is Nintendo's standard LZSS (including the header value 10h, and little-endian 24bit length; which should be always 80h). Special case: Compressed writes with exactly 80h bytes of incoming data are treated as uncompressed writes (to be used when compression ratio is worse than no compression).


DS Cart Infrared P-Walker Memory Map

P-Walker SFR Usage
  [0FFD4h].0  Port 1 Data bit0 OUT  SPI LCD chipselect (0=select)
  [0FFD4h].1  Port 1 Data bit1 OUT  SPI LCD access mode (0=Cmd, 1=Data)
  [0FFD4h].2  Port 1 Data bit2 OUT  SPI EEPROM chipselect (0=select)
  [0FFD6h].0  Port 3 Data bit0 OUT  IrDA PWDOWN (1=disable IrDA RX)
  [0FFD6h].1  Port 3 Data bit1 IN   IrDA RXD  ;\via serial IrDA registers
  [0FFD6h].2  Port 3 Data bit2 OUT  IrDA TXD  ;/
  [0FFDBh].2  Port 8 Data bit2      ?
  [0FFDBh].3  Port 8 Data bit3      ?
  [0FFDBh].4  Port 8 Data bit4 OUT  A/D related ... whatfor LCD? accel? batt?
  [0FFDCh].0  Port 9 Data bit0 OUT  SPI Accelerometer chipselect (0=select)
  [0FFDEh].0  Port B Data bit0 IN   ?  ;\
  [0FFDEh].2  Port B Data bit2 IN   ?  ; maybe buttons
  [0FFDEh].4  Port B Data bit4 IN   ?  ;/
  [0FFDEh].5  Port B Data bit5 OUT  ?
  Timer W General A/B/C  Audio Frequency/Volume
  IrDA                   IR Transfers
  SPI                    SPI 64Kbyte EEPROM, LCD Cmd/Data, Accelerometer
  A/D                    whatfor LCD? accel? batt?
The SPI EEPROM uses same commands as NDS cart savedata:
DS Cartridge Backup
For the other two SPI-like devices, see:
DS Cart Infrared P-Walker Ports LCD Controller
DS Cart Infrared P-Walker Ports Accelerometer BMA150
Note: SPI LCD chipselect is also used for outputting factory test results via SPI bus (requires special hardware attached instead of the LCD screen).

RAM Map (2Kbytes, F780h..FF7Fh)
  F780h 60h      Misc variables
  F7E0h 2        main_callback                          ;<--
  F7E2h ECh      Misc variables
  F8CEh 8+80h    Infrared RX/TX buffer hdr+data (also misc/heap)
  F956h 62Ah     Temp buffer, free RAM, and stack       ;<--
  FF80h -        Stacktop (end of RAM)

ROM Map
For some quick hacks, Dmitry recommends these ROM addresses (which won't work when reflashing the firmware).
  0772h          Send IR packet (F8D6h=src, r0l=len, r0h=hdr[0], r1l=hdr[1])
  08D6h          Default callback (when in IR transfer mode)
  259Eh          Watchdog refresh

EEPROM Map
The EEPROM contains some important basic data, plus GUI related bitmaps (mostly text strings pre-rendered as bitmaps for the local user name & game language) (and maybe(?) also game specific customizations).
  0000h 8        ID "nintendo" (set after initial power-up eeprom init)
  0008h 8        ID whatever   (set via Cmd F0h and FEh) (never read)
  0010h 62h      ???
  0072h 1        Number of watchdog resets
  0073h 0Dh      ???
  0080h 02h+1    ADC calibration (factory-provided)               ;\
  0083h 28h+1    Unique ID      (set via Cmd F0h)                 ; with 1-byte
  00ACh 40h+1    LCD ConfigCmds (set via Cmd F0h)                 ; checksums
  00EDh 68h+1    Identity Data ("provisioned" at walk start time) ; and backup
  0156h 18h+1    Health Data   ("provisioned" at walk start time) ; copies at
  016Fh 01h+1    Copy Flag (00h=Normal, A5h=copy was interrupted) ; 0180h-027Fh
  0171h 0Fh      Unused                                           ;/
  0180h 100h     Backup copies of entries at 0080h-0017Fh
  0280h ...      Various Bitmaps
  8C70h ...      Various Garbage, Bitmaps, Items, Team, Route
  CE8Ah 2        current watts written to eeprom by cmd 20h before replying
                   (likely so remote can read them directly). u16 BE
  CE8Ch ...      Various stuff
  CEF0h 1Ch      Historic step count per day. u32 each, BE,
                   [0] is yesterday, [1] is day before, etc...
  CF0Ch ...      Various stuff

 __________________ Data Structures (in EEPROM and Packets) ___________________

Unique ID (28h bytes)
  00h 28h Generated by the DS game at pairing time, unique per walker

Identity Data (68h bytes) //stored reliably at 0x00ED/0x01ED
All multi-byte values LE, unless otherwise specified
  00h 4   Unknown (LE, always 1?) ;\written from game packet at walk start
  04h 4   Unknown (LE, always 1?) ;  ;<-- 0 at walk end  ;copied from [0]
  08h 2   Unknown (LE, always 7?) ;
  0Ah 2   Unknown (LE, always 7?) ;/ ;<-- 0 at walk end  ;copied from [8?]
  0Ch 2   TrainerTID
  0Eh 2   TrainerSID
  10h 28h Unique ID
  38h 10h EventBitmap (aka bitfield with 128 event flags?)
  48h 10h Trainer Name (8 chars, using a custom 16bit charset, non-unicode)
  58h 1   Unknown
  59h 1   Unknown
  5Ah 1   Unknown
  5Bh 1   Flags (bit0=PairedToGame, bit1=HasPoke, bit2=PokeJoinedOnAWalk)
  5Ch 1   ProtoVer (02h)    (written by DS, refuse peer's with other values)
  5Dh 1   Unknown
  5Eh 1   ProtoSubver (00h) (written by DS, refuse peer's with other values)
  5Fh 1   Unknown (02h)     (written by DS at walk start)
  60h 4   LastSyncTime ;Big Endian  ;in WHAT... maybe seconds since WHEN?
  64h 4   StepCount    ;Big Endian  ;since WHEN... today? lifetime? lastsync?

Peer Play Data (38h bytes) //aka "PEER PLAY DATA"
All multi-byte values LE, unless otherwise specified
  00h 4   curStepCount  (since WHEN?)
  04h 2   curWatts
  06h 2   Unused
  08h 4   Unknown, copied from IdentityData[00h]
  0Ch 2   Unknown, copied from IdentityData[08h]
  0Eh 2   Species
  10h 16h P-Nickname   (11 chars)  ;\the actual names in bitmap format
  26h 10h Trainer Name (8 chars)   ;/are stored elsewhere in EEPROM?
  36h 1   GenderForm
  37h 1   HasSpecialForms (spinda, arceus, unown, etc.)

LcdConfigCmds (40h bytes)
Stored reliably at 00ACh/01ACh.
  00h 1   u8 contrastAndFlags (if 00h/FFh? commands at ROM:BEB8h will be used)
  01h 3Fh u8 commands[3fh] (Commands, or FDh,NNh=Delay(NNh), FEh=End of list)

Enroll Data (71h bytes)
  00h 28h Unique ID             ;always written
  28h 40h LCD Config Data       ;written or verified depending on byte[70h]
  68h 8   Whatever ID           ;always written to EEPROM:0008h
  70h 1   LCD Action (00h=WriteA, 01h=Compare, 03h=WriteB, 02h/04h-FFh=Nop)

HealthData (18h bytes)
Stored reliably at 0156h/0256h. Cached in RAM at F780h.
Big Endian unless otherwise noted.
  00h 4  u32 lifetimeTotalSteps
  04h 4  u32 todaySteps           //zeroed at midnight
  08h 4  u32 lastSyncTime
  0Ch 2  u16 totalDays
  0Eh 2  u16 curWatts
  10h 2  u16 unk_0
  12h 1  u8 unk_1
  13h 1  u8 unk_2
  14h 3  u8 padding[3]
  17h 1  u8 settings (bit0=isOnSpecialRoute, bit1-2=Volume, bit3-6=Contrast)

See Dmitry's webpage for more "game-specifc" data structures and memory addresses.


DS Cart Infrared P-Walker Ports LCD Controller

LCD Command Table
Commands are 1 or 2 bytes long (with D/C=Low, and, unlike normal SPI, one can release /CS after each byte, even when sending 2-byte commands).
  1st Byte     2nd Byte  Description
  00h+(0..Fh)  -       Set Column Address bit0-3   ;\VRAM xloc in 1-pixel units
  10h+(0..7)   -       Set Column Address bit4-6   ;/
  18h+(0..7)   -       Reserved
  20h+(0..7)   -       Set Internal Regulator Resistor Ratio
                         (0..7 = 2.3, 3.0, 3.7, 4.4, 5.1, 5.8, 6.5, 7.2)
  28h+(0..7)   -       Set Power Control Register
                         bit2: Internal Voltage Booster (0=Off, 1=On)
                         bit1: Internal Regulator       (0=Off, 1=On)
                         bit0: Output Op-amp Buffer     (0=Off, 1=On)
  30h+(0..0Fh) -       Reserved
  40h          00h-xxh Set Display Start Line (0..127?) (ROW) ("scroll yloc")
  41h+(0..2)   00h-xxh Same as above?
  44h          00h-xxh Set Display Offset (0..63) (COM0=ROW0..63) (pinout?)
  45h+(0..2)   00h-xxh Same as above?
  48h          00h-xxh Set Multiplex Ratio (num lines, duty 1/((16..64)+icon))
  49h+(0..2)   00h-xxh Same as above?
  4Ch          00h-3Fh Set N-line Inversion (0=Off, 1..31=Reduce crosstalk?)
  4Ch          20h-FFh Same as above?
  4Dh+(0..2)   00h-FFh Same as above?
  50h+(0..7)   -       Set LCD Bias (0..5=1/(4..9), 6=1/9, too)
  57h+(0..0Ch) -       Reserved
  64h+(0..3)   -       Set DC-DC Converter Factor (0=2x/3x, 1=4x, 2/3=5x)
  68h+(0..18h) -       Reserved
  81h          00h-3Fh Set Contrast (0..3Fh, 3Fh=Darkest)
  82h          OTP     Set VL6 voltage (00h..0Fh = original+Signed4bit(N))
  83h          OTP     OTP Programming?
  84h+(0..7)   -       Reserved
  88h          00h-FFh Set White Mode      (bit0-3=FrameA, bit4-7=FrameB)
  89h          00h-FFh Set White Mode      (bit0-3=FrameC, bit4-7=FrameD)
  8Ah          00h-FFh Set Light Gray Mode (bit0-3=FrameA, bit4-7=FrameB)
  8Bh          00h-FFh Set Light Gray Mode (bit0-3=FrameC, bit4-7=FrameD)
  8Ch          00h-FFh Set Dark Gray Mode  (bit0-3=FrameA, bit4-7=FrameB)
  8Dh          00h-FFh Set Dark Gray Mode  (bit0-3=FrameC, bit4-7=FrameD)
  8Eh          00h-FFh Set Black Mode      (bit0-3=FrameA, bit4-7=FrameB)
  8Fh          00h-FFh Set Black Mode      (bit0-3=FrameC, bit4-7=FrameD)
                         Above defines the grayscale palette for color 0-3,
                         normally all frames should use the same setting.
                         Color 0 is usually white (set to zero), color 3 is
                         usually black (set to number of levels selected via
                         cmd 90h). Color 1 and 2 are usually light/dark gray,
                         set to desired contrast, which may depend on the LCD.
  90h+(0..7)   -       Set PWM and FRC for gray-scale operation
                         bit0-1: Levels (0/1=Nine, 2=Twelve, 3=Fifteen Levels)
                         bit2:   Frames (0=Four, 1=Three Frames)
                         Note: Nintendo uses "9 levels" ranging from "0 to 9"
                         (maybe level 0 is treated as off, thus not counted)
  98h+(0..7)   -       Reserved
  A0h+(0..1)   -       Set Segment Remap (0=Col00h is SEG0, 1=Col7Fh is SEG0)
                         Aka xflip mirror?
  A2h+(0..1)   -       Set Icon Enable (0=Disable, 1=Enable)
  A4h+(0..1)   -       Set Entire Display On/Off (0=Show RAM, 1=All Pixels On)
  A6h+(0..1)   -       Set Inverse Display (0=Normal, 1=Inverse On/Off Pixels)
  A8h+(0..1)   -       Set Power Save Mode (0=Standby, 1=Sleep)
  AAh          -       Reserved
  ABh          -       Start Internal Oscillator (needed after reset)
  ACh+(0..1)   ?       Reserved
  AEh+(0..1)   -       Set Display On/Off (0=Off, 1=On)
  B0h+(0..0Fh) -       Set Page Address (00h..0Fh)  ;VRAM yloc in 8-pixel units
  C0h+(0,8)    -       Set COM Output Scan Direction (0=Normal, 8=Remapped)
                         Remapped: COM[0..(N-1)] becomes COM[(N-1)..0])
                         Aka yflip mirror?
  C1h+(0..6)   -       Same as above (Normal)
  C9h+(0..6)   -       Same as above (Remapped)
  D0h+(0..10h) -       Reserved
  E1h          -       Exit Power-save Mode (return from Sleep/Standby modes)
  E2h          -       Software Reset (initialize some internal registers)
  E3h          -       Reserved
  E4h          -       Exit N-line Inversion mode
  E5h+(0..2)   -       Reserved
  E8h          LEN+DTA Transfer VRAM Display Data (for 3-wire SPI mode only)
                         (LEN=00h-FFh, followed by LEN+1 data bytes)
  E9h+(0..6)   -       Reserved
  F0h+(0..0Fh) ..      Test mode commands and Extended features
  F0h          00h-03h Ext. Set VL6 Noise reduction (0=Enable, 3=Disable)
  F1h          08h-0Fh Ext. Set TC Value per 'C (0=-0.05%, 1=-0.07%, 2..7=?)
  F2h          00h-07h Ext. Oscillator Adjustment
                         (0..7 = -9%, -6%, -3%, +0%, +3%, +6%, +9%, +12%)
  F7h          00h-01h Ext. Oscillator Source (0=Internal, 1=External, 2=UNDOC)
  F6h          00h-1Fh Ext. Frame Frequency Adjust
                         bit0-2: FrameFQ (0..7 = 0..7)
                         bit3-4: Fosc    (0-3 = 59kHz, 75kHz, 94kHz, 113kHz)
  FBh          X2h,X6h Ext. Lock/Unlock Interface (bit2: 0=Unlock, 1=Lock)

VRAM Writing
First set the VRAM address using three commands with D/C=Low:
  00h+(xloc) AND 0Fh     ;Set Column Address bit0-3
  10h+(xloc/10h)         ;Set Column Address bit4-6
  B0h+(yloc/8)           ;Set Page Address (00h..0Ah, other=reserved?)
For the actual data transfer, set D/C=High and write data (each two bytes contain vertical 8-pixel columns, with bit0=top, bit7=bottom):
  1st byte = bitplane 1   ;\color 0..3 are usually white, lgray, dgray, black
  2nd byte = bitplane 0   ;/(palette can be changed via cmd 88h-8Fh though)
Note: Column Address (xloc) is auto-incremented after each byte pair, the Page Address (yloc) is NOT incremented when wrapping from x=7Fh to x=00h.
The last page is the "icon", this has only 1 pixel per xloc, maybe intended to enable special symbols instead of pixels (on displays to combine symbols and pixels).

VRAM Reading and Status Byte (both supported in parallel Non-SPI mode only)
The controller supports four modes (Nintendo uses the 4-wire SPI mode):
  3-wire SPI Serial write-only (/CS, CLK, MOSI, with cmd E8h instead D/C pin)
  4-wire SPI Serial write-only (/CS, CLK, MOSI, D/C=Data/Cmd)
  12-wire 8080 Parallel read/write (/CS, D0-D7, D/C, /RD, /WR)
  12-wire 6800 Parallel read/write (/CS, D0-D7, D/C, E, R/W)
VRAM can be read setting the VRAM address as usually, and then reading with D/C=High. And, an 8bit status byte can be read with D/C=Low:
  7    BUSY    Chip is executing instruction (0=Ready, 1=Busy)
  6    ON      Display is On/Off             (0=Off, 1=On)
  5    RES     Chip is executing reset       (0=Ready, 1=Busy)
  4-0  -       Fixed Chip ID                 (08h=SSD1850)

Note
Nintendo uses a 96x64 pixel grayscale LCD screen with 2bpp, without backlight or frontlight. VRAM is double buffered (VRAM size is at least 96x128 pixels).
The display controller seems to be a Solomon System SSD1850 chip... or similar, there are a number of datasheets that are more or less matching the LCD commands used in the firmware:
  SSD0852  128x128 would allow double-buffer, but extended commands are wrong
  SSD0858  104x65  close, but extended commands are wrong
  SSD0859  128x81  could be correct (almost same as SSD1850)
  SSD1820  128x65  wrong, lacks palette (command 88h-8Fh)
  SSD1820A 128x65  wrong, lacks palette (command 88h-8Fh)
  SSD1821  128x81  wrong, lacks palette (command 88h-8Fh)
  SSD1850  128x65  could be correct (ysiz is good, but no double-buffering)
  SSD1851  128x81  as above, but more lines than needed
  SSD1852  128x128 would allow double-buffer, but extended commands are wrong
  SSD1854  128x160 wrong, uses 2-byte command B0h,YYh lacks extended commands
                   (also cmd 18h,20h,4xh,50h,60h-63h,64h,82h,83h,etc. differ)
  SSD1858  104x65  close, but lacks many extended commands
  SSD1859  128x81  could be correct (almost same as SSD1850)
But, Nintendo's firmware contains extended command F7h,02h (which isn't mentioned in any of the above datasheets).
And, the firmware seems to use two 64-line framebuffers at DisplayStart=0 and DisplayStart=64, ie. needing 128 lines in total, which leaves no space for the "icon" scanline (at least not addressable via cmd B0h+y).


DS Cart Infrared P-Walker Ports Accelerometer BMA150

Might do drilling machine, not good honking out paste pretty screenshot?
Official BMA150 register specs are in a Bosch-Captcha, which appears to be intended to fool humans and bots alike (text on hatched background, undefined color codes, increasingly unpleasant medusa-like details at closer look). Anyways, here's a plaintext-hack of the Bosch-Captcha:
  00h  Chip ID     (bit7-3=Unused, bit2-0=02h)
  01h  Version     (bit7-4=al_version, bit3-0=ml_version) (undefined values)
  02h  Acc X Low   (bit7-6=DataLsb, bit5-1=Unused, bit0=NewDataFlag)
  03h  Acc X High  (bit7-0=DataMsb)
  04h  Acc Y Low   (bit7-6=DataLsb, bit5-1=Unused, bit0=NewDataFlag)
  05h  Acc Y High  (bit7-0=DataMsb)
  06h  Acc Z Low   (bit7-6=DataLsb, bit5-1=Unused, bit0=NewDataFlag)
  07h  Acc Z High  (bit7-0=DataMsb)
  08h  Temperature (bit7-0=DataTempMsb) (Lsb not existing, except in Trimming?)
  09h  Status Flags     (see below)
  0Ah  Control Flags    (see below)
  0Bh  Config Flags     (see below)
  0Ch  LG Threshold     (bit7-0)
  0Dh  LG Duration      (bit7-0)
  0Eh  HG Threshold     (bit7-0)
  0Fh  HG Duration      (bit7-0)
  10h  Any Motion Threshold (bit7-0)
  11h  Misc Stuff       (bit7-6=AnyMotionDur, bit5-3=HG Hyst, bit2-0=LG Hyst)
  12h  Customer Reserved 1 (bit7-0)
  13h  Customer Reserved 2 (bit7-0)
  14h  Range/Bandwidth  (bit7-5=Reserved, bit4-3=Range, bit2-0=Bandwidth)
  15h  Misc Flags       (see below)
  16h  Trimming X Low   (bit7-6=OffsetLsb, bit5-0=Gain)
  17h  Trimming Y Low   (bit7-6=OffsetLsb, bit5-0=Gain)
  18h  Trimming Z Low   (bit7-6=OffsetLsb, bit5-0=Gain)
  19h  Trimming T Low   (bit7-6=OffsetLsb, bit5-0=Gain)
  1Ah  Trimming X High  (bit7-0=OffsetMsb)
  1Bh  Trimming Y High  (bit7-0=OffsetMsb)
  1Ch  Trimming Z High  (bit7-0=OffsetMsb)
  1Dh  Trimming T High  (bit7-0=OffsetMsb)
  1Eh-22h BST reserved  (official blank/green)
  23h     BST reserved  (official blank/white)
  24h-2Ah Not used      (official gray/dither)
  2Bh-3Dh EEPROM Defaults for Registers 0Bh-1Dh
  3Eh-42h BST reserved  (official blank/orange)
  43h-49h Not used      (official gray/dither)
  4Ah-4Fh Not mentioned (official not here)
  50h-7Fh BST reserved  (official blank/cyan)
Obscure Notes: Registers are 00h-06h,21h-22h,43h-7Fh are classifed as NOTHING, 07h-20h as IMAGE, and 23h-42h as EEPROM (whatever that crap means). Also, Registers 00h-15h are OPERATIONAL, 16h-3Dh are DEFAULT SETTING, 3Eh-7Fh are BOSCH SENSORTEC RESERVED.

Register 09h - Status Flags
  7   ST Result
  6-5 Not used (official piss/dither)
  4   Alert Phase
  3   LG_latched
  2   HG_latched
  1   LG_status
  0   HG_status

Register 0Ah - Control Flags
  7   Reserved (official gray/dither)
  6   Reset INT
  5   Update IMAGE
  4   EE_W (uh? maybe eeprom write?)
  3   Self Test 1
  2   Self Test 0
  1   Soft Reset
  0   Sleep

Register 0Bh - Config Flags
  7   Alert
  6   Any Motion
  5-4 Counter HG
  3-2 Counter LG
  1   Enable HG
  0   Enable LG

Register 15h - Misc Flags
  7   SPI4
  6   enable_adv_INT
  5   new_data_INT
  4   latch_INT
  3   shadow_dis
  2-1 wake_up_pause
  0   wake_up


DS Cart Infrared Component Lists

Gamecart for Walk with Me/Laufrhythmus
  Case "Nintendo, NTR-031. PAT. PEND., IMWPN1J12"
  PCB  "DA A-4  IRU01-10" (two layers) plus "IRL01-01 "(brown extra film layer)
  U1 32pin  "S906748-1, SanDisk, 11014-64B, P0A837.00, 0843, NTR-IMWP-1" (ROM)
  U2 32pin  "38600R, A06V, AH00167, 0832" (CPU, ROM 8Kbyte, RAM 0.5KByte)
  U3  5pin  "?" (OR-gate? flipflop?) (for forwarding SPI /CS to FLASH /CS)
  U4  8pin  "45PE80VG, HPAMZ V5, KOR 833X, ST e3" (SPI FLASH 1024 Kbytes)
  U1' 7pin  "5  S.. 9" IR transceiver (on brown film layer)
  X1  6pin  "737Wv"   ;7.37MHz?    /FLASH.CS --|""""|-- GND
  R1,R2,RA1 resistors                          | U3 |-- /SPI.CS (from NDS)
  C1,C2,C3,C4,C5,C6 capacitors         VDD33 --|____|-- U2.pinxxx
Note: The printed part number on the CPU is 38600R, which does officially have ROM 8Kbyte, RAM 0.5KByte (and the software does use only that much memory, but it does actually contain twice as much ROM and RAM, ie. it seems to be a 38602R chip... or, as the part number is wrong, it MIGHT even be a F38602 with FLASH memory?).
IR transceiver wiring: 1=GND, 2=CPU.pin24=TXD, 3=CPU.pin25=RXD, 4=CPU.pin26=PWDOWN, 5=NC, 6=GND, 7=VCC.

Gamecart for P-Letter Black
  PCB  "DI Y-1  IRC02-01" (two layers, without brown extra film layer)
  U1 32pin  "MXIC..." (ROM)
  U2 32pin  "..." (CPU, ROM 8Kbyte, RAM 0.5KByte)
  U3  5pin  "..." (OR-gate? flipflop?) (for forwarding SPI /CS to FLASH /CS)
  U4  8pin  "..." (SPI FLASH)
  U5  7pin  "..." IR transceiver
  X1  6pin  "..."
  R1,R2,RA1 resistors
  C1,C2,C3,C4,C5,C6 capacitors
More or less same as in Walk with Me, but without film layer, and with non-legible part numbers on existing photos.

Activity Meter (Actimeter in german) (Nintendo, 2008-2009)
NTR-IMWJ Aruite Wakaru Seikatsu Rhythm (JP)
NTR-IMWE Personal Trainer: Walking (US)
NTR-IMWP Walk with Me (EU) (Laufrhythmus in german)
NTR-IA8P Active Health with Carol Vorderman (EU)
  Case "Nintendo DS, NTR-027, (C) 2008 Nintendo, NTR-A-HC, Made in Japan"
  Case "CE ./ VCI, ACN 060 566 083, Nintendo"
  PCB  "NTR-DHC-01" (in water resistant case)
  Ux  32pin Side-A "38602R, F22V, AH04731, 0834" (CPU, ROM 16Kbyte, RAM 1KByte)
  U2  8pin  Side-B "564X, 48H3, 30" (SPI EEPROM 8Kbyte, ST M95640-W or similar)
  U3  7pin  Side-B "1  S.  9" IR transceiver
  ??  2pin  Side-A huge smd capacitor shaped thing, maybe analog 1-axis sensor?
  ??  2pin  Side-A huge smd capacitor shaped thing, maybe analog 1-axis sensor?
  Ux/Qx     Side-A many small chips with 3-6 pins and few markings
  Xx  3pin  Side-A "CB825"      ;32.768-kHz or 38.4-kHz Crystal Resonator?
  Yx  6pin  Side-A ":i] 3.68t"  ;3.68MHz (115.2kHz*32)
  C1..C34   Plenty capacitors
  R1..R28   Plenty resistors
  BTI 2pin  Side-B Battery holder (for CR2032 H, 3V)
  Button    Side-A Push button (communication button)
  |<  4pin  Side-A Two color LED
Activity Meter Instruction Booklet, 310 pages: "Do not disassemble or attempt to repair the Activity Meter yourself. Doing so could result in injury or electrocution."
IR transceiver wiring: 1=BAT+, 2=TX-RC=NC?, 3=1K-to-CPU.pin25=RXD, 4=CPU.pin26=PWDOWN, 5=CPU.pin24=TXD, 6=?, 7=GND.

P-Walker (Nintendo, 2009)
NTR-IPKx/NTR-IPGx P-letter HeartGold/SoulSilver
TWL-IRBO/TWL-IRAO P-letter Black/White
TWL-IREO/TWL-IRDO P-letter Black/White 2
  Case "?"
  PCB "NTR-PHC-01" (with green solder stop & unconventional black text layer)
  U1  32pin Side-B "F38606, F04V, AK04052, 0942" (CPU,FLASH 48Kbyte,RAM 2KByte)
  U2  4pin  Side-A "?"
  U3  4pin  Side-A "?"
  U4  4pin  Side-A "M_RA"
  U5  7pin  Side-B IR transceiver
  U6  8pin  Side-A "Sxxxx, xxxx" (maybe SPI EEPROM?)
  U7  12pin Side-B "043, A939, 021" (accelerometer?) (Bosch BMA150 ?)
  U8  5pin  Side-A "?"
  Q1  6pin  Side-A "Z4"
  D1  3pin  Side-A "?" dual diode or so
  X1  3pin  Side-B "EAJJ"       ;32.768-kHz or 38.4-kHz Crystal Resonator?
  Y1  6pin  Side-B "3.68"       ;3.68MHz (115.2kHz*32)
  BZ1 2pin  Side-B wires to piezo speaker (aka buzzer)
  CN1 14pin Side-A LCD connector 14pin? or 2x14pin? (without backlight)
            (with SSD1850 display controller (or similar) inside of LCD screen)
            (96x64 2-bit greyscale screen) (reportedly with SPI bus)
  BT+/-     Side-B Battery contacts for removeable battery (for CR2032, 3V)
  C1..C29   Plenty capacitors
  R1..R22   Plenty resistors
  SW's      Side-A Three buttons (left, center, right)

Fit Meter (for Wii Fit U) (2013?)
  PCB "SAMU-01" (with green solder stop & unconventional black text layer)
  U1  40pin Side-B "R5F101EEA, 1242KE415, SINGAPORE" (RL78 CPU)
  U2  7pin  Side-B "845G2947" IR transceiver, with metal shield
  U3  16pin Side-B (not installed)
  U4  16pin Side-A --UNKNOWN MARKING, BAD PHOTO-- maybe accelerometer
  U5  4pin  Side-A --UNKNOWN MARKING, BAD PHOTO-- maybe SPI EEPROM/FLASH
  U6  4pin  Side-A (not installed)
  U7  7pin  Side-B "I357, U231, 094" whatever, in metal shielded case
  X1  3pin  Side-B "EABL" crystal or so
  BZ1 2pin  Side-B wires to piezo speaker (aka buzzer)
  CN1 14pin Side-A LCD connector 14pin? or 2x14pin? (without backlight)
  BT+/-     Side-B Battery contacts for removeable battery
  Q1  3pin  Side-A Transistor or so
  D1..D2    Side-A Diodes (3pin each)
  C1..C29   Plenty capacitors
  R1..R22   Plenty resistors
  SW's      Side-A Three buttons (left, center, right)
Similar as P-Walker, but uses a RL78 CPU (alike 3DS MCU) instead of H8/386.

The IR transceivers do resemble RPM841-H16 or similar (as used in 3DS). Observe that 7pin transceiver pinouts are NOT same. Walk with Me, Activity Meter, and 3DS all have different 7pin transceiver wirings (and, some have additional metal shields).


H8/386 SFRs

H8/386 Special Function Registers at F000h and up
  F020h FLMCR1  FLASH Memory Control 1
  F021h FLMCR2  FLASH Memory Control 2
  F022h FLPWCR  FLASH Memory Power Control
  F023h EBR1    FLASH Erase Block 1
  F02Bh FENR    FLASH Memory Enable
  F067h RTCFLG  RTC Interrupt Flag
  F068h RSECDR  RTC Seconds / Free running counter
  F069h RMINDR  RTC Minutes
  F06Ah RHRDR   RTC Hours
  F06Bh RWKDR   RTC Day-of-week
  F06Ch RTCCR1  RTC Control 1
  F06Dh RTCCR2  RTC Control 2
  F06Fh RTCCSR  RTC Clock Source Select
  F078h ICCR1   I2C Bus Control 1
  F079h ICCR2   I2C Bus Control 2
  F07Ah ICMR    I2C Bus Mode
  F07Bh ICIER   I2C Bus Interrupt Enable
  F07Ch ICSR    I2C Bus Status
  F07Dh SAR     I2C Slave Address
  F07Eh ICDRT   I2C Bus Transmit Data
  F07Fh ICDRR   I2C Bus Receive Data
  F085h PFCR    System Port Function Control
  F086h PUCR8   Port 8 Pull-up Control
  F087h PUCR9   Port 9 Pull-up Control
  F08Ch PODR9   Port 9 Open-drain Control
  F0D0h TMB1    Timer B1 Mode
  F0D1h TC/LB1  Timer B1 Counter (R) / Load (W)
  F0DCh CMCR0   Compare Control 0
  F0DDh CMCR1   Compare Control 1
  F0DEh CMDR    Compare Data
  F0E0h SSCRH   SPI Synchronous Serial Control H     (AccessState3)
  F0E1h SSCRL   SPI Synchronous Serial Control L     (AccessState3)
  F0E2h SSMR    SPI Synchronous Serial Mode          (AccessState3)
  F0E3h SSER    SPI Synchronous Serial Enable        (AccessState3)
  F0E4h SSSR    SPI Synchronous Serial Status        (AccessState3)
  F0E9h SSRDR   SPI Synchronous Serial Receive Data  (AccessState3)
  F0EBh SSTDR   SPI Synchronous Serial Transmit Data (AccessState3)
  F0F0h TMRW    Timer W Mode
  F0F1h TCRW    Timer W Control
  F0F2h TIERW   Timer W Interrupt Enable
  F0F3h TSRW    Timer W Status
  F0F4h TIOR0   Timer W I/O control 0
  F0F5h TIOR1   Timer W I/O control 1
  F0F6h TCNT    Timer W Counter   (16bit)
  F0F8h GRA     Timer W General A (16bit)
  F0FAh GRB     Timer W General B (16bit)
  F0FCh GRC     Timer W General C (16bit)
  F0FEh GRD     Timer W General D (16bit)
H8/386 Special Function Registers at FF80h and up, with [FFnn] & [FFnn].bitno
  FF8Ch ECPWCR  Async Event Counter PWM Compare (16bit)
  FF8Eh ECPWDR  Async Event Counter PWM Data (16bit)
  FF91h SPCR    IrDA UART Serial 3 Port Control
  FF92h AEGSR   Async Event Input Pin Edge Select
  FF94h ECCR    Async Event Counter Control
  FF95h ECCSR   Async Event Counter Control/Status
  FF96h ECH     Async Event Counter H
  FF97h ECL     Async Event Counter L
  FF98h SMR3    IrDA UART Serial 3 Mode          (AccessState3)
  FF99h BRR3    IrDA UART Serial 3 Bit Rate      (AccessState3)
  FF9Ah SCR3    IrDA UART Serial 3 Control       (AccessState3)
  FF9Bh TDR3    IrDA UART Serial 3 Transmit Data (AccessState3)
  FF9Ch SSR3    IrDA UART Serial 3 Status        (AccessState3)
  FF9Dh RDR3    IrDA UART Serial 3 Receive Data  (AccessState3)
  FFA6h SEMR    IrDA UART Serial 3 Extended Mode (AccessState3)
  FFA7h IrCR    IrDA Control
  FFB0h TMWD    Timer WD Watchdog Mode
  FFB1h TCSRWD1 Timer WD Watchdog Control/Status 1
  FFB2h TCSRWD2 Timer WD Watchdog Control/Status 2
  FFB3h TCWD    Timer WD Watchdog Counter
  FFBCh ADRR    A/D Converter Result (16bit)
  FFBEh AMR     A/D Converter Mode
  FFBFh ADSR    A/D Converter Start
  FFC0h PMR1    Port 1 Mode
  FFC2h PMR3    Port 3 Mode
  FFCAh PMRB    Port B Mode
  FFD4h PDR1    Port 1 Data
  FFD6h PDR3    Port 3 Data
  FFDBh PDR8    Port 8 Data
  FFDCh PDR9    Port 9 Data
  FFDEh PDRB    Port B Data
  FFE0h PUCR1   Port 1 Pull-up Control
  FFE1h PUCR3   Port 3 Pull-up Control
  FFE4h PCR1    Port 1 Control
  FFE6h PCR3    Port 3 Control
  FFEBh PCR8    Port 8 Control
  FFECh PCR9    Port 9 Control
  FFF0h SYSCR1  System Control 1
  FFF1h SYSCR2  System Control 2
  FFF2h IEGR    Interrupt Edge Select
  FFF3h IENR1   Interrupt Enable 1
  FFF4h IENR2   Interrupt Enable 2
  FFF5h OSCCR   System Oscillator Control
  FFF6h IRR1    Interrupt Flag 1
  FFF7h IRR2    Interrupt Flag 2
  FFFAh CKSTPR1 Clock Stop 1
  FFFBh CKSTPR2 Clock Stop 2


H8/386 Exception Vectors

H8/386 Exception Vectors (Vector 0000h has highest priority, 004Eh lowest)
Below are for Normal Mode with 16bit addressing (Extended Mode has 32bit vectors at 0000h..009Fh accordingly).
  0000h Reset/Watchdog
  0002h Reserved
  0004h Reserved
  0006h Reserved
  0008h Reserved
  000Ah Reserved
  000Ch Reserved
  000Eh External NMI interrupt
  0010h Trap 0 opcode
  0012h Trap 1 opcode
  0014h Trap 2 opcode
  0016h Trap 3 opcode
  0018h Reserved
  001Ah CPU Direct transition by executing SLEEP
  001Ch Reserved
  001Eh Reserved
  0020h External IRQ0 interrupt
  0022h External IRQ1 interrupt
  0024h External IRQAEC interrupt
  0026h Reserved
  0028h Reserved
  002Ah Comparator COMP0
  002Ch Comparator COMP1
  002Eh RTC per 0.25 seconds (4Hz)  ;0.25-second overflow
  0030h RTC per 0.5 seconds (2Hz)   ;0.5-second overflow
  0032h RTC per second (1Hz)        ;Second periodic overflow
  0034h RTC per minute              ;Minute periodic overflow
  0036h RTC per hour                ;Hour periodic overflow
  0038h RTC per day                 ;Day-of-week periodic overflow
  003Ah RTC per week (7 days)       ;Week periodic overflow
  003Ch RTC Free-running overflow
  003Eh WDT overflow (interval timer)
  0040h Asynchronous event counter overflow
  0042h Timer B1 Overflow
  0044h Serial SPI (or IIC2) (aka I2C ?)
  0046h Timer W Overflow or Capture/compare A,B,C,D
  0048h Reserved
  004Ah IrDA UART Serial 3
  004Ch A/D Conversion end
  004Eh Reserved
Note: The SSU (aka SPI) and IIC (aka I2C) share the same vector address. When using the IIC, shift the SSU to standby mode using CKSTPR2.


H8/300H Operands

CPU Registers
  R0..R6  32bit General Purpose   ;\can be alternately used as
  R7 (SP) 32bit Stack Pointer     ;/8bit/16bit registers (see below)
  PC      24bit Program Counter
  CCR     8bit  Flags (occupies 16bit when pushed/stored in memory)
Registers R0..R7 can be split into 8bit/16bit registers (alike 80x86 registers):
  .-----------------------.
  | ERx                   | 32bit  (ERx)
  |-----------+-----------|
  | Ex        | Rx        | 16bit  (Rx)
  '-----------+-----+-----|
              ' RxH | RxL | 8bit   (RxB)
              '-----'-----'
There are no opcodes for splitting upper 16bit in Ex into 8bit ExL,ExH (except, the sign/zero-extend opcodes seem to allow to extend ExL to Ex).

Normal and Extended Mode
The CPU can be wired to two different addressing modes:
  Normal Mode   --> 16bit addressing (default)
  Extended Mode --> 24bit addressing
Normal mode is usually used (the CPU has less than 64K ROM/RAM anyways), the opcodes with [er0..er7] memory addressing are then actually accessing [r0..r7], ie. the upper 16bit in e0..e7 are ignored (and can be used for general purpose data).
Extended mode, if it were ever used, uses the lower 24bit of er0..er7 for [er0..er7] addressing, and CALL/RET and indirect JMP opcodes are a bit slower, and exception vectors are 32bit wide.

Memory Addressing
Data is stored in Big-Endian. 16bit/32bit values must be stored at even addresses (with bit0 cleared) (there is no need to clear bit1 for 32bit values, namely, push/pop work regardless of bit1).
  Native        Nocash
  @aa:8         [FFaa]        Memory at FF00h..FFFFh (upper RAM and SFR's)
  @aa:16        [nnnn]
  @aa:24        [nnnnnn]
  @Erm          [Erm]
  @(d:16,ERm)   [ERm+nnnn]
  @(d:24,ERm)   [ERm+nnnnnn]
  @ERm+         [ERm+]          Memory access with post-increment
  @-ERm         [ERm-]          Memory access with pre-decrement
  (implied)     [ER6+],[ER5+]   Memory block transfer (EEPMOV)

Bit Addressing
  Native        Nocash
  #nn:8,@aa:8   [FFaa].n
  RnB,@aa:8     [FFaa].RnB
  #nn:8,RdB     RdB.n
  RnB,RdB       RdB.RnB
Note: The "#nn:8" suggests native syntax to use "#0x80" to select bit7, however, the existing disassembler does instead use "#7".


H8/300H Opcodes

All opcodes are multiples of 2 bytes (2,4,6,8,10 bytes), all opcodes should be always located at even addresses (ie. bit0 of jump address/disp operands should be always 0).

Register Encoding
  0..7  8bit Registers R0H..R7H  (bit8-15)     ;\RxB
  8..F  8bit Registers R0L..R7L  (bit0-7)      ;/
  0..7  16bit Registers R0..R7   (bit0-15)     ;\Rx
  8..F  16bit Registers E0..E7   (bit16-31)    ;/
  0..7  32bit Registers ER0..ER7 (bit0-31)     ;-ERx (in normal opcodes)
  8..F  32bit Registers ER0..ER7 (bit0-31)     ;-ERx (in opcodes marked *m,*s)

H8/300H Main Opcodes
  Opcode             Native                  Nocash             States IxHUNZVC
  0..                --> Misc 0xxx
  1..                --> Misc 1xxx
  2dnn               MOV.B @aa:8,RdB         MOV.B RdB,[FFaa]        4 ----nz0-
  3snn               MOV.B Rs,@aa:8          MOV.B [FFaa],Rs         4 ----nz0-
  4cnn               --> Jumps (relative 8bit range)
  5..                --> Jumps (various) and unsigned mul/div
  6..                --> Misx 6xxx
  7..                --> Misc 7xxx
  8dnn               ADD.B #nn:8,RdB         ADD.B RdB,nn            2 --h-nzvc
  9dnn               ADDX  #nn:8,RdB         ADC.B RdB,nn            2 --h-nzvc
  Adnn               CMP.B #nn:8,RdB         CMP.B RdB,nn            2 --h-nzvc
  Bdnn               SUBX  #nn:8,RdB         SBC.B RdB,nn            2 --h-nzvc
  Cdnn               OR.B  #nn:8,RdB         OR.B  RdB,nn            2 ----nz0-
  Ddnn               XOR.B #nn:8,RdB         XOR.B RdB,nn            2 ----nz0-
  Ednn               AND.B #nn:8,RdB         AND.B RdB,nn            2 ----nz0-
  Fdnn               MOV.B #nn:8,RdB         MOV.B RdB,nn            2 ----nz0-

H8/300H Misc 0xxx
  0000               NOP                     NOP                     2 --------
  01..               --> Misc 01xx ;Memory Load/Store (32bit ERn) etc.
  020d               STC.B CCR,RdB           MOV.B RdB,CCR           2 --------
  030s               LDC.B RsB,CCR           MOV.B CCR,RsB           2 xxxxxxxx
  04nn               ORC   #nn:8,CCR         OR.B  CCR,nn            2 xxxxxxxx
  05nn               XORC  #nn:8,CCR         XOR.B CCR,nn            2 xxxxxxxx
  06nn               ANDC  #nn:8,CCR         AND.B CCR,nn            2 xxxxxxxx
  07nn               LDC.B #nn:8,CCR         MOV.B CCR,nn            2 xxxxxxxx
  08sd               ADD.B RsB,RdB           ADD.B RdB,RsB           2 --h-nzvc
  09sd               ADD.W Rs,Rd             ADD.W Rd,Rs             2 --h-nzvc
  0A..               --> Increment/Add
  0B..               --> Increment/Add
  0Csd               MOV.B RsB,RdB           MOV.B RdB,RsB           2 ----nz0-
  0Dsd               MOV.W Rs,Rd             MOV.W Rd,Rs             2 ----nz0-
  0Esd               ADDX  RsB,RdB           ADC.B RdB,RsB           2 --h-nzvc
  0F0d               DAA   RdB               DAA.B RdB               2 --U-nzUc
  0Fsd            *s MOV.L ERs,ERd           MOV.L ERd,ERs           2 ----nz0-

H8/300H Misc 01xx ;Memory Load/Store (32bit ERn) etc.
  010069md           MOV.L @ERm,ERd          MOV.L ERd,[ERm]         8 ----nz0-
  014069m0           LDC.W @ERm,CCR          MOV.W CCR,[ERm]         6 xxxxxxxx
  010069ms        *m MOV.L ERs,@ERm          MOV.L [ERm],ERs         8 ----nz0-
  014069m0        *m STC.W CCR,@ERm          MOV.W [ERm],CCR         6 --------
  01006B0dnnnn       MOV.L @aa:16,ERd        MOV.L ERd,[nnnn]       10 ----nz0-
  01406B00nnnn       LDC.W @aa:16,CCR        MOV.W CCR,[nnnn]        8 xxxxxxxx
  01006B2d00nnnnnn   MOV.L @aa:24,ERd        MOV.L ERd,[nnnnnn]     12 ----nz0-
  01406B2000nnnnnn   LDC.W @aa:24,CCR        MOV.W CCR,[nnnnnn]     10 xxxxxxxx
  01006B8snnnn       MOV.L ERs,@aa:16        MOV.L [nnnn],ERs       10 ----nz0-
  01406B80nnnn       STC.W CCR,@aa:16        MOV.W [nnnn],CCR        8 --------
  01006BAs00nnnnnn   MOV.L ERs,@aa:24        MOV.L [nnnnnn],ERs     12 ----nz0-
  01406BA000nnnnnn   STC.W CCR,@aa:24        MOV.W [nnnnnn],CCR     10 --------
  01006Dmd           MOV.L @ERm+,ERd         MOV.L ERd,[ERm+]       10 ----nz0-
  01406Dm0           LDC.W @ERm+,CCR         MOV.W CCR,[ERm+]        8 xxxxxxxx
  01006Dms        *m MOV.L ERs,@-ERm         MOV.L [ERm-],ERs       10 ----nz0-
  01406Dm0        *m STC.W CCR,@-ERm         MOV.W [ERm-],CCR        8 --------
  01006Fmdnnnn       MOV.L @(d:16,ERm),ERd   MOV.L ERd,[ERm+nnnn]   10 ----nz0-
  01406Fm0nnnn       LDC.W @(d:16,ERm),CCR   MOV.W CCR,[ERm+nnnn]    8 xxxxxxxx
  01006Fmsnnnn    *m MOV.L ERs,@(d:16,ERm)   MOV.L [ERm+nnnn],ERs   10 ----nz0-
  01406Fm0nnnn    *m STC.W CCR,@(d:16,ERm)   MOV.W [ERm+nnnn],CCR    8 --------
  010078m06B2d00..   MOV.L @(d:24,ERm),ERd   MOV.L ERd,[ERm+nnnnnn] 14 ----nz0-
  014078m06B2000..   LDC.W @(d:24,ERm),CCR   MOV.W CCR,[ERm+nnnnnn] 12 xxxxxxxx
  010078m06BAs00..*? MOV.L ERs,@(d:24,ERm)   MOV.L [ERm+nnnnnn],ERs 14 ----nz0-
  014078m06BA000..   STC.W CCR,@(d:24,ERm)   MOV.W [ERm+nnnnnn],CCR 12 --------
  0180               SLEEP                   HALT                    2 --------
  01C050sd           MULXS.B RsB,Rd          SMUL.B Rd,RsB          16 ----nz--
  01C052sd           MULXS.W Rs,ERd          SMUL.W ERd,Rs          24 ----nz--
  01D051sd           DIVXS.B RsB,Rd          SDIV.B Rd,RsB          16 ----nz--
  01D053sd           DIVXS.W Rs,ERd          SDIV.W ERd,Rs          24 ----nz--
  01F064sd           OR.L    ERs,ERd         OR.L   ERd,ERs          4 ----nz0-
  01F065sd           XOR.L   ERs,ERd         XOR.L  ERd,ERs          4 ----nz0-
  01F066sd           AND.L   E?Rs,ERd        AND.L  ERd,ERs          4 ----nz0-

H8/300H Misc 1xxx
  10..               --> Shift/Rotate (shift left)
  11..               --> Shift/Rotate (shift right)
  12..               --> Shift/Rotate (rotate left)
  13..               --> Shift/Rotate (rotate right)
  14sd               OR.B  RsB,RdB           OR.B  RdB,RsB           2 ----nz0-
  15sd               XOR.B RsB,RdB           XOR.B RdB,RsB           2 ----nz0-
  16sd               AND.B RsB,RdB           AND.B RdB,RsB           2 ----nz0-
  17..               --> Not/Neg/Extend
  18sd               SUB.B RsB,RdB           SUB.B RdB,RsB           2 --h-nzvc
  19sd               SUB.W Rs,Rd             SUB.W Rd,Rs             2 --h-nzvc
  1A..               --> Decrement/Subtract
  1B..               --> Decrement/Subtract
  1Csd               CMP.B RsB,RdB           CMP.B RdB,RsB           2 --h-nzvc
  1Dsd               CMP.W Rs,Rd             CMP.W Rd,Rs             2 --h-nzvc
  1Esd               SUBX  RsB,RdB           SBC.B RdB,RsB           2 --h-nzvc
  1F0d               DAS   RdB               DAS.B RdB               2 --U-nzU?
  1Fsd            *s CMP.L ERs,ERd           CMP.L ERd,ERs           2 --h-nzvc

H8/300H Shift/Rotate (Shift Logical/Arithmetic, Rotate through Carry or not)
  100d               SHLL.B RdB              SHL.B RdB               2 ----nz0c
  101d               SHLL.W Rd               SHL.W Rd                2 ----nz0c
  103d               SHLL.L ERd              SHL.L ERd               2 ----nz0c
  108d               SHAL.B RdB              SAL.B RdB               2 ----nzvc
  109d               SHAL.W Rd               SAL.W Rd                2 ----nzvc
  10Bd               SHAL.L ERd              SAL.L ERd               2 ----nzvc
  110d               SHLR.B RdB              SHR.B RdB               2 ----0z0c
  111d               SHLR.W Rd               SHR.W Rd                2 ----0z0c
  113d               SHLR.L ERd              SHR.L ERd               2 ----0z0c
  118d               SHAR.B RdB              SAR.B RdB               2 ----nz0c
  119d               SHAR.W Rd               SAR.W Rd                2 ----nz0c
  11Bd               SHAR.L ERd              SAR.L ERd               2 ----nz0c
  120d               ROTXL.B RdB             RCL.B RdB               2 ----nz0c
  121d               ROTXL.W Rd              RCL.W Rd                2 ----nz0c
  123d               ROTXL.L ERd             RCL.L ERd               2 ----nz0c
  128d               ROTL.B RdB              ROL.B RdB               2 ----nz0c
  129d               ROTL.W Rd               ROL.W Rd                2 ----nz0c
  12Bd               ROTL.L ERd              ROL.L ERd               2 ----nz0c
  130d               ROTXR.B RdB             RCR.B RdB               2 ----nz0c
  131d               ROTXR.W Rd              RCR.W Rd                2 ----nz0c
  133d               ROTXR.L ERd             RCR.L ERd               2 ----nz0c
  138d               ROTR.B RdB              ROR.B RdB               2 ----nz0c
  139d               ROTR.W Rd               ROR.W Rd                2 ----nz0c
  13Bd               ROTR.L ERd              ROR.L ERd               2 ----nz0c

H8/300H Not/Neg/Extend
  170d               NOT.B RdB               NOT.B RdB               2 ----nz0-
  171d               NOT.W Rd                NOT.W Rd                2 ----nz0-
  173d               NOT.L Rd                NOT.L ERd               2 ----nz0-
  175d               EXTU.W Rd               UMOV Rd,RdL ;or Ed,EdL? 2 ----0z0-
  177d               EXTU.L ERd              UMOV ERd,Rd             2 ----0z0-
  178d               NEG.B RdB               NEG.B RdB               2 --h-nzvc
  179d               NEG.W Rd                NEG.W Rd                2 --h-nzvc
  17Bd               NEG.L Rd                NEG.L ERd               2 --h-nzvc
  17Dd               EXTS.W Rd               SMOV Rd,RdL ;or Ed,EdL? 2 ----nz0-
  17Fd               EXTS.L ERd              SMOV ERd,Rd             2 ----nz0-

H8/300H Increment/Add and Decrement/Subtract
  0A0d               INC.B RdB               INC.B RdB,1             2 ----nzv-
  1A0d               DEC.B RdB               DEC.B RdB,1             2 ----nzv-
  0Asd            *s ADD.L E?Rs,ERd          ADD.L ERd,ERs           2 --h-nzvc
  1Asd            *s SUB.L ERs,ERd           SUB.L ERd,ERs           2 --h-nzvc
  0B0d               ADDS  #1,ERd            INC.S ERd,1             2 --------
  1B0d               SUBS  #1,ERd            DEC.S ERd,1             2 --------
  0B5d               INC.W #1,Rd             INC.W Rd,1              2 ----nzv-
  1B5d               DEC.W #1,Rd             DEC.W Rd,1              2 ----nzv-
  0B7d               INC.L #1,ERd            INC.L ERd,1             2 ----nzv-
  1B7d               DEC.L #1,ERd            DEC.L ERd,1             2 ----nzv-
  0B8d               ADDS  #2,ERd            INC.S ERd,2             2 --------
  1B8d               SUBS  #2,ERd            DEC.S ERd,2             2 --------
  0B9d               ADDS  #4,ERd            INC.S ERd,4             2 --------
  1B9d               SUBS  #4,ERd            DEC.S ERd,4             2 --------
  0BDd               INC.W #2,Rd             INC.W Rd,2              2 ----nzv-
  1BDd               DEC.W #2,Rd             DEC.W Rd,2              2 ----nzv-
  0BFd               INC.L #2,ERd            INC.L ERd,2             2 ----nzv-
  1BFd               DEC.L #2,ERd            DEC.L ERd,2             2 ----nzv-

H8/300H Jump Opcodes and Unsigned Mul/Div
  50sd               MULXU.B RsB,Rd          UMUL.B Rd,RsB          14 ----nz--
  51sd               DIVXU.B RsB,Rd          UDIV.B Rd,RsB          14 ----nz--
  52sd               MULXU.W Rs,ERd          UMUL.W ERd,Rs          22 ----nz--
  53sd               DIVXU.W Rs,ERd          UDIV.W ERd,Rs          22 ----nz--
  5470               RTS                     RET                  8,10 --------
  55nn               BSR d:8                 CALL $+/-nn           6,8 --------
  5670               RTE                     RETI                   10 xxxxxxxx
  57n0               TRAPA #n:2              TRAP 0..3 ;[0010h+n*2] 14 1x------
  58c0nnnn           --> Jumps (relative 16bit range)
  59s0               JMP @ERs                JMP  ERs                4 --------
  5Annnnnn           JMP @aa:24              JMP  nnnnnn             6 --------
  5Baa               JMP @@aa:8              JMP  [FFaa]          8,10 --------
  5C00nnnn           BSR d:16                CALL $+/-nnnn        8,10 --------
  5Ds0               JSR @ERs                CALL ERs              6,8 --------
  5Ennnnnn           JSR @aa:24              CALL nnnnnn          8,10 --------
  5Faa               JSR @@aa:8              CALL [FFaa]          8,12 --------

H8/300H Relative Jump Opcodes (8bit/16bit range)
  4cnn               Bcc d:8                 Jcc   $+/-nn            4 --------
  58c0nnnn           Bcc d:16                Jcc   $+/-nnnn          6 --------
The 4bit condition code can be:
  0  BRA or BT    JMP        ;always/true
  1  BRN or BF    -          ;never/false
  2  BHI          JA         ;unsigned-above
  3  BLS          JBE        ;unsigned-below-equal
  4  BCC or BHS   JNC or JAE ;unsigned-above-equal
  5  BCS or BLO   JC  or JB  ;unsigned-below
  6  BNE          JNZ or JNE ;not equal/zero
  7  BEQ          JZ  or JE  ;equal/zero
  8  BVC          JNO        ;signed-no overflow
  9  BVS          JO         ;signed-n-overflow
  A  BPL          JNS        ;signed-n-plus
  B  BMI          JS         ;signed-n-minus
  C  BGE          JGE        ;signed-n-greater-eq
  D  BLT          JL         ;signed-n-less
  E  BGT          JG         ;signed-n-greater
  F  BLE          JLE        ;signed-n-less-equal
Destination address should be equal (although, the opcodes are weirdly using byte offsets, hence limiting 8bit range to even 7bit range).
The execution time for condition=false is unknown. The time for BRN (always false) is said to be equal to two NOPs (but unknown why one would use that opcode, and if it does refer to the BRN opcode with 8bit and/or 16bit range).

H8/300H Misc 6xxx
  60nd               BSET   RnB,RdB          SET   RdB.RnB           2 --------
  61nd               BNOT   RnB,RdB          NOT   RdB.RnB           2 --------
  62nd               BCLR   RnB,RdB          CLR   RdB.RnB           2 --------
  63nd               BTST   RnB,RdB          TST   RdB.RnB           2 -----z--
  64sd               OR.W   Rs,Rd            OR.W  Rd,Rs             2 ----nz0-
  65sd               XOR.W  Rs,Rd            XOR.W Rd,Rs             2 ----nz0-
  66sd               AND.W  Rs,Rd            AND.W Rd,Rs             2 ----nz0-
  67nd            *i B{I}ST #nn:8,RdB        MOV   RdB.n,{not} C     2 --------
  68md               MOV.B  @ERm,RdB         MOV.B RdB,[ERm]         4 ----nz0-
  68ms            *m MOV.B  RsB,@ERm         MOV.B [ERm],RsB         4 ----nz0-
  69md               MOV.W  @ERm,Rd          MOV.W Rd,[ERm]          4 ----nz0-
  69ms            *m MOV.W  Rs,@ERm          MOV.W [ERm],Rs          4 ----nz0-
  6A0dnnnn           MOV.B  @aa:16,RdB       MOV.B RdB,[aaaa]        6 ----nz0-
  6A2d00nnnnnn       MOV.B  @aa:24,RdB       MOV.B RdB,[aaaaaa]      8 ----nz0-
  6A4dnnnn           MOVFPE @aa:16,RdB       MOV.B RdB,[periph:aaaa] * ----nz0-
  6A8snnnn           MOV.B  RsB,@aa:16       MOV.B [aaaa],RsB        6 ----nz0-
  6AAs00nnnnnn       MOV.B  RsB,@aa:24       MOV.B [aaaaaa],RsB      8 ----nz0-
  6ACsnnnn           MOVTPE RsB,@aa:16       MOV.B [periph:aaaa],RsB * ----nz0-
  6B0dnnnn           MOV.W  @aa:16,Rd        MOV.W Rd,[aaaa]         6 ----nz0-
  6B2d00nnnnnn       MOV.W  @aa:24,Rd        MOV.W Rd,[aaaaaa]       8 ----nz0-
  6B8snnnn           MOV.W  Rs,@aa:16        MOV.W [aaaa],Rs         6 ----nz0-
  6BAs00nnnnnn       MOV.W  Rs,@aa:24        MOV.W [aaaaaa],Rs       8 ----nz0-
  6Cmd               MOV.B  @ERm+,RdB        MOV.B RdB,[ERm+]        6 ----nz0-
  6Cms            *m MOV.B  RsB,@-ERm        MOV.B [ERm-],RsB        6 ----nz0-
  6Dmd               MOV.W  @ERm+,RdB        MOV.W RdB,[ERm+]        6 ----nz0-
  6Dms            *m MOV.W  RsB,@-ERm        MOV.W [ERm-],RsB        6 ----nz0-
  6Emdnnnn           MOV.B  @(d:16,ERm),RdB  MOV.B RdB,[ERm+nnnn]    6 ----nz0-
  6Emsnnnn        *m MOV.B  RsB,@(d:16,ERm)  MOV.B [ERm+nnnn],RsB    6 ----nz0-
  6Fmdnnnn           MOV.W  @(d:16,ERm),Rd   MOV.W Rd,[ERm+nnnn]     6 ----nz0-
  6Fmsnnnn        *m MOV.W  Rs,@(d:16,ERm)   MOV.W [ERm+nnnn],Rs     6 ----nz0-

H8/300H Misc 7xxx
  70nd               BSET  #nn:8,RdB         SET   RdB.n             2 --------
  71nd               BNOT  #nn:8,RdB         NOT   RdB.n             2 --------
  72nd               BCLR  #nn:8,RdB         CLR   RdB.n             2 --------
  73nd               BTST  #nn:8,RdB         TST   RdB.n             2 -----z--
  74nd            *i B{I}OR  #nn:8,RdB       OR    C,{not} RdB.n     2 -------c
  75nd            *i B{I}XOR #nn:8,RdB       XOR   C,{not} RdB.n     2 -------c
  76nd            *i B{I}AND #nn:8,RdB       AND   C,{not} RdB.n     2 -------c
  77nd            *i B{I}LD  #nn:8,RdB       MOV   C,{not} RdB.n     2 -------c
  78m06A2d00nnnnnn   MOV.B @(d:24,ERm),RdB   MOV.B RdB,[ERm+nnnnnn] 10 ----nz0-
  78m06AAs00nnnnnn   MOV.B RsB,@(d:24,ERm)   MOV.B [ERm+nnnnnn],RsB 10 ----nz0-
  78m06B2d00nnnnnn   MOV.W @(d:24,ERm),Rd    MOV.W Rd,[ERm+nnnnnn]  10 ----nz0-
  78m06BAs00nnnnnn*? MOV.W Rs,@(d:24,ERm)    MOV.W [ERm+nnnnnn],Rs  10 ----nz0-
  79..               --> Immediate (16bit)
  7A..               --> Immediate (32bit)
  7B5C498F           EEPMOV.B              MOV [ER6+],[ER5+],R4L- 8+4n --------
  7BD4598F           EEPMOV.W              MOV [ER6+],[ER5+],R4-  8+4n --------
  7C..               --> Bit Operations (Memory at ERm)
  7D..               --> Bit Operations (Memory at ERm)
  7E..               --> Bit Operations (Memory at FFaa)
  7F..               --> Bit Operations (Memory at FFaa)
The EEPMOV opcodes were originally intended to write to an EEPROM, but they can be used as generic memory transfers with number of bytes in R4L or R4. EEPMOV.B is blocking IRQs and NMIs. EEPMOV.W is also blocking IRQs, however, EEPMOV.W gets aborted upon NMI (without resuming the transfer upon return, so software must manually retry if R4=nonzero after executing EEPMOV.W in combination with NMI sources).

H8/300H Immediate 16bit/32bit
  790dnnnn           MOV.W #nnnn:16,Rd       MOV.W Rd,nnnn           4 ----nz0-
  791dnnnn           ADD.W #nnnn:16,Rd       ADD.W Rd,nnnn           4 --h-nzvc
  792dnnnn           CMP.W #nnnn:16,Rd       CMP.W Rd,nnnn           4 --h-nzvc
  793dnnnn           SUB.W #nnnn:16,Rd       SUB.W Rd,nnnn           4 --h-nzvc
  794dnnnn           OR.W  #nnnn:16,Rd       OR.W  Rd,nnnn           4 ----nz0-
  795dnnnn           XOR.W #nnnn:16,Rd       XOR.W Rd,nnnn           4 ----nz0-
  796dnnnn           AND.W #nnnn:16,Rd       AND.W Rd,nnnn           4 ----nz0-
  7A0dnnnnnnnn       MOV.L #nnnnnnnn:32,E?Rd MOV.L E?Rd,nnnnnnnn     6 ----nz0-
  7A1dnnnnnnnn       ADD.L #nnnnnnnn:32,ERd  ADD.L ERd,nnnnnnnn      6 --h-nzvc
  7A2dnnnnnnnn       CMP.L #nnnnnnnn:32,ERd  CMP.L ERd,nnnnnnnn      6 --h-nzvc
  7A3dnnnnnnnn       SUB.L #nnnnnnnn:32,ERd  SUB.L ERd,nnnnnnnn      6 --h-nzvc
  7A4dnnnnnnnn       OR.L  #nnnnnnnn:32,ERd  OR.L  ERd,nnnnnnnn      6 ----nz0-
  7A5dnnnnnnnn       XOR.L #nnnnnnnn:32,ERd  XOR.L ERd,nnnnnnnn      6 ----nz0-
  7A6dnnnnnnnn       AND.L #nnnnnnnn:32,ERd  AND.L ERd,nnnnnnnn      6 ----nz0-

H8/300H Bit Operations
  7Cm074n0        *i B{I}OR  #nn:8,@ERm      OR    C,{not} [ERm].n   6 -------c
  7Cm075n0        *i B{I}XOR #nn:8,@ERm      XOR   C,{not} [ERm].n   6 -------c
  7Cm076n0        *i B{I}AND #nn:8,@ERm      AND   C,{not} [ERm].n   6 -------c
  7Cm077n0        *i B{I}LD  #nn:8,@ERm      MOV   C,{not} [ERm].n   6 -------c
  7Dm060n0           BSET    RnB,@ERm        SET   [ERm].RnB         8 --------
  7Dm061n0           BNOT    RnB,@ERm        NOT   [ERm].RnB         8 --------
  7Dm062n0           BCLR    RnB,@ERm        CLR   [ERm].RnB         8 --------
  7Dm063n0           BTST    RnB,@ERm        TST   [ERm].RnB         8 -----z--
  7Dm067n0        *i B{I}ST  #nn:8,@ERm      MOV   [ERm].n,{not} C   8 --------
  7Dm070n0           BSET    #nn:8,@ERm      SET   [ERm].n           8 --------
  7Dm071n0           BNOT    #nn:8,@ERm      NOT   [ERm].n           8 --------
  7Dm072n0           BCLR    #nn:8,@ERm      CLR   [ERm].n           8 --------
  7Dm073n0           BTST    #nn:8,@ERm      TST   [ERm].n           8 -----z--
  7Eaa74n0        *i B{I}OR  #nn:8,@aa:8     OR    C,{not} [FFaa].n  6 -------c
  7Eaa75n0        *i B{I}XOR #nn:8,@aa:8     XOR   C,{not} [FFaa].n  6 -------c
  7Eaa76n0        *i B{I}AND #nn:8,@aa:8     AND   C,{not} [FFaa].n  6 -------c
  7Eaa77n0        *i B{I}LD  #nn:8,@aa:8     MOV   C,{not} [FFaa].n  6 -------c
  7Faa60n0           BSET    RnB,@aa:8       SET   [FFaa].RnB        8 --------
  7Faa61n0           BNOT    RnB,@aa:8       NOT   [FFaa].RnB        8 --------
  7Faa62n0           BCLR    RnB,@aa:8       CLR   [FFaa].RnB        8 --------
  7Faa63n0           BTST    RnB,@aa:8       TST   [FFaa].RnB        8 -----z--
  7Faa67n0        *i B{I}ST  #nn:8,@aa:8     MOV   [FFaa].n,{not} C  8 --------
  7Faa70n0           BSET    #nn:8,@aa:8     SET   [FFaa].n          8 --------
  7Faa71n0           BNOT    #nn:8,@aa:8     NOT   [FFaa].n          8 --------
  7Faa72n0           BCLR    #nn:8,@aa:8     CLR   [FFaa].n          8 --------
  7Faa73n0           BTST    #nn:8,@aa:8     TST   [FFaa].n          8 -----z--
Nintendo uses undocumented opcode 7Eaa73n0 instead of official 7Faa73n0. Unknown if both are working. Unknown if all other opcodes in 7EaaXXn0 range do also act like 7FaaXXn0, and perhaps also 7Cm0XXn0 like 7Dm0XXn0 (nintendo uses the offical 7D/7F for SET/NOT/CLR, so weirdness may apply for TST only).

H8/300H Encoding Notes
  *i   optional inverted source operand (when setting bit3 in the "n" digit)
  *s   must have bit3 set in "s" digit
  *m   must have bit3 set in "m" digit
  *?   must have bit3 set-or-not-set (has conflicting info in official specs)
  E?Rs meant to be ERs (although official specs omit the E in some cases)
  E?Rd meant to be ERd (although official specs omit the E in some cases)
  xxxS meant to be Silent, no flags affected (although specs say Sign Extend)
  xxxX meant to mean Carry, or meant to mean nothing specific in other cases

H8/300H Pseudo Opcodes
The official "PUSH/POP.W/L Rn" opcodes are normal MOV.W/L opcodes with ER7 (SP) and post-increment or pre-decrement.
  6DFn               PUSH.W Rn    ;MOV.W [ER7-],Rn
  6D7n               POP.W  Rn    ;MOV.W Rn,[ER7+]
  01006DFn           PUSH.L ERn   ;MOV.L [ER7-],ERn
  01006D7n           POP.L  ERn   ;MOV.L ERn,[ER7+]
Although not officially defined, one could also implement "PUSH/POP.W CCR".
There are no PUSH/POP.B opcodes (because that would misalign the stack).

H8/300H N/A
  ---N/A---          MOV.L @aa:8,ERd         MOV.L ERd,[FFaa]        - ----nz0-
  ---N/A---          MOV.L ERs,@aa:8         MOV.L [FFaa],ERs        - ----nz0-
  ---N/A---          MOV.W @aa:8,Rd          MOV.W Rd,[FFaa]         - ----nz0-
  ---N/A---          MOV.W Rs,@aa:8          MOV.W [FFaa],Rs         - ----nz0-
  ---N/A---          SUB.B #nn:8,RdB         SUB.B RdB,nn            - --h-nzvc


DS Cart Unknown Extras

DS Cartridges with built-in MicroSD Card Slot
The DS Vision cartridge contains a built-in microSD card slot. Users can download videos from internet (against a fee), store the videos on microSD cards, and then view them on the NDS via DS Vision cartridge.
Unknown how the microSD is accessed; via parallel 'ROM' bus and/or via serial SPI bus; by which commands? Also unknown if the thing contains built-in video decoder hardware, or if videos are decoded on ARM cpus.

DS Cartridge with Bluetooth Keyboard (Typing Adventure)
Mostly unknown. The components in the cartridge are:
  typical Macronix ROM
  STMicroelectronics M25PE10 SPI FLASH memory, presumably 128K
  Broadcom BCM2070 Bluetooth controller
  26MHz crystal oscillator
the FLASH chip isn't connected directly to the cart-SPI bus, instead it's prolly accessed through the Bluetooth controller.

NTR-UNSJ - Japanese TV Tuner
Some huge cartridge with digital TV receiver.
Unknown if the "U" in the gamecode means that it contains NAND, too.
DSi Launcher sets BPTWL[21h].bit0=0 for this cartridge (unknown what for).

NTR/TWL-Uxxx gamecodes (for carts with uncommon hardware)
  NTR-UNSJ      Japanese TV Tuner, with TV receiver
  NTR-UBRP      Nintendo DS Brower, with RAM cart in GBA slot
  NTR-UAMA      DS Vision Starter Kit, with microSD
  NTR-UEIJ      Starry Sky Navigation, with azimuth
  NTR/TWL-Uxxx  NAND carts (see NAND chapter)


DS Cart Cheat Action Replay DS

The first commercial DS cheat code solution, this device was developed by Datel. It supports swapping out cartridges after loading the AR software. For updating, the user may either manually enter codes or use the included proprietary USB cable that comes with the device. The user has been able to manually update codes since firmware version 1.52.

Action Replay DS Codes
  ABCD-NNNNNNNN       Game ID ;ASCII Gamecode [00Ch] and CRC32 across [0..1FFh]
  00000000 XXXXXXXX   manual hook codes (rarely used) (default is auto hook)
  0XXXXXXX YYYYYYYY   word[XXXXXXX+offset] = YYYYYYYY
  1XXXXXXX 0000YYYY   half[XXXXXXX+offset] = YYYY
  2XXXXXXX 000000YY   byte[XXXXXXX+offset] = YY
  3XXXXXXX YYYYYYYY   IF YYYYYYYY > word[XXXXXXX]   ;unsigned    ;\
  4XXXXXXX YYYYYYYY   IF YYYYYYYY < word[XXXXXXX]   ;unsigned    ; for v1.54,
  5XXXXXXX YYYYYYYY   IF YYYYYYYY = word[XXXXXXX]                ; when X=0,
  6XXXXXXX YYYYYYYY   IF YYYYYYYY <> word[XXXXXXX]               ; uses
  7XXXXXXX ZZZZYYYY   IF YYYY > ((not ZZZZ) AND half[XXXXXXX])   ; [offset]
  8XXXXXXX ZZZZYYYY   IF YYYY < ((not ZZZZ) AND half[XXXXXXX])   ; instead of
  9XXXXXXX ZZZZYYYY   IF YYYY = ((not ZZZZ) AND half[XXXXXXX])   ; [XXXXXXX]
  AXXXXXXX ZZZZYYYY   IF YYYY <> ((not ZZZZ) AND half[XXXXXXX])  ;/
  BXXXXXXX 00000000   offset = word[XXXXXXX+offset]
  C0000000 YYYYYYYY   FOR loopcount=0 to YYYYYYYY  ;execute Y+1 times
  C4000000 00000000   offset = address of the C4000000 code           ;v1.54
  C5000000 XXXXYYYY   counter=counter+1, IF (counter AND YYYY) = XXXX ;v1.54
  C6000000 XXXXXXXX   [XXXXXXXX]=offset                               ;v1.54
  D0000000 00000000   ENDIF
  D1000000 00000000   NEXT loopcount
  D2000000 00000000   NEXT loopcount, and then FLUSH everything
  D3000000 XXXXXXXX   offset = XXXXXXXX
  D4000000 XXXXXXXX   datareg = datareg + XXXXXXXX
  D5000000 XXXXXXXX   datareg = XXXXXXXX
  D6000000 XXXXXXXX   word[XXXXXXXX+offset]=datareg, offset=offset+4
  D7000000 XXXXXXXX   half[XXXXXXXX+offset]=datareg, offset=offset+2
  D8000000 XXXXXXXX   byte[XXXXXXXX+offset]=datareg, offset=offset+1
  D9000000 XXXXXXXX   datareg = word[XXXXXXXX+offset]
  DA000000 XXXXXXXX   datareg = half[XXXXXXXX+offset]
  DB000000 XXXXXXXX   datareg = byte[XXXXXXXX+offset] ;bugged on pre-v1.54
  DC000000 XXXXXXXX   offset = offset + XXXXXXXX
  EXXXXXXX YYYYYYYY   Copy YYYYYYYY parameter bytes to [XXXXXXXX+offset...]
  44332211 88776655   parameter bytes 1..8 for above code  (example)
  0000AA99 00000000   parameter bytes 9..10 for above code (padded with 00s)
  FXXXXXXX YYYYYYYY   Copy YYYYYYYY bytes from [offset..] to [XXXXXXX...]
IF/ENDIF can be nested up to 32 times. FOR/NEXT cannot be nested, any FOR statement does forcefully terminate any prior loop. FOR does backup the current IF condidition flags, and NEXT does restore these flags, so ENDIF(s) aren't required inside of the loop. The NEXT+FLUSH command does (after finishing the loop) reset offset=0, datareg=0, and does clear all condition flags, so further ENDIF(s) aren't required after the loop.
Before v1.54, the DB000000 code did accidently set offset=offset+XXXXXXX after execution of the code. For all word/halfword accesses, the address should be aligned accordingly. For the COPY commands, addresses should be aligned by four (all data is copied with ldr/str, except, on odd lengths, the last 1..3 bytes do use ldrb/strb).
offset, datareg, loopcount, and counter are internal registers in the action replay software.

> The condition register is checked, for all code types
> but the D0, D1 and D2 code type
Makes sense.

> and for the C5 code type it's checked AFTER the counter has
> been incremented (so the counter is always incremented
I love that exceptions ;-)

Hook
The hook codes consist of a series of nine 00000000 XXXXXXXX codes, and must be marked as (M) code (for not being confused with normal 0XXXXXXX YYYYYYYY codes). For all nine codes, the left 32bit are actually don't care (but should be zero), the meaning of the right 32bit varies from 1st to 9th code.
  1st: Address used prior to launching game (eg. 23xxxxxh)
  2nd: Address to write the hook at (inside the ARM7 executable)
  3rd: Hook final address (huh?)
  4th: Hook mode selection (0=auto, 1=mode1, 2=mode2)
  5th: Opcode that replaces the hooked one (eg. E51DE004h)
  6th: Address to store important stuff  (default 23FE000h)
  7th: Address to store the code handler (default 23FE074h)
  8th: Address to store the code list    (default 23FE564h)
  9th: Must be 1 (00000001h)
For most games, the AR does automatically hook code on the ARM7. Doing that automatically is nice, but hooking ARM7 means that there is no access to VRAM, TCM and Cache, which <might> cause problems since efficient games <should> store all important data in TCM or Cache (though, in practice, I'd doubt that any existing NDS games are that efficient).

Thanks
To Kenobi and Dualscreenman from Kodewerx for above ARDS cheat info.


DS Cart Cheat Codebreaker DS

This is Pelican's entry into the DS cheat-device industry. It supports swapping out the cartridges, and alternately, also gives the user the option of connecting another gamecard onto it. For updating, the user may either manually enter codes, or use Wifi to connect to the Codebreaker update site (that updating will overwrite all manually entered codes though).

Codebreaker DS Codes
  ---Initialization---
  0000CR16 GAMECODE                    Specify Game ID, use Encrypted codes
  8000CR16 GAMECODE                    Specify Game ID, use Unencrypted codes
  BEEFC0DE XXXXXXXX                    Change Encryption Keys
  A0XXXXXX YYYYYYYY                    Bootup-Hook 1, X=Address, Y=Value
  A8XXXXXX YYYYYYYY                    Bootup-Hook 2, X=Address, Y=Value
  F0XXXXXX TYYYYYYY         Code-Hook 1 (T=Type,Y=CheatEngineAddr,X=HookAddr)
  F8XXXXXX TPPPPPPP         Code-Hook 2 (T=Type,X=CheatEngineHookAddr,P=Params)
  ---General codes---
  00XXXXXX 000000YY                    [X]=YY
  10XXXXXX 0000YYYY                    [X]=YYYY
  20XXXXXX YYYYYYYY                    [X]=YYYYYYYY
  60XXXXXX 000000YY ZZZZZZZZ 00000000  [[X]+Z]=YY
  60XXXXXX 0000YYYY ZZZZZZZZ 10000000  [[X]+Z]=YYYY
  60XXXXXX YYYYYYYY ZZZZZZZZ 20000000  [[X]+Z]=YYYYYYYY
  30XXXXXX 000000YY                    [X]=[X] + YY
  30XXXXXX 0001YYYY                    [X]=[X] + YYYY
  38XXXXXX YYYYYYYY                    [X]=[X] + YYYYYYYY
  70XXXXXX 000000YY                    [X]=[X] OR  YY
  70XXXXXX 001000YY                    [X]=[X] AND YY
  70XXXXXX 002000YY                    [X]=[X] XOR YY
  70XXXXXX 0001YYYY                    [X]=[X] OR  YYYY
  70XXXXXX 0011YYYY                    [X]=[X] AND YYYY
  70XXXXXX 0021YYYY                    [X]=[X] XOR YYYY
  ---Memory fill/copy---
  40XXXXXX 2NUMSTEP 000000YY 000000ZZ  byte[X+(0..NUM-1)*STEP*1]=Y+(0..NUM-1)*Z
  40XXXXXX 1NUMSTEP 0000YYYY 0000ZZZZ  half[X+(0..NUM-1)*STEP*2]=Y+(0..NUM-1)*Z
  40XXXXXX 0NUMSTEP YYYYYYYY ZZZZZZZZ  word[X+(0..NUM-1)*STEP*4]=Y+(0..NUM-1)*Z
  50XXXXXX YYYYYYYY ZZZZZZZZ 00000000  copy Y bytes from [X] to [Z]
  ---Conditional codes (bugged)---
  60XXXXXX 000000YY ZZZZZZZZ 01c100VV  IF [[X]+Z] .. VV   THEN [[X]+Z]=YY
  60XXXXXX 000000YY ZZZZZZZZ 01c0VVVV  IF [[X]+Z] .. VVVV THEN [[X]+Z]=YY
  60XXXXXX 0000YYYY ZZZZZZZZ 11c100VV  IF [[X]+Z] .. VV   THEN [[X]+Z]=YYYY
  60XXXXXX 0000YYYY ZZZZZZZZ 11c0VVVV  IF [[X]+Z] .. VVVV THEN [[X]+Z]=YYYY
  60XXXXXX YYYYYYYY ZZZZZZZZ 21c100VV  IF [[X]+Z] .. VV   THEN [[X]+Z]=YYYYYYYY
  60XXXXXX YYYYYYYY ZZZZZZZZ 21c0VVVV  IF [[X]+Z] .. VVVV THEN [[X]+Z]=YYYYYYYY
  ---Conditional codes (working)---
  D0XXXXXX NNc100YY                    IF [X] .. YY   THEN exec max(1,NN) lines
  D0XXXXXX NNc0YYYY                    IF [X] .. YYYY THEN exec max(1,NN) lines
The condition digits (c=0..7), have the following functions:
  0 IF [mem] =  imm THEN ...              4 IF ([mem] AND imm) =  0   THEN ...
  1 IF [mem] <> imm THEN ...              5 IF ([mem] AND imm) <> 0   THEN ...
  2 IF [mem] <  imm THEN ... (unsigned)   6 IF ([mem] AND imm) =  imm THEN ...
  3 IF [mem] >  imm THEN ... (unsigned)   7 IF ([mem] AND imm) <> imm THEN ...
Notes
  GAMECODE  Cartridge Header[00Ch] (32bit in reversed byte-order)
  CR16      Cartridge Header[15Eh] (16bit in normal byte-order)
  XXXXXX    27bit addr (actually 7 digits, XXXXXXX, overlaps 5bit code number)
The "bugged" conditional codes (60XXXXXX) are accidently skipping NN lines when the condition is false, where NN is taken from the upper 8bit of the code's last 32bit values (ie. exactly as for the D0XXXXXX codes). For byte-writes, that would be NN=01h, which can be eventually dealt with, although there may be compatibility problems which future versions that might fix that bug. For halfword/word writes, NN would be 11h or 21h, so that codes are about totally unusable.

Codebreaker DS / Encrypted Codes
The overall "address value" decryption works like so:
  for i=4Fh to 00h
    y=77628ECFh
    if i>13h then y=59E5DC8Ah
    if i>27h then y=054A7818h
    if i>3Bh then y=B1BF0855h
    address = (Key0-value) xor address
    value   = value - Key1 - (address ror 1Bh)
    address = (address xor (value + y)) ror 13h
    if (i>13h) then
      if (i<=27h) or (i>3Bh) then x=Key2 xor Key1 xor Key0
      else x=((Key2 xor Key1) and Key0) xor (Key1 and Key2)
      value=value xor (x+y+address)
      x = Secure[((i*4+00h) and FCh)+000h]
      x = Secure[((i*4+34h) and FCh)+100h] xor x
      x = Secure[((i*4+20h) and FCh)+200h] xor x
      x = Secure[((i*4+08h) and FCh)+300h] xor x
      address = address - (x ror 19h)
  next i
Upon startup, the initial key settings are:
  Secure[0..7FFh] = Copy of the ENCRYPTED 1st 2Kbytes of the game's Secure Area
  Key0 = 0C2EAB3Eh, Key1 = E2AE295Dh, Key2 = E1ACC3FFh, Key3 = 70D3AF46h
  scramble_keys
Upon BEEFC0DE XXXXXXXX, the keys get changed like so:
  Key0 = Key0 + (XXXXXXXX ror 1Dh)
  Key1 = Key1 - (XXXXXXXX ror 05h)
  Key2 = Key2 xor (Key3 xor Key0)
  Key3 = Key3 xor (Key2  -  Key1)
  scramble_keys
The above scramble_keys function works like so:
  for i=0 to FFh
    y = byte(xlat_table[i])
    Secure[i*4+000h] = (Secure[i*4+000h] xor Secure[y*4]) + Secure[y*4+100h]
    Secure[i*4+400h] = (Secure[i*4+400h] xor Secure[y*4]) - Secure[y*4+200h]
  next i
  for i=0 to 63h
    Key0 = Key0 xor (Secure[i*4] + Secure[i*4+190h])
    Key1 = Key1 xor (Secure[i*4] + Secure[i*4+320h])
    Key2 = Key2 xor (Secure[i*4] + Secure[i*4+4B0h])
    Key3 = Key3 xor (Secure[i*4] + Secure[i*4+640h])
  next i
  Key0 = Key0  -  Secure[7D0h]
  Key1 = Key1 xor Secure[7E0h]
  Key2 = Key2  +  Secure[7F0h]
  Key3 = Key3 xor Secure[7D0h] xor Secure[7F0h]
the xlat_table consists of 256 fixed 8bit values:
  34h,59h,00h,32h,7Bh,D3h,32h,C9h,9Bh,77h,75h,44h,E0h,73h,46h,06h
  0Bh,88h,B3h,3Eh,ACh,F2h,BAh,FBh,2Bh,56h,FEh,7Ah,90h,F7h,8Dh,BCh
  8Bh,86h,9Ch,89h,00h,19h,CDh,4Ch,54h,30h,01h,93h,30h,01h,FCh,36h
  4Dh,9Fh,FDh,D7h,32h,94h,AEh,BCh,2Bh,61h,DFh,B3h,44h,EAh,8Bh,A3h
  2Bh,53h,33h,54h,42h,27h,21h,DFh,A9h,DDh,C0h,35h,58h,EFh,8Bh,33h
  B4h,D3h,1Bh,C7h,93h,AEh,32h,30h,F1h,CDh,A8h,8Ah,47h,8Ch,70h,0Ch
  17h,4Eh,0Eh,A2h,85h,0Dh,6Eh,37h,4Ch,39h,1Fh,44h,98h,26h,D8h,A1h
  B6h,54h,F3h,AFh,98h,83h,74h,0Eh,13h,6Eh,F4h,F7h,86h,80h,ECh,8Eh
  EEh,4Ah,05h,A1h,F1h,EAh,B4h,D6h,B8h,65h,8Ah,39h,B3h,59h,11h,20h
  B6h,BBh,4Dh,88h,68h,24h,12h,9Bh,59h,38h,06h,FAh,15h,1Dh,40h,F0h
  01h,77h,57h,F5h,5Dh,76h,E5h,F1h,51h,7Dh,B4h,FAh,7Eh,D6h,32h,4Fh
  0Eh,C8h,61h,C1h,EEh,FBh,2Ah,FCh,ABh,EAh,97h,D5h,5Dh,E8h,FAh,2Ch
  06h,CCh,86h,D2h,8Ch,10h,D7h,4Ah,CEh,8Fh,EBh,03h,16h,ADh,84h,98h
  F5h,88h,2Ah,18h,ACh,7Fh,F6h,94h,FBh,3Fh,00h,B6h,32h,A2h,ABh,28h
  64h,5Ch,0Fh,C6h,23h,12h,0Ch,D2h,BAh,4Dh,A3h,F2h,C9h,86h,31h,57h
  0Eh,F8h,ECh,E1h,A0h,9Ah,3Ch,65h,17h,18h,A0h,81h,D0h,DBh,D5h,AEh
all used operations are unsigned 32bit integer.

Thanks
To Kenobi and Dualscreenman from Kodewerx for above CBDS cheat info.


DS Cart DLDI Driver

DLDI (Dynamically Linked Device Interface for libfat) is a popular yet undocumented flashcart driver for homebrew NDS software dating back to 2006. Below was reverse-engineered 11/2018.

file.dldi --> driver file (can be small like 1.5Kbyte, or max 32Kbyte)
file.nds --> ROM image (must contain 32Kbyte space with DLDI ID for patching)

Driver patch file standard header
  00h 4  DLDI ID       (EDh,A5h,8Dh,BFh) (aka BF8DA5EDh)  ;\patching tools will
  04h 8  DLDI String   (20h,"Chishm",00h)                 ; refuse any other
  0Ch 1  DLDI Version  (01h in .dldi, don't care in .nds) ;/values
  0Dh 1  Size of .dldi+BSS (rounded up to 1 SHL N bytes) (max 0Fh=32Kbytes)
  0Eh 1  Sections to fix/destroy (see FIX_xxx)
  0Fh 1  Space in .nds file (1 SHL N) (0Eh..0Fh in .nds, can be 0 in .dldi)
  10h 48 ASCII Full Driver Name (max 47 chars, plus zero padding)
  40h 4  Address of ALL start (text) ;-base address (BF800000h in .dldi)
  44h 4  Address of ALL end   (data) ;-for highly-unstable FIX_ALL addr.adjusts
  48h 4  Address of GLUE start       ;\for semi-stable FIX_GLUE addr.adjusts
  4Ch 4  Address of GLUE end         ;/  ("Interworking glue" for ARM-vs-THUMB)
  50h 4  Address of GOT start        ;\for semi-stable FIX_GOT addr.adjusts
  54h 4  Address of GOT end          ;/  ("Global Offset Table")
  58h 4  Address of BSS start        ;\for zerofilling "BSS" via FIX_BSS
  5Ch 4  Address of BSS end          ;/  ("Block Started by Symbol")
  60h 4  ASCII Short Driver/Device Name (4 chars, eg. "MYHW" for MyHardware)
  64h 4  Flags 2 (see FEATURE_xxx) (usually 13h=GbaSlot, or 23h=NdsSlot)
  68h 4  Address of Function startup() ;<-- must be at offset +80h !! ;\
  6Ch 4  Address of Function isInserted() ;out: 0=no/fail, 1=yes/okay ; all
  70h 4  Address of Function readSectors(sector,numSectors,buf)       ; return
  74h 4  Address of Function writeSectors(sector,numSectors,buf)      ; 0=fail,
  78h 4  Address of Function clearStatus()                            ; 1=okay
  7Ch 4  Address of Function shutdown()                               ;/
  80h .. Driver Code (can/must begin with "startup()")            ;\max 7F80h
  ..  .. Glue section (usually a small snippet within above code) ; bytes (when
  ..  .. GOT section (usually after above code) (pointer table)   ; having 32K
  ..  .. BSS section (usually at end, may exceed .dldi filesize)  ; allocated)
  ..  .. Optional two garbage NOPs at end of default.dldi         ;/
hdr[0Eh] - Sections to fix/destroy (FIX_xxx):
  0    FIX_ALL   ;-installer uses highly-unstable guessing in whole dldi file
  1    FIX_GLUE  ;-installer uses semi-stable address guessing in GLUE area
  2    FIX_GOT   ;-installer uses semi-stable address guessing in GOT area
  3    FIX_BSS   ;-installer will zerofill BSS area
  4-7  Reserved (0)
hdr[64h] - Flags 2 (FEATURE_xxx) (usually 13h=GbaSlot, or 23h=NdsSlot):
  0    FEATURE_MEDIUM_CANREAD          00000001h (usually set)
  1    FEATURE_MEDIUM_CANWRITE         00000002h (a few carts can't write)
  2-3  Reserved (0)
  4    FEATURE_SLOT_GBA                00000010h (need EXMEMCNT bit7 adjusted)
  5    FEATURE_SLOT_NDS                00000020h (need EXMEMCNT bit11 adjusted)
  6-31 Reserved (0)
Note: The allocated driver size in hdr[0Fh] was 0Fh=32Kbytes between 2006 and 2016, however, libnds has changed that to 0Eh=16Kbytes in January 2017 (maybe intending to free more RAM, especially when using ARM7 WRAM).
However, there's at least one driver exceeding 16K (rpg_nand.dldi in AKAIO package; the driver disguises itself as 8K driver in hdr[0Dh], but its BSS area actually needs ways MORE than 16K).

Required entries in .nds file
Officially, dldi could be at any 4-byte aligned location, however, for faster lookup, better use this locations:
  dldi area should be located at a 40h-byte aligned address in ROM image.
  dldi area should be located in ARM9 (or ARM7) bootcode area.
An "empty" driver needs to contain:
  dldi[00h..0Bh] must contain DLDI ID word/string
  dldi[0Fh]      must contain allocated size (0Eh=16Kbyte or 0Fh=32Kbyte)
  dldi[40h..43h] must contain RAM base address of DLDI block
  and other entries should contain valid dummy strings and dummy functions.
An installed driver should contain a copy of the .dldi file, with addresses adjusted to RAM locations, and BSS area zerofilled (if FIX_BSS was set)
  dldi[0Fh] must be kept as in the old .nds file (not as in .dldi file)
Some installers might try to detect homebrew by looking at nds carthdr for deciding whether or not to try to install dldi (unknown if/which ones are doing such things and looking at which carthdr entries).

Functions
startup, isInserted, clearStatus, shutdown can be dummy functions that do nothing (other than returning r0=1=okay).
Alternately startup/shutdown can initialize or power down the hardware, clearStatus is meant to be some sort of soft reset, and isInserted is allowing to test if the SD card is inserted & working.
read/write sectors are reading/writing one or more sectors. Sector size is 200h bytes, sector numbers is 0=First 200h bytes, 1=Next 200h bytes, and so on.
buf should be usually 4-byte aligned, however, some drivers do also support unaligned buffers using slower transfer code (better implement that when making .dldi drivers, but better don't rely on it being supported when making .nds files).
The driver functions can support SD and SDHC (or the flashcart manufacturer might release driver updates if SDHC wasn't supported).
Higher level FAT functions must be contained in the .nds file (so a driver update won't help if the .nds file lacks FAT32) (and ExFAT most unlikely to be supported).
Functions should be ARM7 compatible, ie. don't use BLX or POP r15 for mode switching, so the driver can be used on both ARM9 and ARM7 (or even on GBA).

SLOT_GBA/NDS
SLOT_GBA/NDS seem to relate to GBA and NDS slots, the driver can probably have only one of the SLOT bits set (the functions don't allow to select which slot to use).
Purpose is unclear to me, maybe just telling the .nds file that the flashcart is in the given slot (and thereby shouldn't expect other hardware in that slot). Or maybe telling telling the installer which hardware the driver is supposed for.

FIX_xxx does maybe relate to address adjustments made by the dldi installer. Unknown if/how that's working.
DS Cart DLDI Driver - Guessed Address-Adjustments

Some DLDI flashcarts support extra features like Rumble. However, that extra hardware is accessed via direct I/O, not via DLDI driver. Unknown which I/O ports are used for that stuff - probably something compatible with official GBA/NDS rumble cart(s).


DS Cart DLDI Driver - Guessed Address-Adjustments

The DLDI installer uses some guessing method for address-adjustments (the FIX_xxx flags are supposed to patch addresses, but not opcodes or other data).

Unaligned-Word patching and over-shooting bug
The central mistake in the official DLDI installer is that it is patching all words at [start..end-1], using 1-byte address increments instead of 4-byte increments. This includes patching words at non-word aligned locations, or patching words whose lower bytes were already patched, and over-shooting to words at [end-1..end+2].

ddmem Base BF800000h
Most or all .dldi files are using ddmem base BF800000h (defined in dldi.ld). That value was chosen because it won't conflict with opcodes (as NDS BIOS doesn't use SWI function 80h, BF80xxxxh would be an invalid SWI function in ARM; and BF80h would be an invalid opcode in THUMB).
So far, this would have worked well, but it doesn't work with unaligned-word patching bug (eg. THUMB opcodes 8000h,BF00h, or ARM opcodes xxBF80xxh or the like). And, even if it would have worked for opcodes - it might still fail for data values.

FIX_GOT
GOT does usually contain BF80xxxxh address pointers (plus some 00000000h words). The guessing works quite stable (the maximum for 32K files is xxxxh=7FFFh, so there's no risk to encounter xxxx=BF80h) (one could encounter xxxxh=xxBFh, but the previously patched word is usually in RAM area, eg. 02xxxxxxh, so this would form BF02h, without risk to be seen as BF80h).
BUG: The GOT table is usually located at the end of the .dldi file, meaning that the over-shooting bug will see three uninitialized bytes at [got_end+0..2], and may go amok if they are BF80xxh or xxBF80h. The value of those bytes depends on left-over from previously installed .dldi driver(s) and on the ddmem base used in the .nds file, so the bug may take place randomly depending on several factors.

FIX_GLUE
GLUE does usually contain a handful of opcodes and .pool values for switching between ARM and THUMB code. The intention is to patch the addresses in the .pool, and to leave the opcodes intact. This can be potentially stable, assuming that the used opcodes in the GLUE (and the next three bytes after glue_end) usually won't contain BF80h).

FIX_ALL
This is the mother of all bugs. Fortunately there aren't any .dldi drivers with FIX_ALL flag - and one should never make drivers that do use it.
ALL is covering the whole dldi space, including the 80h-byte DLDI header, the code area, including GLUE area, and GOT area, and probably also the yet uninitialized BSS area, and the next three bytes after end_all.
Patching the whole code area means an increased risk to hit opcodes or data values that contain BF80h. The over-shooting bug may even destroy the next three bytes after the 32Kbyte area.
Patching the DLDI header could destroy the header itself, the header in the .dldi file usually won't contain BF80h at unintended locations, however, the pointers in that header are adjusted before applying FIX_ALL, for example, RAM base 0200BF00h (in .nds file) combined with a function at BF800080h (in .dldi file) would result in 0200BF80h. The nasty thing is that the problem won't occur with other RAM base values (in other .nds files).

Avoiding the bugs
When making .dldi drivers: Never use FIX_ALL. And preferably avoid FIX_GOT and FIX_GLUE as well (ARM CPU can do relative jumps and relative addressing, eg. via ADR and ADRL pseudo opcodes, so there's no point in needing address adjustments). Or otherwise append padding after GOT area, and try to avoid using opcodes/data with BF80h in/after GLUE area.
When making dldi installers: Best patch only word-aligned words (ARM CPU can't access unaligned data, so there's little chance that DLDI drivers would ever contain unaligned words). Or, when maintaining unaligned patching: At the very least skip the 80h-byte header on FIX_ALL, and after patching a word at other locations, skip the next three bytes, and don't do the over-shooting at end.
When making .nds files: There isn't too much that could be done here. One could set ddmem to 64Kbyte aligned addresses (so functions won't end up at xxxxBF80h). Or one could even set ddmem to BF800000h (so patching will leave everything unchanged & intact - so one could then do the address adjustments manually, and hopefully more reliable than other DLDI installers).


DS Encryption by Gamecode/Idcode (KEY1)

KEY1 - Gamecode / Idcode Encryption
The KEY1 encryption relies only on the gamecode (or firmware idcode), it does not contain any random components. The fact that KEY1 encrypted commands appear random is just because the <unencrypted> commands contain random values, so the encryption result looks random.

KEY1 encryption is used for KEY1 encrypted gamecart commands (ie. for loading the secure area). It is also used for resolving the extra decryption of the first 2K of the secure area, and for firmware decryption, and to decode some encrypted values in gamecart/firmware header.

Initial Encryption Values
Below formulas can be used only with a copy of the 1048h-byte key tables from NDS/DSi BIOS. The values can be found at:
  NDS.ARM7 ROM: 00000030h..00001077h (values 99 D5 20 5F ..) Blowfish/NDS-mode
  DSi.ARM9 ROM: FFFF99A0h..FFFFA9E7h (values 99 D5 20 5F ..) ""
  DSi.TCM Copy: 01FFC894h..01FFD8DBh (values 99 D5 20 5F ..) ""
  DSi.ARM7 ROM: 0000C6D0h..0000D717h (values 59 AA 56 8E ..) Blowfish/DSi-mode
  DSi.RAM Copy: 03FFC654h..03FFD69Bh (values 59 AA 56 8E ..) ""
  DSi.Debug:    (stored in launcher) (values 69 63 52 05 ..) Blowfish/DSi-debug
The DSi ROM sections are disabled after booting, but the RAM/TCM copies can be dumped (eg. with some complex main memory hardware mods, or via unlaunch exploit). The DSi.Debug key is stored in launcher, and it's used when SCFG_OP is nonzero (as so on debugging on hardware).

encrypt_64bit(ptr) / decrypt_64bit(ptr)
  Y=[ptr+0]
  X=[ptr+4]
  FOR I=0 TO 0Fh (encrypt), or FOR I=11h TO 02h (decrypt)
    Z=[keybuf+I*4] XOR X
    X=[keybuf+048h+((Z SHR 24) AND FFh)*4]
    X=[keybuf+448h+((Z SHR 16) AND FFh)*4] + X
    X=[keybuf+848h+((Z SHR  8) AND FFh)*4] XOR X
    X=[keybuf+C48h+((Z SHR  0) AND FFh)*4] + X
    X=Y XOR X
    Y=Z
  NEXT I
  [ptr+0]=X XOR [keybuf+40h] (encrypt), or [ptr+0]=X XOR [keybuf+4h] (decrypt)
  [ptr+4]=Y XOR [keybuf+44h] (encrypt), or [ptr+4]=Y XOR [keybuf+0h] (decrypt)

apply_keycode(modulo)
  encrypt_64bit(keycode+4)
  encrypt_64bit(keycode+0)
  [scratch]=0000000000000000h   ;S=0 (64bit)
  FOR I=0 TO 44h STEP 4         ;xor with reversed byte-order (bswap)
    [keybuf+I]=[keybuf+I] XOR bswap_32bit([keycode+(I MOD modulo)])
  NEXT I
  FOR I=0 TO 1040h STEP 8
    encrypt_64bit(scratch)      ;encrypt S (64bit) by keybuf
    [keybuf+I+0]=[scratch+4]    ;write S to keybuf (first upper 32bit)
    [keybuf+I+4]=[scratch+0]    ;write S to keybuf (then lower 32bit)
  NEXT I

init_keycode(idcode,level,modulo,key)
  if key=nds then copy [nds_arm7bios+0030h..1077h] to [keybuf+0..1047h]
  if key=dsi then copy [dsi_arm7bios+C6D0h..D717h] to [keybuf+0..1047h]
  [keycode+0]=[idcode]
  [keycode+4]=[idcode]/2
  [keycode+8]=[idcode]*2
  IF level>=1 THEN apply_keycode(modulo) ;first apply (always)
  IF level>=2 THEN apply_keycode(modulo) ;second apply (optional)
  [keycode+4]=[keycode+4]*2
  [keycode+8]=[keycode+8]/2
  IF level>=3 THEN apply_keycode(modulo) ;third apply (optional)

firmware_decryption
  init_keycode(firmware_header+08h,1,0Ch,nds) ;idcode (usually "MACP"), level 1
  decrypt_64bit(firmware_header+18h)          ;rominfo
  init_keycode(firmware_header+08h,2,0Ch,nds) ;idcode (usually "MACP"), level 2
  decrypt ARM9 and ARM7 bootcode by decrypt_64bit (each 8 bytes)
  decompress ARM9 and ARM7 bootcode by LZ77 function (swi)
  calc CRC16 on decrypted/decompressed ARM9 bootcode followed by ARM7 bootcode
Note: The sizes of the compressed/encrypted bootcode areas are unknown (until they are fully decompressed), one way to solve that problem is to decrypt the next 8 bytes each time when the decompression function requires more data.

gamecart_decryption
  init_keycode(cart_header+0Ch,1,08h,nds)   ;gamecode, level 1, modulo 8
  decrypt_64bit(cart_header+78h)            ;rominfo (secure area disable)
  init_keycode(cart_header+0Ch,2,08h,nds)   ;gamecode, level 2, modulo 8
  encrypt_64bit all NDS KEY1 commands (1st command byte in MSB of 64bit value)
  after loading the secure_area, calculate secure_area crc, then
  decrypt_64bit(secure_area+0)              ;first 8 bytes of secure area
  init_keycode(cart_header+0Ch,3,08h,nds)   ;gamecode, level 3, modulo 8
  decrypt_64bit(secure_area+0..7F8h)        ;each 8 bytes in first 2K of secure
  init_keycode(cart_header+0Ch,1,08h,dsi)   ;gamecode, level 1, modulo 8
  encrypt_64bit all DSi KEY1 commands (1st command byte in MSB of 64bit value)
After secure area decryption, the ID field in the first 8 bytes should be "encryObj", if it matches then first 8 bytes are filled with E7FFDEFFh, otherwise the whole 2K are filled by that value.

Gamecart Command Register
Observe that the byte-order of the command register [40001A8h] is reversed. The way how the CPU stores 64bit data in memory (and the way how the "encrypt_64bit" function for KEY1-encrypted commands expects data in memory) is LSB at [addr+0] and MSB at [addr+7]. This value is to be transferred MSB first. However, the DS hardware transfers [40001A8h+0] first, and [40001A8h+7] last. So, the byte order must be reversed when copying the value from memory to the command register.

Note
The KEY1 encryption is based on Bruce Schneier's "Blowfish Encryption Algorithm".


DS Encryption by Random Seed (KEY2)

KEY2 39bit Seed Values
The pre-initialization settings at cartridge-side (after reset) are:
  Seed0 = 58C56DE0E8h
  Seed1 = 5C879B9B05h
The post-initialization settings (after sending command 4llllmmmnnnkkkkkh to the cartridge, and after writing the Seed values to Port 40001Bxh) are:
  Seed0 = (mmmnnn SHL 15)+6000h+Seedbyte
  Seed1 = 5C879B9B05h
The seedbyte is selected by Cartridge Header [013h].Bit0-2, this index value should be usually in range 0..5, however, possible values for index 0..7 are: E8h,4Dh,5Ah,B1h,17h,8Fh,99h,D5h.
The 24bit random value (mmmnnn) is derived from the real time clock setting, and also scattered by KEY1 encryption, anyways, it's just random and doesn't really matter where it comes from.

KEY2 Encryption
Relies on two 39bit registers (x and y), which are initialized as such:
  x = reversed_bit_order(seed0)  ;ie. LSB(bit0) exchanged with MSB(bit38), etc.
  y = reversed_bit_order(seed1)
During transfer, x, y, and transferred data are modified as such:
  x = (((x shr 5)xor(x shr 17)xor(x shr 18)xor(x shr 31)) and 0FFh)+(x shl 8)
  y = (((y shr 5)xor(y shr 23)xor(y shr 18)xor(y shr 31)) and 0FFh)+(y shl 8)
  data = (data xor x xor y) and 0FFh


DS Firmware Serial Flash Memory

ST Microelectronics SPI Bus Compatible Serial FLASH Memory
 Chips used as wifi-flash:
  ID 20h,40h,12h - ST M45PE20 - 256 KBytes (Nintendo DS) (in my old DS)
  ID 20h,50h,12h - ST M35PE20 - 256 KBytes (Nintendo DS) (in my DS-Lite)
  ID 20h,80h,13h - ST M25PE40 - 512 KBytes (iQue DS, with chinese charset)
  ID 20h,40h,11h - ST 45PE10V6 - 128 Kbytes (Nintendo DSi) (in my DSi)
  ID 20h,58h,0Ch?- 5A32        - 4 Kbytes (Nintendo DSi, newer models)
  ID ?           - 26FV032T    - (Nintendo DSi, J27H020) (this has big package)
  ID ?           - 5K32        - (3DS?)
  ID 62h,62h,0Ch - 32B, 3XH    - 4 Kbytes (New3DS)
 Other similar chips (used in game cartridges):
  ID 20h,40h,13h - ST 45PE40V6 - 512 KBytes (DS Zelda, NTR-AZEP-0)
  ID 20h,40h,14h - ST 45PE80V6 - 1024 Kbytes (eg. Spirit Tracks, NTR-BKIP)
 +ID 62h,11h,00h - Sanyo ?          - 512 Kbytes (P-Letter Diamond, ADAE)
  ID 62h,16h,00h - Sanyo LE25FW203T - 256 KBytes (Mariokart backup)
 +ID 62h,26h,11h - Sanyo ?          - ? Kbytes (3DS: CTR-P-AXXJ)
 +ID 62h,26h,13h - Sanyo ?          - ? Kbytes (3DS: CTR-P-APDJ)
  ID C2h,22h,11h - Macronix MX25L1021E? 128 Kbytes (eg. 3DS Starfox)
  ID C2h,22h,13h - Macronix ...? 512 Kbytes (eg. 3DS Kid Icarus, 3DS Sims 3)
  ID C2h,20h,17h - Macronix MX25L6445EZNI-10G 8192 Kbytes (DSi Art Academy)
  ID 01h,F0h,00h - Garbage/Infrared on SPI-bus? (eg. P-Letter White)
  ID 03h,F8h,00h - Garbage/Infrared on SPI-bus? (eg. P-Letter White 2)
FLASH has more than 100,000 Write Cycles, more than 20 Year Data Retention
The Firmware Flash Memory is accessed via SPI bus,
DS Serial Peripheral Interface Bus (SPI)

Instruction Codes
  06h  WREN Write Enable (No Parameters)
  04h  WRDI Write Disable (No Parameters)
  9Fh  RDID Read JEDEC Identification (Read 1..3 ID Bytes)
             (Manufacturer, Device Type, Capacity)
  05h  RDSR Read Status Register (Read Status Register, endless repeated)
             Bit7-2  Not used (zero)
             Bit1    WEL Write Enable Latch             (0=No, 1=Enable)
             Bit0    WIP Write/Program/Erase in Progess (0=No, 1=Busy)
  03h  READ Read Data Bytes (Write 3-Byte-Address, read endless data stream)
  0Bh  FAST Read Data Bytes at Higher Speed (Write 3-Byte-Address, write 1
             dummy-byte, read endless data stream) (max 25Mbit/s)
  0Ah  PW   Page Write (Write 3-Byte-Address, write 1..256 data bytes)
             (changing bits to 0 or 1) (reads unchanged data, erases the page,
             then writes new & unchanged data) (11ms typ, 25ms max)
  02h  PP   Page Program (Write 3-Byte-Address, write 1..256 data bytes)
             (changing bits from 1 to 0) (1.2ms typ, 5ms max)
  DBh  PE   Page Erase 100h bytes (Write 3-Byte-Address) (10ms typ, 20ms max)
  D8h  SE   Sector Erase 10000h bytes (Write 3-Byte-Address) (1s typ, 5s max)
  B9h  DP   Deep Power-down (No Parameters) (consumption 1uA typ, 10uA max)
             (3us) (ignores all further instructions, except RDP)
  ABh  RDP  Release from Deep Power-down (No Parameters) (30us)
Write/Program may not cross page-boundaries. Write/Program/Erase are rejected during first 1..10ms after power up. The WEL bit is automatically cleared on Power-Up, on /Reset, and on completion of WRDI/PW/PP/PE/SE instructions. WEL is set by WREN instruction (which must be issued before any write/program/erase instructions). Don't know how RDSR behaves when trying to write to the write-protected region?

Communication Protocol
  Set Chip Select LOW to invoke the command
  Transmit the instruction byte
  Transmit any parameter bytes
  Transmit/receive any data bytes
  Set Chip Select HIGH to finish the command
All bytes (and 3-byte addresses) transferred most significant bit/byte first.

DSi "5A32" chip (32Kit aka 4Kbyte)
Early DSi DWM-W015 boards did have 128Kbyte FLASH, but later boards have custum 4Kbyte FLASH chips (these 4K chips are found on later DSi DWM-W015 boards, and DSi DWM-W024 boards, and 3DS DWM-W028 boards). The chips are having a 24bit address bus (needed for NDS compatibility), and, a weird non-writeable gap within a 128Kbyte memory are:
  000000h..0002FFh  Writeable only if /WP=HIGH (otherwise writes are ignored)
  000300h..01F2FFh  Not writeable (FFh-filled, writes are ignored)
  01F300h..01FFFFh  Writeable
  020000h and up    Mirrors of 0..01FFFFh (same read/write-ability as above)
There are several part numbers: "5A32" (DSi), "5K32" (3DS), "32B, 3XH" (3DS), and "26FV032T" (DSi), that chips are probably all the same size & functionally same; most of those 4Kbyte chips have tiny packages (except "26FV032T" which comes in classic large package).

Pin-Outs (Large Package, in NDS, and early DSi boards)
  1   D    Serial Data In (latched at rising clock edge)          _________
  2   C    Serial Clock (max 25MHz)                             /|o        |
  3   /RES Reset                                            1 -| |         |- 8
  4   /S   Chip Select (instructions start at falling edge) 2 -| |         |- 7
  5   /W   Write Protect (makes first 256 pages read-only)  3 -| |_________|- 6
  6   VCC  Supply (2.7V..3.6V typ) (4V max) (DS:VDD3.3)     4 -|/          |- 5
  7   VSS  Ground                                              |___________|
  8   Q    Serial Data Out (changes at falling clock edge)

Pin-Outs (Tiny Package, in newer DSi boards, and 3DS)
  1   /S   Chip Select (instructions start at falling edge)     ___________
  2   Q    Serial Data Out (changes at falling clock edge)  1 -| o         |- 8
  3   /W   Write Protect (makes first pages read-only)      2 -|           |- 7
  4   VSS  Ground                                           3 -|           |- 6
  5   D    Serial Data In (latched at rising clock edge)    4 -|___________|- 5
  6   C    Serial Clock
  7   /RES Reset
  8   VCC  Supply (2.7V..3.6V typ) (DSi: VDD33)


DS Firmware Header

Firmware Memory Map
  00000h-00029h  Firmware Header
  0002Ah-001FFh  Wifi Settings
  00200h-3F9FFh  Firmware Code/Data                       ;-NDS only (not DSi)
  00200h-002FEh  00h-filled                               ;\
  002FFh         80h                                      ;
  00300h-1F2FFh  FFh-filled (not write-able on 4K chips)  ; DSi only (not NDS)
  1F300h-1F3FEh  FFh-filled (write-able)                  ;
  1F3FFh         Whatever Debug/Bootflags                 ;
  1F400h-1F5FFh  Wifi Access Point 4  ;\with WPA/WPA2     ;
  1F600h-1F7FFh  Wifi Access Point 5  ; support           ;
  1F800h-1F9FFh  Wifi Access Point 6  ;/                  ;/
  3FA00h-3FAFFh  Wifi Access Point 1  ;\
  3FB00h-3FBFFh  Wifi Access Point 2  ; Open/WEP only
  3FC00h-3FCFFh  Wifi Access Point 3  ;/
  3FD00h-3FDFFh  Not used
  3FE00h-3FEFFh  User Settings Area 1
  3FF00h-3FFFFh  User Settings Area 2
On iQue DS (with 512K flash memory), user settings are moved to 7FE00h and up, and, there seems to be some unknown stuff at 200h..27Fh.

Firmware Header (00000h-001FFh)
  Addr Size Expl.
  000h 2    part3 romaddr/8 (arm9 gui code) (LZ/huffman compression)
  002h 2    part4 romaddr/8 (arm7 wifi code) (LZ/huffman compression)
  004h 2    part3/4 CRC16 arm9/7 gui/wifi code
  006h 2    part1/2 CRC16 arm9/7 boot code
  008h 4    firmware identifier (usually nintendo "MAC",nn) (or nocash "XBOO")
            the 4th byte (nn) occassionally changes in different versions
  00Ch 2    part1 arm9 boot code romaddr/2^(2+shift1) (LZSS compressed)
  00Eh 2    part1 arm9 boot code 2800000h-ramaddr/2^(2+shift2)
  010h 2    part2 arm7 boot code romaddr/2^(2+shift3) (LZSS compressed)
  012h 2    part2 arm7 boot code 3810000h-ramaddr/2^(2+shift4)
  014h 2    shift amounts, bit0-2=shift1, bit3-5=shift2, bit6-8=shift3,
            bit9-11=shift4, bit12-15=firmware_chipsize/128K
  016h 2    part5 data/gfx romaddr/8 (LZ/huffman compression)
  018h 8    Optional KEY1-encrypted "enPngOFF"=Cartridge KEY2 Disable
            (feature isn't used in any consoles, instead contains timestamp)
  018h 5    Firmware version built timestamp (BCD minute,hour,day,month,year)
  01Dh 1    Console type
              FFh=Nintendo DS
              20h=Nintendo DS-lite
              57h=Nintendo DSi (also iQueDSi)
              43h=iQueDS
              63h=iQueDS-lite
            The entry was unused (FFh) in older NDS, ie. replace FFh by 00h)
              Bit0   seems to be DSi/iQue related
              Bit1   seems to be DSi/iQue related
              Bit2   seems to be DSi related
              Bit3   zero
              Bit4   seems to be DSi related
              Bit5   seems to be DS-Lite related
              Bit6   indicates presence of "extended" user settings (DSi/iQue)
              Bit7   zero
  01Eh 2    Unused (FFh-filled)
  020h 2    User Settings Offset (div8) (usually last 200h flash bytes)
  022h 2    Unknown (7EC0h or 0B51h)
  024h 2    Unknown (7E40h or 0DB3h)
  026h 2    part5 CRC16 data/gfx
  028h 2    unused (FFh-filled)
  02Ah-1FFh Wifi Calibration Data (see next chapter)

DSi
  000h 1Dh   Zerofilled (bootcode is in new eMMC chip, not on old FLASH chip)
  01Dh 6     Same as on DS (header: Console Type and User Settings Offset)
  022h 6     Zerofilled (bootcode is in new eMMC chip, not on old FLASH chip)
  028h..1FCh Same as on DS (wifi calibration)
  1FDh 1     Wifi Board (01h=DWM-W015, 02h=W024, 03h=W028)   ;\this was
  1FEh 1     Wifi Flash (20h=With access point 4/5/6)        ; FFh-filled
  1FFh 1     Same as on DS (FFh)                             ;/on DS
  200h FFh   Zerofilled                                      ;\
  2FFh 1     Unknown (80h)                                   ; this was
  300h   1F000h FFh's (not write-able on 4K chips)           ; bootcode
  1F300h FFh    FFh's (write-able) ;twl-debugger: 00h's      ; on DS
  1F3FFh 1      FFh                ;twl-debugger: 40h        ;/
The bytes [000h..027h] cannot be changed on DSi because they are part of the RSA signature in DSi's Boot Info Block (at eMMC offset 200h..3FFh).


DS Firmware Wifi Calibration Data

Wifi Calibration/Settings (located directly after Firmware Header)
  Addr Size Expl.
  000h-029h Firmware Header (see previous chapter)
  02Ah 2    CRC16 (with initial value 0) of [2Ch..2Ch+config_length-1]
  02Ch 2    config_length (usually 0138h, ie. entries 2Ch..163h)
  02Eh 1    Unused        (00h)
  02Fh 1    Version (0=v1..v4, 3=v5, 5=v6..v7,6=W006,15=W015,24=W024,34=N3DS)
  030h 6    Unused        (00h-filled) (DS-Lite and DSi: FF,FF,FF,FF,FF,00)
  036h 6    48bit MAC address (v1-v5: 0009BFxxxxxx, v6-v7: 001656xxxxxx)
  03Ch 2    list of enabled channels ANDed with 7FFE (Bit1..14 = Channel 1..14)
            (usually 3FFEh, ie. only channel 1..13 enabled)
  03Eh 2    Whatever Flags (usually FFFFh)
  040h 1    RF Chip Type (NDS: usually 02h) (DS-Lite and DSi/3DS: usually 03h)
  041h 1    RF Bits per entry at 0CEh (usually 18h=24bit=3byte) (Bit7=?)
  042h 1    RF Number of entries at 0CEh (usually 0Ch)
  043h 1    Unknown (usually 01h)
  044h 2    Initial Value for [4808146h]  ;W_CONFIG_146h
  046h 2    Initial Value for [4808148h]  ;W_CONFIG_148h
  048h 2    Initial Value for [480814Ah]  ;W_CONFIG_14Ah
  04Ah 2    Initial Value for [480814Ch]  ;W_CONFIG_14Ch
  04Ch 2    Initial Value for [4808120h]  ;W_CONFIG_120h
  04Eh 2    Initial Value for [4808122h]  ;W_CONFIG_122h
  050h 2    Initial Value for [4808154h]  ;W_CONFIG_154h
  052h 2    Initial Value for [4808144h]  ;W_CONFIG_144h
  054h 2    Initial Value for [4808130h]  ;W_CONFIG_130h
  056h 2    Initial Value for [4808132h]  ;W_CONFIG_132h
  058h 2    Initial Value for [4808140h]  ;W_CONFIG_140h ;maybe ACK timeout?
  05Ah 2    Initial Value for [4808142h]  ;W_CONFIG_142h
  05Ch 2    Initial Value for [4808038h]  ;W_POWER_TX
  05Eh 2    Initial Value for [4808124h]  ;W_CONFIG_124h
  060h 2    Initial Value for [4808128h]  ;W_CONFIG_128h
  062h 2    Initial Value for [4808150h]  ;W_CONFIG_150h
  064h 69h  Initial 8bit values for BB[0..68h]
  0CDh 1    Unused (00h)
Below for Type2 (ie. when [040h]=2) (Mitsumi MM3155 and RF9008):
  0CEh 24h  Initial 24bit values for RF[0,4,5,6,7,8,9,0Ah,0Bh,1,2,3]
  0F2h 54h  Channel 1..14 2x24bit values for RF[5,6]
  146h 0Eh  Channel 1..14 8bit values for BB[1Eh] (usually somewhat B1h..B7h)
  154h 0Eh  Channel 1..14 8bit values for RF[9].Bit10..14 (usually 10h-filled)
Below for Type3 (ie. when [040h]=3) (Mitsumi MM3218) (and AR6013G):
  --- Type3 values are originated at 0CEh, following addresses depend on:  ---
  1) number of initial values, found at [042h]        ;usually 29h
  2) number of BB indices,     found at [0CEh+[042h]] ;usually 02h
  3) number of RF indices,     found at [043h]        ;usually 02h
  --- Below example addresses assume above values to be set to 29h,02h,02h ---
  0CEh 29h  Initial 8bit values for RF[0..28h]
  0F7h 1    Number of BB indices per channel
  0F8h 1    1st BB index
  0F9h 14   1st BB data for channel 1..14
  107h 1    2nd BB index
  108h 14   2nd BB data for channel 1..14
  116h 1    1st RF index
  117h 14   1st RF data for channel 1..14
  125h 1    2nd RF index
  126h 14   2nd RF data for channel 1..14
  134h 46   Unused (FFh-filled)
Below for both Type2 and Type3:
  162h 1    Unknown (usually 19h..1Ch)
  163h 1    Unused (FFh) (Inside CRC16 region, with config_length=138h)
  164h 99h  Unused (FFh-filled) (Outside CRC16 region, with config_length=138h)
  1FDh 1    DSi/3DS Wifi Board (01h=W015, 02h=W024, 03h=W028);\this was
  1FEh 1    DSi/3DS Wifi Flash (20h=With access point 4/5/6) ; FFh-filled on DS
  1FFh 1    DSi/3DS Same as on DS (FFh)                      ;/
Most of the Wifi settings seem to be always the same values on all currently existing consoles. Except for:
Values that are (obviously) different are the CRC16, and 4th-6th bytes of the MAC address. Also, initial values for BB[01h] and BB[1Eh], and channel 1..14 values for BB[1Eh], and unknown entry [162h] contain different calibration settings on all consoles.
Firmware v5 is having a new wifi ID [2Fh]=03h, and different RF[9] setting.
Firmware v6 (dslite) has wifi ID [2Fh]=05h, and same RF[9] setting as v5, additionally, v6 and up have different 2nd-3rd bytes of the MAC address.

Moreover, a LOT of values are different with Type3 chips (ie. when [040h]=3).

Note
Unlike for Firmware User Settings, the Firmware Header (and Wifi Settings) aren't stored in RAM upon boot. So the data must be retrieved via SPI bus by software.


DS Firmware Wifi Internet Access Points

Connection data 1 at WifiFlash[00020h]*8-400h (eg. 01FA00h/03FA00h/07FA00h)
Connection data 2 at WifiFlash[00020h]*8-300h (eg. 01FB00h/03FB00h/07FB00h)
Connection data 3 at WifiFlash[00020h]*8-200h (eg. 01FC00h/03FC00h/07FC00h)
These three 100h byte regions are used to memorize known internet access points. The NDS firmware doesn't use these regions, but games that support internet are allowed to read (and configure/write) them. The DSi firmware also supports configuring these entries.
  Addr Siz Expl.
  000h 64  Unknown (usually 00h-filled) (no Proxy supported on NDS)
  040h 32  SSID (ASCII name of the access point) (padded with 00h's)
  060h 32  SSID for WEP64 on AOSS router (each security level has its own SSID)
  080h 16  WEP Key 1 (for type/size, see entry E6h)
  090h 16  WEP Key 2  ;\
  0A0h 16  WEP Key 3  ; (usually 00h-filled)
  0B0h 16  WEP Key 4  ;/
  0C0h 4   IP Address           (0=Auto/DHCP)
  0C4h 4   Gateway              (0=Auto/DHCP)
  0C8h 4   Primary DNS Server   (0=Auto/DHCP)
  0CCh 4   Secondary DNS Server (0=Auto/DHCP)
  0D0h 1   Subnet Mask (0=Auto/DHCP, 1..1Ch=Leading Ones) (eg. 6 = FC.00.00.00)
  0D1h ..  Unknown (usually 00h-filled)
  0E6h 1   WEP Mode (0=None, 1/2/3=5/13/16 byte hex, 5/6/7=5/13/16 byte ascii)
  0E7h 1   Status (00h=Normal, 01h=AOSS, FFh=connection not configured/deleted)
  0E8h 1   Zero (not SSID Length, ie. unlike as entry 4,5,6 on DSi)
  0E9h 1   Unknown (usually 00h)
  0EAh 2   DSi only: MTU (Max transmission unit) (576..1500, usually 1400)
  0ECh 3   Unknown (usually 00h-filled)
  0EFh 1   bit0/1/2 - connection 1/2/3 (1=Configured, 0=Not configured)
  0F0h 6   Nintendo Wifi Connection (WFC) 43bit User ID
           (ID=([F0h] AND 07FFFFFFFFFFh)*1000, shown as decimal string
           NNNN-NNNN-NNNN-N000) (the upper 5bit of the last byte are
           containing additional/unknown nonzero data)
  0F6h 8   Unknown (nonzero stuff !?!)
  0FEh 2   CRC16 for Entries 000h..0FDh (with initial value 0000h)
For connection 3: entries [0EFh..0FDh] - always zero-filled?
The location of the first data block is at the User Settings address minus 400h, ie. Firmware Header [00020h]*8-400h.

Connection data 4 at WifiFlash[00020h]*8-A00h (eg. 01F400h) (DSi only)
Connection data 5 at WifiFlash[00020h]*8-800h (eg. 01F600h) (DSi only)
Connection data 6 at WifiFlash[00020h]*8-600h (eg. 01F800h) (DSi only)
The DSi has three extra 200h-byte regions (for use DSi games, with the new WPA/WPA2 encryption support, and with additional proxy support), these extra regions are found under "Advanced Setup" in the DSi firmware's "Internet" configuration menu.
  Addr Siz Expl.
  000h 32  Proxy Authentication Username (ASCII string, padded with 00's)
  000h 32  Proxy Authentication Password (ASCII string, padded with 00's)
  040h 32  SSID (ASCII string, padded with 00's) (see [0E8h] for length)
  060h ..  Maybe same as NDS
  080h 16  WEP Key (zerofilled for WPA)
  0xxh ..  Maybe same as NDS
  0C0h 4   IP Address           (0=Auto/DHCP)
  0C4h 4   Gateway              (0=Auto/DHCP)
  0C8h 4   Primary DNS Server   (0=Auto/DHCP)
  0CCh 4   Secondary DNS Server (0=Auto/DHCP)
  0D0h 1   Subnet Mask (0=Auto/DHCP, 1..1Ch=Leading Ones) (eg. 6 = FC.00.00.00)
  0D1h ..  Unknown (zerofilled)
  0E6h 1   WEP (00h=None/WPA/WPA2, 01h/02h/03h/05h/06h/07h=WEP, same as NDS)
  0E7h 1   WPA (00h=Normal, 10h=WPA/WPA2, 13h=WPS+WPA/WPA2, FFh=unused/deleted)
  0E8h 1   SSID Length in characters (01h..20h, or 00h=unused)
  0E9h 1   Unknown (usually 00h)
  0EAh 2   MTU Value (Max transmission unit) (576..1500, usually 1400)
  0ECh 3   Unknown (usually 00h-filled)
  0EFh 1   bit0/1/2 - connection 4/5/6 (1=Configured, 0=Not configured)
  0F0h 14  Zerofilled (or maybe ID as on NDS, if any such ID exists for DSi?)
  0FEh 2   CRC16 for Entries 000h..0FDh (with initial value 0000h)
  100h 32  Precomputed PSK (based on WPA/WPA2 password and SSID) ;\all zero
  120h 64  WPA/WPA2 password (ASCII string, padded with 00's)    ;/for WEP
  160h 33  Zerofilled
  181h 1   WPA (0=None/WEP, 4=WPA-TKIP, 5=WPA2-TKIP, 6=WPA-AES, 7=WPA2-AES)
  182h 1   Proxy Enable         (00h=None, 01h=Yes)
  183h 1   Proxy Authentication (00h=None, 01h=Yes)
  184h 48  Proxy Name (ASCII string, max 47 chars, padded with 00's)
  1B4h 52  Zerofilled
  1E8h 2   Proxy Port (16bit)
  1EAh 20  Zerofilled
  1FEh 2   CRC16 for Entries 100h..1FDh (with initial value 0000h) (0=deleted)
The location of the first data block (aka settings number 4) is at the User Settings address minus A00h, ie. Firmware Header [00020h]*8-A00h.
Observe that NDS consoles do have NDS Firmware bootcode/data in that area, so those new regions can exist on DSi only (or on homebrew NDS firmwares). Presence of the new regions is indicated in Firmware Header [001FEh], that byte is usually FFh=NDS or 20h=DSi, the DSi browser does internally replace FFh by 10h, and does then check if byte>=20h (ie. the new areas exist if the byte is 20h..FEh).
Note that the Proxy feature can be used to redirect internet access (when using a custom proxy server, one could redirect commercial games to homebrew servers; as done by the http://pbsds.net/ project) (actually the same should be possible with the DNS server entry, possibly with less traffic).

Note
The location of the user settings & connection data varies (eg. 01Fxxxh=DSi, 03Fxxxh=NDS, 07Fxxxh=iQueDS).

Nintendo Zone Beacons
DSi games and DSi browser can reportedly also connect to Nintendo's public access points (those that are announced via Nintendo Zone Beacons).

Hidden Connection data at WifiFlash[00020h]*8-100h (eg. xxFD00h)
This seems to hold an extra 100h-byte region (same as Connection data 1-3), some (or all) NDS/DSi games seem to be capable of using it (although it isn't shown in config menues). One theory is that it might be used for the Nintendo Wi-Fi USB Connector?


DS Firmware User Settings

Current Settings (RAM 27FFC80h-27FFCEFh, DSi: 2FFFC80h-2FFFCEFh)
User Settings 0 (Firmware 3FE00h-3FEFFh) ;(DSi & iQue use different address,
User Settings 1 (Firmware 3FF00h-3FFFFh) ;see Firmware Header [020h])
  Addr Size Expl.
  000h  2   Version (5) (Always 5, for all NDS/DSi Firmware versions)
  002h  1   Favorite color (0..15) (0=Gray, 1=Brown, etc.)
  003h  1   Birthday month (1..12) (Binary, non-BCD)
  004h  1   Birthday day   (1..31) (Binary, non-BCD)
  005h  1   Not used (zero)
  006h  20  Nickname string in UTF-16 format
  01Ah  2   Nickname length in characters    (0..10)
  01Ch  52  Message string in UTF-16 format
  050h  2   Message length in characters     (0..26)
  052h  1   Alarm hour     (0..23) (Binary, non-BCD)
  053h  1   Alarm minute   (0..59) (Binary, non-BCD)
  054h  2
  056h  1   80h=enable alarm (huh?), bit 0..6=enable?
  057h  1   Zero (1 byte)
  058h  2x2 Touch-screen calibration point (adc.x1,y1) 12bit ADC-position
  05Ch  2x1 Touch-screen calibration point (scr.x1,y1) 8bit pixel-position
  05Eh  2x2 Touch-screen calibration point (adc.x2,y2) 12bit ADC-position
  062h  2x1 Touch-screen calibration point (scr.x2,y2) 8bit pixel-position
  064h  2   Language and Flags (see below)
  066h  1   Year (2000..2255) (when having entered date in the boot menu)
  067h  1   Unknown (usually 00h...08h or 78h..7Fh or so)
  068h  4   RTC Offset (difference in seconds when RTC time/date was changed)
  06Ch  4   Not used (FFh-filled, sometimes 00h-filled) (=MSBs of above?)
Below not stored in RAM (found only in FLASH memory)...
  070h  2   Update counter (used to check latest) (must be 0000h..007Fh)
  072h  2   CRC16 of entries 00h..6Fh (70h bytes)
  074h  8Ch Not used (FFh-filled) (or extended data, see below)
Below extended data was invented for iQue DS (for adding the chinese language setting), and is also included in Nintendo DSi models. Presence of extended data is indicated in Firmware Header entry [1Dh].Bit6.
  074h  1   Unknown (01h) (maybe version?)
  075h  1   Extended Language (0..5=Same as Entry 064h, plus 6=Chinese)
            (for language 6, entry 064h defaults to english; for compatibility)
            (for language 0..5, both entries 064h and 075h have same value)
  076h  2   Bitmask for Supported Languages (Bit0..6)
            (007Eh for iQue DS, ie. with chinese, but without japanese)
            (0042h for iQue DSi, chinese (and english, but only for NDS mode))
            (003Eh for DSi/EUR, ie. without chinese, and without japanese)
  078h  86h Not used (FFh-filled on iQue DS, 00h-filled on DSi)
  0FEh  2   CRC16 of entries 74h..FDh (8Ah bytes)
Note: The DSi does store the user settings in eMMC files (TWLCFGn.dat), that files include NDS-style settings (username etc), plus additional DSi-specific settings (country, parental controls, etc). For backwards compatibilty, the DSi does also store a copy of those settings in NDS-style format in Wifi FLASH and Main RAM at 2FFFC80h.
DSi SD/MMC Firmware System Settings Data Files
DSi Backlight level and DSi sound volume seem to be stored in the BPTWL chip (or possibly in its attached I2C potentiometer).

Language and Flags (Entry 064h)
  0..2 Language (0=Japanese, 1=English, 2=French, 3=German,
       4=Italian, 5=Spanish, 6..7=Reserved) (for Chinese see Entry 075h)
       (the language setting also implies time/data format)
  3    GBA mode screen selection (0=Upper, 1=Lower)
  4-5  Backlight Level    (0..3=Low,Med,High,Max) (DS-Lite only)
  6    Bootmenu Disable   (0=Manual/bootmenu, 1=Autostart Cartridge)
  7-8  ?
  9    Settings Lost (1=Prompt for User Info, and Language, and Calibration)
  10   Settings Okay (0=Prompt for User Info)
  11   Settings Okay (0=Prompt for User Info) (Same as Bit10)
  12   No function
  13   Settings Okay (0=Prompt for User Info, and Language)
  14   Settings Okay (0=Prompt for User Info) (Same as Bit10)
  15   Settings Okay (0=Prompt for User Info) (Same as Bit10)
The Health and Safety message is skipped if Bit9=1, or if one or more of the following bits is zero: Bits 10,11,13,14,15. However, as soon as entering the bootmenu, the Penalty-Prompt occurs.

Note: There are two User Settings areas in the firmware chip, at offset 3FE00h and 3FF00h, if both areas have valid CRCs, then the current/newest area is that whose Update Counter is one bigger than in the other/older area.
  IF count1=((count0+1) AND 7Fh) THEN area1=newer ELSE area0=newer
When changing settings, the older area is overwritten with new data (and incremented Update Counter). The two areas allow to recover previous settings in case of a write-error (eg. on a battery failure during write).

Battery Removal
Even though the battery is required only for the RTC (not for the firmware flash memory), most of the firmware user settings are reset when removing the battery. This appears to be a strange bug-or-feature of the DS bios, at least, fortunately, it still keeps the rest of the firmware intact.


DS Firmware Extended Settings

Extended Settings contain some additional information which is not supported by the original firmware (current century, date/time formats, temperature calibration, etc.), the settings are supported by Nocash Firmware, by the no$gba emulator, and may be eventually also supported by other emulators. If present, the values can be used by games, otherwise games should use either whatever default settings, or contain their own configuration menu.

Extended Settings - loaded to 23FEE00h (aka fragments of NDS9 boot code)
  Addr Siz Expl.
  00h  8  ID "XbooInfo"
  08h  2  CRC16 Value [0Ch..0Ch+Length-1]
  0Ah  2  CRC16 Length (from 0Ch and up)
  0Ch  1  Version (currently 01h)
  0Dh  1  Update Count (newer = (older+1) AND FFh)
  0Eh  1  Bootmenu Flags
            Bit6   Important Info  (0=Disable, 1=Enable)
            Bit7   Bootmenu Screen (0=Upper, 1=Lower)
  0Fh  1  GBA Border (0=Black, 1=Gray Line)
  10h  2  Temperature Calibration TP0 ADC value  (x16) (sum of 16 ADC values)
  12h  2  Temperature Calibration TP1 ADC value  (x16) (sum of 16 ADC values)
  14h  2  Temperature Calibration Degrees Kelvin (x100) (0=none)
  16h  1  Temperature Flags
            Bit0-1 Format (0=Celsius, 1=Fahrenheit, 2=Reaumur, 3=Kelvin)
  17h  1  Backlight Intensity (0=0ff .. FFh=Full)
  18h  4  Date Century Offset       (currently 20, for years 2000..2099)
  1Ch  1  Date Month Recovery Value (1..12)
  1Dh  1  Date Day Recovery Value   (1..31)
  1Eh  1  Date Year Recovery Value  (0..99)
  1Fh  1  Date/Time Flags
            Bit0-1 Date Format   (0=YYYY-MM-DD, 1=MM-DD-YYYY, 2=DD-MM-YYYY)
            Bit2   Friendly Date (0=Raw Numeric, 1=With Day/Month Names)
            Bit5   Time DST      (0=Hide DST, 1=Show DST=On/Off)
            Bit6   Time Seconds  (0=Hide Seconds, 1=Show Seconds)
            Bit7   Time Format   (0=24 hour, 1=12 hour)
  20h  1  Date Separator      (Ascii, usually Slash, or Dot)
  21h  1  Time Separator      (Ascii, usually Colon, or Dot)
  22h  1  Decimal Separator   (Ascii, usually Comma, or Dot)
  23h  1  Thousands Separator (Ascii, usually Comma, or Dot)
  24h  1  Daylight Saving Time (Nth)
             Bit 0-3 Activate on (0..4 = Last,1st,2nd,3rd,4th)
             Bit 4-7 Deactivate on (0..4 = Last,1st,2nd,3rd,4th)
  25h  1  Daylight Saving Time (Day)
             Bit 0-3 Activate on (0..7 = Mon,Tue,Wed,Thu,Fri,Sat,Sun,AnyDay)
             Bit 4-7 Deactivate on (0..7 = Mon,Tue,Wed,Thu,Fri,Sat,Sun,AnyDay)
  26h  1  Daylight Saving Time (of Month)
             Bit 0-3 Activate DST in Month   (1..12)
             Bit 4-7 Deactivate DST in Month (1..12)
  27h  1  Daylight Saving Time (Flags)
             Bit 0   Current DST State (0=Off, 1=On)
             Bit 1   Adjust DST Enable (0=Disable, 1=Enable)
Note: With the original firmware, the memory region at 23FEE00h and up contains un-initialized, non-zero-filled data (fragments of boot code).


DS File Formats

DS Files - 2D Video
DS Files - 3D Video
DS Files - Sound (SDAT etc.)
DS Files - Text Messages (MESG)
DS Files - Text Manuals
DS Cartridge Nitro Font Resource Format
DS Cartridge NitroROM and NitroARC File Systems
LZ Decompression Functions
LZ Decompression Functions ASH0
ZIP Decompression
PNG Bitmaps
DS Encrypted Arika Archives with ALZ1 compression
DS Files - Vicarious Vision GFC/GOB Archives with ZLIB compression


DS Files - Text Messages (MESG)

MESG files contain localized strings (like "Okay" and "Cancel" and longer text messages). Different languages are stored separate message files, usually with .bmg extension. MESG files are used in NDS/DSi titles (in little endian), and also on Wii (in big endian).
DSi titles are: DSi Shop, Launcher, System Settings, and DSi Camera (however, the DSi-to-3DS Transfer Tool uses the newer MsgPrjBn/MsgStdBn format; despite of being a DSi program).

MESG Header
  000h 8     ID "MESGbmg1"         ;or "GSEM1gmb" in Super Mario 64 DS
  008h 4     Total Filesize        ;or Filesize+1 in Super Mario 64 DS
  00Ch 4     Number of Chunks (2=INF1+DAT1, 3=INF1+DAT1+MID1)
  010h 1     Encoding (1=CP1252, 2=UTF-16, 3=Shift-JIS, 4=UTF-8)
  011h 15    Padding (0)
Encoding UTF-16 appears to be most common (Super Mario 64 DS uses Shift-JIS).

INF1 Chunk (Message Info)
It comes just after the BMG header. It contains information (like pointers) about the messages.
  000h 4     Chunk ID "INF1"       ;or "1FNI" in Super Mario 64 DS
  004h 4     Chunk Size
  008h 2     Number of messages (N)
  00Ah 2     Size of each INF data in bytes  ;or in BITs in Super Mario 64 DS
  00Ch 4     "BMG file ID = ID for this BMG file (usually 0)"
  010h N*siz Message Info (32bit offset from DAT1+8, and optional attributes)
For each message, there is a INF data about it. At Wii Fit, there is just the message offset. At Wii Fit Plus, there is two another fields.
  000h 4     Offset to the message (after DAT1+8 section header)
  004h siz-4 Attributes/flags (if entrysize is bigger than 4 bytes)
The optional Attribute bits could be used to select different font types or window styles.

DAT1 Chunk (Message Strings)
  000h 4     Chunk ID "DAT1"       ;or "1TAD" in Super Mario 64 DS
  004h 4     Chunk Size            ;or Size+1 in Super Mario 64 DS
  008h ..    Message strings (usually UTF-16, depending on Encoding in header)
The DSi Camera uses both char 001Ah and 0025h for escape codes.
UTF-16 string characters:
  0000                           End of String (except inside Escape sequences)
  000A                           Linebreak
  001A,nn,command,parameters     Escape Sequences (nn=length in bytes)
  001A,08,00,0000,00xx           Set font size (64h=100%=Normal Size)
  001A,08,00,0001,00xx           Set text color to xx
  001A,08,01,0000,24xx           Draw Unicode char U+2460..246E ;"(1)"..("15)"
  001A,08,01,0000,xxxx           Draw Unicode char U+E068..F12B ;custom?
  001A,06,02,0000                Draw Name of current player
  001A,0A,02,0010,000x,000w      Draw Integer from index x with w digits
  001A,08,02,0011,00xx           Unknown (with xx=0..8)
  001A,08,02,0012,0000           Draw Name of a player
  001A,08,02,0013,0000           Unknown
  001A,08,02,0014,0000           Unknown
  001A,08,02,0015,0000           Unknown
  001A,0A,02,0016,0000,0000      Unknown
  001A,08,02,0017,0000           Unknown
  001A,08,02,0020,0000           Draw Name of a Wii friend
  001A,08,03,0010,0000           Unknown
  001A,0C,04,0000,000x,yyyy,zzzz Unknown (x=0..1, y=0524..14A4, and z=y+1)
  0025,00xx,00yy,00zz            Escape codes in form of "%xyz" (or similar)
  00xx                           ASCII Characters 20h..7Eh
  E0xx                           Custom button symbols (eg. in DSi Launcher)
Shift-JIS (or whatever) strings in Super Mario 64 DS:
  0D       Linebreak?
  10..1F   Escape codes?
  xx,xx    Unknown (doesn't really look like english Shift-JIS characters)
  FF       End of String

MID1 Chunk (Message IDs) (if any)
  000h 4     Chunk ID "MID1"
  004h 4     Chunk Size
  008h 2     Number of messages (same as in INF1 block)
  00Ah 2     Unknown (usually 1000h)
  00Ch 4     Padding (0)
  010h 4*N   Message IDs
Messages can be repeated in the different files (such like menu and ingame), if so, all messages with the same message ID of the same language are always having the same text, no differences between the text files can be found.
"Elements with the same table index are attributes (not IDs?) for the same string."

FLW1 and FLT1 Chunks (if any)
Some games are reportedly having additional "FLW1" and "FLT1" chunks. Unknown which games, and unknown what for, and unknown if such chunks exist in any DS games (or only in Wii games or whatever).

Thanks to http://wiki.tockdom.com/wiki/BMG


DS Files - Text Manuals

Manual files are common in DSiware download titles, unknown if DS/DSi cartridges did also use that files (or if they did stick with print manuals).
Used in DSi Flipnote, Sudoku, Paper Plane, Deep Psyche, Dr. Mario, DSi-to-3DS Transfer Tool.
Usually found in "rom:\..\manpages_narc.blz" (with two folders in the .blz file, "arc" for the manual, and "gpArc" with a quick reference on how to read the manual; the latter containing only two "pages", without "content" file).

NTLI File (manual language info) (in "ntli" folder)
  000h 4     ID "NTLI"
  004h 2     Byte Order  (FEFFh)
  006h 2     Version     (can be 0200h)
  008h 4     Total Filesize
  00Ch 2     Header Size (10h)
  00Eh 4     Number of Chunks (usually 1 = mtl1)
mtl1 Chunk
  000h 4     Chunk ID "mtl1"
  004h 4     Chunk Size
  008h 4     Number of supported languages
  00Ch 2*N   Language IDs (two-letter ASCII spelled backwards)
Known IDs are ne=English, rf=French, se=Spanish, ti=Italian, ed=German.
EUR games do usually support 5 languages (Deep Psyche supports less).
IDs for Japanese/Chinese/Korean are unknown (also unknown if US has different IDs for english/spanish etc, and if portugese or so do exist on DSi).
Note: The two-letters do directly translate to the "ntmc\xx\" and "ntpg\xx\" folder names.

NTMC File (manual contents) (in "ntmc\xx\" folders)
The content contains "hyperlinks" to the actual chapters. A chapter can be divided into subsections (with the subsections being shown at the right of the main chapter name).
  000h 4     ID "NTMC"
  004h 2     Byte Order  (FEFFh)
  006h 2     Version     (can be 0200h)
  008h 4     Total Filesize
  00Ch 2     Header Size (10h)
  00Eh 4     Number of Chunks (usually 3 = nap1+txp1+mtc1)
nap1 Chunk
  000h 4     Chunk ID "nap1"
  004h 4     Chunk Size
  008h 4     Number of chapters (aka pages) minus 1?  (eg. 18h=19h)
  00Ch 4*N   Offsets to filenames (from nap+0Ch)
  ...  ..    Filenames (ASCII, terminated by 00h)
txp1 Chunk
  000h 4     Chunk ID "txp1"
  004h 4     Chunk Size
  008h 4     Number of something?? minus 1            (eg. 25h=26h)
  00Ch 4*N   Offsets to something?? (from txp1+0Ch)
  ...  ..    Somewhat corrupt UTF-16 strings (many aborted with char 20xxh)
mtc1 Chunk
  000h 4     Chunk ID "mtc1"
  004h 4     Chunk Size
  008h 4     Number of dunno what                  (eg. 0Dh=Much more?)
  00Ch 2*?   16bit Indices in txp1? (eg. 0000h..0025h)

NTPG File (manual pages) (or rather chapters?) (in "ntpg\xx\" folders)
The pages can contain text, tables, and symbols/images/screenshots (there appears to be no support for hyperlinks inside of the pages; probably because they default to be displayed on upper screen, without touchscreen support).
  000h 4     ID "NTPC"
  004h 2     Byte Order  (FEFFh)
  006h 2     Version     (can be 0200h)
  008h 4     Total Filesize
  00Ch 2     Header Size (10h)
  00Eh 4     Number of Chunks (usually 7 = nap1+txp1+pag1+pan1+pas1+txt1+pae1)
nap1 Chunk
  000h 4     Chunk ID "nap1"
  004h 4     Chunk Size (10h)
  008h 4     Zero (unlike as in NTMC file)
  00Ch 4     Unknown (4)
txp1 Chunk
  000h 4     Chunk ID "txp1"
  004h 4     Chunk Size
  008h 4     Number of something?? minus 1            (eg. 02h=03h)
  00Ch 4*N   Offsets to something?? (from txp1+0Ch)
  ...  ..    UTF-16 strings (Headline, Body, Footer?)
pag1 Chunk
  000h 4     Chunk ID "pag1"
  004h 4     Chunk Size (10h)
  008h 2?    0000h text color black?
  00Ah 2?    0160h link color or so?
  00Ch 2?    7FFFh bg color white?
  00Eh 2?    0000h
pan1 Chunk
  000h 4     Chunk ID "pan1"
  004h 4     Chunk Size (10h)
  008h 2?    0000h
  00Ah 2?    0000h
  00Ch 2?    0100h
  00Eh 2?    0160h link color or so?
pas1 Chunk (start?)
  000h 4     Chunk ID "pan1"
  004h 4     Chunk Size (0Ch)
  008h 4?    00000001h
txt1 Chunk
  000h 4     Chunk ID "txt1"
  004h 4     Chunk Size
  008h 2?    0008h
  00Ah 2?    0008h
  00Ch 2?    00F0h
  00Eh 2?    0150h
  010h 2?    0001h
  012h 2?    0015h  Number of 8-byte entries? start/end line-wrapping list?
  014h 2?    000Dh
  016h 2?    0010h
  018h 4?    00000000h
  01Ch 4?    00001CE7h
  020h 4?    00000000h
  024h 4?    00000000h
  028h N*8   Unknown 8-byte entries? (00xxh,0010h,0000h,00yyh)
             Or maybe positioning for symbols/images/tables?
pae1 Chunk (end?)
  000h 4     Chunk ID "pae1"
  004h 4     Chunk Size (08h)

NTTF File (manual graphics/symbols) (in "nttf" folder)
  000h 2  Bitmap Width in bytes (eg. 0Fh, 10h, 14h, 40h, 60h)
  002h 2  Bitmap Height         (eg. 12h, 0Eh, 14h, 30h, 47h)
  004h 1  Unknown, maybe Texture Format? (always 04h=256-Color?)
  005h 1  Unknown, maybe Color0.alpha?   (00h or 01h) (often same as [007h])
  006h 2  Number of Palette entries (usually 10h, 80h, or 100h)
  008h 8  Zerofilled
  010h .. Palette data (with 16bit values in range 0000h..7FFFh)
  ...  .. Bitmap data (seems to be always 8bpp)
Width/height can be odd (the bitmap doesn't contain any padding to even width/height... except, maybe padding to bytesize in case color depths other than 8bpp should exist?).

Notes
DSi manuals are using the TWLFontTable.dat system font (Flipnote, at least).
3DS manuals consist of CLYT and CLIM files (inside of a manual BCMA darc archive in a NCCH file).


DS Wireless Communications

DS Wifi I/O Map
DS Wifi Control
DS Wifi Interrupts
DS Wifi Power-Down Registers
DS Wifi Receive Control
DS Wifi Receive Buffer
DS Wifi Receive Statistics
DS Wifi Transmit Control
DS Wifi Transmit Buffers
DS Wifi Transmit Errors
DS Wifi Status
DS Wifi Timers
DS Wifi Multiplay Master
DS Wifi Multiplay Slave
DS Wifi Configuration Ports
DS Wifi Baseband Chip (BB)
DS Wifi RF Chip
DS Wifi RF9008 Registers
DS Wifi Unknown Registers
DS Wifi Unused Registers
DS Wifi Initialization
DS Wifi Flowcharts
DS Wifi Hardware Headers
DS Wifi Nintendo Beacons
DS Wifi Nintendo DS Download Play
DS Wifi IEEE802.11 Frames
DS Wifi IEEE802.11 Managment Frames (Type=0)
DS Wifi IEEE802.11 Control and Data Frames (Type=1 and 2)
DS Wifi WPA/WPA2 Handshake Messages (EAPOL)
DS Wifi WPA/WPA2 Keys and MICs
DS Wifi WPA/WPA2 Encryption
DS Wifi FFC ID
DS Wifi Dslink/Wifiboot Protocol
DS Firmware Wifi Calibration Data
DS Firmware Wifi Internet Access Points

2.4GHz band, Wireless LAN (WLAN) IEEE802.11b protocol

Credits
A very large part of the DS Wifi chapters is based on Stephen Stair's great DS Wifi document, thanks there.


DS Wifi I/O Map

Notice
Wifi Registers & RAM cannot be written to by STRB opcodes (ignored).

Registers - NDS7 - 4808000h..4808FFFh
  Address  Dir   Name            r/w  [Init] Description
  4808000h R     W_ID            ---- [1440] Chip ID (1440h=DS, C340h=DS-Lite)
  4808004h R/W   W_MODE_RST      9fff [0000] Mode/Reset
  4808006h R/W   W_MODE_WEP      --7f [0000] Mode/Wep modes
  4808008h R/W   W_TXSTATCNT     ffff [0000] Beacon Status Request
  480800Ah R/W   W_X_00Ah        ffff [0000] [bit7 - ingore rx duplicates]
  4808010h R/W   W_IF            ackk [0000] Wifi Interrupt Request Flags
  4808012h R/W   W_IE            ffff [0000] Wifi Interrupt Enable
  4808018h R/W   W_MACADDR_0     ffff [0000] Hardware MAC Address, 1st 2 bytes
  480801Ah R/W   W_MACADDR_1     ffff [0000] Hardware MAC Address, next 2 bytes
  480801Ch R/W   W_MACADDR_2     ffff [0000] Hardware MAC Address, last 2 bytes
  4808020h R/W   W_BSSID_0       ffff [0000] BSSID (first 2 bytes)
  4808022h R/W   W_BSSID_1       ffff [0000] BSSID (next 2 bytes)
  4808024h R/W   W_BSSID_2       ffff [0000] BSSID (last 2 bytes)
  4808028h R/W   W_AID_LOW       ---f [0000] usually as lower 4bit of AID value
  480802Ah R/W   W_AID_FULL      -7ff [0000] AID value assigned by a BSS.
  480802Ch R/W   W_TX_RETRYLIMIT ffff [0707] Tx Retry Limit (set from 00h-FFh)
  480802Eh R/W   W_INTERNAL      ---1 [0000]
  4808030h R/W   W_RXCNT         ff0e [0000] Receive control
  4808032h R/W   W_WEP_CNT       ffff [0000] WEP engine enable
  4808034h R?    W_INTERNAL      0000 [0000] bit0,1 (see ports 004h,040h,1A0h)
Power-Down Registers (and Random Generator)
  4808036h R/W   W_POWER_US      ---3 [0001]
  4808038h R/W   W_POWER_TX      ---7 [0003]
  480803Ch R/W   W_POWERSTATE    -r-2 [0200]
  4808040h R/W   W_POWERFORCE    8--1 [0000]
  4808044h R     W_RANDOM        0xxx [0xxx]
  4808048h R/W   W_POWER_?       ---3 [0000]
Receive Control/Memory
  4808050h R/W   W_RXBUF_BEGIN   ffff [4000]
  4808052h R/W   W_RXBUF_END     ffff [4800]
  4808054h R     W_RXBUF_WRCSR   0rrr [0000]
  4808056h R/W   W_RXBUF_WR_ADDR -fff [0000]
  4808058h R/W   W_RXBUF_RD_ADDR 1ffe [0000]
  480805Ah R/W   W_RXBUF_READCSR -fff [0000]
  480805Ch R/W   W_RXBUF_COUNT   -fff [0000]
  4808060h R     W_RXBUF_RD_DATA rrrr [xxxx]
  4808062h R/W   W_RXBUF_GAP     1ffe [0000]
  4808064h R/W   W_RXBUF_GAPDISP -fff [0000]
Transmit Control/Memory
  4808068h R/W   W_TXBUF_WR_ADDR 1ffe [0000]
  480806Ch R/W   W_TXBUF_COUNT   -fff [0000]
  4808070h W     W_TXBUF_WR_DATA xxxx [xxxx]
  4808074h R/W   W_TXBUF_GAP     1ffe [0000]
  4808076h R/W   W_TXBUF_GAPDISP 0fff [0000]
  4808078h W     W_INTERNAL      mirr [mirr] Read: Mirror of 068h
  4808080h R/W   W_TXBUF_BEACON  ffff [0000] Beacon Transmit Location
  4808084h R/W   W_TXBUF_TIM     --ff [0000] Beacon TIM Index in Frame Body
  4808088h R/W   W_LISTENCOUNT   --ff [0000] Listen Count
  480808Ch R/W   W_BEACONINT     -3ff [0064] Beacon Interval
  480808Eh R/W   W_LISTENINT     --ff [0000] Listen Interval
  4808090h R/W   W_TXBUF_CMD     ffff [0000] Multiplay Command
  4808094h R/W   W_TXBUF_REPLY1  ffff [0000] Multiplay Next Reply
  4808098h R     W_TXBUF_REPLY2  0000 [0000] Multiplay Current Reply
  480809Ch R/W   W_INTERNAL      ffff [0050] value 4x00h --> preamble+x*12h us?
  48080A0h R/W   W_TXBUF_LOC1    ffff [0000]
  48080A4h R/W   W_TXBUF_LOC2    ffff [0000]
  48080A8h R/W   W_TXBUF_LOC3    ffff [0000]
  48080ACh W     W_TXREQ_RESET   fixx [0050]
  48080AEh W     W_TXREQ_SET     fixx [0050]
  48080B0h R     W_TXREQ_READ    --1f [0010]
  48080B4h W     W_TXBUF_RESET   0000 [0000]    (used by firmware part4)
  48080B6h R     W_TXBUSY        0000 [0000]    (used by firmware part4)
  48080B8h R     W_TXSTAT        0000 [0000]
  48080BAh ?     W_INTERNAL      0000 [0000]
  48080BCh R/W   W_PREAMBLE      ---3 [0001]
  48080C0h R/W x W_CMD_TOTALTIME ffff [0000]    (used by firmware part4)
  48080C4h R/W x W_CMD_REPLYTIME ffff [0000]    (used by firmware part4)
xxx
  48080C8h ?     W_INTERNAL      0000 [0000]
  48080D0h R/W   W_RXFILTER      1fff [0401]
  48080D4h R/W   W_CONFIG_0D4h   ---3 [0001]
  48080D8h R/W   W_CONFIG_0D8h   -fff [0004]
  48080DAh R/W   W_RX_LEN_CROP   ffff [0602]
  48080E0h R/W   W_RXFILTER2     ---f [0008]
Wifi Timers
  48080E8h R/W   W_US_COUNTCNT   ---1 [0000] Microsecond counter enable
  48080EAh R/W   W_US_COMPARECNT ---1 [0000] Microsecond compare enable
  48080ECh R/W   W_CONFIG_0ECh   3f1f [3F03]
  48080EEh R/W   W_CMD_COUNTCNT  ---1 [0001]
  48080F0h R/W   W_US_COMPARE0   fc-- [FC00] Microsecond compare, bits 0-15
  48080F2h R/W   W_US_COMPARE1   ffff [FFFF] Microsecond compare, bits 16-31
  48080F4h R/W   W_US_COMPARE2   ffff [FFFF] Microsecond compare, bits 32-47
  48080F6h R/W   W_US_COMPARE3   ffff [FFFF] Microsecond compare, bits 48-63
  48080F8h R/W   W_US_COUNT0     ffff [0000] Microsecond counter, bits 0-15
  48080FAh R/W   W_US_COUNT1     ffff [0000] Microsecond counter, bits 16-31
  48080FCh R/W   W_US_COUNT2     ffff [0000] Microsecond counter, bits 32-47
  48080FEh R/W   W_US_COUNT3     ffff [0000] Microsecond counter, bits 48-63
  4808100h ?     W_INTERNAL      0000 [0000]
  4808102h ?     W_INTERNAL      0000 [0000]
  4808104h ?     W_INTERNAL      0000 [0000]
  4808106h ?     W_INTERNAL      0000 [0000]
  480810Ch R/W   W_CONTENTFREE   ffff [0000] ...
  4808110h R/W   W_PRE_BEACON    ffff [0000]
  4808118h R/W   W_CMD_COUNT     ffff [0000]
  480811Ch R/W   W_BEACON_COUNT  ffff [0000] reloaded with W_BEACONINT
Configuration Ports (and some other Registers)
  4808120h R/W   W_CONFIG_120h   81ff [0048] init from firmware[04Ch]
  4808122h R/W   W_CONFIG_122h   ffff [4840] init from firmware[04Eh]
  4808124h R/W   W_CONFIG_124h   ffff [0000] init from firmware[05Eh], or 00C8h
  4808126h ?     W_INTERNAL      fixx [ 0080]
  4808128h R/W   W_CONFIG_128h   ffff [0000] init from firmware[060h], or 07D0h
  480812Ah ?     W_INTERNAL      fixx [1000] lower 12bit same as W_CONFIG_128h
  4808130h R/W   W_CONFIG_130h   -fff [0142] init from firmware[054h]
  4808132h R/W   W_CONFIG_132h   8fff [8064] init from firmware[056h]
  4808134h R/W   W_POST_BEACON   ffff [FFFF] ...
  4808140h R/W   W_CONFIG_140h   ffff [0000] init from firmware[058h], or xx
  4808142h R/W   W_CONFIG_142h   ffff [2443] init from firmware[05Ah]
  4808144h R/W   W_CONFIG_144h   --ff [0042] init from firmware[052h]
  4808146h R/W   W_CONFIG_146h   --ff [0016] init from firmware[044h]
  4808148h R/W   W_CONFIG_148h   --ff [0016] init from firmware[046h]
  480814Ah R/W   W_CONFIG_14Ah   --ff [0016] init from firmware[048h]
  480814Ch R/W   W_CONFIG_14Ch   ffff [162C] init from firmware[04Ah]
  4808150h R/W   W_CONFIG_150h   ff3f [0204] init from firmware[062h], or 202h
  4808154h R/W   W_CONFIG_154h   7a7f [0058] init from firmware[050h]
Baseband Chip Ports
  4808158h W     W_BB_CNT        mirr [00B5] BB Access Start/Direction/Index
  480815Ah W     W_BB_WRITE      ???? [0000] BB Access data byte to write
  480815Ch R     W_BB_READ       00rr [00B5] BB Access data byte read
  480815Eh R     W_BB_BUSY       000r [0000] BB Access Busy flag
  4808160h R/W   W_BB_MODE       41-- [0100] BB Access Mode
  4808168h R/W   W_BB_POWER      8--f [800D] BB Access Powerdown
Internal Stuff
  480816Ah ?     W_INTERNAL      0000 [0001] (or 0000h?)
  4808170h ?     W_INTERNAL      0000 [0000]
  4808172h ?     W_INTERNAL      0000 [0000]
  4808174h ?     W_INTERNAL      0000 [0000]
  4808176h ?     W_INTERNAL      0000 [0000]
  4808178h W     W_INTERNAL      fixx [0800] Read: mirror of 17Ch
RF Chip Ports
  480817Ch R/W   W_RF_DATA2      ffff [0800]
  480817Eh R/W   W_RF_DATA1      ffff [C008]
  4808180h R     W_RF_BUSY       000r [0000]
  4808184h R/W   W_RF_CNT        413f [0018]
xxx
  4808190h R/W   W_INTERNAL      ffff [0000]
  4808194h R/W   W_TX_HDR_CNT    ---7 [0000] used by firmware part4 (0 or 6)
  4808198h R/W   W_INTERNAL      ---f [0000]
  480819Ch R     W_RF_PINS       fixx [0004]
  48081A0h R/W   W_X_1A0h        -933 [0000] used by firmware part4 (0 or 823h)
  48081A2h R/W   W_X_1A2h        ---3 [0001] used by firmware part4
  48081A4h R/W   W_X_1A4h        ffff [0000] "Rate used when signal test..."
Wifi Statistics
  48081A8h R     W_RXSTAT_INC_IF rrrr [0000] Stats Increment Flags
  48081AAh R/W   W_RXSTAT_INC_IE ffff [0000] Stats Increment IRQ Enable
  48081ACh R     W_RXSTAT_OVF_IF rrrr [0000] Stats Half-Overflow Flags
  48081AEh R/W   W_RXSTAT_OVF_IE ffff [0000] Stats Half-Overflow IRQ Enable
  48081B0h R/W   W_RXSTAT        --ff [0000]
  48081B2h R/W   W_RXSTAT        ffff [0000] RX_LengthRateErrorCount
  48081B4h R/W   W_RXSTAT        rrff [0000] ... firmware uses also MSB ... ?
  48081B6h R/W   W_RXSTAT        ffff [0000]
  48081B8h R/W   W_RXSTAT        --ff [0000]
  48081BAh R/W   W_RXSTAT        --ff [0000]
  48081BCh R/W   W_RXSTAT        ffff [0000]
  48081BEh R/W   W_RXSTAT        ffff [0000]
  48081C0h R/W   W_TX_ERR_COUNT  --ff [0000] TransmitErrorCount
  48081C4h R     W_RX_COUNT      fixx [0000]
[1D0 - 1DE are 15 entries related to multiplayer response errors]
  48081D0h R/W   W_CMD_STAT      ff-- [0000]
  48081D2h R/W   W_CMD_STAT      ffff [0000]
  48081D4h R/W   W_CMD_STAT      ffff [0000]
  48081D6h R/W   W_CMD_STAT      ffff [0000]
  48081D8h R/W   W_CMD_STAT      ffff [0000]
  48081DAh R/W   W_CMD_STAT      ffff [0000]
  48081DCh R/W   W_CMD_STAT      ffff [0000]
  48081DEh R/W   W_CMD_STAT      ffff [0000]
Internal Diagnostics Registers (usually not used for anything)
  48081F0h R/W   W_INTERNAL      ---3 [0000]
  4808204h ?     W_INTERNAL      fixx [0000]
  4808208h ?     W_INTERNAL      fixx [0000]
  480820Ch W     W_INTERNAL      fixx [0050]
  4808210h R     W_TX_SEQNO      fixx [0000]
  4808214h R     W_RF_STATUS     XXXX [0009]    (used by firmware part4)
  480821Ch W     W_IF_SET        fbff [0000] Force Interrupt (set bits in W_IF)
  4808220h R/W   W_RAM_DISABLE   ffff [0000] WifiRAM control
  4808224h R/W   W_INTERNAL      ---3 [0003]
  4808228h W     W_X_228h        fixx [0000]    (used by firmware part4) (bit3)
  4808230h R/W   W_INTERNAL      --ff [0047]
  4808234h R/W   W_INTERNAL      -eff [0EFF]
  4808238h R/W   W_INTERNAL      ffff [0000] ;rx_seq_no-60h+/-x   ;why that?
                                   ;other day: fixed value, not seq_no related?
  480823Ch ?     W_INTERNAL      fixx [0000] like W_TXSTAT... ONLY for beacons?
  4808244h R/W   W_X_244h        ffff [0000]    (used by firmware part4)
  4808248h R/W   W_INTERNAL      ffff [0000]
  480824Ch R     W_INTERNAL      fixx [0000] ;rx_mac_addr_0 ;\OverTheHedge
  480824Eh R     W_INTERNAL      fixx [0000] ;rx_mac_addr_1 ;/writes FFFFh?
  4808250h R     W_INTERNAL      fixx [0000] ;rx_mac_addr_2
  4808254h ?     W_CONFIG_254h   fixx [0000] (read: FFFFh=DS, EEEEh=DS-Lite)
  4808258h ?     W_INTERNAL      fixx [0000]
  480825Ch ?     W_INTERNAL      fixx [0000]
  4808260h ?     W_INTERNAL      fixx [ 0FEF]
  4808264h R     W_INTERNAL      fixx [0000] ;rx_addr_1 (usually "rxtx_addr-x")
  4808268h R     W_RXTX_ADDR     fixx [0005] ;rxtx_addr
  4808270h R     W_INTERNAL      fixx [0000] ;rx_addr_2 (usually "rx_addr_1-1")
  4808274h ?     W_INTERNAL      fixx [ 0001]
  4808278h R/W   W_INTERNAL      ffff [000F]
  480827Ch ?     W_INTERNAL      fixx [ 000A]
  4808290h (R/W) W_X_290h        fixx [FFFF] bit 0 = ? (used by firmware part4)
  4808298h W     W_INTERNAL      fixx [0000]
  48082A0h R/W   W_INTERNAL      ffff [0000]
  48082A2h R     W_INTERNAL      XXXX [7FFF] 15bit shift reg (used during tx?)
  48082A4h R     W_INTERNAL      fixx [0000] ;rx_rate_1 not ALWAYS same as 2C4h
  48082A8h W     W_INTERNAL      fixx [0000]
  48082ACh ?     W_INTERNAL      fixx [ 0038]
  48082B0h W     W_INTERNAL      fixx [0000]
  48082B4h R/W   W_INTERNAL      -1-3 [0000]
  48082B8h ?     W_INTERNAL      fixx [0000] ;dsi launcher checks if zero
  48082C0h R/W   W_INTERNAL      ---1 [0000]
  48082C4h R     W_INTERNAL      fixx [000A] ;rx_rate_2 (0Ah,14h = 1,2 Mbit/s)
  48082C8h R     W_INTERNAL      fixx [0000] ;rx_duration/length/rate (or so?)
  48082CCh R     W_INTERNAL      fixx [0000] ;rx_framecontrol; from ieee header
  48082D0h DIS   W_INTERNAL                  ;"W_POWERACK" (internal garbage)
                                             ;normally DISABLED (unless FORCE)
  48082F0h R/W   W_INTERNAL      ffff [0000]
  48082F2h R/W   W_INTERNAL      ffff [0000]
  48082F4h R/W   W_INTERNAL      ffff [0000]
  48082F6h R/W   W_INTERNAL      ffff [0000]
All other ports in range 4808000h..4808FFFh are unused.
All registers marked as "W_INTERNAL" aren't used by Firmware part4, and are probably unimportant, except for whatever special diagnostics purposes.
Reading from write-only ports (W) often mirrors to data from other ports.

Additionally, there are 69h Baseband Chip Registers (BB), and 0Fh RF Chip Registers (see BB and RF chapters).

For Wifi Power Managment (POWCNT2), for Wifi Waitstates (WIFIWAITCNT), see:
DS Power Control
For the Power LED Blink Feature (conventionally used to indicate Wifi activity) see:
DS Power Management Device

For Wifi Configuration and Calibration data in Firmware Header, see:
DS Cartridges, Encryption, Firmware

Wifi RAM - NDS7 - Memory (4804000h..4805FFFh)
  4804000h W_MACMEM RX/TX Buffers (2000h bytes) (excluding below specials)
  4805F60h Used for something, not included in the rx circular buffer.
  4805F80h W_WEPKEY_0 (32 bytes)
  4805FA0h W_WEPKEY_1 (32 bytes)
  4805FC0h W_WEPKEY_2 (32 bytes)
  4805FE0h W_WEPKEY_3 (32 bytes)
Unlike all other NDS memory, Wifi RAM is left uninitialized after boot.

4805F60h - Reserved 20h-byte RAM area
Nintendo's software does init/change several values:
  [480xxxxh]=5A5Ah/A5A5h  ;-initial dummy WifiRAM memfill values
  [4805F70h]=FFFFh        ;\
  [4805F72h]=FFFFh        ; set to FFFFh by software
  [4805F76h]=FFFFh        ;
  [4805F7Eh]=FFFFh        ;/
The hardware does update several values (unless disabled in W_RAM_DISABLE.bit5):
  [4805F6Eh]=0F00h (nothing received), or 0F01h (received something)
And, if received packet was accepted (eg. when W_RXFILTER.bit0=1=AcceptAll):
  [4805F70h]=Received MAC Address (6 bytes, looks same as port 480824Ch)
  [4805F76h]=xxx0h (increasing value, Sequence Control from packet header)
And, in multiplay slave mode (when receiving CMD packets?):
  [4805F7Eh]=xxx0h (next higher sequence number? ie. [4805F76h]+10h)

4805F80h - W_WEPKEY_0 thru W_WEPKEY_3 - Wifi WEP keys (R/W)
These WEP key slots store the WEP keys that are used for encryption for 802.11 keys IDs 0-3.


DS Wifi Control

4808000h - W_ID - Wifi Chip ID (R)
  0-15   Chip ID (1440h on NDS, C340h on NDS-lite)
The NDS-lite is more or less backwards compatible with the original NDS (the W_RXBUF_GAPDISP and W_TXBUF_GAPDISP are different, and most of the garbage effects on unused/mirrored ports are different, too).

4808004h - W_MODE_RST - Wifi Hardware mode / reset (R/W)
  0     Adjust some ports (0/1=see lists below) (R/W)
        TX Master Enable for LOC1..3 and Beacon  (0=Disable, 1=Enable)
  1-12  Unknown (R/W)
  13    Reset some ports (0=No change, 1=Reset/see list below) (Write-Only)
  14    Reset some ports (0=No change, 1=Reset/see list below) (Write-Only)
  15    Unknown (R/W)

4808006h - W_MODE_WEP - Wifi Software mode / Wep mode (R/W)
  0-2   Unknown, specify a software mode for wifi operation
        (may be related to hardware but a correlation has not yet been found)
  3-5   WEP Encryption Key Size:
         0=Reserved (acts same as 1)
         1=64bit WEP  (IV=24bit + KEY=40bit)  (aka 3+5 bytes)   ;standard/us
         2=128bit WEP (IV=24bit + KEY=104bit) (aka 3+13 bytes)  ;standard/world
         3=152bit WEP (IV=24bit + KEY=128bit) (aka 3+16 bytes)  ;uncommon
         4=Unknown, mabye 256bit WEP (IV=24bit + KEY=232bit) (aka 3+29 bytes)?
         5=Reserved (acts same as 1)
         6=Reserved (acts same as 1)
         7=Reserved (acts same as 1)
  6     Unknown
  7-15  Always zero

4808018h - W_MACADDR_0 - MAC Address (R/W)
480801Ah - W_MACADDR_1 - MAC Address (R/W)
480801Ch - W_MACADDR_2 - MAC Address (R/W)
48bit MAC Address of the console. Should be initialized from firmware[036h]. The hardware receives only packets that are sent to this address (or to group addresses, like FF:FF:FF:FF:FF:FF).

4808020h - W_BSSID_0 - BSSID (R/W)
4808022h - W_BSSID_1 - BSSID (R/W)
4808024h - W_BSSID_2 - BSSID (R/W)
48bit BSSID stored here. Ie. the MAC address of the host, obtained from Beacon frames (on the host itself, that should be just same as W_MACADDR). See W_RXFILTER.

4808028h - W_AID_LOW (R/W)
  Bit0-3   Multiplay Slave number (1..15, or 0)
  Bit4-15  Not used
Usually set to zero, or equal to the lower 4bit of the W_AID_FULL value.

480802Ah - W_AID_FULL - Association ID (R/W)
  Bit0-10  Association ID (AID) (1..2007, or zero)
  Bit11-15 Not used

4808032h - W_WEP_CNT - WEP Engine Enable (R/W)
  0-14  Unknown (usually zero)
  15    WEP Engine Enable  (0=Disable, 1=Enable)
Normally, bit15 should be always set (but it will only affect WEP-encrypted packets, ie. packets with Frame Control bit14=1 in 802.11 header). When disabled, WEP packets aren't received at all (neither in encrypted nor decrypted form), and sending WEP packets might be also ignored(?).
The firmware contains some code that does toggle the bit off for a moment (apparently to reset something after transfer errors).

4808044h - W_RANDOM - Random Generator (R)
  0-10  Random
  11-15 Not used (zero)
The random generator is updated at 33.51MHz rate, as such:
  X = (X AND 1) XOR (X ROL 1)  ;(rotation within 11bit range)
That random sequence goes through 5FDh different values before it restarts.
When reading from the random register, the old latched value is returned to the CPU, and the new current random value is then latched, so reads always return the older value, timed from the previous read.
Occassionally, about once every some thousand reads, the latching appears to occur 4 cycles earlier than normally, so the value on the next read will be 4 cycles older than expected.
The random register has ACTIVE mirrors.

48080BCh - W_PREAMBLE - Preamble Control (R/W)
  Bit   Dir  Expl.
  0     R/W  Unknown                    (this does NOT affect TX)
  1     R/W  Preamble (0=Long, 1=Short) (this does NOT affect TX)
  2     W    Preamble (0=Long, 1=Short) (this does affect TX) (only at 2Mbit/s)
  3-15  -    Always zero
Short preamble works only with 2Mbit/s transfer rate (ie. when set as so in TX hardware header). 1Mbit/s rate always uses long preamble.
  Type   Carrier Signal  SFD Value     PLCP Header     Data
  Long   128bit, 1Mbit   16bit, 1Mbit  48bit, 1Mbit    N bits, 1Mbit or 2Mbit
  Short  56bit, 1Mbit    16bit, 1Mbit  48bit, 2Mbit    N bits, 2Mbit
Length of the Carrier+SFD+PLCP part is thus 192us (long) or 96us (short).
Note: The Carrier+SFD+PLCP part is sent between IRQ14 and IRQ07 (not between IRQ07 and IRQ01).
Firmware also changes W_CONFIG_140h alongsides with the preamble setting.

Writing "0-then-1" to W_MODE_RST.Bit0 does reset following ports:
  [4808034h]=0002h ;W_INTERNAL
  [480819Ch]=0046h ;W_RF_PINS
  [4808214h]=0009h ;W_RF_STATUS
  [480827Ch]=0005h ;W_INTERNAL
  [48082A2h]=?     ;...unstable?

Writing "1-then-0" to W_MODE_RST.Bit0 does reset following ports:
  [480827Ch]=000Ah ;W_INTERNAL

Writing "1" to W_MODE_RST.Bit13 does reset following ports:
  [4808056h]=0000h ;W_RXBUF_WR_ADDR
  [48080C0h]=0000h ;W_CMD_TOTALTIME
  [48080C4h]=0000h ;W_CMD_REPLYTIME
  [48081A4h]=0000h ;W_X_1A4h
  [4808278h]=000Fh ;W_INTERNAL
  ...Also, following may be affected (results are unstable though)...
  [48080AEh]=?     ;or rather the actual port (which it is an mirror of)
  [48080BAh]=?     ;W_INTERNAL (occassionally unstable)
  [4808204h]=?     ;W_INTERNAL
  [480825Ch]=?     ;W_INTERNAL
  [4808268h]=?     ;W_RXTX_ADDR
  [4808274h]=?     ;W_INTERNAL

Writing "1" to W_MODE_RST.Bit14 does reset following ports:
  [4808006h]=0000h ;W_MODE_WEP
  [4808008h]=0000h ;W_TXSTATCNT
  [480800Ah]=0000h ;W_X_00Ah
  [4808018h]=0000h ;W_MACADDR_0
  [480801Ah]=0000h ;W_MACADDR_1
  [480801Ch]=0000h ;W_MACADDR_2
  [4808020h]=0000h ;W_BSSID_0
  [4808022h]=0000h ;W_BSSID_1
  [4808024h]=0000h ;W_BSSID_2
  [4808028h]=0000h ;W_AID_LOW
  [480802Ah]=0000h ;W_AID_FULL
  [480802Ch]=0707h ;W_TX_RETRYLIMIT
  [480802Eh]=0000h ;W_INTERNAL
  [4808050h]=4000h ;W_RXBUF_BEGIN
  [4808052h]=4800h ;W_RXBUF_END
  [4808084h]=0000h ;W_TXBUF_TIM
  [48080BCh]=0001h ;W_PREAMBLE
  [48080D0h]=0401h ;W_RXFILTER
  [48080D4h]=0001h ;W_CONFIG_0D4h
  [48080E0h]=0008h ;W_RXFILTER2
  [48080ECh]=3F03h ;W_CONFIG_0ECh
  [4808194h]=0000h ;W_TX_HDR_CNT
  [4808198h]=0000h ;W_INTERNAL
  [48081A2h]=0001h ;W_X_1A2h
  [4808224h]=0003h ;W_INTERNAL
  [4808230h]=0047h ;W_INTERNAL


DS Wifi Interrupts

4808010h - W_IF - Wifi Interrupt Request Flags (R/W)
  0   Receive Complete  (packet received and stored in the RX fifo)
  1   Transmit Complete (packet is done being transmitted) (no matter if error)
  2   Receive Event Increment        (IRQ02, see W_RXSTAT_INC_IE)
  3   Transmit Error Increment       (IRQ03, see W_TX_ERR_COUNT)
  4   Receive Event Half-Overflow    (IRQ04, see W_RXSTAT_OVF_IE)
  5   Transmit Error Half-Overflow   (IRQ05, see W_TX_ERR_COUNT.Bit7)
  6   Start Receive     (IRQ06, a packet has just started to be received)
  7   Start Transmit    (IRQ07, a packet has just started to be transmitted)
  8   Txbuf Count Expired            (IRQ08, see W_TXBUF_COUNT)
  9   Rxbuf Count Expired            (IRQ09, see W_RXBUF_COUNT)
  10  Not used (always zero, even when trying to set it with W_IF_SET)
  11  RF Wakeup                      (IRQ11, see W_POWERSTATE)
  12  Multiplay CMD done (or failed) (IRQ12, see W_CMD_COUNT)
  13  Post-Beacon Timeslot           (IRQ13, see W_POST_BEACON)
  14  Beacon Timeslot                (IRQ14, see W_BEACON_COUNT/W_US_COMPARE)
  15  Pre-Beacon Timeslot            (IRQ15, see W_BEACON_COUNT/W_PRE_BEACON)
Write a '1' to a bit to clear it. For the Half-Overflow flags that works ONLY if the counter MSBs are zero (ie. one must first read the counters (to reset them), and THEN acknowledge the corresponding W_IF bit).
The Transmit Start/Complete bits (Bit7,1) are set for EACH packet (including beacons, and including retries).

4808012h - W_IE - Wifi Interrupt Enable Flags (R/W)
  0-15  Enable Flags, same bits as W_IF  (0=Disable, 1=Enable)
In W_IE, Bit10 is R/W, but seems to have no function since IRQ10 doesn't exist.

480821Ch - W_IF_SET (W_INTERNAL) - Force Wifi Interrupt Flags (W)
  0-15  Set corresponding bits in W_IF  (0=No change, 1=Set Bit)
Notes: Bit10 cannot be set since no IRQ10 exists. This register does only set IRQ flags, but without performing special actions (such like W_BEACON_COUNT and W_POST_BEACON reloads that occur on real IRQ14's).

Wifi Primary IRQ Flag (IF.Bit24, Port 4000214h)
IF.Bit24 gets set <only> when (W_IF AND W_IE) changes from 0000h to non-zero.
IF.Bit24 can be reset (ack) <even> when (W_IF AND W_IE) is still non-zero.
  Caution  Caution  Caution  Caution  Caution
  That means, when acknowledging IF.Bit24, then NO FURTHER wifi IRQs
  will be executed whilst and as long as (W_IF AND W_IE) is non-zero.
One work-around is to process/acknowledge ALL wifi IRQs in a loop, including further IRQs that may occur inside of that loop, until (W_IF AND W_IE) becomes 0000h.
Another work-around (for single IRQs) would be to acknowledge IF and W_IF, and then to set W_IE temporarily to 0000h, and then back to the old W_IE setting.


DS Wifi Power-Down Registers

4808036h - W_POWER_US (R/W)
  0     Disable W_US_COUNT and W_BB_ports  (0=Enable, 1=Disable)
  1     Unknown (usually 0)
  2-15  Always zero
Bit0=0 enables RFU by setting RFU.Pin11=HIGH, which activates the 22.000MHz oscillator on the RFU board, the 22MHz clock is then output to RFU.Pin26.

4808038h - W_POWER_TX (R/W)
transmit-related power save or sth
init from firmware[05Ch]
  0     Auto Wakeup (1=Leave Idle Mode a while after Pre-Beacon IRQ15)
  1     Auto Sleep  (0=Enter Idle Mode on Post-Beacon IRQ13)
  2     Unknown
  3     Unknown (Write-only) (used by firmware)
  4-15  Always zero

480803Ch - W_POWERSTATE (R/W)/(R)
  0     Unknown (usually 0)                         (R/W)
  1     Request Power Enable (0=No, 1=Yes/queued)   (R/W, but not always)
  2-7   Always zero
  8     Indicates that Bit9 is about the be cleared (Read only)
  9     Current power state (0=Enabled, 1=Disabled) (Read only)
  10-15 Always zero
[value =1: queue disable power state] ;<-- seems to be incorrect
[value =2: queue enable power state] ;<-- seems to be correct
Enabling causes wakeup interrupt (IRQ11).
Note: That queue stuff seems to work only if W_POWER_US=0 and W_MODE_RST=1.

4808040h - W_POWERFORCE - Force Power State (R/W)
  0     New value for W_POWERSTATE.Bit9  (0=Clear/Delayed, 1=Set/Immediately)
  1-14  Always zero
  15    Apply Bit0 to W_POWERSTATE.Bit9  (0=No, 1=Yes)
Setting W_POWERFORCE=8001h whilst W_POWERSTATE.Bit9=0 acts immediately:
  (Doing this is okay. Switches to power down mode. Similar to IRQ13.)
  [4808034h]=0002h ;W_INTERNAL
  [480803Ch]=02xxh ;W_POWERSTATE
  [48080B0h]=0000h ;W_TXREQ_READ
  [480819Ch]=0046h ;W_RF_PINS
  [4808214h]=0009h ;W_RF_STATUS (idle)
Setting W_POWERFORCE=8000h whilst W_POWERSTATE.Bit9=1 acts delayed:
  (Don't do this. After that sequence, the hardware seems to be messed up)
  W_POWERSTATE.Bit8 gets set to indicate the pending operation,
  while pending, changes to W_POWERFORCE aren't applied to W_POWERSTATE,
  while pending, W_POWERACK becomes Read/Write-able,
  writing 0000h to W_POWERACK does clear W_POWERSTATE.Bit8,
  and does apply POWERFORCE.Bit0 to W_POWERSTATE.Bit9
  and does deactivate Port W_POWERACK again.

4808048h - W_POWER_? (R/W)
  0     Unknown
  1     Unknown
  2-15  Always zero
At whatever time (during transmit or so) it gets set to 0003h by hardware.

See also: POWCNT2, W_BB_POWER.


DS Wifi Receive Control

4808030h - W_RXCNT - Wifi Receive Control (parts R/W and W)
  0     Copy W_RXBUF_WR_ADDR to W_RXBUF_WRCSR (aka force RX buf empty)      (W)
  1-3   Unknown                                                           (R/W)
  4-6   Always zero
  7     Copy W_TXBUF_REPLY1 to W_TXBUF_REPLY2, set W_TXBUF_REPLY1 to 0000h  (W)
  8-14  Unknown                                                           (R/W)
  15    Enable Queuing received data to RX FIFO                           (R/W)

48080D0h - W_RXFILTER - (R/W)
  0     For Broadcasts? (0=Insist on W_BSSID, 1=Accept no matter of W_BSSID)
  1     Unknown (usually zero)
  2     Unknown (usually zero)
  3     Unknown (usually zero)
  4     Unknown (usually zero)
  5     Unknown (usually zero)
  6     Unknown (usually zero)
  7     Unknown (0 or 1)
  8     Empty Packets (0=Ignore, 1=Accept; with RXHDR[0]=801Fh)
  9     Unknown (0 or 1)
  10    Unknown (0 or 1)       (when set, receives beacons, and maybe others)
  11    Unknown (usually zero)     ;reportedly "allow toDS" ?
  12    Update W_RXBUF_WRCSR after IEEE header (instead after full packets?)
         (setting bit12 causes a mess, where new "packets" in RX buf could
         either contain RXHDR+IEEE header, or Data corresponding to that
         headers, which could be useful only if there's a way to distinguish
         between headers and data, and knowing the size of the data blocks).
  13-15 Not used (always zero)
Specifies what packets to allow. Some random notes...
  0000h = Disable receive.
  FFFFh = Enable receive.
  0400h = Receives managment frames (and possibly others, too)
The exact meaning of the bits is unknown. The most import part is the address filtering based on the DA and BSSID values in IEEE header:
  DA=W_MACADDR                    is always received
  DA=Broadcast, and BSSID=W_BSSID is always received
  DA=Broadcast, and BSSID=other   is received only if RXFILTER.bit0=1
Broadcast addresses (aka group addresses) have DA.firstbyte.bit0=1. RXFILTER.bit0 should be set when searching beacons, and cleared after connecting to an access point.

48080E0h - W_RXFILTER2 - (R/W)
  0     Unknown (0=Receive Data Frames, 1=Ignore Data Frames) (?)
  1     Unknown
  2     Unknown
  3     Unknown (usually set)
  4-15  Not used (always zero)
Firmware writes values 08h, 0Bh, 0Dh (aka 1000b, 1011b, 1101b).
Firmware usually has bit0 set, even when receiving data frames, so, in some situations data frames seem to pass-through even when bit0 is set...? Possibly that situation is when W_BSSID matches...?
Control/PS-Poll frames seem to be passed always (even if W_RXFILTER2=0Fh).


DS Wifi Receive Buffer

The dimensions of the circular Buffer are set with BEGIN/END values, hardware automatically wraps to BEGIN when an incremented pointer hits END address.

Write Area
Memory between WRCSR and READCSR is free for receiving data, the hardware writes incoming packets to this region (to WRCSR and up) (but without exceeding READCSR), once when it has successfully received a complete packet, the hardware moves WRCSR after the packet (aligned to a 4-byte boundary).

Read Area
Memory between READCSR and WRCSR contains received data, which can be read by the CPU via RD_ADDR and RD_DATA registers (or directly from memory). Once when having processed that data, the CPU must set READCSR to the end of it.

4808050h - W_RXBUF_BEGIN - Wifi RX Fifo start location (R/W)
4808052h - W_RXBUF_END - Wifi RX Fifo end location (R/W)
  0-15  Byte-offset in Wifi Memory (usually 4000h..5FFEh)
Although the full 16bit are R/W, only the 12bit halfword offset in Bit1-12 is actually used, the other bits seem to have no effect.
Some or all (?) of the below incrementing registers are automatically matched to begin/end, that is, after incrementing, IF adr=end THEN adr=begin.

4808054h - W_RXBUF_WRCSR - Wifi RX Fifo Write or "end" cursor (R)
  0-11  Halfword Address in RAM
  12-15 Always zero
Hardware does set this register pointing to end of the most recently received packet (plus 32bit alignment padding). Hardware will write the next packet to that address. And more importantly, software can read from RX fifo up to that address.

4808056h - W_RXBUF_WR_ADDR - Wifi RX Fifo Write Cursor Latch value (R/W)
  0-11  Halfword Address in RAM
  12-15 Always zero
This is a value that is latched into W_RXBUF_WRCSR, when the W_RXCNT latch bit (W_RXCNT.Bit0) is written.

4808058h - W_RXBUF_RD_ADDR - Wifi CircBuf Read Address (R/W)
  0     Always zero
  1-12  Halfword Address in RAM for reading via W_RXBUF_RD_DATA
  13-15 Always zero
The circular buffer limits are the same as the range specified for the receive FIFO, however the address can be set outside of that range and will only be affected by the FIFO boundary if it crosses the FIFO end location by reading from the circular buffer.

480805Ah - W_RXBUF_READCSR - Wifi RX Fifo Read or "start" cursor (R/W)
  0-11  Halfword Address in RAM
  12-15 Always zero
This value is specified the same as W_RXBUF_WRCSR - it's purely software controlled so it's up to the programmer to move the start cursor after loading a packet. If W_RXBUF_READCSR != W_RXBUF_WRCSR, then one or more packets exist in the FIFO that need to be processed (see the section on HW RX Headers, for information on calculating packet lengths). Once a packet has been processed, the software should advance the read cursor to the beginning of the next packet.

4808060h - W_RXBUF_RD_DATA - Wifi CircBuf Read Data (R)
  0-15  Data
returns the 16bit value at the address specified by W_RXBUF_RD_ADDR, and increments W_RXBUF_RD_ADDR by 2. If the increment causes W_RXBUF_RD_ADDR to equal the address specified in W_RXBUF_END, W_RXBUF_RD_ADDR will be reset to the address specified in W_RXBUF_BEGIN.
Ports 1060h, 6060h, 7060h are PASSIVE mirrors of 0060h, reading from these mirrors returns the old latched value from previous read from 0060h, but without reading a new value from RAM, and without incrementing the address.

4808062h - W_RXBUF_GAP - Wifi RX Gap Address (R/W)
  0     Always zero
  1-12  Halfword Address in RAM
  13-15 Always zero
Seems to be intended to define a "gap" in the circular buffer, done like so:
  Addr=Addr+2 and 1FFEh  ;address increment (by W_RXBUF_RD_DATA read)
  if Addr=RXBUF_END then ;normal begin/end wrapping (done before gap wraps)
     Addr=RXBUF_BEGIN
  if Addr=RXBUF_GAP then ;now gap-wrap (may include further begin/end wrap)
     Addr=RXBUF_GAP+RXBUF_GAPDISP*2
     if Addr>=RXBUF_END then Addr=Addr+RXBUF_BEGIN-RXBUF_END  ;wrap more
To disable the gap stuff, set both W_RXBUF_GAP and W_RXBUF_GAPDISP to zero.

4808064h - W_RXBUF_GAPDISP - Wifi RX Gap Displacement Offset (R/W)
  0-11  Halfword Offset, used with W_RXBUF_GAP (see there)
  12-15 Always zero
Caution: On the DS-Lite, after adding it to W_RXBUF_RD_ADDR, the W_RXBUF_GAPDISP setting is destroyed (reset to 0000h) by hardware. The original DS leaves W_RXBUF_GAPDISP intact.

480805Ch - W_RXBUF_COUNT (R/W)
  0-11  Decremented on reads from W_RXBUF_RD_DATA
  12-15 Always zero
Triggers IRQ09 when it reaches zero, and does then stay at zero (without further decrementing, and without generating further IRQs).
Note: Also decremented on (accidental) writes to read-only W_RXBUF_RD_DATA.


DS Wifi Receive Statistics

48081A8h - W_RXSTAT_INC_IF - Statistics Increment Flags (R)
  0-12   Increment Flags (see Port 48081B0h..1BFh)
  13-15  Always zero
Bitmask for which statistics have been increased at least once.
Unknown how to reset/acknowledge these bits (neither reading/writing 48081A8h, nor reading 48081B0h..1BFh, nor writing 48081ACh seem to work).

48081AAh - W_RXSTAT_INC_IE - Statistics Increment Interrupt Enable (R/W)
  0-12   Counter Increment Interrupt Enable (see 48081B0h..1BFh) (1=Enable)
  13-15  Unknown (usually zero)
Statistic Interrupt Enable Control register for Count Up.
Note: ------> seems to trigger IRQ02 ...?

48081ACh - W_RXSTAT_OVF_IF - Statistics Half-Overflow Flags (R)
  0-12   Half-Overflow Flags (see Port 48081B0h..1BFh)
  13-15  Always zero
The W_RXSTAT_OVF_IF bits are simply containing the current bit7-value of the corresponding counters, setting or clearing that counter bits is directly reflected to W_RXSTAT_OVF_IF.
The recommended way to acknowledge W_RXSTAT_OVF_IF is to read the corresponding counters (which are reset to 00h after reading). For some reason, the firmware is additionally writing FFFFh to W_RXSTAT_OVF_IF (that is possibly a bug, or it does acknowledge something internally?).

48081AEh - W_RXSTAT_OVF_IE - Statistics Half-Overflow Interrupt Enable (R/W)
  0-12   Half-Overflow Interrupt Enable (see Port 48081B0h..1BFh) (1=Enable)
  13-15  Unknown (usually zero)
Statistic Interrupt Enable for Overflow, bits same as in W_RXSTAT_INC_IE
Note: ------> seems to trigger IRQ04 ...?

48081B0h..1BFh - W_RXSTAT - Receive Statistics (R/W, except 1B5h: Read-only)
W_RXSTAT is a collection of 8bit counters, which are incremented upon certain events. These entries are automatically reset to 0000h after reading. Should be accessed with LDRH opcodes (using LDRB to read only 8bits does work, but the read is internally expanded to 16bit, and so, the whole 16bit value will be reset to 0000h).
  Port      Dir  Bit  Expl.
  48081B0h  R/W  0    W_RXSTAT  ?
  48081B1h  -    -    Always 0  -
  48081B2h  R/W  1    W_RXSTAT  ?    "RX_RateErrorCount"
  48081B3h  R/W  2    W_RXSTAT  Length>2348 error
  48081B4h  R/W  3    W_RXSTAT  RXBUF Full error
  48081B5h  R    4?   W_RXSTAT  ?    (R) (but seems to exist; used by firmware)
  48081B6h  R/W  5    W_RXSTAT  Length=0 or Wrong FCS Error
  48081B7h  R/W  6    W_RXSTAT  Packet Received Okay
                             (also increments on W_MACADDR mis-match)
                             (also increments on internal ACK packets)
                             (also increments on invalid IEEE type=3)
                             (also increments TOGETHER with 1BCh and 1BEh)
                             (not incremented on RXBUF_FULL error)
  48081B8h  R/W  7    W_RXSTAT  ?
  48081B9h  -    -    Always 0  -
  48081BAh  R/W  8    W_RXSTAT  ?
  48081BBh  -    -    Always 0  -
  48081BCh  R/W  9    W_RXSTAT  WEP Error (when FC.Bit14 is set)
  48081BDh  R/W  10   W_RXSTAT  ?
  48081BEh  R/W  11   W_RXSTAT  (duplicated sequence control)
  48081BFh  R/W  12   W_RXSTAT  ?

48081C4h - W_RX_COUNT (W_INTERNAL) (R)
  0-?   Receive Okay Count (increments together with ports 48081B4h, 48081B7h)
  8-?   Receive Error Count (increments together with ports 48081B3h, 48081B6h)
Increments when receiving a packet. Automatically reset to zero after reading.

48081D0h..1DFh - W_CMD_STAT - Multiplay Response Error Counters (R/W)
The multiplay error counters are only used when sending a multiplay command (via W_TXBUF_CMD) to any connected slaves (which must be indicated by flags located in the second halfword of the multiplay command's frame body).
  48081D0h        Not used (always zero)
  48081D1h..1DFh  Client 1..15 Response Error (increments on missing replies)
If one or more of those slaves fail to respond, then the corresponding error counters get incremented (at the master side). Automatically reset to zero after reading.
Unknown if these counters do also increment at the slave side?


DS Wifi Transmit Control

48080ACh - W_TXREQ_RESET - Reset Transfer Request Bits (W)
  0-3   Reset corresponding bits in W_TXREQ_READ (0=No change, 1=Reset)
  4-15  Unknown (if any)
Firmware writes values 01h,02h,08h,0Dh, and FFFFh.

48080AEh - W_TXREQ_SET - Set Transfer Request Bits (W)
  0-3   Set corresponding bits in W_TXREQ_READ   (0=No change, 1=Set)
  4-15  Unknown (if any)
Firmware writes values 01h,02h,05h,08h,0Dh.

48080B0h - W_TXREQ_READ - Get Transfer Request Bits (R)
  0     Send W_TXBUF_LOC1  (1=Transfer, if enabled in W_TXBUF_LOC1.Bit15)
  1     Send W_TXBUF_CMD   (1=Transfer, if enabled in W_TXBUF_CMD.Bit15)
  2     Send W_TXBUF_LOC2  (1=Transfer, if enabled in W_TXBUF_LOC2.Bit15)
  3     Send W_TXBUF_LOC3  (1=Transfer, if enabled in W_TXBUF_LOC3.Bit15)
  4     Unknown (Beacon?)  (always 1, except when cleared via W_POWERFORCE)
  5-15  Unknown/Not used
Bit0-3 can be set/reset via W_TXREQ_SET/W_TXREQ_RESET. The setting in W_TXREQ_READ remains intact even after the transfer(s) have completed.
If more than one of the LOC1,2,3 bits is set, then LOC3 is transferred first, LOC1 last.
Beacons are transferred in every Beacon Timeslot (if enabled in W_TXBUF_BEACON.Bit15).
Bit0,2,3 are automatically reset upon IRQ14 (by hardware).

48080B6h - W_TXBUSY (R)
  0     W_TXBUF_LOC1  (1=Requested Transfer busy, or not yet started at all)
  1     W_TXBUF_CMD   (1=Requested Transfer busy, or not yet started at all)
  2     W_TXBUF_LOC2  (1=Requested Transfer busy, or not yet started at all)
  3     W_TXBUF_LOC3  (1=Requested Transfer busy, or not yet started at all)
  4     W_TXBUF_BEACON  (1=Beacon Transfer busy)
  5-15  Unknown (if any)
Busy bits. If all three W_TXBUF_LOC's are sent, then it goes through values 0Dh,05h,01h,00h; ie. LOC3 is transferred first, LOC1 last. The register is updated upon IRQ01 (by hardware).
Bit4 is set only in Beacon Timeslots.

48080B8h - W_TXSTAT - RESULT - Status of transmitted frame (R)
For LOC1-3, this register is updated at the end of a transfer (upon the IRQ01 request), if retries occur then it is updated only after the final retry.
For BEACON, this register is updated only if enabled in W_TXSTATCNT.Bit15, and only after successful transfers (since beacon errors result in infinite retries).
For CMD, this register is updated only if enabled in W_TXSTATCNT.Bit13,14).
Bit0/1 act similar to W_IF Bit1/3, however, the W_IF Bits are set after each transmit (including retries).
  0     One (or more) Packet has Completed (1=Yes)
        (No matter if successful, for that info see Bit1)
        (No matter if ALL packets are done, for that info see Bit12-13)
  1     Packet Failed (1=Error)
  2-7   Unknown/Not used
  8-11  Usually 0, ...but firmware is checking for values 03h,08h,0Bh
        (gets set to 07h when transferred W_TXBUF_LOC1/2/3 did have Bit12=set)
        (gets set to 00h otherwise)
        (gets set to 03h after beacons   ;if enabled in W_TXSTATCNT.Bit15)
        (gets set to 08h after cmd's     ;if enabled in W_TXSTATCNT.Bit14)
        (gets set to 0Bh after cmd ack's ;if enabled in W_TXSTATCNT.Bit13)
        (gets set to 04h after reply's   ;if enabled in W_TXSTATCNT.Bit12)
  12-13 Packet that updated W_TXSTAT (0=LOC1/BEACON/CMD/REPLY, 1=LOC2, 2=LOC3)
  14-15 Unknown/Not used
No idea how to reset bit0/1 once when they are set?

4808008h - W_TXSTATCNT (R/W)
  0-11  Unknown (usually zero) (otherwise disables RXing multiplay REPLY's?)
  12    Update W_TXSTAT=0401h and trigger IRQ01 after REPLY transmits   (1=Yes)
  13    Update W_TXSTAT=0B01h and trigger IRQ01 after CMD ACK transmits (1=Yes)
  14    Update W_TXSTAT=0800h and trigger IRQ01 after CMD DATA transmits(1=Yes)
  15    Update W_TXSTAT=0301h and trigger IRQ01 after BEACON transmits  (1=Yes)
Note: LOC1..3 transmits are always updating W_TXSTAT and triggering IRQ01.

4808194h - W_TX_HDR_CNT - Disable Transmit Header Adjustments (R/W)
  0     IEEE FC.Bit12 and Duration (0=Auto/whatever, 1=Manual/Wifi RAM)
  1     IEEE Frame Check Sequence  (0=Auto/FCS/CRC32, 1=Manual/Wifi RAM)
  2     IEEE Sequence Control      (0=Auto/W_TX_SEQNO, 1=Manual/Wifi RAM)
  3-15  Always zero
Allows to disable automatic adjustments of the IEEE header and checksum.
Note: W_TX_SEQNO can be also disabled by W_TXBUF_LOCn.Bit13 and by TXHDR[04h].

4808210h - W_TX_SEQNO - Transmit Sequence Number (R)
  0-11   Increments on IRQ07 (Transmit Start Interrupt)
  12-15  Always zero
Also incremented shortly after IRQ12.
When enabled in W_TXBUF_LOCn.Bit13, this value replaces the upper 12bit of the IEEE Frame Header's Sequence Control value (otherwise, when disabled, the original value in Wifi RAM is used, and, in that case, W_TX_SEQNO is NOT incremented).
Aside from W_TXBUF_LOCn.Bit13, other ways to disable W_TX_SEQNO are: Transmit Hardware Header entry TXHDR[04h], and W_TX_HDR_CNT.Bit2.


DS Wifi Transmit Buffers

4808068h - W_TXBUF_WR_ADDR - Wifi CircBuf Write Address (R/W)
  0     Always zero
  1-12  Halfword Address in RAM for Writes via W_TXBUF_WR_DATA
  13-15 Always zero

4808070h - W_TXBUF_WR_DATA - Wifi CircBuf Write Data (W)
  0-15  Data to be written to address specified in W_TXBUF_WR_ADDR
After writing to this register, W_TXBUF_WR_ADDR is automatically incremented by 2, and, if it gets equal to W_TXBUF_GAP, then it gets additonally incremented by W_TXBUF_GAPDISP*2.

4808074h - W_TXBUF_GAP - Wifi CircBuf Write Top (R/W)
  0     Always zero
  1-12  Halfword Address
  13-15 Always zero

4808076h - W_TXBUF_GAPDISP - CircBuf Write Offset from Top to Bottom (R/W)
  0-11  Halfword Offset (added to; if equal to W_TXBUF_GAP)
  12-15 Always zero
Should be "0-write_buffer_size" (wrap from end to begin), or zero (no wrapping).
Caution: On the DS-Lite, after adding it to W_TXBUF_WR_ADDR, the W_TXBUF_GAPDISP setting is destroyed (reset to 0000h) by hardware. The original DS leaves W_TXBUF_GAPDISP intact.

Note: W_TXBUF_GAP and W_TXBUF_GAPDISP may be (not TOO probably) also used by transmits via W_TXBUF_LOCn and W_TXBUF_BEACON (not tested).

4808080h - W_TXBUF_BEACON - Beacon Transmit Location (R/W)
4808090h - W_TXBUF_CMD - Multiplay Command Transmit Location (R/W)
48080A0h - W_TXBUF_LOC1 - Transmit location 1 (R/W)
48080A4h - W_TXBUF_LOC2 - Transmit location 2 (R/W)
48080A8h - W_TXBUF_LOC3 - Transmit location 3 (R/W)
  0-11  Halfword Address of TX Frame Header in RAM
  12    For LOC1-3: When set, W_TXSTAT.bit8-10 are set to 07h after transfer
                    And, when set, the transferred frame-body gets messed up?
        For BEACON: Unknown, no effect on W_TXSTAT
        For CMD: Unknown, no effect on W_TXSTAT
  13    IEEE Sequence Control (0=From W_TX_SEQNO, 1=Value in Wifi RAM)
        For BEACON: Unknown (always uses W_TX_SEQNO) (no matter of bit13)
  14    Unknown
  15    Transfer Request (1=Request/Pending)
For LOC1..3 and CMD, Bit15 is automatically cleared after (or rather: during?) transfer (no matter if the transfer was successful). For Beacons, bit15 is kept unchanged since beacons are intended to be transferred repeatedly.
W_TXBUF_CMD.Bit15 can be set ONLY while W_CMD_COUNT is non-zero.

48080B4h - W_TXBUF_RESET (W)
  0     Disable LOC1    (0=No change, 1=Reset W_TXBUF_LOC1.Bit15)
  1     Disable CMD     (0=No change, 1=Reset W_TXBUF_CMD.Bit15)
  2     Disable LOC2    (0=No change, 1=Reset W_TXBUF_LOC2.Bit15)
  3     Disable LOC3    (0=No change, 1=Reset W_TXBUF_LOC3.Bit15)
  4-5   Unknown/Not used
  6     Disable REPLY2  (0=No change, 1=Reset W_TXBUF_REPLY2.Bit15)
  7     Disable REPLY1  (0=No change, 1=Reset W_TXBUF_REPLY1.Bit15)
  8-15  Unknown/Not used
Firmware writes values FFFFh, 40h, 02h, xxxx, 09h, 01h, 02h, C0h.

4808084h - W_TXBUF_TIM - Beacon TIM Index in Frame Body (R/W)
  0-7   Location of TIM parameters within Beacon Frame Body
  8-15  Not used/zero
Usually set to 15h, that assuming that preceding Frame Body content is: Timestamp(8), BeaconInterval(2), Capability(2), SuppRatesTagLenParams(4), ChannelTagLenParam(3), TimTagLen(2); so the value points to TimParams (ie. after TimTagLen).

480806Ch - W_TXBUF_COUNT (R/W)
  0-11  Decremented on writes to W_TXBUF_WR_DATA
  12-15 Always zero
Triggers IRQ08 when it reaches zero, and does then stay at zero (without further decrementing, and without generating further IRQs).
Note: Not affected by (accidental) reads from write-only W_TXBUF_WR_DATA.


DS Wifi Transmit Errors

Automatic ACKs
Transmit errors occur on missing ACKs. The NDS hardware is automatically responding with an ACK when receiving a packet (if it has been addressed to the receipients W_MACADDR setting). And, when sending a packet, the NDS hardware is automatically checking for ACK responses.
The only exception are packets that are sent to group addresses (ie. Bit0 of the 48bit MAC address being set to "1", eg. Beacons sent to FF:FF:FF:FF:FF:FF), the receipient(s) don't need to respond to such packets, and the sender always passes okay without checking for ACKs.

480802Ch - W_TX_RETRYLIMIT (R/W)
Specifies the maximum number of retries on Transmit Errors (eg. 07h means one initial transmit, plus up to 7 retries, ie. max 8 transmits in total).
  0-7   Retry Count (usually 07h)
  8-15  Unknown     (usually 07h)
The Retry Count value is decremented on each Error (unless it is already 00h). There's no automatic reload, so W_TX_RETRYLIMIT should be reinitialized by software prior to each transmit (or, actually, there IS a reload?).
When sending multiple packets (by setting more than one bit with W_TXREQ_SET), then the first packet may eat-up all retries, leaving only a single try to the other packet(s).

48081C0h - W_TX_ERR_COUNT - TransmitErrorCount (R/W)
  0-7   TransmitErrorCount
  8-15  Always zero
Increments on Transmit Errors. Automatically reset to zero after reading.
IRQ03 triggered when W_TX_ERR_COUNT is incremented (for NON-beacons ONLY).
IRQ05 triggered when W_TX_ERR_COUNT > 7Fh (happens INCLUDING for beacons).

Error Notification
Transmit Errors can be sensed via W_TX_ERR_COUNT, IRQ03, IRQ05, TX Hardware Header entry [00h], and W_TXSTAT.Bit1.

W_TXBUF_BEACON Errors
As the name says, W_TXBUF_BEACON is intended for sending Beacons to group addresses (which do not require to respond by ACKs). So, transmit errors would occur only when mis-using W_TXBUF_BEACON to send packets to individual addresses, but the W_TXBUF_BEACON error handling isn't fully implemented:
First of, W_TX_RETRYLIMIT isn't used, instead, W_TXBUF_BEACON errors will result in infinite retries.
Moreover, W_TXBUF_BEACON errors seem to increment W_TX_ERR_COUNT, but without generating IRQ03, however, IRQ05 is generated when W_TX_ERR_COUNT>7Fh.

Other Errors
The NDS transmit hardware seems to do little error checking on the packet headers. The only known error-checked part is byte [04h] in the TX hardware header (which must be 00h, 01h, or 02h). Aside from that, when sent to a group address, it is passing okay even with invalid IEEE type/subtypes, and even with Length/Rate entries set to zero. However, when sending such data to an individual address, the receiving NDS won't respond by ACKs.

Note
Received ACKs aren't stored in WifiRAM (or, possibly, they ARE stored, but without advancing W_RXBUF_WRCSR, so that the software won't see them, and so that they will be overwritten by the next packet).


DS Wifi Status

480819Ch - W_RF_PINS - Status of RF-Chip Control Signals (R)
  0    Reportedly "carrier sense" (maybe 1 during RX.DTA?) (usually 0)
  1    TX.MAIN (RFU.Pin17) Transmit Data Phase          (0=No, 1=Active)
  2    Unknown (RFU.Pin3)  Seems to be always high      (Always 1=high?)
  3-5  Not used                                         (Always zero)
  6    TX.ON   (RFU.Pin14) Transmit Preamble+Data Phase (0=No, 1=Active)
         Uhhh, no that seems to be still wrong...
         Bit6 is often set, even when not transmitting anything...
  7    RX.ON   (RFU.Pin15) Receive Mode                 (0=No, 1=Enable)
  8-15 Not used                                         (Always zero)
Physical state of the RFU board's RX/TX pins. Similar to W_RF_STATUS.
XXX better expl. for bit0-1:
  0    RX.BUSY Receiving Preamble or Data   (0=Idle or TX Busy, 1=RX Busy)
  1    Data Phase (for both RX/TX mode)     (0=Idle or Preamble, 1=Data)

4808214h - W_RF_STATUS - Current Transmit/Receive State (R)
  0-3  Current Transmit/Receive State:
        0 = Initial value on Power-up (before raising W_MODE_RST.Bit0)
        1 = RX Mode enabled (waiting for incoming data)
        2 = Switching from RX to TX (takes a few clock cycles)
        3 = TX Mode active  (sending preamble and data)
        4 = Switching from TX to RX (takes a few clock cycles)
        5 = Multiplay: CMD was sent, waiting for replies (RF_PINS=0084h) (uh?)
            Or rather: CMD was received, preparing reply? (on slave side!)
        6 = RX (processing incoming data?)
        7 = Switching from RX/REPLY to TX/ACK (between STAT=5 and STAT=8)
        8 = Multiplay: Sending REPLY, or CMD-Ack (RF_PINS=0046h)
        9 = Idle (upon IRQ13, and upon raising W_MODE_RST.Bit0)
  4-15 Always zero?
Numeric Status Code. Similar to W_RF_PINS.

4808268h - W_RXTX_ADDR - Current Receive/Transmit Address (R)
  0-11   Halfword address
  12-15  Always zero
Indicates the halfword that is currently transmitted or received. Can be used by Start Receive IRQ06 handler to determine how many halfwords of the packet have been already received (allowing to pre-examine portions of the packet header even when the whole packet isn't fully received). Can be also used in Transmit Start IRQ07 handler to determine which packet is currently transmitted.


DS Wifi Timers

48080E8h - W_US_COUNTCNT - Microsecond counter enable (R/W)
  0     Counter Enable (0=Disable, 1=Enable)
  1-15  Always zero
Activates W_US_COUNT, and also W_BEACON_COUNT and W_POST_BEACON (which are decremented when lower 10bit of W_US_COUNT wrap from 3FFh to 000h). Note: W_POWER_US must be enabled, too.

48080F8h - W_US_COUNT0 - Microsecond counter, bits 0-15 (R/W)
48080FAh - W_US_COUNT1 - Microsecond counter, bits 16-31 (R/W)
48080FCh - W_US_COUNT2 - Microsecond counter, bits 32-47 (R/W)
48080FEh - W_US_COUNT3 - Microsecond counter, bits 48-63 (R/W)
  0-63  Counter Value in microseconds (incrementing)
Clocked by the 22.00MHz oscillator on the RFU board (ie. not by the 33.51MHz system clock). The 22.00MHz are divided by a 22-step prescaler.

48080EAh - W_US_COMPARECNT - Microsecond compare enable (R/W)
  0     Compare Enable (0=Disable, 1=Enable) (IRQ14/IRQ15)
  1     Force IRQ14    (0=No, 1=Force Now)   (Write-only)
  2-15  Always zero
Activates IRQ14 on W_US_COMPARE matches, and IRQ14/IRQ15 on W_BEACON_COUNT.

48080F0h - W_US_COMPARE0 - Microsecond compare, bits 0-15 (R/W)
48080F2h - W_US_COMPARE1 - Microsecond compare, bits 16-31 (R/W)
48080F4h - W_US_COMPARE2 - Microsecond compare, bits 32-47 (R/W)
48080F6h - W_US_COMPARE3 - Microsecond compare, bits 48-63 (R/W)
  0     Block Beacon IRQ14 until W_US_COUNT=W_US_COMPARE (0=No, 1=Block)  (W)
  1-9   Always zero
  10-63 Compare Value in milliseconds (aka microseconds/1024)             (R/W)
Triggers IRQ14 (see IRQ14 notes below) when W_US_COMPARE matches W_US_COUNT.
Usually set to FFFFFFFFFFFFFC00h (ie. almost/practically never). Instead, IRQ14 is usually derived via W_BEACON_COUNT.

480811Ch - W_BEACON_COUNT - Beacon Counter (R/W)
Triggers IRQ14 and IRQ15 (see IRQ14/IRQ15 notes below) when it reaches 0000h (if W_PRE_BEACON is non-zero, then IRQ15 occurs that many microseconds in advance).
  0-15  Decrementing Millisecond Counter (reloaded with W_BEACONINT upon IRQ14)
Set to W_BEACONINT upon IRQ14 events (unlike the other W_US_COMPARE related actions, this is done always, even if W_US_COMPARECNT is zero).
When reaching 0000h, it is immediately reloaded (as for US_COUNT matches), so the counting sequence is ..,3,2,1,BEACONINT,.. (not 3,2,1,ZERO,BEACONINT).

4808134h - W_POST_BEACON - Post-Beacon Counter (R/W)
  0-15  Decrementing Millisecond Counter (reloaded with FFFFh upon IRQ14)
Triggers IRQ13 when it reaches 0000h (no matter of W_US_COMPARECNT), and does then stay fixed at 0000h (without any further decrement/wrapping to FFFFh).
Set to FFFFh upon IRQ14 (by hardware), the IRQ14 handler should then adjust the register (by software) by adding the Tag=DDh Beacon header's Stepping value (usually 000Ah) to it.
Seems to be used to indicate beacon transmission time (possibly including additional time being reserved for responses)?

480808Ch - W_BEACONINT - Beacon Interval (R/W)
Reload value for W_BEACON_COUNT.
  0-9   Frequency in milliseconds of beacon transmission
  10-15 Always zero
Should be initialized randomly to 0CEh..0DEh or so. The random setting reduces risk of repeated overlaps with beacons from other hosts.

4808110h - W_PRE_BEACON - Pre-Beacon Time (R/W)
  0-15  Pre-Beacon Time in microseconds (static value, ie. NOT decrementing)
Allows to define the distance between IRQ15 and IRQ14. The setting doesn't affect the IRQ14 timing (which occurs at the W_BEACON_COUNT'th millisecond boundary), but IRQ15 occurs in advance (at the W_BEACON_COUNT'th millisecond boundary minus W_PRE_BEACON microseconds). If W_PRE_BEACON is zero, then both IRQ14 and IRQ15 occur exactly at the same time.

4808088h - W_LISTENCOUNT - Listen Count (R/W)
  0-7   Decremented by hardware at IRQ14 events (ie. once every beacon)
  8-15  Always zero
Reload occurs immediately BEFORE decrement, ie. with W_LISTENINT=04h, it will go through values 03h,02h,01h,00h,03h,02h,01h,00h,etc.

480808Eh - W_LISTENINT - Listen Interval (R/W)
  0-7   Listen Interval, counted in beacons (usually 02h)
  8-15  Always zero
Reload value for W_LISTENCOUNT.

480810Ch - W_CONTENTFREE (R/W)
  0-15  Decrementing microsecond counter
Operated always (no matter of W_US_COUNTCNT).
Once when it has reached 0000h, it seems to stay fixed at 0000h.
"[Set to the remaining duration of contention-free period when
receiving beacons - only *really* necessary for powersaving mode]"

IRQ13 Notes (Post-Beacon Interrupt)
IRQ13 is generated by W_POST_BEACON. It's simply doing:
  W_IF.Bit13=1      ;interrupt request
If W_POWER_TX.Bit1=0, then additionally enter sleep mode:
  [4808034h]=0002h ;W_INTERNAL   ;(similar to W_POWERFORCE=8001h)
  [480803Ch]=02xxh ;W_POWERSTATE ;(W_TXREQ_READ.Bit4 is kept intact though)
  [480819Ch]=0046h ;W_RF_PINS.7=0;disable receive (enter idle mode) (RX.ON=Low)
  [4808214h]=0009h ;W_RF_STATUS=9;indicate idle mode
Unlike for IRQ14/IRQ15, that's done no matter of W_US_COMPARECNT.

IRQ14 Notes (Beacon Interrupt)
IRQ14 is generated by W_US_COMPARE, and by W_BEACON_COUNT.
Aside from just setting the IRQ flag in W_IF, the hardware does:
  W_BEACON_COUNT=W_BEACONINT                             ;next IRQ15/IRQ14
  (Above is NOT done when IRQ14 was forced via W_US_COMPARECNT.Bit1)
If W_US_COMPARECNT is 1, then the hardware does additionally:
  (Below IS ALSO DONE when IRQ14 was forced via W_US_COMPARECNT.Bit1)
  W_IF.Bit14=1
  W_POST_BEACON=FFFFh ;about 64 secs (ie. almost never) ;next IRQ13 ("never")
  W_TXREQ_READ=W_TXREQ_READ AND FFF2h
  if W_TXBUF_BEACON.15 then W_TXBUSY.Bit4=1
  if W_LISTENCOUNT=00h then W_LISTENCOUNT=W_LISTENINT
  W_LISTENCOUNT=W_LISTENCOUNT-1
If W_TXBUF_BEACON.Bit15=1, then following is done shortly after IRQ14:
  W_RF_PINS.Bit7=0  ;disable receive (RX.ON=Low)
  W_RF_STATUS=2     ;indicate switching from RX to TX mode
If W_TXBUF_BEACON.Bit15=1, then following is done a bit later:
  W_RF_PINS.Bit6=1  ;transmit preamble start (TX.ON=High)
  W_RF_STATUS=3     ;indicate TX mode
The IRQ14 handler should then do the following (by software):
  W_POST_BEACON = W_POST_BEACON + TagDDhSteppingValue  ;next IRQ13
For using only ONE of the two IRQ14 sources: W_BEACON_COUNT can be disabled by setting both W_BEACON_COUNT and W_BEACONINT to zero. W_US_COMPARE can be sorts of "disabled" by setting it to value distant from W_US_COUNT, such like compare=count-400h.

IRQ07 Notes (Transmit Start Data; occurs after preamble)
  W_IF.Bit7=1       ;interrupt request
  W_RF_PINS.Bit1=1  ;start data transfer (preamble finished now) (TX.MAIN=High)
Below only if packet was sent through W_TXBUF_BEACON, or if it was sent via W_TXBUF_LOCn, with W_TXBUF_LOCn.Bit13 being zero:
  [TXBUF...] = W_TX_SEQNO*10h   ;auto-adjust IEEE Sequence Control
  W_TX_SEQNO=W_TX_SEQNO+1       ;increase sequence number

IRQ01 Notes (Transmit Done)
The following happens shortly before IRQ01:
  W_RF_PINS.Bit6=0  ;disable TX (TX.ON=Low)
  W_RF_STATUS=4     ;indicate switching from TX to RX mode
Then, upon IRQ01, the following happens:
  W_IF.Bit1=1       ;interrupt request
  W_RF_PINS.Bit1=0  ;disable TX (TX.MAIN=Low)
  W_RF_PINS.Bit7=1  ;enable RX (RX.ON=High)
  W_RF_STATUS=1     ;indicate RX mode

IRQ15 Notes (Pre-Beacon Interrupt)
IRQ15 is generated via W_BEACON_COUNT and W_PRE_BEACON. It's simply doing:
  if W_US_COMPARECNT=1 then W_IF.Bit15=1
If W_POWER_TX.Bit0=1, then additionally wakeup from sleep mode:
  W_RF_PINS.Bit7=1  ;enable RX (RX.ON=High) ;\gets set like so a good while
  W_RF_STATUS=1     ;indicate RX mode       ;/after IRQ15 (but not immediately)

Beacon IRQ Sequence
  IRQ15  Pre-Beacon  (beacon will be transferred soon)
  IRQ14  Beacon      (beacon will be transferred very soon) (carrier starts)
  IRQ07  Tx Start    (beacon transfer starts) (if enabled in W_TXBUF_BEACON.15)
  IRQ01  Tx End      (beacon transfer done) (if enabled in W_TXSTATCNT.15)
  IRQ13  Post-Beacon (beacon transferred) (unless next IRQ14 occurs earlier)
That, for tranmitting beacons. (For receiving, IRQ07/IRQ01 would be replaced by Rx IRQ's, provided that a remote unit is sending beacons).


DS Wifi Multiplay Master

These registers are used for multiplay host-to-client (aka master to slave) commands.

48080EEh - W_CMD_COUNTCNT (R/W)
  0     Enable W_CMD_COUNT (0=Disable, 1=Enable)
  1-15  Always Zero

4808118h - W_CMD_COUNT (R/W)
  0-15  Decremented once every 10 microseconds (Stopped at 0000h)
Defines the time interval during which W_TXBUF_CMD transfers are possible. That CMD will be automatically transferred again if there are errors (missing REPLY's), but it will abort if there isn't enough time left in W_CMD_COUNT.
IRQ12 is thrown when cmd/reply were successful, or when CMD_COUNT reached zero (failed).
Firmware Beacon IRQ14 handler checks for W_CMD_COUNT<=0Ah.

48080C0h - W_CMD_TOTALTIME - (R/W)
  0-15  Duration per ALL slave response packet(s) in microseconds
Before sending a MASTER packet, this port should be set to the same value as the MASTER packet's IEEE header's Duration/ID entry.

48080C4h - W_CMD_REPLYTIME - (R/W)
  0-15  Duration per SINGLE slave response packet in microseconds
Before sending a MASTER packet, this port should be set to the expected per slave response time.
Note: Nintendo's multiboot/pictochat code is also putting this value in the 1st halfword of the MASTER packet's frame body.

At 2MBit/s transfer rate, the values should be set up sorts of like so:
  master_time = (master_bytes*4)+(60h)     ;60h = 96 decimal = short preamble
  slave_time = (slave_bytes*4)+(0D0h..0D2h)
  all_slave_time = (EAh..F0h)+(slave_time+0Ah)*num_slaves
  txhdr[2]   = slave_bits      ;hardware header (*)
  ieee[2]    = all_slave_time  ;ieee header (duration/id)
  body[0]    = slave_time      ;duration per slave (for multiboot/pictochat)
  body[2]    = slave_bits      ;frame body -- required (*)
  [48080C0h] = all_slave_time  ;W_CMD_TOTALTIME
  [48080C4h] = slave_time      ;W_CMD_REPLYTIME duration per slave
  [4808118h] = (388h+(num_slaves*slave_time)+master_time+32h)/10  ;W_CMD_COUNT
  [4808090h] = 8000h+master_packet_address   ;start transmit      ;W_TXBUF_CMD
With the byte values counting the ieee frame header+body+fcs.
(*) The hardware doesn't actually seem to use the "slave_bits" entry in the hardware header, instead, it is using the "slave_bits" entry in the frame body(!)

Flowchart (at Master side)
 After starting transfer via TXREQ and TXBUF_CMD write:
   TXBUSY=2 (formerly 0) (after TXBUF_CMD write, or sometimes a bit later)
 After about 50-500 microseconds:                               ;\
   RF_STAT=3 (TXing) (formerly 2)                               ;
   RXTX_ADDR=0006h..0008h (TXbuf+0Ch..) (formerly in RXBUF)     ; CMD
   SEQNO+1                                                      ;
 After TX preamble:                                             ;
   IF=80h (TX Start, for CMD)                                   ;
   RXTX_ADDR=0009h..0xxxh (TXbuf..)                             ;
 After TX data:                                                 ;
   optional: IF=02h (TX Done, for CMD) (if enabled in TXSTATCNT);
   optional: TXSTAT=0800h (CMD done)   (if enabled in TXSTATCNT);
   RF_STAT=5 (CMD done, prepare for REPLY)                      ;/
 US=0017h                                                       ;\
   RXTX_ADDR=rxbuf..                                            ;
 After RX preamble:                                             ;
   IF=40h (RX Start, for REPLY)                                 ; REPLY
   RXTX_ADDR=rxbuf..                                            ; (if any)
 After RX data:                                                 ;
   IF=01h (RX Done, for REPLY)                                  ;
   WRCSR+18h (for REPLY)                                        ;/
 After a dozen microseconds:                                    ;\
   RF_STAT=7 ;Switching from REPLY to ACK                       ;
   RF_STAT=8 ;TXing ACK  (shortly after above STAT=7)           ;
   RXTX_ADDR=0FC0h (special dummy addr during TX ACK)           ;
 After TX preamble:                                             ; ACK
   IF=80h (TX Start, for ACK)                                   ;
 After TX data:                                                 ;
   optional: IF=02h (TX Done, for ACK) (if enabled in TXSTATCNT);
   optional: TXSTAT=0B01h (ACK done)   (if enabled in TXSTATCNT);
   TXBUSY=0000h (formerly 0002h)                                ;
   TXBUF_CMD.bit15=0                                            ;
   TXHDR_0=0001h (okay)           (formerly 0000h)              ;
   TXHDR_2=0000h (no error flags) (formerly 0002h)              ;
   SEQNO+1                                                      ;
   RF_STAT=1   ;RX awaiting                                     ;
   IF=1000h (CMD timeslot done) (shortly AFTER above IF=02h)    ;/


Sending a W_TXBUF_CMD frame starts the following process:
 1. MP host sends the CMD frame, as soon as possible. after preamble,
     IRQ7 is triggered
 2. once the transfer is finished: if bit14 in W_TXSTATCNT is set,
     W_TXSTAT is set to 0x0800, and IRQ1 is triggered
     somewhere here: set W_RF_STATUS=5, RFPINS=0x0084
 3. hardware waits for MP clients' replies, duration is:
     16 + ((10 + W_CMD_REPLYTIME) * count_ones(client_mask_from_frame_body))
 4. MP host sends the CMD ack. after preamble, IRQ7 is triggered
     (this is why you get two IRQ7's from a CMD transfer)
 5. during the ack transfer, W_RF_STATUS is 8, and W_RXTXADDR is 0x0FC0
 6. once the transfer is finished: if bit13 in W_TXSTATCNT is set,
     W_TXSTAT is set to 0x0B01, and IRQ1 is triggered.
 7. the TX header of the CMD frame is adjusted: bits in TXheader[02] are
     cleared to indicate that the corresponding clients responded
     successfully. Nintendo software checks this.
I haven't looked a lot into how retries work. they seem to repeat the entire process.
the CMD ack is sent automatically. the packet is what is described here: the 03:09:BF:00:00:03 flow. MP clients will receive it like a regular frame.
IRQ12 is used to signal the end of the CMD transfer process. it will be either when the final ack is done transferring, if everything was successful, or otherwise at the end of W_CMD_COUNT.



DS Wifi Multiplay Slave

The slave mode is activated by setting W_AID_LOW to a nonzero value (the slave number in range 1..15). That settings specifies that (and when) to send replies to incoming commands.

The replies are queued in W_TXBUF_REPLY1 (next packet) and W_TXBUF_REPLY2 (readonly, current packet).
Software does usually write to the REPLY1 register. Upon incomings CMD's, the hardware does automatically forward REPLY1 to REPLY2 (and reset REPLY1 to 0000h).
Because of that queuing, one should use two alternating Wifi RAM locations (ie. don't overwrite the current packet when preparing the next packet).
Alternately, one can manually forward REPLY1 to REPLY2 (via W_RXCNT.bit7, but that's normally not needed, except maybe for things like manually resetting REPLY2).

These registers are used for multiplay client-to-host (aka slave to master) responses.

4808094h - W_TXBUF_REPLY1 - Multiplay Next Reply Transmit Location (R/W)
4808098h - W_TXBUF_REPLY2 - Multiplay Current Reply Transmit Location (R)
  0-11  Halfword address
  12-14 Unknown (the bits can be set, ie. they DO exist)
  15    Enable
Note: W_TXBUF_REPLY2.Bit15 is NOT cleared after SENDING the reply (instead, REPLY2 gets overwritten by REPLY1 when RECEIVING the next CMD).

Flowchart (at Slave side)
  At incoming CMD DATA packet:                                          ;\
    RF_STATUS=6  ;RX processing incoming stuff                          ;
  After RX preamble:                                                    ; CMD
    IRQ6 (RX Start, for CMD DATA)                                       ; DATA
  After RX data:                                                        ;
    IRQ0 (RX Done, for CMD DATA)                                        ;
    WRCSR=WRCSR+(size of CMD DATA)                                      ;
    RF_STATUS=5  ;preparing REPLY                                       ;
    if REPLY2.bit15=1                                                   ;
      TXHDR[1]=TXHDR[0]  ;<-- or sometimes random?  ;\adjust TXHDR[0,1] ;
      TXHDR[0]=01h       ;<-- mark done/discarded   ;/for <old> REPLY2  ;
    REPLY2=REPLY1, REPLY1=0000h                     ;-forward new reply ;
    if REPLY2.bit15=1                                                   ;
      TXHDR[4] incremented (unless already max FFh) ;\adjust TXHDR[4,5] ;
      TXHDR[5]=00h                                  ;/for <new> REPLY2  ;
      TX_SEQNO incremented  ;<-- done here if REPLY2 exists             ;/
  After some moment (at the AID_LOW slot?):                             ;\
    RF_STATUS=8  ;TX sending REPLY                                      ;
  After TX preamble:                                                    ; REPLY
    IRQ7 (TX Start, for REPLY)                                          ;
  After TX data:                                                        ;
    RF_STATUS=1  ;RX awaiting next packet                               ;
    optional: IRQ1 (TX Done) (only if enabled in TXSTATCNT, and REPLY2.bit15=1)
    optional: TXSTAT=0401h   (only if enabled in TXSTATCNT)             ;
    if REPLY2.bit15=0                                                   ;
      SEQNO increased      ;<-- done here when REPLY2 is empty          ;/
  After some moment:                                                    ;\
    RF_STATUS=6  ;RX processing incoming stuff                          ;
  After RX preamble:                                                    ; CMD
    IRQ6 (RX Start, for CMD ACK)                                        ; ACK
  After RX data:                                                        ;
    IRQ0 (RX Done, for CMD ACK)                                         ;
    WRCSR=WRCSR+(size of CMD ACK)                                       ;
    RF_STATUS=1  ;RX awaiting next packet                               ;/
  Thereafter, Nintendo's software seems to require a delay (at least
  100h microseconds) before receiving the next CMD DATA packet.


on client side
The reply transfer is automatically initiated when receiving a MP CMD frame (this seems to be based on the incoming IEEE header's frame control value and/or broadcast address, CMD frames typically have FC=0228h).

When receiving the MP CMD frame, the hardware determines its position using its W_AID_LOW register and the frame's client bitmask, then waits for its turn to reply.

W_TXBUF_REPLY1 is latched into W_TXBUF_REPLY2, and reset to zero.
The byte at TXHDR[04h] is set incremented. Nintendo software checks for this.

when transferring the MP reply itself:
IRQ7 is triggered. W_RF_STATUS is 8.
at the end: if W_TXSTATCNT.bit12=1, W_TXSTAT is set to 0401h, and IRQ1 is triggered.

Reportedly...
It will always send a reply - if W_TXBUF_REPLY1 isn't configured, it will send an empty reply frame (with frame control 0x0158). W_RXTXADDR isn't modified when sending a default empty reply.



DS Wifi Configuration Ports

4808120h - W_CONFIG_120h (R/W) ;init from firmware[04Ch] ;81ff 0048->SAME
4808122h - W_CONFIG_122h (R/W) ;init from firmware[04Eh] ;ffff 4840->SAME
4808124h - W_CONFIG_124h (R/W) ;init from firmware[05Eh] ;ffff 0000->0032
4808128h - W_CONFIG_128h (R/W) ;init from firmware[060h] ;ffff 0000->01F4
4808130h - W_CONFIG_130h (R/W) ;init from firmware[054h] ;0fff 0142->0140
4808132h - W_CONFIG_132h (R/W) ;init from firmware[056h] ;8fff 8064->SAME
4808140h - W_CONFIG_140h (R/W) ;init from firmware[058h] ;ffff 0000->E0E0
4808142h - W_CONFIG_142h (R/W) ;init from firmware[05Ah] ;ffff 2443->SAME
4808144h - W_CONFIG_144h (R/W) ;init from firmware[052h] ;00ff 0042->SAME
4808146h - W_CONFIG_146h (R/W) ;init from firmware[044h] ;00ff 0016->0002
4808148h - W_CONFIG_148h (R/W) ;init from firmware[046h] ;00ff 0016->0017
480814Ah - W_CONFIG_14Ah (R/W) ;init from firmware[048h] ;00ff 0016->0026
480814Ch - W_CONFIG_14Ch (R/W) ;init from firmware[04Ah] ;ffff 162C->1818
4808150h - W_CONFIG_150h (R/W) ;init from firmware[062h] ;ff3f 0204->0101
4808154h - W_CONFIG_154h (R/W) ;init from firmware[050h] ;7a7f 0058->SAME
These ports are to be initialized from firmware settings.
Above comments show the R/W bits (eg. 81FFh means bit15 and bit8-0 are R/W, bit14-9 are always zero), followed by the initial value on Reset (eg. 0048h), followed by new value after initialization from firmware settings (eg. 0032h, or SAME if the Firmware value is equal to the Reset value; these values seem to be identical in all currently existing consoles).
Note: Firmware part4 changes W_CONFIG_124h to C8h, and W_CONFIG_128h to 7D0h, and W_CONFIG_150h to 202h, and W_CONFIG_140h depending on tx rate and preamble:
  W_CONFIG_140h = firmware[058h]+0202h             ;1Mbit/s
  W_CONFIG_140h = firmware[058h]+0202h-6161h       ;2Mbit/s with long preamble
  W_CONFIG_140h = firmware[058h]+0202h-6161h-6060h ;2Mbit/s with short preamble

48080ECh - W_CONFIG_0ECh (R/W) ;firmware writes 3F03h (same as on power-up)
48080D4h - W_CONFIG_0D4h (R/W) ;firmware writes 0003h (affectd by W_MODE_RST)
48080D8h - W_CONFIG_0D8h (R/W) ;firmware writes 0004h (same as on power-up)
4808254h - W_CONFIG_254h (?) ;firmware writes 0000h (read: EEEEh on DS-Lite)
Firmware just initializes these ports with fixed values, without further using them after initialization.

48080DAh - W_RX_LEN_CROP (R/W) ;firmware writes 0602h (same as on power-up)
  0-7   Decrease RX Length by N halfwords for Non-WEP packets (usually 2)
  8-15  Decrease RX Length by N halfwords for WEP packets     (usually 6)
Used to exclude the FCS (and WEP IV+ICV) from the length entry in the Hardware RX Header.


DS Wifi Baseband Chip (BB)

BB-Chip Mitsumi MM3155 (DS), or BB/RF-Chip Mitsumi MM3218 (DS-Lite)

4808158h - W_BB_CNT - Baseband serial transfer control (W)
  0-7   Index     (00h-68h)
  8-11  Not used  (should be zero)
  12-15 Direction (5=Write BB_WRITE to Chip, 6=Read from Chip to BB_READ)
Transfer is started after writing to this register.

480815Ah - W_BB_WRITE - Baseband serial write data (W)
  0-7   Data to be sent to chip (by following W_BB_CNT transfer)
  8-15  Not used (should be zero)

480815Ch - W_BB_READ - Baseband serial read data (R)
  0-7   Data received from chip (from previous W_BB_CNT transfer)
  8-15  Not used (always zero)

480815Eh - W_BB_BUSY - Baseband serial busy flag (R)
  0     Transfer Busy (0=Ready, 1=Busy)
  1-15  Always zero
Used to sense transfer completion after writes to W_BB_CNT.
Not sure if I am doing something wrong... but the busy flag doesn't seem to get set immediately after W_BB_CNT writes, and works only after waiting a good number of clock cycles?

4808160h - W_BB_MODE (R/W)
  0-7   Always zero
  8     Unknown (usually 1) (no effect no matter what setting?)
  9-13  Always zero
  14    Unknown (usually 0) (W_BB_READ gets unstable when set)
  15    Always zero
This register is initialized by firmware bootcode - don't change.

4808168h - W_BB_POWER (R/W)
  0-3   Disable whatever   (usually 0Dh=disable)
  4-14  Always zero
  15    Disable W_BB_ports (usually 1=Disable)
Must be set to 0000h before accessing BB registers.

Read-Write-Ability of the BB-Chip Mitsumi MM3155 registers (DS)
  Index    Num Dir Expl.
  00h        1 R   always 6Dh (R) (Chip ID)
  01h..0Ch  12 R/W 8bit R/W
  0Dh..12h   6 -   always 00h
  13h..15h   3 R/W 8bit R/W
  16h..1Ah   5 -   always 00h
  1Bh..26h  12 R/W 8bit R/W
  27h        1 -   always 00h
  28h..4Ch     R/W 8bit R/W
  4Dh        1 R   always 00h or BFh (depending on other regs)
  4Eh..5Ch     R/W 8bit R/W
  5Dh        1 R   always 01h (R)
  5Eh..61h     -   always 00h
  62h..63h   2 R/W 8bit R/W
  64h        1 R   always FFh or 3Fh (depending on other regs)
  65h        1 R/W 8bit R/W
  66h        1 -   always 00h
  67h..68h   2 R/W 8bit R/W
  69h..FFh     -   always 00h

Read-Write-Ability of the BB/RF-Chip Mitsumi MM3218 (DS-Lite)
Same as above. Except that reading always seems to return [5Dh]=00h. And, for whatever reason, Nintendo initializes DS-Lite registers by writing [00h]=03h and [66h]=12h. Nethertheless, the registers always read as [00h]=6Dh and [66h]=00h, ie. same as on original DS.

Important BB Registers
Registers 0..68h are initialized by firmware bootcode, and (most) of these settings do not need to be changed by other programs, except for:
  Addr Initial Meaning
  01h 0x9E    [unsetting/resetting bit 7 initializes/resets the system?]
  02h         unknown (firmware is messing with this register)
  06h         unknown (firmware is messing with this register, too)
  13h 0x00    CCA operation - criteria for receiving
                    0=only use Carrier Sense (CS)
                    1=only use Energy Detection (ED)
                    2=receive if CS OR ED
                    3=receive only if CS AND ED
  1Eh 0xBB    see change channels flowchart (Ext. Gain when RF[09h].bit16=0)
  35h 0x1F    Energy Detection (ED) criteria
              value 0..61 (representing energy levels of -60dBm to -80dBm)


DS Wifi RF Chip

RF-Chip RF9008 (compatible to RF2958 from RF Micro Devices, Inc.) (Original DS)
BB/RF-Chip Mitsumi MM3218 (DS-Lite)

480817Ch - W_RF_DATA2 - RF chip serial data/transfer enable (R/W)
For Type2 (ie. firmware[040h]<>3):
  0-1   Upper 2bit of 18bit data
  2-6   Index   (00h..1Fh) (firmware uses only 00h..0Bh)
  7     Command (0=Write data, 1=Read data)
  8-15  Should be zero (not used with 24bit transfer)
For Type3 (ie. firmware[040h]=3):
  0-3   Command (5=Write data, 6=Read data)
  4-15  Should be zero (not used with 20bit transfer)
Writing to this register starts the transfer.

480817Eh - W_RF_DATA1 - RF chip serial data (R/W)
For Type2 (ie. firmware[040h]<>3):
  0-15  Lower 16bit of 18bit data
For Type3 (ie. firmware[040h]=3):
  0-7   Data (to be written to chip) (or being received from chip)
  8-15  Index (usually 00h..28h) (index 40h..FFh are mirrors of 00h..3Fh)
This value should be set before setting W_RF_DATA2.

4808180h - W_RF_BUSY - RF chip serial busy flag (R)
  0     Transfer Busy (0=Ready, 1=Busy)
  1-15  Always zero
Used to sense transfer completion after writes to W_RF_DATA2.

4808184h - W_RF_CNT - RF chip serial control (R/W)
  0-5   Transfer length (init from firmware[041h].Bit0-5)
  6-7   Always zero
  8     Unknown         (init from firmware[041h].Bit7)
  9-13  Always zero
  14    Unknown         (usually 0)
  15    Always zero
This register is initialized by firmware bootcode - don't change.
Usually, Type2 has length=24bit and flag=0. Type3 uses length=20bit and flag=1.

Caution For Type2 (ie. firmware[040h]<>3)
Before accessing Type2 RF Registers, first BB[01h] must have been properly initialized (ie. BB[01h].Bit7 must have been toggled from 0-to-1).


DS Wifi RF9008 Registers

RF9008 (RF2958 compatible)
2.4GHz Spread-Spectrum Transceiver - RF Micro Devices, Inc.

RF chip data (Type2) (initial NDS settings from firmware, example)
  Firmware   Index   Data
  (24bit)    (4bit)  (18bit)
  00C007h  =  00h  + 0C007h ;-also set to 0C008h for power-down
  129C03h  =  04h  + 29C03h
  141728h  =  05h  + 01728h ;\these are also written when changing channels
  1AE8BAh  =  06h  + 2E8BAh ;/
  1D456Fh  =  07h  + 1456Fh
  23FFFAh  =  08h  + 3FFFAh
  241D30h  =  09h  + 01D30h ;-bit10..14 should be also changed per channel?
  """"50h  =  """  + """50h ;firmware v5 and up uses narrower tx filter
  280001h  =  0Ah  + 00001h
  2C0000h  =  0Bh  + 00000h
  069C03h  =  01h  + 29C03h
  080022h  =  02h  + 00022h
  0DFF6Fh  =  03h  + 1FF6Fh

RF[00h] - Configuration Register 1 (CFG1) (Power on: 00007h)
  17-16 Reserved, program to zero (0)
  15-14 Reference Divider Value (0=Div2, 1=Div3, 2=Div44, 3=Div1)
  3     Sleep Mode Current      (0=Normal, 1=Very Low)
  2     RF VCO Regulator Enable (0=Disable, 1=Enable)
  1     IF VCO Regulator Enable (0=Disable, 1=Enable)
  0     IF VGA Regulator Enable (0=Disable, 1=Enable)

RF[01h] - IF PLL Register 1 (IFPLL1) (Power on: 09003h)
  17    IF PLL Enable                      (0=Disable, 1=Enable)
  16    IF PLL KV Calibration Enable       (0=Disable, 1=Enable)
  15    IF PLL Coarse Tuning Enable        (0=Disable, 1=Enable)
  14    IF PLL Loop Filter Select          (0=Internal, 1=External)
  13    IF PLL Charge Pump Leakage Current (0=Minimum value, 1=2*Minimum value)
  12    IF PLL Phase Detector Polarity     (0=Positive, 1=Negative)
  11    IF PLL Auto Calibration Enable     (0=Disable, 1=Enable)
  10    IF PLL Lock Detect Enable          (0=Disable, 1=Enable)
  9     IF PLL Prescaler Modulus           (0=4/5 Mode, 1=8/9 Mode)
  8-4   Reserved, program to zero (0)
  3-0   IF VCO Coarse Tuning Voltage       (N=Voltage*16/VDD)

RF[02h] - IF PLL Register 2 (IFPLL2) (Power on: 00022h)
  17-16 Reserved, program to zero (0)
  15-0  IF PLL divide-by-N value

RF[03h] - IF PLL Register 3 (IFPLL3) (Power on: 1FF78h)
  17    Reserved, program to zero (0)
  16-8  IF VCO KV Calibration, delta N value (signed)  ;DeltaF=(DN/Fr)
  7-4   IF VCO Coarse Tuning Default Value
  3-0   IF VCO KV Calibration Default Value

RF[04h] - RF PLL Register 1 (RFPLL1) (Power on: 09003h)
  17-10 Same as for RF[01h] (but for RF, not for IF)
  9     RF PLL Prescaler Modulus (0=8/9 Mode, 1=8/10 Mode)
  8-0   Same as for RF[01h] (but for RF, not for IF)

RF[05h] - RF PLL Register 2 (RFPLL2) (Power on: 01780h)
  17-6  RF PLL Divide By N Value
  5-0   RF PLL Numerator Value (Bits 23-18)

RF[06h] - RF PLL Register 3 (RFPLL3) (Power on: 00000h)
  17-0  RF PLL Numerator Value (Bits 17-0)

RF[07h] - RF PLL Register 4 (RFPLL4) (Power on: 14578h)
  17-10 Same as for RF[03h] (but for RF, not for IF) ;and, DN=(deltaF/Fr)*256

RF[08h] - Calibration Register 1 (CAL1) (Power on: 1E742h)
  17-13  VCO1 Warm-up Time  ;TVCO1=(approximate warm-up time)*(Fr/32)
  12-8   VCO1 Tuning Gain Calibration ;TLOCK1=(approximate lock time)*(Fr/128)
  7-3    VCO1 Coarse Tune Calibration Reference  ;VALUE=(average time)*(Fr/32)
  2-0    Lock Detect Resolution (0..7)

RF[09h] - TXRX Register 1 (TXRX1) (Power on: 00120h)
  17    Receiver DC Removal Loop          (0=Enable DC Removal Loop, 1=Disable)
  16    Internal Variable Gain for VGA  (0=Disable/External, 1=Enable/Internal)
  15    Internal Variable Gain Source (0=From TXVGC Bits, 1=From Power Control)
  14-10 Transmit Variable Gain Select (TXVGC)   (0..1Fh = High..low gain)
  9-7   Receive Baseband Low Pass Filter     (0=Wide Bandwidth, 7=Narrow)
  6-4   Transmit Baseband Low Pass Filter    (0=Wide Bandwidth, 7=Narrow)
  3     Mode Switch            (0=Single-ended mode, 1=Differential mode)
  2     Input Buffer Enable TX (0=Input Buffer Controlled by TXEN, 1=By BBEN)
  1     Internal Bias Enable   (0=Disable/External, 1=Enable/Internal)
  0     TX Baseband Filters Bypass        (0=Not Bypassed, 1=Bypassed)

RF[0Ah] - Power Control Register 1 (PCNT1) (Power on: 00000h)
  17-15 Select MID_BIAS Level                          (1.6V through 2.6V)
  14-9  Desired output power at antenna                (N*0.5dBm)
  8-3   Power Control loop-variation-adjustment Offset (signed, N*0.5dB)
  2-0   Desired delay for using a single TX_PE line    (N*0.5us)

RF[0Bh] - Power Control Register 2 (PCNT2) (Power on: 00000h)
  17-12 Desired MAX output power when PABIAS=MAX=2.6V (N*0.5dBm)
  11-6  Desired MAX output power when PABIAS=MID_BIAS (N*0.5dBm)
  5-0   Desired MAX output power when PABIAS=MIN=1.6V (N*0.5dBm)

RF[0Ch] - VCOT Register 1 (VCOT1) (Power on: 00000h)
  17    IF VCO Band Current Compensation (0=Disable, 1=Enable)
  16    RF VCO Band Current Compensation (0=Disable, 1=Enable)
  15-0  Reserved, program to zero (0)

RF[0Dh..1Ah] - N/A (Power on: 00000h)
  Not used.

RF[1Bh] - Test Register 1 (TEST) (Power on: 0000Fh)
  17-0  This is a test register for internal use only.

RF[1Ch..1Eh] - N/A (Power on: 00000h)
  Not used.

RF[1Fh] - Reset Register (Power on: 00001h)
  17-0  Don't care (writing any value resets the chip)


DS Wifi Unknown Registers

480800Ah - W_X_00Ah (R/W)
  0-15  Unknown (usually zero)
"[bit7 - ingore rx duplicates]" <--- that is NOT correct (no effect).
Firmware writes 0000h to it. That, done many times. So, eventually some bits in this register are automatically set by hardware in whatever situations, otherwise repeatedly writing 0000h to it would be kinda useless...?

---

Below Ports W_X_244h and W_X_228h might be related to deciding when to send multiplay replies...?

4808244h - W_X_244h (R/W) x ffff [0000] (used by firmware part4)
Unknown. Seems to be W_IF/W_IE related. Firmware sets Port 4808244h bits 6,7,12 to 1-then-0 upon IRQ06,IRQ07,IRQ12 respectively.

4808228h - W_X_228h (W) fixx [0000] (used by firmware part4) (bit3)
Unknown. Firmware writes 8-then-0 (done in IRQ06 handler, after Port 4808244h access).

---

Below Ports 48081A0h, 48081A2h, 48081A4h are somehow related to BB[02h]...

48081A0h - W_X_1A0h - (R/W) -933 [0000]
  0-1   Unknown
  2-3   Always zero
  4-5   Unknown
  6-7   Always zero
  8     Unknown
  9-10  Always zero
  11    Unknown
  12-15 Always zero
Firmware writes values 000h, 823h. Seems to be power-related. The following experimental code toggles RXTX.ON (RFU.Pin4): "x=0 / @@lop: / [48081A0h]=x / [4808036h]=0 / x=x XOR 3 / wait_by_loop(1000h) / b @@lop".
Also, writing to port 48081A0h affects ports 4808034h, 480819Ch, 480821Ch, and 48082A2h.

48081A2h - W_X_1A2h - (R/W) ---3 [0001] (used by firmware part4)
  0-1   Unknown. Firmware writes values 03h, 01h, and VAR.
  2-15  Always zero
Used in combination with Port 48081A0h, so it's probably power-related, too.

48081A4h - W_X_1A4h - (R/W) ffff [0000]
"Rate used when signal test is enabled (0x0A or 0x14 for 1 or 2 mbit)"
(Not too sure if that's correct, there is no visible relation to any rate.)
(This register seems to be R/W only on certain Port 48081A0h settings.)
Unknown. Firmware writes whatever.

---

4808220h - W_RAM_DISABLE - RAM Control (R/W)
  0-1   Disable WifiRAM      (0=Normal, other=locks memory at 4804000h-5FFFh)
  2-4   Unknown              (0=Normal, other=prevents/affects RX to ram?)
  5     Disable Special Log? (0=Normal, 1=Prevent 4805F6Eh..5F77h updates)
  6-15  Unknown              (0=Normal, other=?)

4808290h - W_X_290h - (R/W or Disabled)
Reportedly, this is the "antenna" register, which should exist on official devkits, allowing to switch between wired Ethernet, and wireless Wifi mode.
  0     Unknown (R/W) (if present)
  1-15  Not used
On normal NDS release versions, this register seems to be disabled (if it is implemented at all), and trying to read from it acts as for unused registers, ie. reads return FFFFh (or probably 0000h on NDS-lite). The NDS firmware contains code for accessing this port, even in release versions.

W_INTERNAL
All registers marked as "W_INTERNAL" aren't used by Firmware part4, and are probably unimportant, except for whatever special diagnostics purposes.

Wifi DMA
Wifi RAM can be accessed with normal "Start Immediately" DMA transfers (typically by reading through W_RXBUF_RD_DATA, so the DMA automatically wraps from END to BEGIN).
Additionally, DMA0 and DMA2 can be reportedly synchronized to "Wireless Interrupt" (rather than using "Start Immediately" timing), no idea if/how that's working though... and if it gets started on any Wifi IRQ, or only on specific IRQs...?
Possibly some of the above unknown registers, or some unknown bits in other registers, are DMA related...?
Reportedly, early firmwares did use "Wireless Interrupt" DMAs (that'd be firmware v1/v2... or, only earlier unreleased prototype versions?).


DS Wifi Unused Registers

Wifi WS0 and WS1 Regions in NDS7 I/O Space
Wifi hardware occupies two 32K slots, but most of it is filled with unused or duplicated regions. The timings (waitstates) for WS0 and WS1 are initialized in WIFIWAITCNT (by firmware).
  4800000h-4807FFFh Wifi WS0 Region (32K)  ;used for RAM at 4804000h
  4808000h-4808000h Wifi WS1 Region (32K)  ;used for registers at 4808000h
  4810000h-4FFFFFFh Not used (00h-filled)
Structure of the 32K Wifi Regions (WS0 and WS1)
  Wifi-WS0-Region    Wifi-WS1-Region    Content
  4800000h-4800FFFh  4808000h-4808FFFh  Registers
  4801000h-4801FFFh  4809000h-4809FFFh  Registers (mirror)
  4802000h-4803FFFh  480A000h-480BFFFh  Unused
  4804000h-4805FFFh  480C000h-480DFFFh  Wifi RAM  (8K)
  4806000h-4806FFFh  480E000h-480EFFFh  Registers (mirror)
  4807000h-4807FFFh  480F000h-480FFFFh  Registers (mirror)
Wifi Registers (recommended 4808000h-4808FFFh) appear more stable in WS1?
Wifi RAM (recommended 4804000h-4805FFFh) appears more stable in WS0?

Unused Ports (Original NDS)
Aside from those ports listed in the Wifi I/O Map, all other ports in range 4808000h..4808FFFh are unused. On the original DS, reading from these ports returns FFFFh.

Unused Ports (NDS-Lite)
Reading from unused I/O ports acts as PASSIVE mirror of W_RXBUF_RD_DATA. Exceptions are: Ports 4808188h, and 48082D8h..48082E6h; which always return 0000h.

Unused Memory (Original NDS)
Unused Wifi Memory is at 2000h..3FFFh. On the original DS, reading from that region returns FFFFh.

Unused Memory (NDS-Lite)
Reading from unused memory acts as PASSIVE mirror of WifiRAM (ie. reading from it returns the value being most recently read from 4000h..5FFFh) (that not affected by indirect WifiRAM reads via W_RXBUF_RD_DATA) (and, that not affected by writes to wifi memory, including writes that do overwrite the most recent read value) (and, that only if WifiRAM is properly enabled, ie. Port 4808220h.Bits0-1 should be 0).
Moreover, certain addresses are additionally ORed with mirrored I/O Ports. That addresses are:
  2030h, 2044h, 2056h, 2080h, 2090h, 2094h, 2098h, 209Ch, 20A0h, 20A4h,
  20A8h, 20AAh, 20B0h, 20B6h, 20BAh, 21C0h, 2208h, 2210h, 2244h, 31D0h,
  31D2h, 31D4h, 31D6h, 31D8h, 31DAh, 31DCh, 31DEh.
For example, 2044h is a PASSIVE mirror of WifiRAM, ORed with an ACTIVE mirror of W_RANDOM (Port 044h). Note that some mirrors are at 2000h-2FFFh, and some at 3000h-3FFFh. The W_CMD_STAT mirrors are PASSIVE (that, in unused memory region only) (in normal port-mirror regions like 1000h-1FFF, W_CMD_STAT mirrors are ACTIVE).

Known (W) Mirrors (when reading from Write-only ports)
  Read from (W)           Mirrors to (NDS)       Or to (NDS-Lite)
  070h W_TXBUF_WR_DATA    060h W_RXBUF_RD_DATA   074h W_TXBUF_GAP
  078h W_INTERNAL         068h W_TXBUF_WR_ADDR   074h W_TXBUF_GAP
  0ACh W_TXREQ_RESET      09Ch W_INTERNAL        ? (zero)
  0AEh W_TXREQ_SET        09Ch W_INTERNAL        ? (zero)
  0B4h W_TXBUF_RESET      0B6h W_TXBUSY          ? (zero)
  158h W_BB_CNT           15Ch W_BB_READ         ? (zero)
  15Ah W_BB_WRITE         ? (zero)               ? (zero)
  178h W_INTERNAL         17Ch W_RF_DATA2        ? (zero)
  20Ch W_INTERNAL         09Ch W_INTERNAL        ? (zero)
  21Ch W_IF_SET           010h W_IF              010h-OR-05Ch-OR-more?
  228h W_X_228h           ? (zero)               ? (zero)
  298h W_INTERNAL         084h W_TXBUF_TIM       084h W_TXBUF_TIM
  2A8h W_INTERNAL         238h W_INTERNAL        238h W_INTERNAL
  2B0h W_INTERNAL         084h W_TXBUF_TIM       084h W_TXBUF_TIM
Notes: The mirror to W_RXBUF_RD_DATA is a passive mirror.
The DS-Lite mirror at 21Ch consists of several ports ORed with each other (known components are Ports 010h and 05Ch, but there seem to be even more values ORed with it).

Port Mirror Regions
The Wifi Port region at 000h..FFFh is mirrored to 1000h..1FFFh, 6000h..6FFFh, and 7000h..7FFFh. Many of that mirrored ports are PASSIVE mirrors. Eg. reading from 1060h (mirror of Port 060h, W_RXBUF_RD_DATA) returns the old W_RXBUF_RD_DATA value (but without loading a new value from Wifi RAM, and without incrementing W_RXBUF_RD_ADDR). However, other registers, like W_RANDOM do have ACTIVE mirrors.


DS Wifi Initialization

Initialization sequence
These events must be done somewhat in sequence. There is some flexibility as to how they can be ordered but it's best to follow this order:
  [4000304h].Bit1 = 1 ;POWCNT2  ;-Enable power to the wifi system
  W_MACADDR = firmware[036h]    ;-Set 48bit Mac address
  reg[012h] = 0000h   ;W_IE     ;-Disable interrupts
Wake Up the wireless system:
  reg[036h] = 0000h ;W_POWER_US ;\clear all powerdown bits
  delay 8 ms                    ; (works without that killer-delay ?)
  reg[168h] = 0000h ;W_BB_POWER ;/
  IF firmware[040h]=02h         ;\
    temp=BB[01h]                ; for wifitype=02h only:
    BB[01h]=temp AND 7Fh        ; reset BB[01h].Bit7, then restore old BB[01h]
    BB[01h]=temp                ; (that BB setting enables the RF9008 chip)
  ENDIF                         ;/
  delay 30 ms                   ;-(more killer-delay now getting REALLY slow)
  call init_sub_functions       ;- same as "Init 16 registers by firmware[..]"
                                ;  and "Init RF registers", below.
                                ;  this or the other one probably not necessary
Init the Mac system:
  reg[004h] = 0000h   - W_MODE_RST       ;set hardware mode
  reg[008h] = 0000h   - W_TXSTATCNT      ;
  reg[00Ah] = 0000h   - ? W_X_00Ah       ;(related to rx filter)
  reg[012h] = 0000h   - W_IE             ;disable interrupts (again)
  reg[010h] = FFFFh   - W_IF             ;acknowledge/clear any interrupts
  reg[254h] = 0000h   - W_CONFIG_254h    ;
  reg[0B4h] = FFFFh   - W_TXBUF_RESET    ;--reset all TXBUF_LOC's
  reg[080h] = 0000h   - W_TXBUF_BEACON   ;disable automatic beacon transmission
  reg[02Ah] = 0000h   - W_AID_FULL       ;\clear AID
  reg[028h] = 0000h   - W_AID_LOW        ;/
  reg[0E8h] = 0000h   - W_US_COUNTCNT    ;disable microsecond counter
  reg[0EAh] = 0000h   - W_US_COMPARECNT  ;disable microsecond compare
  reg[0EEh] = 0001h   - W_CMD_COUNTCNT   ;(is 0001h on reset anyways)
  reg[0ECh] = 3F03h   - W_CONFIG_0ECh    ;
  reg[1A2h] = 0001h   - ?                ;
  reg[1A0h] = 0000h   - ?                ;
  reg[110h] = 0800h   - W_PRE_BEACON     ;
  reg[0BCh] = 0001h   - W_PREAMBLE       ;disable short preamble
  reg[0D4h] = 0003h   - W_CONFIG_0D4h    ;
  reg[0D8h] = 0004h   - W_CONFIG_0D8h    ;
  reg[0DAh] = 0602h   - W_RX_LEN_CROP    ;
  reg[076h] = 0000h   - W_TXBUF_GAPDISP  ;disable gap/skip (offset=zero)
Init 16 registers by firmware[044h..063h]
  reg[146h] = firmware[044h] ;W_CONFIG_146h
  reg[148h] = firmware[046h] ;W_CONFIG_148h
  reg[14Ah] = firmware[048h] ;W_CONFIG_14Ah
  reg[14Ch] = firmware[04Ah] ;W_CONFIG_14Ch
  reg[120h] = firmware[04Ch] ;W_CONFIG_120h
  reg[122h] = firmware[04Eh] ;W_CONFIG_122h
  reg[154h] = firmware[050h] ;W_CONFIG_154h
  reg[144h] = firmware[052h] ;W_CONFIG_144h
  reg[130h] = firmware[054h] ;W_CONFIG_130h
  reg[132h] = firmware[056h] ;W_CONFIG_132h
  reg[140h] = firmware[058h] ;W_CONFIG_140h
  reg[142h] = firmware[05Ah] ;W_CONFIG_142h
  reg[038h] = firmware[05Ch] ;W_POWER_TX
  reg[124h] = firmware[05Eh] ;W_CONFIG_124h
  reg[128h] = firmware[060h] ;W_CONFIG_128h
  reg[150h] = firmware[062h] ;W_CONFIG_150h
Init RF registers
  numbits = BYTE firmware[041h]    ;usually 18h
  numbytes = (numbits+7)/8         ;usually 3
  reg[0x184] = (numbits+80h) AND 017Fh  -- W_RF_CNT
  for i=0 to BYTE firmware[042h]-1 ;number of entries (usually 0Ch) (0..0Bh)
   if BYTE firmware[040h]=3
    RF[i]=firmware[0CEh+i]
   else
    RF_Write(numbytes at firmware[0CEh+i*numbytes])
   endif
Init the BaseBand System
  (this should be not required, already set by firmware bootcode)
  reg[160h] = 0100h  ;W_BB_MODE
  BB[0..68h] = firmware[64h+(0..68h)]
Set Mac address
  copy 6 bytes from firmware[036h] to mac address at 0x04800018  (why again ?)
Now just set some default variables
  reg[02Ch]=0007h  ;W_TX_RETRYLIMIT - XXX needs to be set for every transmit?
  Set channel (see section on changing channels)
  Set Mode 2 -- sets bottom 3 bits of W_MODE_WEP to 2
  Set Wep Mode / key -- Wep mode is bits 3..5 of W_MODE_WEP
  BB[13h] = 00h  ;CCA operation (use only carrier sense, without ED)
  BB[35h] = 1Fh  ;Energy Detection Threshold (ED)
-- To further init wifi to the point that you can properly send
-- and receive data, there are some more variables that need to be set.
  reg[032h] = 8000h -- W_WEP_CNT     ;Enable WEP processing
  reg[134h] = FFFFh -- W_POST_BEACON ;reset post-beacon counter to LONG time
  reg[028h] = 0000h -- W_AID_LOW     ;\clear W_AID value, again?!
  reg[02Ah] = 0000h -- W_AID_FULL    ;/
  reg[0E8h] = 0001h -- W_US_COUNTCNT ;enable microsecond counter
  reg[038h] = 0000h -- W_POWER_TX    ;disable transmit power save
  reg[020h] = 0000h -- W_BSSID_0     ;\
  reg[022h] = 0000h -- W_BSSID_1     ; clear BSSID
  reg[024h] = 0000h -- W_BSSID_2     ;/
-- TX prepare
  reg[0AEh] = 000Dh -- W_TXREQ_SET   ;flush all pending transmits (uh?)
-- RX prepare
  reg[030h] = 8000h    W_RXCNT         ;enable RX system (done again below)
  reg[050h] = 4C00h    W_RXBUF_BEGIN   ;(example values)
  reg[052h] = 5F60h    W_RXBUF_END     ;(length = 4960 bytes)
  reg[056h] = 0C00h/2  W_RXBUF_WR_ADDR ;fifo begin latch address
  reg[05Ah] = 0C00h/2  W_RXBUF_READCSR     ;fifo end, same as begin at start.
  reg[062h] = 5F60h-2  W_RXBUF_GAP     ;(set gap<end) (zero should work, too)
  reg[030h] = 8001h    W_RXCNT  ;enable, and latch new fifo values to hardware
--
  reg[030h] = 8000h    W_RXCNT       enable receive (again?)
  reg[010h] = FFFFh    W_IF          clear interrupt flags
  reg[012h] = whatever W_IE          set enabled interrupts
  reg[1AEh] = 1FFFh    W_RXSTAT_OVF_IE desired STAT Overflow interrupts
  reg[1AAh] = 0000h    W_RXSTAT_INC_IE desired STAT Increase interrupts
  reg[0D0h] = 0181h    W_RXFILTER set to 0x581 when you successfully connect
                        to an access point and fill W_BSSID with a mac
                        address for it. (W_RXFILTER) [not sure on the values
                        for this yet]
  reg[0E0h] = 000Bh  -- W_RXFILTER2     ;
  reg[008h] = 0000h  -- ? W_TXSTATCNT   ;(again?)
  reg[00Ah] = 0000h  -- ? W_X_00Ah      ;(related to rx filter) (again?)
  reg[004h] = 0001h  -- W_MODE_RST      ;hardware mode
  reg[0E8h] = 0001h  -- W_US_COUNTCNT   ;enable microsecond counter (again?)
  reg[0EAh] = 0001h  -- W_US_COMPARECNT ;enable microsecond compare
  reg[048h] = 0000h  -- W_POWER_?    ;[disabling a power saving technique]
  reg[038h].Bit1 = 0 -- W_POWER_TX   ;[this too]
  reg[048h] = 0000h  -- W_POWER_?    ;[umm, it's done again. necessary?]
  reg[0AEh] = 0002h  -- W_TXREQ_SET  ;
  reg[03Ch].Bit1 = 1 -- W_POWERSTATE ;queue enable power (RX power, we believe)
  reg[0ACh] = FFFFh  -- W_TXREQ_RESET;reset LOC1..3
That's it, the DS should be now happy to send and receive packets.
It's very possible that there are some unnecessary registers set in here.


DS Wifi Flowcharts

Wifi Transmit Procedure
To transmit data via wifi (Assuming you've already initialized wifi and changed channels to the channel you want):
 (1) Copy the TX Header followed by the 802.11 packet to send anywhere it
      will fit in MAC memory (halfword-aligned)
 (2) Take the offset from start of MAC memory that you put the packet,
      divide it by 2, and or with 0x8000 - store this in one of the
      W_TXBUF_LOC registers
 (3) Set W_TX_RETRYLIMIT, to allow your packet to be retried until an ack is
      received (set it to 7, or something similar)
 (4) Store the bit associated with the W_TXBUF_LOC register you used
      into W_TXREQ_SET - this will send the packet.
 (5) You can then read the result data in W_TXSTAT when the TX is over
      (you can tell either by polling or interrupt) to find out how many
      retries were used, and if the packet was ACK'd
Of course, this is just the simplest approach, you can be a lot more clever about it.

Wifi Receive Procedure
To receive data via wifi, you either need to handle the wifi received data interrupt, or you need to poll W_RXBUF_WRCSR - whenever it is != W_RXBUF_READCSR, there is a new packet. When there is a new packet, take the following approach:
 (1) Calculate the length of the new packet (read "received frame length"
      which is +8 bytes from the start of the packet) - total frame length
      is (12 + received frame length) padded to a multiple of 4 bytes.
 (2) Read the data out of the RX FIFO area (keep in mind it's a circular
      buffer and you may have to wrap around the end of the buffer)
 (3) Set the value of W_RXBUF_READCSR to the location of the next packet
      (add the length of the packet, and wrap around if necessary)
Keep in mind, W_RXBUF_READCSR and W_RXBUF_WRCSR must be multiplied by 2 to get a byte offset from the start of MAC memory.

Wifi Change Channels Procedure (ch=1..14)
For Type2 or Type5 (ie. firmware[040h]<>3): ;(Type2, used in Original-DS)
  RF[firmware[F2h+(ch-1)*6]/40000h] = firmware[F2h+(ch-1)*6] AND 3FFFFh
  RF[firmware[F5h+(ch-1)*6]/40000h] = firmware[F5h+(ch-1)*6] AND 3FFFFh
  delay a few milliseconds  ;huh?
  IF RF[09h].bit16=0     ;External Gain (default)
   BB[1Eh]=firmware[146h+(ch-1)]                         ;set BB.Gain register
  ELSEIF RF[09h].bit15=0 ;Internal Gain from TXVGC Bits
   RF[09h].Bit10..14 = (firmware[154h+(ch-1)] AND 1Fh)   ;set RF.TXVGC Bits
  ENDIF
For Type3 (ie. firmware[040h]=3): ;(Type3, used in DS-Lite)
  num_initial_regs = firmware[042h]
  addr=0CEh+num_initial_regs
  num_bb_writes = firmware[addr]
  num_rf_writes = firmware[43h]
  addr=addr+1
  for i=1 to num_bb_writes
    BB[firmware[addr]] = firmware[addr+ch]
    addr=addr+15
  next i
  for i=1 to num_rf_writes
    RF[firmware[addr]] = firmware[addr+ch]
    addr=addr+15
  next i
Congrats, you are now ready to transmit/receive on whatever channel you picked.

Channels
The IEEE802.11b standard (and the NDS hardware) support 14 channels (1..14).
Channels 1..13 use frequencies 2412MHz..2472MHz (in 5MHz steps). Channel 14 uses frequency 2484MHz. Which channels are allowed to be used varies from country to country, as indicated by Bit1..14 of firmware[03Ch]. Channel 14 is rarely used (dated back to an older japanese standard).

Caution: Nearby channels do overlap, you'll get transmission errors on packets that are transferred simultaneously with packets on nearby channels. But, you won't successfully receive packets from nearby channels (so you won't even "see" that they are there, which is bad, as it doesn't allow you to share the channel synchronized with other hosts; ie. it'd be better if two hosts are using the SAME channel, rather than to use nearby channels).
To avoid that problem, conventionally only channels 1,6,11 are used - however Nintendo uses channels 1,7,13 - which is causing conflicts between channel 6,7, and maybe also between 11,13.


DS Wifi Hardware Headers

Hardware TX Header (12 bytes) (TXHDR)
The TX header immediately precedes the data to be sent, and should be put at the location that will be given to the register activating a transmission.
  Addr Siz Expl.
  00h  2   Status - In: Don't care - Out: Status (0000h=Failed, 0001h=Okay)
             0000h=Retrying? (TXBUF_LOCn)
             0001h=Okay      (TXBUF_LOCn,TXBUF_BEACON,TXBUF_CMD)
             xx01h=Okay      (TXBUF_REPLY, with increasing "xx")
             0003h=Failed    (TXBUF_LOCn)
             0005h=Failed    (TXBUF_CMD, with errorflags in TXHDR[2])
  02h  2   Unknown - In: Don't care
             Bit0: Usually zero.
             Bit1..15 --------> flags for multiboot slaves number 1..15
             (Should be usually zero, except when sending multiplay commands
             via W_TXBUF_CMD. In that case, the slave flags should be ALSO
             stored in the second halfword of the FRAME BODY. Actually, the
             hardware seems to use only that entry (in the BODY), rather than
             using this entry (in the hardware header)).
  04h  1   Unknown - In: Must be 00h..02h (should be 00h)
             00h = use W_TX_SEQNO (if enabled in TXBUF_LOCn)
             01h = force NOT to use W_TX_SEQNO (even if it is enabled in LOCn)
             02h = seems to behave same as 01h
             03h..FFh = results in error: W_TXSTAT.Bit1 gets set (though
                        header entry[00h] is kept set to 0001h=Okay)
             other theory: maybe an 8bit retry count with 00h=first try?
  05h  1   Unknown - In: Don't care - Out: Set to 00h
  06h  2   Unknown - In: Don't care
  08h  1   Transfer Rate (0Ah=1Mbit/s, 14h=2Mbit/s) (other values=1MBit/s, too)
  09h  1   Unknown - In: Don't care
  0Ah  2   Length of IEEE Frame Header+Body+checksum(s) in bytes
           (14bits, upper 2bits are unused/don't care)
The eight "Don't care" bytes should be usually set to zero (although setting them to FFh seems to be working as well). Entries [00h] and [05h] are modified by hardware, all other entries are kept unchanged.

Important note! TX length includes the length of a 4-byte "FCS" (checksum) for the packet. The hardware generates the FCS for you, but you still must include it in the packet length. Also note that if the 802.11 WEP enabled bit is set in the header, the packet will be automatically encrypted via the wep algorithm - however, the software is responsible for providing the 4-byte IV block with the WEP key ID and the 24bit IV value. - ALSO, you must include the length of the *encrypted* FCS used in packets that have wep enabled (increase the tx length by another 4 bytes) - this value is calculated automaticly for you, but you are responsible for including it in the length of your packet (if you have data there, it'll be replaced by the FCS.)

Hardware RX Header (12 bytes) (RXHDR)
The RX header is an informational structure that provides needed information about a received packet. It is written right before the received packet data in the rx circular buffer.
  Addr Siz Expl.
  00h  2   Flags
             Bit0-3: Frame type/subtype:
               00h: managment/any frame (except beacon and invalid subtypes)
               01h: managment/beacon frame
               05h: control/ps-poll frame
               08h: data/any frame (subtype0..7) (ie. except invalid subtypes)
              Values 0Ch..0Fh are for Multiplay cmd/reply packets:
               0Ch: CMD frame            ;FC=0228h=Data, FromDS, Data+CF_Poll
               0Dh: CMD ack frame        ;FC=0218h=Data, FromDS, Data+CF-Ack
               0Eh: REPLY frame (data)   ;FC=0118h=Data, ToDS, Data+CF-Ack
               0Fh: REPLY frame (empty)  ;FC=0158h=Data, ToDS, CF_Ack
               0Fh: Also ALL empty packets (raw IEEE header, with 0-byte body)
             Bit4:   Seems to be always set
             Bit5-7: Seems to be always zero
             Bit8: Set when FC.Bit10 is set (more fragments)
             Bit9: Set when the lower-4bit of Sequence Control are nonzero,
                   it is also set when FC.Bit10 is set (more fragments)
                   So, probably, it is set on fragment-mismatch-errors
             Bit10-14: Seems to be always zero
             Bit15: Set when Frame Header's BSSID value equals W_BSSID register
  02h  2   Unknown (0040h=Normal, 0440h=WEP?, or Unchanged for multiplay CMDs?)
  04h  2   Unchanged (not updated by hardware, contains old Wifi RAM content)
  06h  2   Transfer Rate (N*100kbit/s) (ie. 14h for 2Mbit/s)
  08h  2   Length of IEEE Frame Header+Body in bytes (excluding FCS checksum)
  0Ah  1   MAX RSSI (bit0=always 1?)  ;\Received Signal Strength Indicator
  0Bh  1   MIN RSSI                   ;/
Important Note: Received frame lengths are always multiples of 4 bytes. While the actual header length + received frame length may be less, when incrementing the read cursor you must pad the length to a multiple of 4 bytes.

IEEE Header
The above Hardware headers should (must) be followed by valid IEEE headers. Although that headers are to be generated by software, the hardware does do some interaction with the IEEE headers, such like comparing address fields with W_MACADDR and W_BSSID. And, it does modify some entries of it:
1) The sequence control value is replaced by W_TX_SEQNO*10h (when enabled in W_TXBUF_LOCn.Bit13), this replacement does also overwrite the local TXBUF value.
2) The frame control value is modified, namely, the hardware tends to set Bit12 of it. This replacement does NOT modify the local TXBUF, but the remote RXBUF will receive the modified value. Also, Bit0-1 (protocol version) are forcefully set to 0.
3) Transmits via W_TXBUF_BEACON do additionally modify the 64bit timestamp (so W_TXBUF_BEACON should be used ONLY for packets WITH timestamp, ie. Beacons or Probe-Responses). The local TXBUF seems to be left unchanged, but the remote RXBUF will contain the (sender's) W_US_COUNT value.
C) For Control Frames, the hardware headers Length value is transferred as normally (ie. excluding the FCS length, remote RXBUF will contain TXBUF length minus 4), but - no matter of that length value - only 10 or 16 bytes (depending on the subtype) of the IEEE frame are actually transferred and/or stored in RXBUF.
X) For Control Frames with Subtype 0Ah, the AID entry is set to C000h, that, probably ORed with original value in WifiRAM, or with the W_AID_FULL register?
XX) No idea if it's possible to send Control Frames with subtype 0Bh..0Fh, as for now, it seems that either they aren't sent, or the receipient is ignoring them (or processing them internally, but without storing them in RXBUF).

RSSI (Received Signal Strength Indicator)
The MAX RSSI is decoded as so:
 arm7_xlat_rssi_r0:  ;bit0=unused, bit1=extraflag, bit2-7=unsigned value
  tst     r0,2h           ;bit1
  mov     r0,r0,asr 2h    ;div4 (sign bits in bit31-8 are always zero-expanded)
  addeq   r0,r0,19h       ;add extra constant... when bit1=0 !!!!!!
  and     r0,r0,0FFh      ;blah (max is FFh/4+19h)
  bx      r14
The MIN RSSI value is unknown and not used by existing software (it's usually smaller than the 8bit MAX RSSI value, though that value is actually 6bit+1bit, so it's hard to say what is bigger/smaller), actually MIN RSSI might be something different like SNR (Signal to Noise Ratio).


DS Wifi Nintendo Beacons

Beacons are most commonly used to announce Wifi Internet Access Points. The special Nintendo Beacons are used to announce Local Network games (randomly broadcast on channel 1, 7, or 13).

All beacon frames transmitted by a DS host have the following format
  TXHDR using 2MBit/s rate
  802.11 Management frame header
  802.11 Beacon header (Timestamp, BeaconInterval=00xxh, Capability=0021h)
  Supported rates      (Tag=01h, Len=02h, 82h,84h)       ;1Mbit/s and 2Mbit/s
  Distribution Channel (Tag=03h, Len=01h, 0xh)           ;channel 1, 7, or 13
  TIM vector           (Tag=05h, Len=05h, 00h,02h,0,0,0) ;adjusted by hardware
  Custom extension     (Tag=DDh, Len=18h+N, see below)

Nintendo specific beacon info (information element Tag=DDh)
  00h 4  Nintendo Beacon OUI (00h,09h,BFh,00h)
  04h 2  Stepping Offset for 4808134h/W_POST_BEACON (always 000Ah)
  06h 2  LCD Video Sync in 15.625Hz units (VCOUNT*7Fh-W_US_COUNT*2)/80h
  08h 4  Fixed ID (00400001h)
  0Ch 4  Game ID  (0040xxxxh) (or 00000857h=Nintendo Zone)
  10h 2  Randomly generated Stream code (0000h..FFFFh?)
  12h 1  Number of bytes from entry 18h and up (70h for multiboot) (0 if Empty)
  13h 1  Beacon Type (1=Multicart/Pictochat, 9=Empty, 0Bh=Multiboot, ?=Zone)
  14h 2  CMD data size   (01FEh = FFh halfwords) (or 0100h)
  16h 2  REPLY data size (0008h = 4 halfwords)
For Empty (length zero, may occur at very begin of multiboot)
  18h -  Nothing, no data
For Multicart (variable length)
  18h .. Custom data, usually containing the host name, either in 8bit ascii,
         or 16bit unicode format. Sometimes taken from Firmware User Settings,
         and sometimes from Cartridge Backup Memory.
For Pictochat (length 8)
  18h 2  Fixed (always 2348h)
  1Ah 2  Unknown xxxx
  1Ch 1  Chatroom number (00h..03h for Chatroom A..D)
  1Dh 1  Number of users already connected (1..16, including master)
  1Eh 2  Fixed (always 0004h)
For Multiboot (aka DS Download Play) (always 70h bytes)
  18h 4  Game ID (0040xxxxh) (same as [0Ch]) (varies from game to game)
  1Ch 1  Last Snippet flag (00h=Snippet #0..8, 02h=Snippet #9)
  1Dh 1  Session Number (00h=First) (increments when restarting a new upload)
  1Eh 1  Number of slaves already connected (0..15, excluding master)
           Uh, actually [1Eh] is always 01h, even for 2..3 slaves?
  1Fh 1  Snippet number (0..9=Snippet #0..9)
  20h 2  Checksum (on entries [22h..87h])
          chksum=0, for i=22h to 86h step 2, chksum=chksum+halfword[i], next i,
          chksum=FFFFh AND NOT (chksum+chksum/10000h)
  22h 1  In Snippet #0..8: Snippet number (0..8, same as [1Fh])
         In Snippet #9: Number or players connected (0..16, may include master)
  23h 1  Highest Snippet number (09h=Snippet #9)
  24h 2  In Snippet #0..8: Snippet Size in bytes (62h for #0..7, 48h for #8)
         In Snippet #9: Player Mask (eg. 000Fh=4-Players, including Master)
  26h 62h Snippet Data (always 62h bytes, zeropadded if size<62h)
For Nintendo Zone (with Game ID=00000857h) (always 70h bytes):
  18h 70h Encrypted Nintendo Zone Beacon Info (see below)

Multiboot Advertisement Snippets
Snippet #0..8 are merged to form a larger datablock with following info:
  000h 32  Icon Palette (same as for ROM Cartridge Icon)
  020h 512 Icon Bitmap  (same as for ROM Cartridge Icon)
  220h 1   Favorite color (00h..0Fh)       ;\
  221h 1   Username Length (0..10)         ; from firmware user settings
  222h 20  Username (max 10 chars UCS-2)   ;/
  236h 1   Max number of players (1..16, may include master)
  237h 1   Unknown (00h)
  238h 96  Game name (48 UCS-2)   (same as 1st line of ROM Cartridge Title)
  298h 192 Description (96 UCS-2) (same as further lines of ROM Cart Title)
  358h 26  Unused (padding 48h-byte Snippet #8 to 62h-byte size)
Snippet #9 contains slave names:
  000h 2   Slave Mask (eg. 000Eh for three slaves) (initially 0000h, see note)
  002h 1   Slave 1 Number*10h+Color (10h+color)     ;\
  003h 1   Slave 1 Username Length (0..10)          ; Slave 1 (if any)
  004h 14h Slave 1 Username (max 10 chars UCS-2)    ;/
  018h 1   Slave 2 Number*10h+Color (20h+color)     ;\
  019h 1   Slave 2 Username Length (0..10)          ; Slave 2 (if any)
  01Ah 14h Slave 2 Username (max 10 chars UCS-2)    ;/
  01Eh 1   Slave 3 Number*10h+Color (30h+color)     ;\
  01Fh 1   Slave 3 Username Length (0..10)          ; Slave 3 (if any)
  020h 14h Slave 3 Username (max 10 chars UCS-2)    ;/
  ...
Note: The slave Mask is initially 0000h, and isn't updated until AFTER having transferred the first some Data packets.
Unknown if there can be more 62h-byte snippets appended (if any games support 5 or more slaves).

Authentication/Association process
Connecting to a Host console is done via standard 802.11 managment frames. The Auth/Assoc Requests must be sent during the listen interval (ie. shortly after having received beacons).
  Host sends beacon(s)
  Client sends an Authentication Request (AuthSeq=1)            ;\Auth
  Host sends an Authentication Response (AuthSeq=2)             ;/
  Host sends beacon(s)
  Client sends an Association Request (with special SSID)       ;\Assoc
  Host sends an Association Response                            ;/
  Host sends beacon(s) and begins sending CMD/Data packets
The Nintendo Beacons are transferred without public SSID (without Tag=00h). However, the Association Request must contain a SSID, which is derived from the custom Tag=DDh area.
 SSID for multiboot (20h-byte binary, non-ASCII):
  00h 4   Game ID (0040xxxxh) (from Beacon Tag=DDh, entry 0Ch)
  04h 2   Stream code         (from Beacon Tag=DDh, entry 10h)
  06h 1Ah Zerofilled
Multicart games or Pictochat may use whatever SSID's they want (unknown if there is standard for that).

Encrypted Nintendo Zone Beacon Info (with Game ID=00000857h)
Nintendo Zone beacons are broadcast by DS consoles with special "Beacon Cartridges" (that console is merely sending beacons, it doesn't act as an Access Point itself. Instead, the beacon contains the SSID/password for the actual Access Point in the Shop/Restaurant, or for your own home network).
The SSID/Password in the Zone Beacons can be also used by DSi games and DSi browser (depending on the Flags at [66h]).
  00h 32  Access Point SSID (ASCII, zeropadded if shorter than 32 chars)
  20h 10  Server ApNum (ASCII, ten digits/chars...?)
  2Ah 2   Unknown (0001h)
  2Ch 24  Server? Retailer ID string? (eg. "ShopName Country") (purpose=?)
  44h 32  Access Point WEP key (0/5/13/16 bytes) or WPA/WPA2 password
  64h 1   Unknown (00h for DSi, other values for 3DS)
  65h 1   Access Point WEP mode (0=Open, 1/2/3=5/13/16 bytes)
          (only on 3DS?: 4=WPA-TKIP, 5=WPA2-TKIP, 6=WPA-AES, 7=WPA2-AES)
  66h 2   Flags (0003h)
            Bit0: Enable Nintendo Zone content on DS(i)
            Bit1: Enable Online Gaming and Friend list
            Bit4: Enable Nintendo Zone Viewer on 3DS
            Bit7: Block Nintendo eShop
            Bit8: Block Internet Browser
  68h 4   Unknown (uh, maybe zero?)
  6Ch 2   Unknown (0428h)
  6Eh 2   CRC16 with initial value 0 across [00h..6Dh] (or optionally 0=NoCrc)
The above 70h-bytes are RC4 encrypted (the WEP encryption algorithm) with an 8-byte key:
  Key[0..3] = "!SDW" (aka "WDS!" backwards)
  Key[4..7] = Last 4 bytes of the 6-byte BSSID from Beacon header
When receiving the Nintendo Zone beacon, DSi Launcher will add some animation to the Nintendo Zone icon. The Nintendo Zone tool will occassionally show a green signal strength symbol in upper right (if the SSID and WEP password match for your Access Point). Moreover, the tool should then connect to the server (supposedly using the ApNum entry), but that step seems to fail, probably because Nintendo has shut down the Zone servers someday in 2016-2018.
ApNum:
"Authentication parameter, required for connecting to the server. server uses this to determine which third-party content to link to on the index page. First ASCII number char in this param is region, this is also used to determine which server to connect to. Regions: 0=JP, 1=USA, 2/3=EUR, 4=KOR, 5=China, ?=TWN." Uh, unknown if those "digits" are letters or digits? There is a screenshot showing "1BBUSMN000" for Bestbuy. The 3DS has a hotspot.conf file with numeric ApNums, eg. "2013300000". Unknown if the region digit is required to match the console region.


DS Wifi Nintendo DS Download Play

DS Download Play allows to download small games from other NDS/DSi consoles. This is also known as Wireless Multiboot (WMB), or Single Gamecart Multiplay.

Before downloading: Receive beacons, display Icon/Title, prompt user whether to download that title, and, if so, connect to host (via authentication and association requests). See previous chapter for details.

Download process (after authentication/association)
  Host sends NameRequests, client(s) send UsernameReply
  Host sends RSA frame, client(s) send RsaReply
  Host sends Data (Header/ARM9/ARM7 binaries), client(s) send DataReply
  Host sends Data, if it's the last packet, client(s) send GotAllReply
  Host sends Final message, client(s) send FinalReply
  Client(s) send Deauthentication with Reason=3 and jump to entrypoints
The whole transfer is done at 2MBit/s, without any WEP/WPA encryption, and without ARM9 Secure Area encryption.

CMD DATA, Host-to-client packets (with DA = 03:09:BF:00:00:00)
Sent via 4808090h/W_TXBUF_CMD (multiplayer master)
  00h 2   Value for W_CMD_REPLYTIME (0106h)
  02h 2   Slave Flags, bit1..15 for slave 1..15 (1=connected) (eg. 0002h)
  04h 1   Size in halfwords of Command+Data (ie. [06h..end, excluding footer])
  05h 1   Flags   (11h=Normal, 01h=Footerless/Can be ignored, 00h=Deauth'ed?)
  06h 1   Command (01h=NameRequest, 03h=RSA, 04h=DataPacket, 05h=Done)
 For Command 00h (Dummy, NameDone/RsaDone/DataDone):                 ;\
  07h 5   Unused (zerofilled)                                        ;
 For Command 01h (NameRequest):                                      ;
  07h 5   Unused (zerofilled)                                        ;
 For Command 02h (Error: Wrong Game Serial):                         ;
  07h 5   Unused (zerofilled)                                        ; Data
 For Command 03h (RSA):                                              ;
  07h E4h RSA Signature Frame (see below)                            ;
  EBh 5   Unused (zerofilled)                                        ;
 For Command 04h (Data Packet):                                      ;
  07h 2   Unknown (zero)                                             ;
  09h 2   Packet Number (0=Header, 1..N=ARM9, N+1..Last=ARM7)        ;
  0Bh ..  Data (1F8h bytes, or less for Header, or end of ARM7/ARM9) ;
  xxh 1   Unused (zero)                                              ;
 For Command 05h (Final):                                            ;
  07h 5   Unused (garbage, same as last data command)                ;
 For Command 06h (Unknown): ;normally not used, but ds download play ;
  07h ..  Unknown           ;supports cmd 02h,03h,06h after username ;/
 Extra Footer (usually present, unless Flags [05h].bit4=0):          ;\
  xxh 2   Slave Flags, again? (0002h)  ;or 0000h ?                   ; Footer
  Note: The footer is usually present in most or all packets         ;
  (Super Mario 64 DS has some dummy packets without footer)          ;/
The packet number (and info from RSA frame) allow to compute the packet destination address. That max packet size is 1F8h bytes (at least so when using default Tag=DDh [14h]=1FEh).
The transfer is usually done with increasing packet numbers. However, there may be lost or duplicated packets. And the uploader tends to do weird things like starting with packet 0001h instead of 0000h, and once or then inserting packet 0000h (or other unrequested packets) during transfer.
Essentially, the downloader should maintain a flag array to know which packets were already received, and which ones still need to be requested in Data Replys. The uploader should ignore slightly outdated replies (keep sending the next packet if the wanted packet number is same as most recently transferred one).

REPLY, Client to Host Replies (with DA = 03:09:BF:00:00:10)
Sent via 4808094h/W_TXBUF_REPLY1 (multiplayer slave).
  00h 1  Size in halfwords (of [02h..end])?  (00h=Short, or 04h=Normal)
  01h 1  Flags?                              (00h, 01h, 81h, or 80h)
 Short Dummy Reply:
  02h -  Nothing (can occur once or then during username or data transfer)
 Normal Dummy Reply:
  02h 1  Reply Type (00h=Dummy) (can occur before username transfer)
  03h 7  Unused (zerofilled)
 Username Reply:
  02h 1  Reply Type (07h=Username)
  03h 1  Username snippet number (00h..04h=Snippet #0..4)
  04h 6  Snippet 0: Game ID (0040xxxxh), Favorite Color, UsernameLength(0-10)
  04h 6  Snippet 1: Username Char[0,1,2]
  04h 6  Snippet 2: Username Char[3,4,5]
  04h 6  Snippet 3: Username Char[6,7,8]
  04h 6  Snippet 4: Username Char[9], 0001h/0002h, C500h/0000h
  (There can be more (smaller) snippets if Tag=DDh [16h] is smaller than 8)
 Rsa Reply:
  02h 1  Reply Type (08h=RsaReply)
  03h 7  Unused (garbage, usually same as Username Snippet #2)
 Data Reply:
  02h 1  Reply Type (09h=DataReply)
  03h 2  Next wanted packet number (smallest missing packet number)
  05h 2  Number of different packets received (0001h..Total-1)
  07h 3  Unused (zerofilled)
 Got All Reply:
  02h 1  Reply Type (0Ah=GotAllReply, no further packets needed)
  03h 7  Garbage (old values from last Data Reply)
 Final Reply:
  02h 1  Reply Type (0Bh=FinalReply, confirms the FinalCommand)
  03h 7  Garbage (old values from last Data Reply)
Ideally, software should update the reply immediately after receiving the command (within a few hundred clock cycles) (when failing to write W_TXBUF_REPLY1 in time, the hardware does reportedly generate a completely Empty Dummy Reply with 0-byte data, and FC=0158h).

CMD ACK, Host to client acknowledgements (with DA = 03:09:BF:00:00:03)
Generated automatically by hardware (after sending W_TXBUF_CMD and after receiving Replies) (DA seems to be fully hardcoded in hardware, the other IEEE header fields might be derived from preceeding RX/TX packets and/or from hardware registers).
  00h 2  Unknown/random? (eg. 0046h or 001Bh)
  02h 2  Error Flags (bit1-15=No reply from Slave 1-15, eg. when AID_LOW=0)
Note: The SEQNO value in the IEEE header of CMD ACK must be reportedly one higher than in the corresponding CMD packet (the NDS hardware is doing that automatically, but one may need to take care of it on non-NDS hardware).

RSA signature frame payload (Command 03h)
"Notably: the RSA frame itself is not included as part of the data being signed, bringing up various security issues and making Nintendo's firmware engineers look amateurish at best."
  00h 4   ARM9 Entrypoint             (usually 20008xxh)
  04h 4   ARM7 Entrypoint             (usually 2380000h) (or WRAM?)
  08h 4   Zerofilled
  0Ch 4   Header Destination (temp)   (usually 27FFE00h)
  10h 4   Header Destination (actual) (usually 27FFE00h)
  14h 4   Header Size (160h)
  18h 4   Zerofilled
  1Ch 4   ARM9 Destination (temp)     (usually 2000000h)
  20h 4   ARM9 Destination (actual)   (usually 2000000h)
  24h 4   ARM9 Size
  28h 4   Zerofilled
  2Ch 4   ARM7 Destination (temp)     (usually 22C0000h in Main RAM)
  30h 4   ARM7 Destination (actual)   (usually 2380000h) (or WRAM?)
  34h 4   ARM7 Size
  38h 4   Unknown (00000001h)
  3Ch 4   Signature ID   (61h,63h,01h,00h) (aka "ac", or backwards "ca") ;\
  40h 80h Signature RSA  (RSA signature in OpenPGP SHA1 format)          ;
  C0h 4   Signature Seed (same as value used to create RSA signature)    ;/
                         (Nanostray:22AA9FC2h, Hedge:24272349h)
                         (Eragon:2512EE7Ah, TableHockey:02704DF6h)
  C4h 20h Zerofilled (stored together with above in E4h-byte array)
The temp/actual destination addresses are usually identical, except for ARM7 which is loaded to a separate temp address in Main RAM (needed there for computing its SHA1 on ARM9 side).
The RSA signature is as so: First compute SHA1's on Header and ARM9 and ARM7 areas, and store them in a 40h-byte array:
  00h 14h SHA1 on Header
  14h 14h SHA1 on ARM9 bootcode
  28h 14h SHA1 on ARM7 bootcode
  3Ch 4   Signature Seed (same as the four bytes from [C0h])
Then compute a SHA1 on that 40h-byte array, that SHA1 value is then used in the RSA signature (in OpenPGP SHA1 format, ie. same as SWI 23h in DSi BIOS). The RSA private key is unknown, the RSA public key (9Eh,C1h,CCh,C0h,...) can be found in the NDS Firmware and in the DSi's DS Download Play utility.
Unknown if the 4-byte Seed value is having any special meaning (eg. it might be some checksum, or it might be just some random, timestamp, or dummy expiredate?).
The 4+80h+4 signature bytes at [3Ch..C3h] are conventionally stored at the "end" of the binary, ie. at the offset specified in cartheader[080h].

160h-byte Header
Some Download Play titles have faulty header entries (eg. Table Hockey Tech Demo, with nonsense Icon offset etc). In such cases, dumps are conventionally having a manually repaired header & an extra copy of the original header:
  0000h 160h  Repaired Header (address/size/entrypoint for ARM9,ARM7,Icon,RSA)
  0160h A0h   Zerofilled
  0200h 10h   ID "DS DOWNLOAD PLAY" (8bit characters)
  0210h 10h   ID "----------------" (8bit characters)
  0220h 160h  Original Header (to be uploaded for RSA check)
  0380h 10h   ID "----------------" (8bit characters)
  0390h 10h   ID "Nintendo"         (16bit characters)
  03A0h 10h   ID Zerofilled
  03B0h 10h   ID "----------------" (8bit characters)
  03C0h ..    Zerofilled
The 160h-byte Header itself is about same as in ROM-images. The Icon/Title entry contains the information that is broadcast in Beacons. The Total Size entry points to the 88h-byte RSA Signature. The File/Overlay entries contain unused/dummy values.

Beacons
Beacons should be kept sent during transfer, however, the DS Download tool throws a Deauth message when receiving more than 15 beacons with data traffic (ie. one must pause uploading at least each 16th beacon).
Also, the download should try to sync itself to the LCD Video Sync value in the Beacon (supposedly interpreted relative to the IEEE Beacon Timestamp) (with small uploads, there's probably not enough time to complete the synchronization, so the uploaded executable may still have to finish the synchronization by itself).

Entrypoint/Memory
The Entrypoints are supposedly taken from the RSA frame (not from the 160h-byte header)? There is some error checking on the RSA frame addresses (eg. ARM7 area must exist and must apparently point to RAM or WRAM). Additionally, there is some special info in RAM:
  27FFC40h 2   Boot Indicator (2=Booted from DS Download Play via Wifi)
  27FFC42h 2   Beacon Size (0060h, based on Tag=DDh size: "(88h-08h+41h)/2")
  27FFC44h 2   Looks like RSSI Signal Strength AND FEh (eg. 12h=Low, 82h=High)
  27FFC46h 6   BSSID (master's MAC address)
  27FFC4Ch 2   SSID Size? (0020h)
  27FFC4Eh 4   SSID Game Serial ID (0040xxxxh)
  27FFC52h 2   SSID Random Stream ID (xxxxh)
  27FFC54h 1Ah SSID Padding? (zerofilled)
  27FFC6Eh 2   Beacon Capabilities (0021h)
  27FFC70h 2   Beacon Rates (bit0/1 = 1/2Mbit/s) (0003h)
  27FFC72h 2   Beacon Rates (same as above)      (0003h)
  27FFC74h 2   Beacon Interval (00Cxh..00Dxh)
  27FFC76h 2   Beacon TIM ListenInt (0002h)
  27FFC78h 2   Beacon Channel (1, 7, or 13)
  27FFC7Ah 04h Unknown (zerofilled)
  27FFC7Eh 2   Unused? (zero) (not part of 3Ch-bytes at 27FFC42h)
Multiplayer games can use that info for communicating with each other after the upload. The player number (needed for more than 2 players) doesn't seem to be included in that structure, it might be still in W_AID_LOW though?

List of DS Download Play Games
Games with DS Download Play Support (single-cart multiplayer):
  Game ID   Players  Title
  00400136h 2        Over the Hedge (download contains a 2D minigame)
  00400052h 2        Nanostray
  00400011h 1-4      Super Mario 64 DS
  etc. (unknown if/which games support more than 4 players)
Demos available from DS Download Stations (or was that pre-Download Station?):
  Eragon
  Lara Croft Tomb Raider Legend
  Magnetica
  Metroid Prime Hunters Demo
  Submarine Tech Demo
  (and many trailers with non-playable movie clips)
Download Station (in shops):
  Allows to download some bootmenu, offering downloading demos/trailers?

Exploits (not sure what they do)
  WifiMe - downloader patch for NDS firmware without RSA check?
  Unlaunch.dsi v2.1 - can patch RSA check in DSi's DS Download Play
  HaxxStation - uploader patch for Download Station to upload homebrew/hacks?
Unknown if unchecked entries in RSA frame can be also used to crash/boot?
Unknown if public RSA key can be found in gigaleak or so?

NDS/DSi Games with DS Download Play support
 100 Classic Books
 Absolute Chess (Nintendo DSiWare)
 Absolute Reversi (Nintendo DSiWare)
 Advance Wars: Dual Strike
 Age Of Empires: Mythologies
 America's Test Kitchen: Let's Get Cooking
 Animaniacs: Lights, Camera, Action!
 Arkanoid DS
 Art Academy
 Atari Greatest Hits Volume 1
 Atari Greatest Hits Volume 2
 Avatar, The Last Airbender: Into The Inferno
 Bakugan: Defenders Of The Core
 Battle Of Giants: Dinosaurs
 Battle Of Giants: Dragons
 Battle Of Giants: Mutant Insects
 Beyblade: Metal Fusion
 Big Bang Mini
 Big Brain Academy
 Bleach: Blade Of Fate, The
 Bleach: Dark Souls
 Boing! Docomodake DS
 Bomberman
 Bomberman Land Touch!
 Bomberman Land Touch! 2
 Boogie
 Bookworm (retail version)
 Brain Age: Train Your Brain In Minutes A Day!
 Brain Age 2: More Training In Minutes A Day!
 Brain Assist
 Brain Voyage
 Bratz: Forever Diamondz
 Break 'Em All
 Burnout Legends
 Bust-A-Move DS
 Call Of Duty 4: Modern Warfare
 Candace Kane's Candy Factory
 Carnival Games
 Cars 2
 Cars Mater-National
 Cars Race-O-Rama
 Cartoon Network Racing
 Chameleon
 Cheetah Girls, The: Passport To Stardom
 Chessmaster: The Art Of Learning
 Classic Word Games
 Club Penguin: Elite Penguin Force
 Club Penguin: Elite Penguin Force - Herbert's Revenge
 Clubhouse Games
 Clubhouse Games Express: Card Classics (Nintendo DSiWare)
 Clubhouse Games Express: Family Favorites (Nintendo DSiWare)
 Clubhouse Games Express: Strategy Pack (Nintendo DSiWare)
 Cookie & Cream
 Cooking Mama
 Cooking Mama 2: Dinner With Friends
 Cooking Mama 3: Shop & Chop
 C.O.R.E.
 Corvette Evolution GT
 Cosmo Fighters (Nintendo DSiWare)
 Crafting Mama
 Crash Boom Bang!
 Custom Robo Arena
 Dairojo! Samurai Defenders (Nintendo DSiWare)
 Deca Sports DS
 Diary Girl
 Diddy Kong Racing DS
 Dino Master: Dig, Discover, Duel
 DiRT 2
 Disney Fairies: Tinker Bell
 DK Jungle Climber
 Dokapon Journey
 Draglade
 Dragon Ball Z: Harukanaru Densetsu
 Dragon Booster
 Dragon Quest Heroes: Rocket Slime
 Dreamer: Pop Star
 Dropcast
 Eco-Creatures: Save The Forrest
 Elite Beat Agents
 Everyday Soccer (Nintendo DSiWare)
 Ferrari Challenge: Trofeo Pirelli
 FIFA Soccer 06
 FIFA Soccer 08
 FIFA Soccer 09
 FIFA Soccer 10
 FIFA Street 3
 FIFA World Cup 06
 Final Fantasy Fables: Chocobo Tales
 Flash Focus: Vision Training In Minutes A Day
 Foto Frenzy
 Freedom Wings
 Fritz Chess
 Frogger: Helmet Chaos
 Gardening Mama
 Gauntlet
 Geometry Wars: Galaxies
 Godzilla: Unleashed Double Smash
 Golden Compass, The
 GoldenEye: Rogue Agent
 Grease
 GRID
 Gunpey DS
 Harry Potter And The Deathly Hallows, Part 1
 Harry Potter And The Deathly Hallows, Part 2
 Harry Potter And The Order Of The Phoenix
 Harvest Moon: Frantic Farming
 Hasbro Family Game Night
 Hearts Spades Euchre (Nintendo DSiWare)
 Heavy Armor Brigade
 High School Musical 2: Work This Out!
 Homie Rollerz
 Igor: The Game
 Imagine Babysitters
 Imagine Ballet Star
 Imagine Ice Champions
 Imagine Rock Star
 Imagine Teacher
 Intellivision Lives!
 Ivy The Kiwi? (retail version)
 Jeopardy
 Jewel Quest Expeditions
 Jumble Madness
 Kirby: Squeak Squad
 Kirby Super Star Ultra
 Konami Classics Series: Arcade Hits
 Labyrinth
 Learn Science
 Left Brain Right Brain
 Left Brain Right Brain 2
 Legend Of Zelda, The: Phantom Hourglass
 Legend Of Zelda, The: Spirit Tracks
 Legendary Starfy, The
 LEGO Star Wars II: The Original Trilogy
 Little League World Series Baseball 2009
 L.O.L.
 Lost In Blue 2
 Lost In Blue 3
 Lunar Knights
 Madagascar
 Madagascar: Escape 2 Africa
 Madden NFL 08
 Madden NFL 09
 Magnetica
 Mario & Sonic At The Olympic Games
 Mario & Sonic At The Olympic Winter Games
 Mario Hoops 3-On-3
 Mario Kart DS
 Mario Party DS
 Mario Vs. Donkey Kong 2: March Of The Minis
 Marvel Super Hero Squad
 Math Play
 Mega Man ZX Advent
 Meteos
 Meteos: Disney Magic
 Metroid Prime Hunters
 Metroid Prime Pinball
 Might & Magic: Clash Of Heroes
 Mini Ninjas
 MLB Power Pros 2008
 Monopoly/Boggle/Yahtzee/Battleship
 Monster Band
 Monster Bomber
 Monster Racers
 Monsters Vs Aliens
 MX Vs ATV Reflex
 My DoItAll
 My Frogger Toy Trials
 My Word Coach
 MySims
 MySims Agents
 MySims Kingdom
 MySims Party
 MySims Racing
 MySims SkyHeroes
 Nacho Libre
 Namco Museum DS
 Nanostray
 Nanostray 2
 Need For Speed Carbon: Own The City
 Need For Speed: Nitro
 Need For Speed: ProStreet
 Need For Speed: Undercover
 Nervous Brickdown
 NEVES
 New Carnival Games
 New International Track & Field
 New Super Mario Bros.
 New York Times Crosswords, The
 Nicktoons: Attack Of The ToyBots
 Nicktoons: Battle For Volcano Island
 Ninjatown
 Over The Hedge
 PDC World Championship Darts
 Peggle Dual Shot
 Personal Trainer: Math
 Petz Dogz 2
 Petz Dogz Fashion
 Phineas And Ferb Ride Again
 Phineas And Ferb: Across The 2nd Dimension
 Picross 3D
 Picross DS
 PICTOIMAGE
 Ping Pals
 Pirates: Duels On The High Seas
 Pirates Of The Caribbean: At World's End
 Planet 51: The Game
 Planet Puzzle League
 Plants Vs. Zombies
 Playmobil Knights
 Playmobil Pirates
 Pogo Island
 Point Blank DS
 Pokemon Mystery Dungeon: Explorers Of Sky
 Pokemon Trozei!
 Polar Bowler
 Polarium
 Pony Friends
 Pony Friends: Mini-Breeds Edition
 Pony Friends 2
 Pop Island (Nintendo DSiWare)
 Pop Island - Paperfield (Nintendo DSiWare)
 Power Play Pool
 Prey The Stars
 Princess And The Frog, The
 Princess In Love
 Prism: Light The Way
 Pro Evolution Soccer 2008
 Professional Fisherman's Tour: Northern Hemisphere
 Puchi Puchi Virus
 Puyo POP FEVER
 Puzzle De Harvest Moon
 Quest Trio, The
 QuickSpot
 Rabbids Go Home
 Race Driver: Create & Race
 Rafa Nadal Tennis
 Ratatouille
 Rayman Raving Rabbids 2
 Rayman Raving Rabbids TV Party
 Ridge Racer DS
 Ringling Bros. and Barnum & Bailey Circus
 Rio
 Rock Revolution
 Rollin' Rascals
 RooGoo Attack!
 Rub Rabbits
 Rubik's World
 SBK: Snowboard Kids
 Scrabble
 Sega Casino
 Sega Superstars Tennis
 Shaun White Snowboarding
 Shining Stars: Super Starcade
 Shrek The Third
 Simpsons Game, The
 Skate It
 Solitaire Overload
 Sonic Colors
 Sonic Rush
 Sonic Rush Adventure
 Space Bust-A-Move
 Space Invaders Extreme
 Space Invaders Extreme 2
 SpongeBob's Boating Bash
 Squishy Tank
 Star Fox Command
 Stitch Jam
 Style Lab: Makeover
 Super Black Bass Fishing
 Super Dodgeball Brawlers
 Super Mario 64 DS
 Super Monkey Ball: Touch & Roll
 Super Speed Machines
 Superman Returns: The Videogame
 Suzuki Super-Bikes II: Riding Challenge
 Tamagotchi Connection: Corner Shop
 Tamagotchi Connection: Corner Shop 2
 Tamagotchi Connection: Corner Shop 3
 Tank Beat
 Tetris DS
 Tetris Party Deluxe
 ThinkSmart Kids 8+
 Thrillville: Off The Rails
 Tiger Woods PGA Tour 08
 Tinker Bell And The Great Fairy Rescue
 Toon-Doku
 Top Gun
 Totally Spies! 2: Undercover
 Touch Darts
 Touchmaster 2
 Touchmaster 3
 Touchmaster: Connect
 TrackMania DS
 TrackMania Turbo
 Trioncube
 Tropix DS
 True Swing Golf
 Ultimate Mortal Kombat
 Ultimate Puzzle Games: Sudoku Edition
 USA Today Puzzle Craze
 Warhammer 40,000: Squad Command
 Whac-A-Mole
 Wild West, The
 Windy X Windham
 Winning Eleven: Pro Evolution Soccer 2007
 WireWay
 Wizards Of Waverly Place
 Wordfish
 WordJong
 World Championship Games
 World Championship Poker: Deluxe Series
 World Cup Of Pool
 World Of Zoo
 Worms: Open Warfare
 Worms: Open Warfare 2
 Xiaolin Showdown
 Yoshi Touch & Go
 Zendoku
 Zoo Keeper


DS Wifi IEEE802.11 Frames

MAC Frame Format
  10..30 bytes    MAC Header
  0..2312 bytes   Frame Body (in practice, network MTU is circa 1500 bytes max)
  4 bytes         Frame Check Sequence (FCS) (aka CRC32 on Header+Body)

MAC Header (10..30 bytes)
  Size Content
  2    Frame Control Field (FC)
  2    Duration/ID
  6    Address 1
 (6)   Address 2 (if any)
 (6)   Address 3 (if any)
 (2)   Sequence Control (if any)
 (6)   Address 4 (if any)

Frame Control Field (FC)
  Bit  Expl.
  0-1  Protocol Version   (0=Current, 1..3=Reserved)
  2-3  Type               (0=Managment, 1=Control, 2=Data, 3=Reserved)
  4-7  Subtype            (see next chapters) (meaning depends on above Type)
  8    To Distribution System (ToDS)
  9    From Distribution System (FromDS)
  10   More Fragments
  11   Retry
  12   Power Managment    (0=Active, 1=STA will enter Power-Safe mode after..)
  13   More Data
  14   Wired Equivalent Privacy (WEP) Encryption (0=No, 1=Yes)
  15   Order
Bit 8-11 and Bit 13-15 are always 0 in Control Frames.

Duration/ID Field (16bit)
  0000h..7FFFh  Duration (0-32767)
  8000h         Fixed value within frames transmitted during the CFP
                (CFP=Contention Free Period)
  8001h..BFFFh  Reserved
  C000h         Reserved
  C001h..C7D7h  Association ID (AID) (1..2007) in PS-Poll frames
  C7D8h..FFFFh  Reserved

48bit MAC Addresses
MAC Addresses are 48bit (6 bytes) (Bit0 is the LSB of the 1st byte),
  0     Group Flag (0=Individual Address, 1=Group Address)
  1     Local Flag (0=Universally Administered Address, 1=Locally Administered)
  2-23  22bit Manufacturer ID (assigned by IEEE)
  24-47 24bit Device ID (assigned by the Manufacturer)
Special NDS related Addresses:
  00 09 BF xx xx xx  NDS-Consoles (Original NDS with firmware v1-v5)
  00 16 56 xx xx xx  NDS-Consoles (Newer NDS-Lite with firmware v6 and up)
  00 23 CC xx xx xx  DSi-Consoles (Original DSi with early mainboard; nocash)
  00 24 1E xx xx xx  DSi-Consoles (Another DSi; scanlime)
  40 F4 07 xx xx xx  DSi-Consoles (with DWM-W024; nocash)
  E0 E7 51 xx xx xx  DSi-Consoles (with DWM-W024; nocash/desoldered)
  CC 9E 00 xx xx xx  DSi-Consoles (with J27H020; nocash)
  03 09 BF 00 00 00  NDS-Multiboot: host to client (main data flow)
  03 09 BF 00 00 10  NDS-Multiboot: client to host (replies)
  03 09 BF 00 00 03  NDS-Multiboot: host to client (acknowledges replies)
  FF FF FF FF FF FF  Broadcast to all stations (eg. Beacons)

Sequence Control Field
  Bit  Expl.
  0-3  Fragment Number (0=First (or only) fragment)
  4-15 Sequence Number
(increment by 1, except on retransmissions, ie. retries)

WEP Frame Body
  3 bytes     Initialization Vector (WEP IV)
  1 byte      Pad (6bit, all zero), Key ID (2bit)
  1..? bytes  Data (encrypted data)
  4 bytes     ICV (encrypted CRC32 across Data)


DS Wifi IEEE802.11 Managment Frames (Type=0)

All Managment Frames have 24-byte Frame Header, with following values:
  FC(2), Duration(2), DA(6), SA(6), BSSID(6), Sequence Control(2)
The content of the Frame Body depends on the FC's Subtype:
  Subtype                   Frame Body
  0 Association request     Capability, ListenInterval, SSID, SuppRates
  1 Association response    Capability, Status, AID, SuppRates
  2 Reassociation request   Capability, ListenInterval, CurrAP, SSID, SuppRates
  3 Reassociation response  Capability, Status, AID, SuppRates
  4 Probe request           SSID, SuppRates
  5 Probe response          Same as for Beacon (but without TIM)
  8 Beacon                  Timestamp,BeaconInterval,Capability,SSID,SuppRates,
                             FH Parameter Set (when using Frequency Hopping),
                             DS Parameter Set (when using Direct Sequence),
                             CF Parameter Set (when supporting PCF),
                             IBSS Parameter Set (when in an IBSS),
                             TIM (when generated by AP)
  9 Announcement traffic indication message (ATIM)    Body is "null" (=none?)
  A Disassociation          ReasonCode
  B Authentication          AuthAlgorithm, AuthSequence, Status, ChallengeText
  C Deauthentication        ReasonCode
Subtypes 6..7, and D..F are Reserved.

The separate components of the Frame Body are...
64bit Parameters (8 bytes)
  Timestamp: value of the TSFTIMER (see 11.1) of a frame's source. Uh?
48bit Parameters (6 bytes)
  Current AP (Access Point): MAC Address of AP with which station is associated
16bit Parameters (2 bytes)
  Capability Information (see list below)
  Status code (see list below) (0000h=Successful, other=Error code)
  Reason code (see list below) (Error code)
  Association ID (AID) (C000h+1..2007)
  Authentication Algorithm (0=Open System, 1=Shared Key, 2..FFFFh=Reserved)
  Authentication Transaction Sequence Number (Open System:1-2, Shared Key:1-4)
  Beacon Interval (Time between beacons, N*1024 us)
  Listen Interval (see note below)
Information elements (1byte ID, 1byte LEN, followed by LEN byte(s) data)
  ID      LEN      Expl.
  00h     00h-20h  SSID Service Set Identity (LEN=0 for broadcast SSID) (ASCII)
  01h     01h-08h  Supported rates; each (nn AND 7Fh)*500kbit/s, bit7=flag
  02h     05h      FH (Frequency Hopping) Parameter Set
                     DwellTime(16bit), HopSet, HopPattern, HopIndex
  03h     01h      DS (Distribution System) Parameter Set; Channel (01h..0Eh)
  04h     06h      CF Parameter Set; Count, Period, MaxDuration, RemainDuration
  05h     04h..FEh TIM; Count,Period,Control, 1-251 bytes PartialVirtualBitmap
  06h     02h      IBSS Parameter Set; ATIM Window length (16bit)
  07h-0Fh -        Reserved
 (07h)    ..       802.11d Country
 (08h)    ..       802.11d Hopping Pattern Params
 (09h)    ..       802.11d Hopping Pattern Table
 (0Ah)    ..       802.11d Request
  10h     02h..FEh Challenge text; 1-253 bytes Authentication data
                    (Used only for Shared Key sequence no 2,3)
                    (none such for Open System)
                    (none such for Shared key sequence no 1,4)
  11h-1Fh -        Reserved for challenge text extension
  20h-FFh -        Reserved
 (20h)    ..       802.11h Power Constraint
 (21h)    ..       802.11h Power Capability
 (22h)    ..       802.11h TPC Request (Transmit Power Control)
 (23h)    ..       802.11h TPC Report
 (24h)    ..       802.11h Supported Channels
 (25h)    ..       802.11h Channel Switch Announcement
 (26h)    ..       802.11h Measurement Request
 (27h)    ..       802.11h Measurement Report
 (28h)    ..       802.11h Quiet
 (29h)    ..       802.11h IBSS DFS
  2Ah     ..       802.11g ERP Information (spotted in newer beacons)
  30h     var      802.11i Reserved but used for WPA2 RSNIE <-- officially
  32h     ..       802.11g Extended Supported Rates (spotted in newer beacons)
  DDh     var      Reserved but used for WPA RSNIE  <-- vendor specific
  DDh     var      Reserved but used by Nintendo for NDS-Multiboot beacons
  2Dh     ..       Unknown (spotted in newer beacons)
  2Fh     ..       Unknown (spotted in newer beacons)
  3Dh     ..       Unknown (spotted in newer beacons)
  7Fh     ..       Unknown (spotted in newer beacons)
IDs 20h-FFh are commonly used; I've received values 2xh..3xh and DDh (from non-nintendo network routers in the neighborhood); no idea if these "Reserved" IDs are somewhere officially documented?

Capability Information
  Bit0    ESS
  Bit1    IBSS
  Bit2    CF-Pollable
  Bit3    CF-Poll Request
  Bit4    Privacy
  Bit5    Short Preamble  (IEEE802.11b only)
  Bit6    PBCC            (IEEE802.11b only)
  Bit7    Channel Agility (IEEE802.11b only)
  Bit5-7  Reserved (0) (original IEEE802.11 specs)
  Bit8-15 Reserved (0)

Listen Interval
  ... used to indicate to the AP how often an STA wakes to listen to Beacon
  management frames. The value of this parameter is the STA's Listen Interval
  parameter of the MLME-Associate. request primitive and is expressed in
  units of Beacon Interval.

Reason codes
  00h Reserved
  01h Unspecified reason
  02h Previous authentication no longer valid
  03h Deauthenticated because sending station is leaving (or has left) IBSS
       or ESS
  04h Disassociated due to inactivity
  05h Disassociated because AP is unable to handle all currently associated
       stations
  06h Class 2 frame received from nonauthenticated station
  07h Class 3 frame received from nonassociated station
  08h Disassociated because sending station is leaving (or has left) BSS
  09h Station requesting (re)association is not authenticated with responding
       station
  0Ah..FFFFh Reserved

Status codes
  00h Successful
  01h Unspecified failure
  02h..09h Reserved
  0Ah Cannot support all requested cap's in the Capability Information field
  0Bh Reassociation denied due to inability to confirm that association exists
  0Ch Association denied due to reason outside the scope of this standard
  0Dh Responding station doesn't support the specified authentication algorithm
  0Eh Received an Authentication frame with authentication transaction sequence
       number out of expected sequence
  0Fh Authentication rejected because of challenge failure
  10h Authentication rejected due to timeout waiting for next frame in sequence
  11h Association denied because AP is unable to handle additional associated
       stations
  12h Association denied due to requesting station not supporting all of the
       data rates in the BSSBasicRateSet parameter
  13h Association denied due to requesting station not supporting
       the Short Preamble option (IEEE802.11b only)
  14h Association denied due to requesting station not supporting
       the PBCC Modulation option (IEEE802.11b only)
  15h Association denied due to requesting station not supporting
       the Channel Agility option (IEEE802.11b only)
  13h-15h Reserved (original IEEE802.11 specs)
  16h..FFFFh Reserved


DS Wifi IEEE802.11 Control and Data Frames (Type=1 and 2)

Control Frames (Type=1)
All Control Frames have 10-byte or 16-byte headers, depending on the Subtype:
  Subtype                          Frame Header
  0-9 Reserved                     -   -         -      -
  A   Power Save (PS)-Poll         FC  AID       BSSID  TA
  B   Request To Send (RTS)        FC  Duration  RA     TA
  C   Clear To Send (CTS)          FC  Duration  RA     -
  D   Acknowledgment (ACK)         FC  Duration  RA     -
  E   Contention-Free (CF)-End     FC  Duration  RA     BSSID
  F   CF-End + CF-Ack              FC  Duration  RA     BSSID
Control Frames do not have a Frame Body, so the Header is directly followed by the FCS.

Data Frames (Type=2)
All Data Frames consist of the following components:
  FC, Duration/ID, Address 1, Address 2, Address 3, Sequence Control,
  Address 4 (only on From DS to DS), Frame Body, FCS.
The meaning of the 3 or 4 addresses depends on Frame Control FromDS/ToDS bits:
  Frame Control    Address 1  Address 2  Address 3  Address 4
  From STA to STA  DA         SA         BSSID      -
  From DS  to STA  DA         BSSID      SA         -
  From STA to DS   BSSID      SA         DA         -
  From DS  to DS   RA         TA         DA         SA
Frame Control Subtypes for Data Frames (Type=2) are:
  0   Data
  1   Data + CF-Ack
  2   Data + CF-Poll
  3   Data + CF-Ack + CF-Poll
  4   Null function (no data)
  5   CF-Ack (no data)
  6   CF-Poll (no data)
  7   CF-Ack + CF-Poll (no data)
  8-F Reserved
Note: The Frame Header is 24 bytes (or 30 bytes if with Address 4). The Data in Frame Body is usually starting with LLC stuff, ie. AAh,AAh,03h,00h...


DS Wifi WPA/WPA2 Handshake Messages (EAPOL)

4-Way Handshake and Group Key Handshake messages
For WPA, the Group Key Handshake occurs immediately after the 4-way Handshake (effecitively making it a 6-way handshake). For WPA2, the Group Key is contained in the 4-way Handshake, so the Group Key Handshake isn't needed.
For both WPA and WPA2, the access point may change the Group Key every once and then, and invoke a new Group Key Handshake for the new key.

EAPOL Key Frame
This is preceeded by a LLC/SNAP header (AAh,AAh,03h,00h,00h,00h,88h,8Eh), the 888Eh in last two bytes indicates that following bytes to contain an EAPOL Key Frame:
  00h  2    Version/Type (or Type/Version?) (01 03)
  02h  2    Length of [04h..end] (005Fh+LEN)                      ;BIG-ENDIAN
  04h  1    Descriptor Type (FEh=WPA, 02h=WPA2)
  05h  2    Key Information (flags, see below)                    ;BIG-ENDIAN
  07h  2    Key Length (0=None, 20h=TKIP, 10h=CCMP, 05h/0Dh=WEP)  ;BIG-ENDIAN
  09h  8    Key Replay Counter (usually 0 or 1 in first message)  ;BIG-ENDIAN
  11h  32   Key Nonce (ANonce/SNonce)
  31h  16   Key Data IV (RC4 uses IV+KEK) (not used for AES-Key-Wrap)
  41h  8    Key RSC (TSC/PN) (whatever, for GTK)               ;LITTLE-ENDIAN
  49h  8    Reserved (zerofilled)
  51h  16   Key MIC on [00h..end] (with MIC initially zerofilled)       ;HMAC
  61h  2    Key Data Length (LEN) (00 nn)                         ;BIG-ENDIAN
  63h  LEN  Key Data (can be encrypted in certain messages)

Key Information flags
  0-2   Key Descriptor Version (1=WPA/MD5/RC4, 2=WPA2/SHA1/AESkeywrap)
  3     Key Type (0=Group, 1=Pairwise)
  4-5   Reserved (0) or WPA Group Key Index (1 or 2) (zero for WPA2)
  6     Install  (0=No, 1=Yes, configure temporal key)
  7     Key Ack  (0=No, 1=Yes, AP wants a reply; with same Key Replay Counter)
  8     Key MIC  (0=No, 1=Yes, key frame contains MIC)
  9     Secure   (0=No, 1=Yes, initial key-exchange complete)
  10    Error    (0=No, 1=Yes, MIC failure and Request=1)
  11    Request  (0=No, 1=Yes, request AP to invoke a new handshake)
  12    Encrypted(0=No, 1=Yes, Key Data is encrypted; via RC4 or AESkeywrap)
  13-15 Reserved (0)

Key Data
Key Data does usually consist of element(s) in following form:
  00h 1   Element ID (for WPA: DDh=RSNIE - for WPA2: 30h=RSNIE, DDh=KDE)
  01h 1   Element Length of [02h..end]
  02h ..  Element Data (OUI's etc.)
WPA and WPA2 assign different meanings to Element ID value DDh. The 3-byte maker prefix in OUI values does also differ for WPA/WPA2. And, the meaning of the OUI's varies depending on WHERE they are used (eg. 00-0F-AC-02 could be a Cipher Suite entry, or an Authentication entry):
  EAPOL Descriptor Type values
  WPA          WPA2         Meaning
  FEh          02h          Indicates if ElementIDs and OUIs are WPA or WPA2
  EAPOL Key Information flags/values
  0089h        008Ah        Handshake #1  ;\
  0109h        010Ah        Handshake #2  ; 4-way Handshake
  01C9h        13CAh        Handshake #3  ;
  0109h(again) 030Ah        Handshake #4  ;/
  0391h/03A1h  1382h        Handshake #5  ;\Group Key Handshake
  0311h/0321h  0302h        Handshake #6  ;/
  EAPOL Key Data Element IDs
  DDh          30h          Element ID for RSNIE (Robust Network Security info)
  -            DDh          Element ID for KDE (Key Data Encapsulation)
  -            DDh          Element ID for padding (followed by 00h-bytes)
  RSNIE Prefix OUI's (WPA only):
  00-50-F2-01  -            Element Vendor OUI for RSNIE
  RSNIE Group Cipher suite selector OUI's (aka Multicast):
  00-50-F2-01  00-0F-AC-01  RSNIE Group Cipher WEP-40  (default for US/NSA)
  00-50-F2-02  00-0F-AC-02  RSNIE Group Cipher TKIP    (default for WPA)
  00-50-F2-04  00-0F-AC-04  RSNIE Group Cipher CCMP    (default for WPA2)
  00-50-F2-05  00-0F-AC-05  RSNIE Group Cipher WEP-104 (default for WEP)
  RSNIE Pairwise Cipher suite selector OUI's (aka Unicast):
  00-50-F2-00  00-0F-AC-00  RSNIE Pairwise Cipher None (WEP, Group Cipher only)
  00-50-F2-02  00-0F-AC-02  RSNIE Pairwise Cipher TKIP (default for WPA)
  00-50-F2-04  00-0F-AC-04  RSNIE Pairwise Cipher CCMP (default for WPA2)
  RSNIE Authentication AKM suite selector OUI's :
  00-50-F2-01  00-0F-AC-01  RSNIE Authentication over IEEE 802.1X (radius?)
  00-50-F2-02  00-0F-AC-02  RSNIE Authentication over PSK (default/home use)
  KDE Key Data Encapsulation OUI's (WPA2 only):
  -            00-0F-AC-01  KDE GTK         (followed by 2+N bytes)
  -            00-0F-AC-02  KDE STAKey      (followed by 2+6+N bytes)
  -            00-0F-AC-03  KDE MAC address (followed by 6 bytes)
  -            00-0F-AC-04  KDE PMKID       (followed by 16 bytes)

RSNIE (Robust Network Security Information Element)
RSNIE allows to exchange information about the desired/supported encryption methods. RSNIE is found in handshake message 2/3 (and also in Beacons). In most cases one could just ignore the RSNIE stuff (eg. if Wifi FLASH is already configured to use a specific cipher type). A special case might be networks that use a weaker Group Cipher (for older devices) combined with offering stronger Pairwise Ciphers (for devices that support them).
  WPA2 RSNIE (Robust Network Security Information Element):
  00h  1  Element ID (30h=RSNIE for WPA2)
  01h  1  Element Len of [02h..end] (usually 14h)
  02h  2  RSNIE Version 1                        (01 00)     ;WHATEVER-ENDIAN?
  04h  4  RSNIE Group Cipher Suite OUI (CCMP)    (00 0F AC 04)
  08h  2  RSNIE Pairwise Cipher Suite Count (1)  (01 00)      ;LITTLE-ENDIAN
  0Ah  4  RSNIE Pairwise Cipher Suite OUI (CCMP) (00 0F AC 04)
  0Eh  2  RSNIE Authentication Count (1)         (01 00)      ;LITTLE-ENDIAN
  10h  4  RSNIE Authentication OUI (PSK)         (00 0F AC 02)
  14h  2  RSNIE Capabilities                     (00 00)      ;LITTLE-ENDIAN?
  16h (2) RSNIE Optional PMKID Count  ;\usually none such     ;LITTLE-ENDIAN
  18h (16)RSNIE Optional PMKID's      ;/
  WPA RSNIE (Robust Network Security Information Element):
  00h  1  Element ID (DDh=Vendor/RSNIE for WPA)
  01h  1  Element Len of [02h..end] (usually 16h or 18h)
  02h  4  Element Vendor OUI for RSNIE  (00 50 F2 01)       ;<-- WPA only
  06h  2  RSNIE Version value? (1)      (01 00)              ;WHATEVER-ENDIAN?
  08h  4  RSNIE Mcast OUI (TKIP)        (00 50 F2 02)
  0Ch  2  RSNIE Ucast Count (1)         (01 00)               ;LITTLE-ENDIAN
  0Eh  4  RSNIE Ucast OUI (TKIP)        (00 50 F2 02)
  12h  2  RSNIE Auth AKM Count (1)      (01 00)               ;LITTLE-ENDIAN
  14h  4  RSNIE Auth AKM OUI (PSK)      (00 50 F2 02)
  18h (2) RSNIE Capabilities maybe?     (00 00)               ;LITTLE-ENDIAN?
  RSN Capabilities flags (usually 0000h) (also spotted: 0C 00):
  0   RSN Pre-Auth capabilities
  1   RSN No Pairwise capabilities
  2-3 RSN PTKSA Replay Counters (0..3 = 1,2,4,16 replay counters)
  4-5 RSN GTKSA Replay Counters (0..3 = 1,2,4,16 replay counters)
  6   Managment Frame Protection Required
  7   Managment Frame Protection Capable
  8   Joint Multi-band RSNA
  9   PeerKey Enabled
  10  SPP A-MSDU Capable
  11  SPP A-MSDU Required
  12  PBAC
  13  Ext Key ID for Unicast
  14-15 Reserved (0)

KDE Key Data Encapsulation (or raw data for WPA)
KDE (or WPA's raw data) is mainly useful for transferring the GTK group key. Note that Key Data in WPA2 message 3 contains both RSNIE and KDE GTK (and KDE padding). Whilst the raw data in WPA cannot be mixed RSNIE.
  WPA2 KDE GTK (Key Data Encapsulation for Group Key, in encrypted Key Data):
  00h  1   Element ID (DDh=KDE for WPA2)
  01h  1   Element Len (16h)
  02h  4   KDE OUI GTK (00-0F-AC-01) (occurs in message 3/5)
  06h  1   KDE GTK Key ID (01h or 02h)      ;bit2: Tx ?
  07h  1   KDE GTK Reserved (00h)
  08h  16  KDE GTK Key GTK (for Key ID from above byte [06h])
  WPA2 KDE PKMID (Key Data Encapsulation for PKMID) (optional, not needed):
  00h  1   Element ID (DDh=KDE for WPA2)
  01h  1   Element Len (14h)
  02h  4   KDE OUI PMKID (00-0F-AC-04) (optionally occurs in message 1)
  06h  16  KDE PMKID (useless checksum on PMK, sometimes exposed in message 1)
  WPA2 KDE Padding (for padding Key Data to Nx8 bytes for AES-Key-wrap):
  00h  1   Element ID (DDh=KDE for WPA2)
  01h  0-6 Padding (00h) (aka Element Len=00h)
  WPA GTK (raw Group Key; without Element ID or KDE-style encapsulation):
  00h  16  Key GTK (for Key ID from Key Information bit4-5) (in message 5)


DS Wifi WPA/WPA2 Keys and MICs

Summary of WPA/WPA2 Keys
  PSK  Preshared Key (based on password and SSID)
  PMK  Pairwise Master Key (same as PSK)
  PTK  Pairwise Transient Key (based on PMK, AA, SPA, ANonce, SNonce)
  KCK  EAPOL Key Confirmation Key (PTK.bit0..127)    ;for handshake MIC's
  KEK  EAPOL Key Encryption Key   (PTK.bit128..255)  ;for handshake Key Data
  TK   Temporal Key (TKIP:PTK.bit256..511, CCMP:PTK.bit256..383)
  GMK  Group Master Key (don't care, used only internally by the access point)
  GTK  Group Transient Key (for multicast/broadcast) (based on GMK, AA, GNonce)

Summary of WPA/WPA2 Seeds
  password  ASCII password for the Wifi network
  SSID      ASCII name of access point
  AA        MAC address of access point (BSSID)
  SPA       MAC address of DSi console
  Anonce    Random number from access point (handshake message #1 and #3)
  Snonce    Random number from console      (handshake message #2)
  Gnonce    Random number internally used by access point (don't care)

Summary of WPA/WPA2 Checksums
  MIC       Message Integrity Code, checksum on EAPOL messages
  PMKID     PMK ID, checksum on PMK and AA, SPA (optional, don't care)

PRF(key,keylen, src,srclen, dst,dstlen, numrounds) ;Pseudo-Random Function
  for i=0 to (dstlen-1)/14
    call SHA1HMAC(src,srclen, key,keylen, tmpdst)
    tmpsum[0..13] = tmpdst[0..13]
    for j=1 to numrounds-1                        ;only if numrounds>1
      tmpsrc[0..13] = tmpdst[0..13], tmpsrclen=14
      call SHA1HMAC(tmpsrc,tmpsrclen, key,keylen, tmpdst)
      tmpsum[0..13] = tmpsum[0..13] XOR tmpdst[0..13]
    next j
    src[srclen-1] = src[srclen-1] + 01h           ;increase last byte of src
    len=min(14,(dstlen-i*14))
    dst[i*14+(0..(len-1))] = tmpsum[0..(len-1)]
  next i
  src[srclen-1] = src[srclen-1] - (dstlen+13)/14  ;undo increments, if desired
Note: This is using SHA1HMAC for both WPA and WPA2 (unlike the MIC, which is computed via MD5HMAC for WPA, and SHA1HMAC for WPA2).

PSK (Preshared Key) aka PMK (Pairwise Master Key)
  key = password,                      keylen = len(password)  ;ASCII string
  src = ssid + bytes(00h,00h,00h,01h), srclen = len(ssid)+4    ;ASCII string
  dst = PSK,                           dstlen = 32, numrounds=4096
  call PRF(key,keylen, src,srclen, dst,dstlen, numrounds)
  PMK=PSK
Computing the PSK/PMK requires 2x4096 SHA1HMAC calculations, which can be quite slow. The speed could be doubled by pre-computing the SHA1 states for "key XOR 36h's" and "key XOR 5Ch's". And, the PSK/PMK needs to be calculated only when changing the password/ssid (the DSi stores the PSK in Wifi-FLASH).

PTK (Pairwise Transient Key) and KCK/KEK/TK
  src[0..21]  = "Pairwise key expansion"
  src[22]     = byte(00h)
  src[23..28] = min(AA,SPA)         ;\MAC addresses (AA=BSSID, SPA=console)
  src[29..34] = max(AA,SPA)         ;/
  src[35..66] = min(ANonce,SNonce)  ;\nonces from 4-way handshake message 1+2
  src[67..98] = max(ANonce,SNonce)  ;/
  src[99]     = byte(00h)
  srclen = 22+1+6+6+32+32+1 = 100
  key=PSK, keylen=32, numrounds=1
  dst=PTK, dstlen=64  ;WPA needs dstlen=64 (WPA2 would also work with len=48)
  call PRF(key,keylen, src,srclen, dst,dstlen, numrounds)
  KCK    = PTK[00h..0Fh]   ;-for EAPOL handshake MIC checksums
  KEK    = PTK[10h..1Fh]   ;-for EAPOL handshake Key Data decryption
  TK.key = PTK[20h..2Fh]   ;-for data packets
  TX.tx  = PTK[30h..37h]   ;\needed for WPA/TKIP only (not WPA2/AES)
  TX.rx  = PTK[38h..3Fh]   ;/
  TK.keyindex = 0

GTK (Group Transient Key)
  GTK.key = GTK[00h..0Fh]  ;-for data packets
  GTX.tx  = GTK[10h..17h]  ;\needed for WPA/TKIP only (not WPA2/AES)
  GTX.rx  = GTK[18h..1Fh]  ;/
  GTK.keyindex = 1 or 2      ;WPA: from EAPOL Key Information bit4-5
  GTK.keyindex = 1 or 2      ;WPA2: from EAPOL Key Data KDE entry

MIC (Message Integrity Code)
  oldmic = EAPOL[51h..60h]
  EAPOL[51h..60h] = zerofill
  src=EAPOL, srclen=EAPOL[02h]*100h+EAPOL[03h]
  key=KCK, keylen=16
  if (EAPOL[06h] AND 07h)=1 then call MD5HMAC(src,srclen, key,keylen, dst)
  if (EAPOL[06h] AND 07h)=2 then call SHA1HMAC(src,srclen, key,keylen, dst)
  newmic = dst[0..0Fh]      ;16-byte MD5 result, or first 16byte of SHA1 result
  EAPOL[51h..60h] = newmic
  if newmic <> oldmic then error  ;when verifying MIC

PMKID (whatever ID, optional/useless, don't care)
  key=PMK, keylen=32
  src[0..7]   = "PMK Name"
  src[8..13]  = AA   ;aka MAC address of access point (BSSID)
  src[14..19] = SPA  ;aka MAC address of console
  srclen = 8+6+6 = 20
  call SHA1HMAC(src,srclen, key,keylen, dst)
  PMKID = dst[0..0Fh]   ;first 16byte of SHA1 result
Note: SHA1HMAC is used for WPA2. Unknown if WPA uses SHA1HMAC, or MD5HMAC, or if WPA does have PMKIDs at all.

Deriving GTK (done internally by access point, don't care)
  src[0..18]  = "Group key expansion"
  src[19]     = byte(00h)
  src[20..25] = AA                 ;MAC address (AA=BSSID)
  src[26..57] = GNonce             ;whaever random/timer/index
  src[58]     = byte(00h)
  srclen = 19+1+6+32+1 = 59
  key=GMK, keylen=32, numrounds=1  ;whatever random key
  dst=GTK, dstlen=32
  call PRF(key,keylen, src,srclen, dst,dstlen, numrounds)
This is the recommended way for creating the GTK, anyways, this is done internally by the access point, and everybody else doesn't need to worry about how the GTK was generated (ie. one just uses the GTK received in EAPOL messages).


DS Wifi WPA/WPA2 Encryption

Summary of Encryption/Decryption functions
  Encrypt/Decrypt WPA/WEP packets     --> RC4 (Rivest Cipher 4 aka ARC4)
  Encrypt/Decrypt WPA EAPOL key data  --> RC4 (Rivest Cipher 4 aka ARC4)
  Encrypt/Decrypt WPA2 EAPOL key data --> AES-Key-Wrap/Unwrap
  Encrypt/Decrypt WPA2 packets        --> AES-CCMP (AES-CTR-with-CBC-MAC)

RC4 (Rivest Cipher 4 aka ARC4) (WEP/WPA)
Both NDS-Wifi and DSi-Wifi have RC4 hardware support for encrypting and decrypting WEP/WPA packets, however, that's working only for full packets (not for the Key Data field in WPA EAPOL packets, so both NDS and DSi will require a RC4 software implementation for the EAPOL part).
  RC4(src,dst,len,preskip,key,keylen):
  for i=0 to FFh, sbox[i]=i, next i             ;-clear sbox
  j=0                                           ;\
  for i=0 to FFh                                ;
    j=(j+sbox[i]+key[i mod keylen]) and FFh     ; apply key
    swap(sbox[i],sbox[j]                        ;
  next i                                        ;/
  i=0, j=0
  for k=1 to preskip+len
    i=(i+1) and FFh, j=(j+sbox[i]) and FFh, swap(sbox[i],sbox[j])
    if preskip>0 then preskip=preskip-1
    else [dst]=[src] xor sbox[(sbox[i]+sbox[j]) and FFh], dst=dst+1, src=src+1
  next k
  parameters for WEP/WPA packets (done by hardware):
  key=iv(3)+password(5/13), keylen=3+5/13           ;WEP Key=WEP.IV+Password
  key=iv(3)+from PTK???,    keylen=3+???            ;WPA Key=WEP.IV+???
  src=data(n)+icv(4), srclen=n+4                    ;src, for WEP
  src=data(n)+mic(8)+icv(4), srclen=n+8+4           ;src, for WPA
  preskip=0
  parameters for WPA EAPOL key data (requires software implementation):
  key=EAPOL[31h..40h]+KEK[00h..0Fh], keylen=10h+10h ;Key = EAPOL Key IV + KEK
  src=EAPOL+63h, srclen=bigendian(EAPOL[61h])       ;src, for WPA
  preskip=100h
  parameters for 70h-byte block in Nintendo Zone beacons (by software):
  key="!SDW"+LastFourBytesOf(BSSID), keylen=8
  src=BeaconTagDDh[18h..87h], srclen=70h
  preskip=0

AES (Advanced Encryption Standard) (WPA2, DSi only)
NDS-Wifi doesn't have any AES hardware support at all, and a software implementation doesn't work because NDS-Wifi automatically applies WEP encryption (and adds/removes the WEP.IV field) when seeing the encryption flag in the frame header (and trying to disable the WEP hardware seems to cause encrypted packets not to be received at all).
DSi-Wifi has hardware support for AES-CCMP encrypted packets, however, AES-Key-Unwrap for Key Data in WPA2 EAPOL packets isn't supported by hardware, and does thus require a software implementation (the ARM7 AES hardware doesn't help because it supports AES-CTR and AES-CCM only).
  AES-Key-Wrap/Unwrap(src,dst,len,key,keylen,mode) (for WPA2 EAPOL Key Data)
  if (len and 7)<>0 then error  ;must be multiple of 8             ;-verify len
  aes_setkey(mode,key,keylen)                                      ;-init key
  if mode=ENCRYPT and [src+00h..07h]<>A6A6A6A6A6A6A6A6h then error ;-verify IV
  if mode=ENCRYPT then org=dst+8, count=1                   ;-for wrap
  if mode=DECRYPT then org=dst+len-8, count=((len-8)/8)*6   ;-for unwrap
  [dst+0..len-1] = [src+0..len-1]                  ;copy IV+DATA to dst
  [tmp+00h..07h] = [dst+00h..07h]                  ;read IV from dst+0
  for i=1 to 6
    ptr=org
    for j=1 to (len-8)/8
      [tmp+08h..0Fh] = [ptr+00h..07h]              ;read DATA from dst+index
      if mode=ENCRYPT then aes_crypt_block(ENCRYPT,tmp,tmp)  ;encrypt tmp
      [tmp+07h]=[tmp+07h] xor count                ;adjust byte[7]
      if mode=DECRYPT then aes_crypt_block(DECRYPT,tmp,tmp)  ;decrypt tmp
      [ptr+00h..07h] = [tmp+08h..0Fh]              ;writeback DATA to dst+index
      if mode=ENCRYPT then ptr=ptr+8, count=count+1
      if mode=DECRYPT then ptr=ptr-8, count=count-1
    next j
  next i
  [dst+00h..07h] = [tmp+00h..07h]                  ;writeback IV to dst+0
  if mode=DECRYPT and [dst+00h..07h]<>A6A6A6A6A6A6A6A6h then error ;-verify IV
  Parameters for Wrap/Unwrap:
  mode=ENCRYPT  ;<-- for Wrap (encrypt, used by access points)
  mode=DECRYPT  ;<-- for Unwrap (decrypt, used by clients)
  key=KEK, keylen=10h bytes (128bit)
  src=EAPOL+63h, srclen=bigendian(EAPOL[61h])
The "aes_setkey" and "aes_crypt_block" functions are same as the BIG-ENDIAN implementations described in DSi AES chapter:
DSi Advanced Encryption Standard (AES)

Access Points / Keys
Keys for different access points are stored in Wifi-FLASH. Access Point 1-3 can be configured as Open/WEP only, and Access Point 4-6 can be Open/WEP/WPA/WPA2 (these extra entries exist on DSi only, the standard NDS firmware doesn't have free memory for storing access point 4-6).
DS Firmware Wifi Internet Access Points

WPA/TKIP Encrypted Packets
  .. MAC Header         ;-Normal Header
  1  TSC1               ;\                   WEPSeed[1]=(TSC1 OR 20h) AND 7Fh
  1  WEPSeed[1]         ; WEP IV and Flags
  1  TSC0 (LSB)         ; (Flags: bit0-4=Rsvd, bit5=ExtIV, bit6-7=KeyID)
  1  Flags              ;/    (bit5: 0=No/WEP, 1=Yes/TKIP)
  1  TSC2               ;\
  1  TSC3               ; WPA Extended IV
  1  TSC4               ;
  1  TSC5 (MSB)         ;/
  .. Data               ;-Normal Data           ;\
  8  MIC                ;-WPA MIC "Michael"     ; encrypted area
  4  ICV                ;-WEP ICV               ;/
  4  FCS                ;-Normal FCS

WPA2/AES-CCMP Encrypted Packets
  .. MAC Header         ;-Normal Header
  1  PN0 (LSB)          ;\
  1  PN1                ; CCMP Header (IV and Flags)
  1  Rsvd               ; (Flags: bit0-4=Rsvd, bit5=ExtIV, bit6-7=KeyID)
  1  Flags              ;     (bit5: 0=No/WEP, 1=Yes/TKIP)
  1  PN2                ;
  1  PN3                ;
  1  PN4                ;
  1  PN5 (MSB)          ;/
  .. Data               ;-Normal Data           ;\encrypted area
  8  MIC                ;-CCMP MIC "AES MAC?"   ;/
  4  FCS                ;-Normal FCS
CCMP related: A2 (MPDU address 2), AAD, PN, Priority field of MPDU.

TKIP MIC
  6  DA
  6  SA
  1  Priority (0) (reserved for future)
  3  Zero (0) (also reserved for future)
  .. Data
  8  MIC (M0..M7) (aka L0..L3, R0..R3)

TKIP mixing
  TTAK     = Phase1 (TK, TA, TSC)
  WEP seed = Phase2 (TTAK, TK, TSC)


DS Wifi FFC ID

Wifi FCC ID
The wifi hardware has been registered by Mitsumi, Hon Hai, and Nintendo themselves:
  https://fccid.io/BKE - Nintendo
  https://fccid.io/EW4 - Mitsumi
  https://fccid.io/MCL - Hon Hai (Foxconn)
The above webpages include some unrelated stuff (like bluetooth), and some duplicate entries. The wifi/console related entries are:
  https://fccid.io/EW4-AGBWA      GBA        ;\GBA wireless adaptor
  https://fccid.io/EW4-OXYWA      GBA-Micro  ;/(not wifi/wlan compatible)
  https://fccid.io/BKENTR001      NDS (non-remove-able board)
  https://fccid.io/BKEUSG-001     NDS-Lite (old remove-able board, with MM3155)
  https://fccid.io/EW4DWMW006     NDS-Lite (new remove-able board, with MM3218)
  https://fccid.io/BKERVL036      Wii
  https://fccid.io/EW4DWMW004     Wii (mitsumi) (also W016, and maybe W014 ?)
  https://fccid.io/MCLJ27H010     Wii (foxconn) (also H003 ?)
  https://fccid.io/EW4DWMW015     DSi (old wifi board, mitsumi)
  https://fccid.io/EW4DWMW024     DSi (new wifi board, mitsumi)
  https://fccid.io/MCLJ27H020     DSi (new wifi board, foxconn)
  https://fccid.io/EW4DWMW028     3DS (mitsumi)
  https://fccid.io/MCLJ27H023     3DS (foxconn)
  https://fccid.io/MCLJ27H02301   2DS (foxconn) (also in 3DS XL)
  https://fccid.io/BKERED001      New3DS (on mainboard)
The pages include test reports, photos (including some prototypes), and most interestingly, the Mitsumi "Label location" pages are including pinout & signal names for most wifi boards.

DSi Wifi board pinout
https://fccid.io/EW4DWMW024/Label/Label-format-and-location-1137926.pdf
https://fccid.io/EW4DWMW015/Label/Label-Location-1031953.pdf
  1  MX_SD_CLK    2  GND
  3  GND          4  VDD_18
  5  SDIO_DATA0   6  VDD_18
  7  SDIO_DATA3   8  GND
  9  SDIO_DATA1   10 VDD_33
  11 SDIO_CMD     12 VDD_33
  13 SDIO_DATA2   14 GND
  15 JTAG_TDO     16 ATH_TX_H
  17 JTAG_TMS     18 SYS_RST_L
  19 GND          20 JTAG_TDI
  21 CLK32k       22 JTAG_TCK
  23 GND          24 JTAG_TRST_L
  25 NC(VDD28_TP) 26 SEL_ATH_L
  27 SPI_CS2      28 W_B      /FLASH_WP
  29 BBP_SLEEP    30 SPI_CLK
  31 RF_SLEEP     32 SPI_DO   MISO
  33 RF_SCS       34 SPI_DI   MOSI
  35 BBP_SCS      36 CCA
  37 BB_RF_SDO    38 RXPE
  39 BB_RF_SDI    40 TRDATA
  41 BB_RF_SCLK   42 GND
  43 NC(VDD18_TP) 44 TRCLK
  45 GND          46 TRRDY
  47 MCLK         48 TXPE
  49 GND          50 RESET

DS-Lite Wifi board DWM-W006 pinout
https://fccid.io/EW4DWMW006/Label/ID-label-format-and-location-706511.pdf
  1  GND          16 +3.3V
  2  TXPE         17 GND
  3  RXPE         18 RF_SCS
  4  CCA          19 BBP_SLEEP
  5  TRRDY        20 BBP_SCS
  6  GND          21 RF_SLEEP
  7  TRCLK        22 RESET
  8  TRDATA       23 GND
  9  GND          24 SPI_CLK
  10 BB_RF_SDO    25 SPI_DI   MOSI
  11 BB_RF_SDI    26 SPI_DO   MISO
  12 BB_RF_SCLK   27 W_B      /FLASH_WP
  13 GND          28 SPI_CS2
  14 MCLK         29 LD       ?
  15 GND          30 GND

Wii Wifi board
https://fccid.io/EW4DWMW004/Label/ID-Label-670426.pdf
  1  GND          12 VDD3.3
  2  SDIO_DATA_2  13 GND
  3  SDIO_DATA_1  14 GPIO_0
  4  GND          15 GND
  5  SDIO_CLK     16 SDIO_DATA_3
  6  GND          17 SDIO_DATA_0
  7  GPIO_1       18 GND
  8  GND          19 SDIO_CMD
  9  N.C.(VDD1.8) 20 GND
  10 N.C.(VDD1.8) 21 ANT_A (MAIN)
  11 VDD3.3       22 ANT_B (AUX)

3DS Wifi Board DWM-W028
https://fccid.io/EW4DWMW028/Label/ID-label-location-1272988.pdf
  1  MCLK         2  RF_CSRF
  3  GND          4  BB_CSBB
  5  RXPE         6  BB_RF_SDIN
  7  TXPE         8  BB_RF_SDOUT
  9  CCA          10 BB_RF_SCK
  11 TRDATA       12 GND
  13 TRCLK        14 BBP_SLEEP_L
  15 TRRDY        16 RF_SLEEP_L
  17 TRST_L       18 SEL_ATH_L
  19 GND          20 GND
  21 SDIO_DATA_0  22 JTAG_TDO
  23 SDIO_DATA_1  24 JTAG_TMS
  25 SDIO_DATA_2  26 JTAG_TDI
  27 SDIO_DATA_3  28 JTAG_TCK
  29 GND          30 SPI_CS2
  31 SDIO_CLK     32 W_B      /FLASH_WP
  33 GND          34 SPI_CLK
  35 SDIO_CMD     36 SPI_DO   MISO
  37 UART_TXD     38 SPI_DI   MOSI
  39 UART_RXD     40 SYS_RST_L
  41 GND          42 ATH_TX_H
  43 CLK32k       44 RESET
  45 GND          46 GND
  47 VDD_18       48 VDD_33
  49 VDD_18       50 VDD_33
Functionally same as DSi, but not pin-compatible, and with two UART pins (instead of the NC pins).

GBA-Micro: device has two channels only: 2426.248MHz and 2456.576MHz.


DS Wifi Dslink/Wifiboot Protocol

Below is the transfer protocol for nocash "wifiboot" and devkitpro "dslink".
All UDP/TCP message are using Port 17491 (4453h).

Wifiboot UDP announce/reply and listen/connect/accept
  PC sends UDP announce message (repeatedly, as broadcast)  ;\
  console does TCP listen (if it isn't already listening)   ; UDP and
  console sends UDP reply message (repeatedly, to PC)       ; listen/accept
  PC does TCP connect (upon UDP reply)                      ;
  console does TCP accept (upon TCP connect)                ;/
The announce/reply strings in UDP messages depend on the file type:
  type      NDS/DSi    3DS.firm       3DS.3dsx    3DS.gba
  announce  "dsboot"   "3dsfirmboot"  "3dsboot"   "gbaboot"
  reply     "bootds"   "bootfirm3ds"  "boot3ds"   "bootgba"
After passing through the announce/reply phase, the actual data is transferred via TCP:

Wifiboot TCP blocks for NDS/DSi
  PC sends NDS header (170h bytes)                 ;SMALLER ;\
  PC sends Info Block (90h bytes)                      ;NEW ;
  console sends 32bit response word (4 bytes)               ;
  PC sends Icon/Title (optional, if response.bit17)    ;NEW ;
  PC sends DSi header (1000h bytes, if response.bit16)      ; TCP transfer
  PC sends ARM7 bootcode                                    ;
  PC sends ARM9 bootcode                                    ;
  PC sends ARM7i bootcode (optional, if response.bit16)     ;
  PC sends ARM9i bootcode (optional, if response.bit16)     ;
  PC sends commandline 32bit length (00000000h=none)        ;
  PC sends commandline string (if any)                      ;/

Wifiboot TCP blocks for 3DS.firm
  PC sends FIRM header (200h bytes)                         ;\
  PC sends Info Block (90h bytes)                           ;
  console sends 32bit response word (4 bytes)               ;
  PC sends Icon/Title (optional, if response.bit17)         ;
  PC sends Logo       (optional, if response.bit18)         ; TCP transfer
  PC sends Banner     (optional, if response.bit19)         ;
  PC sends FIRM section 0                                   ;
  PC sends FIRM section 1                                   ;
  PC sends FIRM section 2                                   ;
  PC sends FIRM section 3                                   ;
  PC sends commandline 32bit length (0=none)                ;
  PC sends commandline string (if any)                      ;/

Wifiboot TCP blocks for 3DS.gba
  PC sends GBA Header (C0h bytes)                           ;\
  PC sends Info Block (90h bytes)                           ;
  PC sends GBA Footer (360h bytes)                          ;
  console sends 32bit response word (4 bytes)               ; TCP transfer
 ;PC sends Icon/Title (optional, if response.bit17)         ;
 ;PC sends Logo       (optional, if response.bit18)         ;
 ;PC sends Banner     (optional, if response.bit19)         ;
  PC sends GBA ROM-Image                                    ;
  PC sends commandline 32bit length (0=none)                ;
  PC sends commandline string (if any)                      ;/

Wifiboot TCP blocks for 3DS.3dsx
Not supported by wifiboot, but supported by devkitpro. The exact protocol is unknown, it seems to be similar to the above protocols, but with deflate compression (see "3dslink" source code for details).

Response word (32bit)
This did originally contain 32bit error flags, and was later changed to contain request flags in bit16 and up (nonetheless, uploaders should keep treating any unexpected or unsupported request flags as errors).
  0-x   Error flags
  16    Request DSi header and ARM7i/ARM9i blocks (DSi)
  17    Request Icon/Title (NDS/DSi/3DS)
  18    Request Logo       (3DS)
  19    Request Banner     (3DS)
  20-31 Reserved (0)
The downloader should set request flags only if it wants to receive extra data, and only if the header or info block indicates that data to be available.

Info Block (90h bytes)
This did formerly contain NDS file bytes 170h..1FFh (ie. as if the cartheader were 200h bytes in size).
  00h 8   Overall ID "BootINFO" (if other: ignore all entries below)
  08h 24  Uploader name/version, zeropadded (eg. "nocash wifiboot v2.6")
  20h 1   Time Seconds    (BCD, 00h..59h)       ;\
  21h 1   Time Minutes    (BCD, 00h..59h)       ; current time (local timezone)
  22h 1   Time Hours      (BCD, 00h..23h)       ; (for updating lost RTC time)
  23h 1   Time DayOfWeek  (0..6, 0=Monday)      ; (or all zeroes = none)
  24h 1   Time Day        (BCD, 01h..31h)       ;
  25h 1   Time Month      (BCD, 01h..12h)       ;
  26h 1   Time Year       (BCD, 00h..99h)       ;
  27h 1   Time Century    (BCD, 00h..99h)       ;/
  28h 4   Icon/Title Size (0=None, 840h/940h/A40h/23C0h=NDS/DSi, 36C0h=3DS)
  2Ch 4   Logo Size       (0=None, Other=3DS only)
  30h 4   Banner Size     (0=None, Other=3DS only)
  34h 5Ch Reserved (0)


DS Xboo

The DS Xboo cable allows to upload NDS ROM-Images (max 3.9MBytes) to the console via parallel port connection. Should be the best, simpliest, easiest, and fastest way to test code on real hardware. And, at a relative decent price of 11 cents per diode it should be by far the least expensive way. You'll have to touch classic tools (screwdrivers, knifes, saws, tweezers, and solder) which will probably scare most of you to hell.

DS XBOO Connection Schematic
  Console Pin/Names             Parallel Port Pin/Names
  RFU.9    FMW.1 D    ---|>|--- DSUB.14    CNTR.14    AutoLF
  RFU.6    FMW.2 C    ---|>|--- DSUB.1     CNTR.1     Strobe
  RFU.10   FMW.3 /RES ---|>|--- DSUB.16    CNTR.31    Init
  RFU.7    FMW.4 /S   ---|>|--- DSUB.17    CNTR.36    Select
  RFU.5    FMW.5 /W   --. SL1A  -          -          N.C.
  RFU.28   FMW.6 VCC  __| SL1B  -          -          N.C.
  RFU.2,12 FMW.7 VSS  --------- DSUB.18-25 CNTR.19-30 Ground
  RFU.8    FMW.8 Q    --------- DSUB.11    CNTR.11    Busy
  P00 Joypad-A        ---|>|--- DSUB.2     CNTR.2     D0
  P01 Joypad-B        ---|>|--- DSUB.3     CNTR.3     D1
  P02 Joypad-Select   ---|>|--- DSUB.4     CNTR.4     D2
  P03 Joypad-Start    ---|>|--- DSUB.5     CNTR.5     D3
  P04 Joypad-Right    ---|>|--- DSUB.6     CNTR.6     D4
  P05 Joypad-Left     ---|>|--- DSUB.7     CNTR.7     D5
  P06 Joypad-Up       ---|>|--- DSUB.8     CNTR.8     D6
  P07 Joypad-Down     ---|>|--- DSUB.9     CNTR.9     D7
  RTC.1 INT aka SI    --------- DSUB.10    CNTR.10    /Ack
Parts List: 15 wires, four (DS) or twelve (DS-Lite) "BAT 85" diodes, 1 parallel port socket.

DS XBOO Connection Notes
The Firmware chip (FMW.Pins) hides underneath of the RFU shielding plate, so it'd be easier to connect the wires to the RFU.Pins (except DS-Lite: The RFU pins are terribly small (and have different pin-numbers), so either using FMW.Pins, or using mainboard vias (see below GIF) would be easier). The easiest way for the /W-to-VCC connection is to shortcut SL1 by putting some solder onto it.
The P00..P07 and INT signals are labeled on the switch-side of the mainboard, however, there should be more room for the cables when connecting them to via's at the bottom-side (except DS-Lite: P01 is found only at switch-side) image below may help to locate that pins,
  http://problemkaputt.de/nds-pins.gif (GIF-Image, 7.5KBytes)
At the parallel port side, DSUB.Pins or CNTR.Pins can be used for 25pin DSUB or 36pin Centronics sockets, the latter one allowing to use a standard printer cable.
The ring printed on the diodes is pointing towards parallel port side, the 4 diodes are required to prevent the parallel port to pull-up LOW levels on the NDS side, be sure to use BAT85 diodes, cheaper ones like 1N4148 are loosing too much voltage and won't gain stable LOW levels.
The power managment chip in the DS-Lite simply refuses to react to the Power-On button when P00..P07 are dragged high by the parallel port (even if it is in HighZ state), the 8 diodes in the data-lines are solving that problem (they are required on DS-Lite only, not on original DS).

DS XBOO Operation Notes
The main Upload function is found in no$gba Utility menu, together with further functions in Remote Access sub-menu.
Before uploading anything: download the original firmware, the file is saved as FIRMnnnn.BIN, whereas "nnnn" is equal to the last 16bit of the consoles 48bit MAC address, so Firmware-images from different consoles are having unique filenames. If you don't already have, also download the NDS BIOS, the BIOS contains encryption seed data required to encrypt/decrypt secure area; without having downloaded the BIOS, no$gba will be working only with unencrypted ROM-images. Next, select Patch Firmware to install the nocash firmware.

DS XBOO Troubleshooting
Be sure that the console is switched on, and that the XBOO cable is connected, and that you have selected the correct parallel port in no$gba setup (the "multiboot" options in Various Options screen), and, of course, try avoid to be fiddling with the joypad during uploads.
I've tested the cable on two computers, the overall upload/download stuff should work stable. The firmware access functions - which are required only for (un-)installation - worked only with one of the two computers; try using a different computer/parallel port in case of problems.

Nocash Firmware
The primary purpose is to receive uploaded NDS-images via parallel port connection, additionally it's containing bootmenu and setup screens similar to the original firmware. The user interface is having less cryptic symbols and should be alltogether faster and easier to use. Important Information about Whatever is supported (but it can be disabled). The setup contains a couple of additional options like automatic daylight saving time adjustment.
The bootmenu allows to boot normal NDS and GBA carts, it does additionally allow to boot NDS-images (or older PassMe-images) from flashcards in GBA slot. Furthermore, benefits of asm coding, the nocash firmware occupies less than 32KBytes, allowing to store (and boot) smaller NDS-images in the unused portion of the firmware memory (about 224KBytes), the zero-filled region between cart header and secure area, at 200h..3FFFh, is automatically excluded, so the image may be slightly bigger than the available free memory space.

Missing
Unlike the original firmware, the current version cannot yet boot via WLAN.


DSi Reference

Basic Hardware Features (mostly same as NDS)
NDS Reference
DSi Basic Differences to NDS

New Hardware Features
DSi I/O Map
DSi Control Registers (SCFG)
DSi XpertTeak (DSP)
DSi New Shared WRAM (for ARM7, ARM9, DSP)
DSi New DMA (NDMA)
DSi Microphone and SoundExt
DSi Advanced Encryption Standard (AES)
DSi Cartridge Header
DSi Touchscreen/Sound Controller
DSi I2C Bus
DSi Cameras
DSi SD/MMC Protocol and I/O Ports
DSi SD/MMC Filesystem
DSi Atheros Wifi SDIO Interface
DSi Atheros Wifi Internal Hardware
DSi GPIO Registers
DSi Console IDs
DSi Unknown Registers
DSi Notes
DSi Exploits
DSi Regions

General Info
ARM CPU Reference
BIOS Functions
External Connectors

Credits: http://www.dsibrew.org/wiki/Special:AllPages (now spammed)


DSi Basic Differences to NDS

Interrupts
There are several new interrupt sources in IE/IF registers, plus further ones in new IE2/IF2 registers.
DS Interrupts

Video
Essentially same as for NDS. Some details can be changed in SCFG_EXT9. For the 2D Engine, DISPSTAT.Bit6 contains a new "LCD Initialization Ready" flag on both ARM7 and ARM9 side (the bit is checked by DSi System Menu) (the bit is supposedly used at power-up, maybe also for wake-up from certain sleep modes).

BIOS SWI Functions
Some SWI Functions are changed (bugged in some cases), new SHA1 and RSA functions are added, and the initial RAM contents are moved from 27FFxxxh to 2FFFxxxh (with some extra fields, eg. a copy of extended DSi cart header).
BIOS Functions

Revised Hardware Functions
Some hardware features have been slightly revised (for example, the division by 0 flag was fixed). The revised functions can be enabled/disabled via SCFG registers.
DSi Control Registers (SCFG)

NDS Slot / Cartridges
DSi carts are using an extended cart header (1000h bytes), with RSA signature (making it problematic to run unlicensed/homebrew code), the icon/title format has been also extended, and the cartridge protocol contains a new command (command 3Dh, for unlocking extra DSi regions on the cartridge, and for reading new DSi secure area blocks).
The NDS Slot's Reset signal can be controlled by software (required because otherwise one could use only command 3Ch or 3Dh, but not both). The Power supply pin can be also controlled by software (yet not 100% confirmed how?). Moreover, there's new cartridge inserted sensor. And, DSi prototypes did have two NDS slots; DSi retail consoles do have only one slot, but they do still contain prototype relicts internally (like extra registers and extra irq sources for second slot) (there appear to be also unused extra pins on the CPU, but they couldn't be used without desoldering the whole chip).

Enable Bits
One new DSi invention is that setting Enable Bits (eg. for NDMA or CAM registers) is write-protecting the corresponding registers (ie. those registers can be initialized only while the Enable Bits are off).

SPI Bus
The SPI bus works same as on NDS, except, one small change is added support for 8MHz SPI clock (in SPICNT.bit2).

SPI Touchscreen Controller
This chip is working entirely different in DSi mode. It's still accessed via SPI bus, but with some new PAGE/INDEX values.
DSi Touchscreen/Sound Controller
The touchscreen hardware can be switched to NDS compatibility mode.

SPI Power Managment Device
The Power Managment Device contains some changed register, and some new extra registers. Internally, it is actually split to two devices: The power managment chipselect signal connects to U3 and U4 chips. Ie. some SPI registers are processed by U3 (power down, and backlight enable), and others by R4 (audio out and microphone).
Further functions like LED control and backlight brightness are moved to the BPTWL chip, accessed via I2C bus instead of SPI bus - the power LED blink feature (which was used on Wifi access) seems to be no longer working, however, the Wifi LED seems to blink automatically on Wifi access; the changed backlight brightness mechanism shouldn't cause compatibility issuses since that feature is somewhat reserved for being controlled by the firmware.

SPI FLASH Memory (Wifi Calibration, User Settings, Firmware)
This memory does still exist, but it's only 128Kbytes in DSi (instead 256K), and most of it is empty (since the DSi Firmware is stored in the eMMC chip). Later DSi models do even have the SPI FLASH capacity reduced to 4Kbytes.

RTC
Should be compatible with NDS. But seems to contain extra registers?
One of the RTC outputs does also seem to supply some (32kHz?) clock to some other mainboard components?
[XXX see Seiko S-35199A01 datasheet].

Wifi
Supports new WPA and WPA2 encryption and supports higher transfer rates (via a new SDIO wifi unit). For the old NDS-wifi mode, there are some new control registers:
  4004020h - SCFG_WL
  4004C04h - GPIO_WIFI
  BPTWL[30h] - Wifi LED related (also needed to enable Atheros Wifi SDIO)
SPI FLASH contains three new access point settings (for WPA/WPA2/proxy support):
DS Firmware Wifi Internet Access Points
The access point configuration can be done via Firmware (unlike as on NDS, where it needed to be done by the games).

GBA Slot
The GBA Slot has been removed. The memory regions and IRQ bits do still exist internally, but the DSi does basically behave as if there is no GBA cartridge inserted. Reading GBA ROM areas does return FFFFh halfwords instead of the usual open bus values though.

NDS Mode
In NDS mode, the DSi is basically working same as NDS: The new extra hardware is disabled, original NDS BIOS ROMs are mapped, and the hardware is simulating the old touchscreen controller.
Nonetheless, there are still a some small differences to real NDS consoles:
- Unlicensed NDS carts don't work (requires RSA, or whitelist for older games)
- GBA Slot is removed (more or less behaves as if no cart inserted)
- DSi ports 4004700h and 4004C0xh can be read (and written?) even in DS mode
- SPI Power Managment has some added/removed/changed registers
- SPI Touchscreen controller doesn't support pressure & temperature
- SPI FLASH exists, but it's smaller, and has extra access point info, etc.
- ARM7 BIOS has only first 20h bytes locked (instead first 1204h bytes)
- Power Button issues a Reset (goes to boot menu) (instead of plain power off)
- Power LED blink feature (for wifi) is replaced by a separate wifi LED
- RTC extra registers (if they do really exist) should exist in DS mode (?)
Unknown: does hot-swapping auto-power-off the nds-cart-slot in nds mode?


DSi I/O Map

DSi Memory Map
The overall memory map is same as on NDS. New/changed areas are:
  0000000h  64Kbyte ARM7 BIOS   (unlike NDS which had only 16KB)
  2000000h  16MByte Main RAM    (unlike NDS which had only 4MB)
  3000000h  800Kbyte Shared RAM (unlike NDS which had only 32KB)
  4004000h  New DSi I/O Ports
  8000000h  Fake GBA Slot (32MB+64KB) (FFh-filled; when mapped to current CPU)
  C000000h  Mirror of 16Mbyte Main RAM
  D000000h  Open Bus? in retail version, Extra 16Mbyte MainRAM in debug version
  FFFF000h  64Kbyte ARM9 BIOS   (unlike NDS which had only 4KB)

DSi I/O Maps
The overall DSi I/O Maps are same as on NDS,
DS I/O Maps
additional new/changed registers are:

ARM9 NDS Register that are changed in DSi mode
  4000004h 2   DISPSTAT (new Bit6, LCD Initialization Ready Flag)
  4000204h 2   EXMEMCNT (removed Bit0-7, ie. the GBA-slot related bits)
  4000210h 4   IE       (new interrupt sources, removed GBA-slot IRQ)
  4000214h 4   IF       (new interrupt sources, removed GBA-slot IRQ)
  40021A0h 4   Unknown, nonzero, probably same/silimar as on DSi7 side
  40021A4h 4   Unknown, zero, probably same/silimar as on DSi7 side
  40021A8h ..
  40021Bxh ..
  4102010h 4
ARM9 DSi System Control
  4004000h 2   SCFG_A9ROM DSi - NDS9 - ROM Status (R) [0000h]
  4004004h 2   SCFG_CLK   DSi - NDS9 - New Block Clock Control (R/W)
  4004006h 2   SCFG_RST   DSi - NDS9 - New Block Reset (R/W)
  4004008h 4   SCFG_EXT9  DSi - NDS9 - Extended Features (R/W)
  4004010h 2   SCFG_MC    Memory Card Interface Status (16bit) (undocumented)
ARM9 DSi New Shared WRAM Bank Control
  4004040h 4   MBK1       WRAM-A Slots for Bank 0,1,2,3  ;\Global ARM7+ARM9
  4004044h 4   MBK2       WRAM-B Slots for Bank 0,1,2,3  ; Slot Mapping
  4004048h 4   MBK3       WRAM-B Slots for Bank 4,5,6,7  ; (R or R/W, depending
  400404Ch 4   MBK4       WRAM-C Slots for Bank 0,1,2,3  ; on MBK9 setting)
  4004050h 4   MBK5       WRAM-C Slots for Bank 4,5,6,7  ;/
  4004054h 4   MBK6       WRAM-A Address Range           ;\Local ARM9 Side
  4004058h 4   MBK7       WRAM-B Address Range           ; (R/W)
  400405Ch 4   MBK8       WRAM-C Address Range           ;/
  4004060h 4   MBK9       WRAM-A/B/C Slot Write Protect (R)
ARM9 DSi New DMA (NDMA)
  4004100h 4   NDMAGCNT   NewDMA Global Control                     ;-Control
  4004104h 4   NDMA0SAD   NewDMA0 Source Address                    ;\
  4004108h 4   NDMA0DAD   NewDMA0 Destination Address               ;
  400410Ch 4   NDMA0TCNT  NewDMA0 Total Length for Repeats          ; NewDMA0
  4004110h 4   NDMA0WCNT  NewDMA0 Logical Block Size                ;
  4004114h 4   NDMA0BCNT  NewDMA0 Block Transfer Timing/Interval    ;
  4004118h 4   NDMA0FDATA NewDMA0 Fill Data                         ;
  400411Ch 4   NDMA0CNT   NewDMA0 Control                           ;/
  4004120h 4   NDMA1SAD                                             ;\
  4004124h 4   NDMA1DAD                                             ;
  4004128h 4   NDMA1TCNT                                            ; NewDMA1
  400412Ch 4   NDMA1WCNT                                            ;
  4004130h 4   NDMA1BCNT                                            ;
  4004134h 4   NDMA1FDATA                                           ;
  4004138h 4   NDMA1CNT                                             ;/
  400413Ch 4   NDMA2SAD                                             ;\
  4004140h 4   NDMA2DAD                                             ;
  4004144h 4   NDMA2TCNT                                            ; NewDMA2
  4004148h 4   NDMA2WCNT                                            ;
  400414Ch 4   NDMA2BCNT                                            ;
  4004150h 4   NDMA2FDATA                                           ;
  4004154h 4   NDMA2CNT                                             ;/
  4004158h 4   NDMA3SAD                                             ;\
  400415Ch 4   NDMA3DAD                                             ;
  4004160h 4   NDMA3TCNT                                            ; NewDMA3
  4004164h 4   NDMA3WCNT                                            ;
  4004168h 4   NDMA3BCNT                                            ;
  400416Ch 4   NDMA3FDATA                                           ;
  4004170h 4   NDMA3CNT                                             ;/
ARM9 DSi Camera Module
  4004200h 2   CAM_MCNT   Camera Module Control (16bit)
  4004202h 2   CAM_CNT    Camera Control (16bit)
  4004204h 4   CAM_DAT    Camera Data (32bit)
  4004210h 4   CAM_SOFS   Camera Trimming Starting Position Setting (32bit)
  4004214h 4   CAM_EOFS   Camera Trimming Ending Position Setting (32bit)
ARM9 DSi DSP - XpertTeak processor
  4004300h 2   DSP_PDATA  DSP Transfer Data
  4004304h 2   DSP_PADR   DSP Transfer Address
  4004308h 2   DSP_PCFG   DSP Configuration
  400430Ch 2   DSP_PSTS   DSP Status
  4004310h 2   DSP_PSEM   DSP ARM9-to-DSP Semaphore          (R/W)
  4004314h 2   DSP_PMASK  DSP DSP-to-ARM9 Semaphore Mask     (R/W)
  4004318h 2   DSP_PCLEAR DSP DSP-to-ARM9 Semaphore Clear    (W)
  400431Ch 2   DSP_SEM    DSP DSP-to-ARM9 Semaphore Data     (R)
  4004320h 2   DSP_CMD0   DSP ARM9-to-DSP Command Register 0 (R/W)
  4004324h 2   DSP_REP0   DSP DSP-to-ARM9 Reply Register 0   (R)
  4004328h 2   DSP_CMD1   DSP ARM9-to-DSP Command Register 1 (R/W)
  400432Ch 2   DSP_REP1   DSP DSP-to-ARM9 Reply Register 1   (R)
  4004330h 2   DSP_CMD2   DSP ARM9-to-DSP Command Register 2 (R/W)
  4004334h 2   DSP_REP2   DSP DSP-to-ARM9 Reply Register 2   (R)
  4004340h C0h DSP_mirror Mirrors of above 40h-byte DSP register area

ARM7 DSi
  4000004h 2   DISPSTAT (new Bit6, LCD Initialization Ready Flag) (as DSi9?)
  40001C0h 2   SPICNT   (new Bit2, for 8MHz transfer clock)
  4000204h 2   EXMEMCNT (removed Bit0-7: GBA-slot related bits)   (as DSi9?)
  4000210h 4   IE       (new interrupt sources, removed GBA-slot IRQ)
  4000214h 4   IF       (new interrupt sources, removed GBA-slot IRQ)
  4000218h     IE2      (new register with more new interrupt sources)
  400021Ch     IF2      (new register with more new interrupt sources)
ARM7 DSi Maybe 2nd ROM slot (DSi prototypes did have 2 cartridge slots)
  40021A0h 4   Unknown, nonzero, probably related to below 40021A4h
  40021A4h 4   Unknown, related to 40001A4h (Gamecard Bus ROMCTRL)
  40021A8h ..
  40021Bxh ..
  4102010h 4
ARM7 DSi System Control
  4004000h 1   SCFG_A9ROM used by BIOS and SystemFlaw   (bit0,1)
  4004001h 1   SCFG_A7ROM used by BIOS and SystemFlaw   (bit0,1,2)
  4004004h 2   SCFG_CLK7  used by SystemFlaw
  4004006h 2   SCFG_JTAG  Debugger Control
  4004008h 4   SCFG_EXT7  used by SystemFlaw
  4004010h 2   SCFG_MC    Memory Card Interface Control (R/W)  ;\
  4004012h 2   SCFG_CARD_INSERT_DELAY (usually 1988h = 100ms)  ; Game Cartridge
  4004014h 2   SCFG_CARD_PWROFF_DELAY (usually 264Ch = 150ms)  ;/
  4004020h 2   SCFG_WL    Wireless Disable    ;bit0 = wifi?
  4004024h 2   SCFG_OP    Debugger Type (R)   ;bit0-1 = (0=retail, ?=debug)
ARM7 DSi New Shared WRAM Bank Control
  4004040h 4   MBK1       WRAM-A Slots for Bank 0,1,2,3  ;\
  4004044h 4   MBK2       WRAM-B Slots for Bank 0,1,2,3  ; Global ARM7+ARM9
  4004048h 4   MBK3       WRAM-B Slots for Bank 4,5,6,7  ; Slot Mapping (R)
  400404Ch 4   MBK4       WRAM-C Slots for Bank 0,1,2,3  ; (set on ARM9 side)
  4004050h 4   MBK5       WRAM-C Slots for Bank 4,5,6,7  ;/
  4004054h 4   MBK6       WRAM-A Address Range           ;\Local ARM7 Side
  4004058h 4   MBK7       WRAM-B Address Range           ; (R/W)
  400405Ch 4   MBK8       WRAM-C Address Range           ;/
  4004060h 4   MBK9       WRAM-A/B/C Slot Write Protect (R/W)
ARM7 DSi New DMA (NDMA)
  4004100h 74h NewDMA (new DMA, as on ARM9i, see there)
ARM7 DSi AES Encryption Unit
  4004400h 4   AES_CNT    (R/W)
  4004404h 4   AES_BLKCNT (W)
  4004408h 4   AES_WRFIFO (W)
  400440Ch 4   AES_RDFIFO (R)
  4004420h 16  AES_IV     (W)
  4004430h 16  AES_MAC    (W)
  4004440h 48  AES_KEY0   (W) ;used for modcrypt
  4004470h 48  AES_KEY1   (W) ;used for ?
  40044A0h 48  AES_KEY2   (W) ;used for JPEG signatures
  40044D0h 48  AES_KEY3   (W) ;used for eMMC sectors
ARM7 DSi I2C Bus
  4004500h 1   I2C_DATA
  4004501h 1   I2C_CNT
ARM7 DSi Microphone
  4004600h 2   MIC_CNT    Microphone Control
  4004604h 4   MIC_DATA   Microphone FIFO
ARM7 DSi SNDEX
  4004700h 2   SNDEXCNT             <-- can be read even in DS mode!
ARM7 DSi SD/MMC Registers for Memory Card access (SD Card and onboard eMMC)
  4004800h 2   SD_CMD              Command and Response/Data Type
  4004802h 2   SD_CARD_PORT_SELECT   (SD/MMC:020Fh, SDIO:010Fh)
  4004804h 4   SD_CMD_PARAM0-1     Argument (32bit, 2 halfwords)
  4004808h 2   SD_STOP_INTERNAL_ACTION
  400480Ah 2   SD_DATA16_BLK_COUNT        "Transfer Block Count"
  400480Ch 16  SD_RESPONSE0-7 (128bit, 8 halfwords)
  400481Ch 4   SD_IRQ_STATUS0-1  ;IRQ Status  (0=ack, 1=req)
  4004820h 4   SD_IRQ_MASK0-1    ;IRQ Disable (0=enable, 1=disable)
  4004824h 2   SD_CARD_CLK_CTL Card Clock Control
  4004826h 2   SD_DATA16_BLK_LEN  Memory Card Transfer Data Length
  4004828h 2   SD_CARD_OPTION Memory Card Option Setup (can be C0FFh)
  400482Ah 2   Fixed always zero?
  400482Ch 4   SD_ERROR_DETAIL_STATUS0-1   Error Detail Status
  4004830h 2   SD_DATA16_FIFO        Data Port  (SD_FIFO?)
  4004832h 2   Fixed always zero?       ;(TC6371AF:BUF1 Data MSBs?)
  4004834h 2   SD_CARD_IRQ_CTL          ;(SD_TRANSACTION_CTL)
  4004836h 2   SD_CARD_IRQ_STAT         ;(SD_CARD_INTERRUPT_CONTROL)
  4004838h 2   SD_CARD_IRQ_MASK         ;(SDCTL_CLK_AND_WAIT_CTL)
  400483Ah 2   Fixed always zero?       ;(SDCTL_SDIO_HOST_INFORMATION)
  400483Ch 2   Fixed always zero?       ;(SDCTL_ERROR_CONTROL)
  400483Eh 2   Fixed always zero?       ;(TC6387XB: LED_CONTROL)
  4004840h 2   Fixed always 003Fh?
  4004842h 2   Fixed always 002Ah?
  4004844h 6Eh Fixed always zerofilled?
  40048B2h 2   Fixed always FFFFh?
  40048B4h 6   Fixed always zerofilled?
  40048BAh 2   Fixed always 0200h?
  40048BCh 1Ch Fixed always zerofilled?
  40048D8h 2   SD_DATA_CTL
  40048DAh 6   Fixed always zerofilled?
  40048E0h 2   SD_SOFT_RESET  Software Reset (bit0=SRST=0=reset)
  40048E2h 2   Fixed always 0009h?      ;(RESERVED2/9, TC6371AF:CORE_REV)
  40048E4h 2   Fixed always zero?
  40048E6h 2   Fixed always zero?       ;(RESERVED3, TC6371AF:BUF_ADR)
  40048E8h 2   Fixed always zero?       ;(TC6371AF:Resp_Header)
  40048EAh 6   Fixed always zerofilled?
  40048F0h 2   Fixed always zero?       ;(RESERVED10)
  40048F2h 2   ? Can be 0003h
  40048F4h 2   ? Can be 0770h
  40048F6h 2   SD_WRPROTECT_2 (R)  ;Write protect for eMMC   (RESERVED4)
  40048F8h 4   SD_EXT_IRQ_STAT0-1  ;Insert/eject for eMMC    (RESERVED5-6)
  40048FCh 4   SD_EXT_IRQ_MASK0-1       ;(TC6371AF:Revision) (RESERVED7-8)
  4004900h 2   SD_DATA32_IRQ
  4004902h 2   Fixed always zero?
  4004904h 2   SD_DATA32_BLK_LEN
  4004906h 2   Fixed always zero?
  4004908h 2   SD_DATA32_BLK_COUNT
  400490Ah 2   Fixed always zero?
  400490Ch 4   SD_DATA32_FIFO
  4004910h F0h Fixed always zerofilled?
ARM7 DSi SD/MMC Registers for SDIO access (for Atheros Wifi)
  4004A00h 512 SDIO_xxx (same as SD_xxx at 4004800h..40049FFh, see there)
  4004A02h 2   SDIO_CARD_PORT_SELECT (slightly different than 4004802h)
ARM7 DSi General Purpose I/O (GPIO) (headphone connect, power button)
  4004C00h 1   GPIO Data In                (R)  (even in DS mode)
  4004C00h 1   GPIO Data Out               (W)
  4004C01h 1   GPIO Data Direction         (R/W)
  4004C02h 1   GPIO Interrupt Edge Select  (R/W)
  4004C03h 1   GPIO Interrupt Enable       (R/W)
  4004C04h 2   GPIO_WIFI                   (R/W)
ARM7 DSi CPU/Console ID (used as eMMC key)
  4004D00h 8   CPU/Console ID Code (64bit) (R)
  4004D08h 2   CPU/Console ID Flag (1bit)  (R)
ARM7 DSi Junk?
  8030200h 2   GBA area, accessed alongsides with SDIO port [4004A30h] (bug?)

Main Memory Control
  2FFFFFEh 2   Main Memory Control (for 16MByte RAM chip)
  DFFFFFEh 2   Main Memory Control (extra 16MByte RAM chip in debug version)


DSi Control Registers (SCFG)

4004000h - DSi9 - SCFG_A9ROM - ROM Status (R) [0000h]
  0     ARM9 BIOS Upper 32K half of DSi BIOS (0=Enabled, 1=Disabled)
  1     ARM9 BIOS for NDS Mode               (0=DSi BIOS, 1=NDS BIOS)
  2-15  Unused (0)
  16-31 Unspecified (0)
Possible values are:
  00h  DSi ROM mapped at FFFFxxxxh, full 64K enabled (during bootstage 1 only)
  01h  DSi ROM mapped at FFFFxxxxh, lower 32K only
  03h  NDS ROM mapped at FFFFxxxxh (internal setting)
  00h  NDS ROM mapped at FFFFxxxxh (visible setting due to SCFG_EXT9.bit31=0)
Checking for A9ROM=01h is common for detecting if the console is a "DSi console running in DSi mode".

4004000h - DSi7 - SCFG_ROM - ROM Control (R/W, Set-Once)
  0     ARM9 BIOS Upper 32Kbyte of DSi BIOS (0=Enabled, 1=Disabled) (FFFF8xxxh)
  1     ARM9 BIOS for NDS Mode              (0=DSi BIOS, 1=NDS BIOS)(FFFF0xxxh)
  2-7   Unused (0)
  8     ARM7 BIOS Upper 32Kbyte of DSi BIOS (0=Enabled, 1=Disabled)  (0008xxxh)
  9     ARM7 BIOS for NDS Mode              (0=DSi BIOS, 1=NDS BIOS) (0000xxxh)
  10    Access to Console ID registers      (0=Enabled, 1=Disabled)  (4004Dxxh)
  11-15 Unused (0)
  16    Unknown, used by bootrom, set to 0  (0=Maybe start ARM9 ?)
  17-31 Unused (0)
Bits in this register can be set once (cannot be changed back from 1 to 0).
Don't change bit1 while executing IRQs or SWI functions on ARM9 side.
The System Menu sets bit10 shortly before starting any Cartridges or DSiware files (except System Base Tools) (for NDS mode, after having set bit10, it's also setting bit1 and bit9).

4004004h - DSi9 - SCFG_CLK - New Block Clock Control (R/W) [0084h]
  0     ARM9 CPU Clock         (0=NITRO/67.03MHz, 1=TWL/134.06MHz) (TCM/Cache)
  1     Teak DSP Block Clock   (0=Stop, 1=Run)
  2     Camera Interface Clock (0=Stop, 1=Run)
  3-6   Unused (0)
  7     New Shared RAM Clock   (0=Stop, 1=Run)               (set via ARM7) (R)
  8     Camera External Clock  (0=Disable, 1=Enable) ("outputs at 16.76MHz")
  9-15  Unused (0)
  16-31 See below (Port 4004006h, SCFG_RST)
Change ARM9 clock only from code within ITCM (and wait at least 8 cycles before accessing any non-ITCM memory).
Disable the corresponding modules before stopping their clocks.

4004004h - DSi7 - SCFG_CLK7 (R/W)
  0     SD/MMC Clock      (0=Stop, 1=Run) (should be same as SCFG_EXT7.bit18)
  1     Unknown/used      (0=Stop, 1=Run) (backlight goes off when cleared?)
  2     Unknown/used      (0=Stop, 1=Run) (unknown effect?)
  3-6   Unused (0)
  7     New Shared RAM Clock (0=Stop, 1=Run)
  8     Touchscreen Clock    (0=Stop, 1=Run) (needed for touchscr input)
  9-15  Unused (0)
  16-31 See below (Port 4004006h, SCFG_JTAG)

4004006h - DSi9 - SCFG_RST - New Block Reset (R/W) [0000h]
  0     Teak DSP Block Reset (0=Apply Reset, 1=Release Reset)
  1-15  Unused (0)

4004006h - DSi7 - SCFG_JTAG - Debugger Control (R/W? or Write-ONCE-only?)
  0     ARM7SEL (set when debugger can do ARM7 debugging)
  1     CPU JTAG Enable
  2-7   Unused (0)
  8     DSP JTAG Enable
  9-15  Unused (0)
Initialized as so: if SCFG_OP=2 then SCFG_JTAG=0102h, elseif SCFG_OP=1 then SCFG_JTAG=0103h, entrypoint=0, endif.

4004008h - DSi9 - SCFG_EXT9 - Extended Features (R/W) [8307F100h]
  0     Revised ARM9 DMA Circuit       (0=NITRO, 1=Revised)
  1     Revised Geometry Circuit       (0=NITRO, 1=Revised)
  2     Revised Renderer Circuit       (0=NITRO, 1=Revised)
  3     Revised 2D Engine Circuit      (0=NITRO, 1=Revised)
  4     Revised Divider Circuit        (0=NITRO, 1=Revised)
  5-6   Unused (0)
  7     Revised Card Interface Circuit (0=NITRO, 1=Revised)
  8     Extended ARM9 Interrupts       (0=NITRO, 1=Extended)
  9-11  Unused (0)
  12    Extended LCD Circuit           (0=NITRO, 1=Extended)
  13    Extended VRAM Access           (0=NITRO, 1=Extended)
  14-15 Main Memory RAM Limit (0..1=4MB/DS, 2=16MB/DSi, 3=32MB/DSiDebugger)
  16    Access to New DMA Controller   (0=Disable, 1=Enable) (40041xxh)
  17    Access to Camera Interface     (0=Disable, 1=Enable) (40042xxh)
  18    Access to Teak DSP Block       (0=Disable, 1=Enable) (40043xxh)
  19-23 Unused (0)
  24    Access to 2nd NDS Cart Slot   (0=Disable, 1=Enable)  (set via ARM7) (R)
  25    Access to New Shared WRAM     (0=Disable, 1=Enable)  (set via ARM7) (R)
  26-30 Unused (0)
  31    Access to SCFG/MBK registers  (0=Disable, 1=Enable) (4004000h-4004063h)
Bit24-25 are READ-ONLY (showing state set via ARM7 side). Note: Official specs for Bit24-25 are nonsense.
Default settings seem to be:
  8307F100h for DSi firmware, DSi cartridges and DSiware
  03000000h for NDS cartridges (and DSiware in NDS mode, eg. Pictochat)
Main RAM mapping depending on bit14-15:
  Mode         2000000h-2FFFFFFh   C000000h-CFFFFFFh   D000000h-DFFFFFFh
  4MB (0 or 1) 1st 4MB (+mirrors)  Zerofilled          Zerofilled
  16MB (2)     1st 16MB            1st 16MB (mirror)   1st 16MB (mirror)
  32MB (3)     1st 16MB            1st 16MB (mirror)   Open bus (or 2nd 16MB)
SCFG_EXT9.bit14-15 affect the Main RAM mapping on <both> ARM9 and ARM7 side (that, at least AFTER games have been booted, however, there's a special case DURING boot process: For NDS games, the firmware switches to 4MB mode on ARM9 side, whilst ARM7 is still relocating memory from the 16MB area at the same time - unknown how that is working exactly, maybe ARM7 isn't affected by SCFG_EXT9 setting until ARM7 has configured/disabled its own SCFG_EXT7 register).
The 32MB mode requires an extra RAM chip (present in DSi debug version only; DSi retail consoles return 16bit open bus values instead of extra memory). RAM Size/Openbus detection is conventionally done by trying to read/write a BYTE at [0DFFFFFAh].

4004008h - DSi7 - SCFG_EXT7 - Extended Features (R/W)
  0     Revised ARM7 DMA Circuit       (0=NITRO, 1=Revised)
  1     Revised Sound DMA              (0=NITRO, 1=Revised)
  2     Revised Sound                  (0=NITRO, 1=Revised)
  3-6   Unused (0)
  7     Revised Card Interface Circuit (0=NITRO, 1=Revised) (set via ARM9) (R)
  8     Extended ARM7 Interrupts      (0=NITRO, 1=Extended) (4000218h)
  9     Extended SPI Clock (8MHz)     (0=NITRO, 1=Extended) (40001C0h)
  10    Extended Sound DMA        ?   (0=NITRO, 1=Extended) (?)
  11    Undocumented/Unknown      ??  (0=NITRO, 1=Extended) (?)
  12    Extended LCD Circuit          (0=NITRO, 1=Extended) (set via ARM9) (R)
  13    Extended VRAM Access          (0=NITRO, 1=Extended) (set via ARM9) (R)
  14-15 Main Memory RAM Limit    (0..1=4MB, 2=16MB, 3=32MB) (set via ARM9) (R)
  16    Access to New DMA Controller  (0=Disable, 1=Enable) (40041xxh)
  17    Access to AES Unit            (0=Disable, 1=Enable) (40044xxh)
  18    Access to SD/MMC registers    (0=Disable, 1=Enable) (40048xxh-40049xxh)
  19    Access to SDIO Wifi registers (0=Disable, 1=Enable) (4004Axxh-4004Bxxh)
  20    Access to Microphone regs     (0=Disable, 1=Enable) (40046xxh)
  21    Access to SNDEXCNT register   (0=Disable, 1=Enable) (40047xxh)
  22    Access to I2C registers       (0=Disable, 1=Enable) (40045xxh)
  23    Access to GPIO registers      (0=Disable, 1=Enable) (4004Cxxh)
  24    Access to 2nd NDS Cart Slot   (0=Disable, 1=Enable) (40021xxh)
  25    Access to New Shared WRAM     (0=Disable, 1=Enable) (3xxxxxxh)
  26-27 Unused (0)
  28    Undocumented/Unknown          (0=???, 1=Normal)     (?)
  29-30 Unused (0)
  31    Access to SCFG/MBK registers  (0=Disable, 1=Enable) (4004000h-4004063h)
Bit7,12-15 are READ-ONLY (showing state set via ARM9 side).
Default settings seem to be:
  93FFFB06h for DSi Firmware (Bootcode and SysMenu/Launcher)
  13FFFB06h for DSiware (eg. SysSettings, Flipnote, PaperPlane)
  13FBFB06h for DSi Cartridges (eg. System Flaw)            (bit18=0=sdmmc off)
  12A03000h for NDS cartridges (and DSiware in NDS mode, eg. Pictochat)
Bits 0,1,2,10,18,31 are taken from carthdr[1B8h].

4004010h - DSi9 - SCFG_MC - NDS Slot Memory Card Interface Status (R)
4004010h - DSi7 - SCFG_MC - NDS Slot Memory Card Interface Control (R/W)
  0     1st NDS Slot Game Cartridge (0=Inserted, 1=Ejected)               (R)
  1     1st NDS Slot Unknown/Unused (0)
  2-3   1st NDS Slot Power State (0=Off, 1=On+Reset, 2=On, 3=RequestOff)  (R/W)
  4     2nd NDS Slot Game Cartridge (always 1=Ejected) ;\DSi              (R)
  5     2nd NDS Slot Unknown/Unused (0)                ; prototype
  6-7   2nd NDS Slot Power State    (always 0=Off)     ;/relict           (R/W)
  8-14  Unknown/Undocumented (0)
  15    Swap NDS Slots (0=Normal, 1=Swap)                                 (R/W)
  16-31 ARM7: See Port 4004012h, ARM9: Unspecified (0)
Note: Additionally, the NDS slot Reset pin can be toggled (via ROMCTRL.Bit29; that bit is writeable on ARM7 side on DSi; which wasn't supported on NDS).
Power state values:
  0=Power is Off
  1=Power On and force Reset (shall be MANUALLY changed to state=2)
  2=Power On
  3=Request Power Off (will be AUTOMATICALLY changed to state=0)
cart_power_on: (official/insane 1+10+27+120ms, but also works with 1+1+0+1ms)
  wait until state<>3                   ;wait if pwr off busy
  exit if state<>0 AND no_reset_wanted  ;exit if already on & no reset wanted
  wait 1ms, then set state=1            ;pwr on & force reset
  wait 10ms, then set state=2           ;pwr on normal state  ;better: 1ms
  wait 27ms, then set ROMCTRL=20000000h ;release reset pin    ;better: 0ms
  wait 120ms (or 270ms on 3DS)          ;more insane delay?   ;better: 1ms/20ms
  ;note: the last delay (after releasing reset) can be 1ms for most carts,
  ;except DSi NAND carts do require 20ms (eg. Face Training)
  ;XXX other day: needs MORE than 20ms (30ms works), temperature related??
cart_power_off: (official 150ms, when using default [4004014h]=264Ch)
  wait until state<>3                   ;wait if pwr off busy
  exit if state<>2                      ;exit if already off
  set state=3                           ;request pwr off
  exit unless you want to know when below pointless delay has ellapsed
  wait until state=0    ;default=150ms  ;wait until pwr off    ;better: skip
Power Off is also done automatically by hardware when ejecting the cartridge.
The Power On sequence does reset ROMCTRL.bit29=0 (reset signal).
Bit15 swaps ports 40001A0h-40001BFh and 4100010h with 40021A0h-40021BFh? and 4102010h?, the primary purpose is mapping the 2nd Slot to the 4xx0xxxh registers (for running carts in 2nd slot in NDS mode; which of course doesn't work because the 2nd slot connector isn't installed), theoretically it would also allow to access the 1st slot via 4xx2xxxh registers (however, that doesn't seem to be fully implemented, cart reading does merely reply FFh's (cart inserted) or 00h's (no cart)). 4102010h can be read by manually polling DRQ in 40021A4h.bit23, and probably by NDMA (but not by old DMA which has no known DRQ mode for 2nd slot).

4004012h - DSi7 - SCFG_CARD_INSERT_DELAY (usually 1988h = 100ms) (R/W)
4004014h - DSi7 - SCFG_CARD_PWROFF_DELAY (usually 264Ch = 150ms) (R/W)
  0-15  Delay in 400h cycle units (at 67.027964MHz)  ;max FFFFh=ca. 1 second
Usually set to 1988h/264Ch by firmware. Power up default is FFFFh/FFFFh, with that setting it takes about 1 second to sense inserted carts (after power-up, or after cart-insert).
Insert delay defines the time until SCFG_MC.bit0 reacts upon cart insert, and until cart access works (cart eject works instantly regardless of the delay setting). The 3DS bootrom uses 051Dh=20ms, which may be good to avoid switch bounce. The DSi/3DS firmwares use 1988h=100ms, which might be reasonable if the switch triggers too early.
Power Off delay defines how fast SCGF_MC.bit2-3 are changing from state=3 (request power off) to state=0 (power off). The 3DS bootrom uses 051Dh=20ms, the DSi/3DS firmwares use 264Ch=150ms, which is both kinda pointless. If the VCC pin is kept powered during that time (?) then the delay might help to finish FLASH writes (which would make sense only if there was data written to cartridge).

4004020h - DSi7 - SCFG_WL - Wireless Disable (R/W)
  0     OFFB, related to Wifi Enable flag from TWLCFGn.dat and HWINFO_S files
  1-15  Unknown/unused (0)
Unknown what that does. SDIO Wifi seems to work regardless of that bit.

4004024h - DSi7 - SCFG_OP - Debugger Type (R)
  0-1   Debug Hardware Type (0=Retail, other=debug variants)
  2-3   Unknown/unused (0)
  4     Unknown (maybe used, since it isn't masked & copied to RAM)
  5-15  Unknown/unused (0)
Changing this register would theoretically allow to install the debug firmware on retail consoles, however, it's unknown where bit0-1 come from (possibly from an internal PROM in the TWL CPU, solder pads underneath of the TWL CPU, or even from a physically different TWL CPU chip version).


DSi XpertTeak (DSP)

The DSi includes an XpertTeak Digital Signal Processor (DSP); which is consisting of a TeakLite II processor, plus some "expert" features (like DMA support). The thing appears to be intended for audio/video decoding, but it's left unused by most DSi games. However, it's used by the "Nintendo DSi Sound" and "Nintendo Zone" system utilities, and by the "Cooking Coach" cartridge.

DSi Teak Misc

XpertTeak I/O Registers (on ARM side)
DSi Teak I/O Ports (on ARM9 Side)

XpertTeak I/O Registers (on Teak side)
DSi Teak MMIO - Register Summary
DSi Teak MMIO[8000h] - Misc Registers (JAM/GLUE)
DSi Teak MMIO[8020h] - Timers (TMR)
DSi Teak MMIO[8050h] - Serial Port (SIO)
DSi Teak MMIO[8060h] - Debug (OCEM, On-chip Emulation Module)
DSi Teak MMIO[8080h] - PLL and Power (PMU, Power Management Unit)
DSi Teak MMIO[80C0h] - Host Port Interface (APBP aka HPI)
DSi Teak MMIO[80E0h] - AHBM - Advanced High Performance Bus Master
DSi Teak MMIO[8100h] - Memory Interface Unit (MIU)
DSi Teak MMIO[8140h] - Code Replacement Unit (CRU)
DSi Teak MMIO[8180h] - Direct Memory Access (DMA)
DSi Teak MMIO[8200h] - Interrupt Control Unit (ICU)
DSi Teak MMIO[8280h] - Audio (Buffered Time Division Multiplexing Port)

TeakLite II Processor
DSi Teak CPU Registers
DSi Teak CPU Control/Status Registers
DSi Teak CPU Address Config/Step/Modulo
DSi TeakLite II Instruction Set Encoding
DSi TeakLite II Operand Encoding


DSi Teak Misc

Teak Instruction Set References
There aren't any official references for the Teak instruction set. However, there's one document that has leaked into internet (plus some docs for older Oak instruction set):
  TeakLite Architecture Specification Revision 4.41 (DSP Group Inc.)
  OakDSPCore Technical Manuals for CWDSP1640 or CWDSP167x (LSI Logic)
  OakDSPCore DSP Subsystem AT75C (Atmel)
TeakLite II supports lots of additional opcodes, the only available info has leaked in form of .DLLs which were (apparently by mistake) bundled with a specific RVDS release version:
  TeakLite II disassembler dll in RVDS (RealView Developer Suite) 4.0 Pro
There's no known way to use the RVDS disassembler GUI to decipher Teak binaries. However, Normmatt found a way to get the .DLLs to disassemble code manually (via LoadLibrary and GetProcAddr), which in turn allowed to disassemble all possible 65536 combinations for all opcodes.
BUG: That RVDS tool disassembles "R0425" operands to "r6" (instead of "r5"), that's definetely wrong for the old "movr" opcode (TeakLite I didn't support any "r6" register at all), and, when looking at disassembled code, it does also look wrong for newer TL2 opcodes.
Actually, the registers CAN be redefined via ar0/ar1/arp0/arp1/arp2/arp3, so it isn't actually a bug.

Teak MMIO Registers
There aren't official docs, but wwylele has discovered a debugger at that contains definitions for most of the MMIO bits:
  searching for "teak" in the "search for chip" box on "www.lauterbach.com"
  should lead to this file: trace32_ceva-teak_r_2019_02_000108303_win64.zip
The zip contains a "perxteak.per" file that contains the MMIO bit definitions (in txt format). The definitions for OCEM do accidentally refer to an older version (without 18bit addresses). Definitions for GLUE, ICU, APBP, DMA, CRU, GPIO, and BTDMP are missing (whereof a similar/older ICU variant is defined in "peroak.per" in the same zip).

Teak COFF Files
The DSi Sound utility contains a COFF file called "aac.a" (inside of its nitro filesystem), and aside from the binary, the file is also including a COFF symbol table with labels in ASCII format.

Teak Undefined Opcodes
There are several "Undefined" opcodes: Any opcodes that have no instruction assigned in the opcode encoding table (or that are excplicitely assigned as "undefined" in the table). Opcodes with invalid parameters (eg. ArArp set to 6..7).
Some opcodes are also having "Unused" operand bits; these bits should be usually zero (nonzero would supposedly mirror to the same instruction, but one shouldn't do that).
Moreover, there are various special cases saying that certain opcodes may not be used with certain registers, eg. "addh" shall not be used with operands Ax,Bx,p (with unknown results when violating that rule).

Teak Memory
Memory is addressed in 16bit WORD units (not in bytes) with separate Instruction and Data busses. Before starting the Teak, store the Teak program code in New Shared WRAM, and then map that memory to Teak side via MBK registers:
DSi New Shared WRAM (for ARM7, ARM9, DSP)
At Teak side, 16bit is the smallest addressable unit (so there's no "byte-order" on Teak side - however, 16bit values should be stored in little endian format on ARM side).
Confusingly, the "movpdw" opcode is doing a 32bit read with two 16bit words ordered in big-endian (and, on ARM side, byte-fractions ordered in little-endian). There are a few more opcodes that can read/write 32bits, with optional address increment/decrement for the 2nd word, so endianness is selectable in that cases; it's also common to use the SAME address for both words (probably intended for scaling a 16bit memory value to 32bits).

Teak Code Memory
TeakLite II supports 18bit program memory addressing (unlike Teak/Oak which supported only 16bit addresses). The 18bits allow to address max 256Kwords (=512Kbytes) of code, whereas, the DSi can map only half that much memory to the DSP (ie. max 256Kbytes code).
Call/Ret are always pushing/popping 32bit return addresses (even when doing "near" calls within the same 16bit page).

Teak Data Memory (RAM and Memory Mapped I/O)
Teak Data Memory is addressed via 16bit address bus (via registers r0..r7), allowing to access max 64Kwords (2Kwords of MMIO, plus 62Kwords of RAM). The memory is divided into three sections (X/Z/Y-spaces), the size/location of that sections can be changed via Port 8114h (in 1Kword units), and alongsides, the MMIO base can be adjusted via Port 811Eh. The default areas are:
  0000h..7FFFh  X Space (for RAM, with 1-stage write-buffer)     ;min zero
  8000h..87FFh  Z Space (for Memory-mapped I/O, no write-buffer) ;min zero
  8800h..FFFFh  Y Space (for RAM, with 1-stage write-buffer))    ;min 1Kword
Confusingly, the DSi Sound utility is mapping 128Kwords of RAM as Teak Data memory, but it's unknown how to access all of that memory. The CPU opcodes, CPU registers, and MMIO registers don't seem to allow to access more than 64Kwords of Data. Maybe the extra memory is accessible via DMA, and maybe the CPU's [r7+imm16] operands might allow to exceed the 64Kbyte range (though they might as well wrap within 64Kbyte range, actually that's more likely, especially for "signed" immediates).

Teak Call Conventions (as done in "aac.a" from DSi Sound)
Functions are called with up to four parameters in a0,a1,b0,b1 (or a0l, a1l, b0l, b1l when needing only 16bits). Any further parameters are pushed on stack before the function call (and are deallocated via "rets Imm8" opcode upon return). Register r7 is often used as stack frame (for accessing pushed incoming parameters & locally allocated variables).
Functions may smash a0, a1, b0, b1. A return value (if any) is stored in a0 (or a0l). All other registers like r0..r7, sv, etc. should be left unchanged (or pushed/popped when needed).

Teak Speed
Cycles per opcode are defined in the TeakLite document (not covering TeakLite II opcodes though). Most instructions (even Multiply opcodes) can complete in a single clock cycle. The main bottleneck appear to be memory access cycles: Code and Data memory can be accessed in parallel, so the overall rule would be:
  NumCycles = max(NumberOfOpcodeWords, NumberOfDataReadsWrites)
Some exceptions with extra cycles are opcodes that are changing PC, or that do read/write program memory (movd and movp). Opcodes exp, max, maxd, min are having restrictions saying that the result may not be used by the "following instruction".
The overall clock speed in the DSi is unknown; some years ago somebody seems to have claimed it to be around 130MHz, but it's unclear where that info came from.
  Teak actual CPU clock(s) are...
  134.055928MHz (aka 134MHz)       <-- for Timer 0, SIO, DMA (no "waitstates")
  107.244742MHz (aka 134MHz/1.25)  <-- for Timer 1, CPU    (with "waitstates")
The ARM9 can access WRAM at 33MHz, whilst Teak seems to be capable of fetching 16bit opcodes and 16bit data at 107MHz from the same WRAM (apparently without even using a cache).


DSi Teak I/O Ports (on ARM9 Side)

4004300h - DSi9 - DSP_PDATA - DSP Transfer Data Read FIFO (R)
  0-15  Data (one stage of the 16-stage Read FIFO)

4004300h - DSi9 - DSP_PDATA - DSP Transfer Data Write FIFO (W)
  0-15  Data (one stage of the 16-stage Write FIFO)

4004304h - DSi9 - DSP_PADR - DSP Transfer Address (W)
  0-15  Lower 16bit of Address in DSP Memory (in 16bit units)
For MMIO, only lower 10bit are used (ie. MMIO[8000h-87FFh] can be accessed via 8000h-87FFh or 0000h-07FFh or other mirrors).
For Data, the 16bit address allows to access 64K-words.
For Code, the 16bit address allows to access 64K-words, but Code works only in write-direction?
For Data/Code, the upper 16bit of Address must be configured on DSP side, in DMA channel 0 registers:
  MMIO[81BEh]   - DMA Select Channel (must be 0 for below DMA 0 regisrers)
  MMIO[81C2h:0] - DMA Channel 0: Source Address, bit16-31 (R/W)
  MMIO[81C6h:0] - DMA Channel 0: Destination Address, bit16-31 (R/W)
The Auto-increment flag in DSP_PCFG.bit1 will increment the 16bit address after each DSP_PDATA unit (but doesn't seem to increment the upper bits after address xxFFFFh).

4004308h - DSi9 - DSP_PCFG - DSP Configuration (R/W)
  0     DSP Reset (0=Release, 1=Reset) ;should be held "1" for 8 DSP clks
  1     DSP Transfer Address Auto-Increment  (0=Off, 1=On)
  2-3   DSP Read Data Length (0=1 word, 1=8 words, 2=16 words, 3=FreeRun)
  4     DSP Read Start Flag (mem transfer via Read FIFO) (1=Start)
  5     Interrupt Enable Read FIFO Full      (0=Off, 1=On)
  6     Interrupt Enable Read FIFO Not-Empty (0=Off, 1=On)
  7     Interrupt Enable Write FIFO Full     (0=Off, 1=On)
  8     Interrupt Enable Write FIFO Empty    (0=Off, 1=On)
  9     Interrupt Enable Reply Register 0    (0=Off, 1=On)
  10    Interrupt Enable Reply Register 1    (0=Off, 1=On)
  11    Interrupt Enable Reply Register 2    (0=Off, 1=On)
  12-15 DSP Memory Transfer (0=DSP/Data, 1=DSP/MMIO, 5=DSP/Code, 7=ARM/AHBM)

400430Ch - DSi9 - DSP_PSTS - DSP Status (R)
  0     Read Transfer Underway Flag    (0=No, 1=Yes/From DSP Memory)
  1     Write Transfer Underway Flag   (0=No, 1=Yes/To DSP Memory)
  2     Peripheral Reset Flag          (0=No/Ready, 1=Reset/Busy)
  3-4   Unused (0)
  5     Read FIFO Full Flag            (0=No, 1=Yes/Full)
  6     Read FIFO Not-Empty Flag       (0=No, 1=Yes, ARM9 may read PDATA)
  7     Write FIFO Full Flag           (0=No, 1=Yes/Full)
  8     Write FIFO Empty Flag          (0=No, 1=Yes/Empty)
  9     Semaphore IRQ Flag             (0=None, 1=IRQ)
  10    Reply Register 0 Update Flag   (0=Was Written by DSP, 1=No)
  11    Reply Register 1 Update Flag   (0=Was Written by DSP, 1=No)
  12    Reply Register 2 Update Flag   (0=Was Written by DSP, 1=No)
  13    Command Register 0 Read Flag   (0=Was Read by DSP, 1=No)
  14    Command Register 1 Read Flag   (0=Was Read by DSP, 1=No)
  15    Command Register 2 Read Flag   (0=Was Read by DSP, 1=No)
Unknown if/when bit10-15 get reset... maybe after reading the status... or when reading a reply or writing a new command?

4004310h - DSi9 - DSP_PSEM - ARM9-to-DSP Semaphore (R/W)
  0-15  ARM9-to-DSP Semaphore 0..15 Flags (0=Off, 1=On)
Reportedly these flags are sent in ARM9-to-DSP direction (=seems correct).
Confusingly, the other DSP_Pxxx registers are for opposite direction?

4004314h - DSi9 - DSP_PMASK - DSP-to-ARM9 Semaphore Mask (R/W)
  0-15  DSP-to-ARM9 Semaphore 0..15 Interrupt Disable (0=Enable, 1=Disable)

4004318h - DSi9 - DSP_PCLEAR - DSP-to-ARM9 Semaphore Clear (W)
  0-15  DSP-to-ARM9 Semaphore 0..15 Clear (0=No Change, 1=Clear/Ack)
Reportedly clears bits in DSP_PSEM/4004310h. [that's probably nonsense, clearing bits in DSP_SEM/400431Ch would make more sense?]

400431Ch - DSi9 - DSP_SEM - DSP-to-ARM9 Semaphore Data (R)
  0-15  DSP-to-ARM9 Semaphore 0..15 Flags (0=Off, 1=On)
Reportedly these flags are received in DSP-to-ARM9 direction.

4004320h - DSi9 - DSP_CMD0 - DSP Command Register 0 (R/W) (ARM9 to DSP)
4004328h - DSi9 - DSP_CMD1 - DSP Command Register 1 (R/W) (ARM9 to DSP)
4004330h - DSi9 - DSP_CMD2 - DSP Command Register 2 (R/W) (ARM9 to DSP)
  0-15  Command/Data to DSP

4004324h - DSi9 - DSP_REP0 - DSP Reply Register 0 (R) (DSP to ARM9)
400432Ch - DSi9 - DSP_REP1 - DSP Reply Register 1 (R) (DSP to ARM9)
4004334h - DSi9 - DSP_REP2 - DSP Reply Register 2 (R) (DSP to ARM9)
  0-15  Reply/Data from DSP

Further Teak related registers
SCFG_CLK, SCFG_RST, SCFG_EXT registers, MBK registers, and SNDEXCNT register.
DSi Control Registers (SCFG)
DSi New Shared WRAM (for ARM7, ARM9, DSP)
DSi Microphone and SoundExt
And, for the final audio output and microphone input,
DSi Touchscreen/Sound Controller


DSi Teak MMIO - Register Summary

I/O ports are mapped in "data memory" at 8000h-87FFh (2Kwords). All ports are 16bit wide, located at even word addresses (words at odd addresses seem to be always 0000h, except, there ARE some odd ports used at 806xh).

8000h Mirrors
  8000h..8002h 3300 3300 3300 R   Mirror of Port 80D6h
8004h JAM
  8004h        0000 0000 87FF R/W JAM Unknown
  8006h        ?    ?    ?    ??  JAM Unknown/Crash, DANGER (crashes on read)
  8008h..800Eh 3300 3300 3300 R   Mirror of Port 80D6h
8010h GLUE
  8010h        0000 0000 0003 R/W GLUE CFG0
  8012h        0000 0000 0003 R/W GLUE Unknown 2bit
  8014h        0000 0000 FFFF R/W GLUE Unknown 16bit
  8016h        0000 0000 0000 R   GLUE Unknown (DSi=0000h, New3DS=00BAh)
  8018h        0000 0000 BDEF R/W GLUE Whatever Parity/Shuffle
  801Ah        C902 C902 C902 R   GLUE Chip config ID (for xpert_offsets_tbl)
  801Ch..801Eh 0003 0003 0003 R   Mirror of port 8010h
8020h Timers
  8020h        0000 0000 7xDF R/W Timer 0 Control (bit11=DANGER)      ;\
  8022h        0000 0000 0000 W   Timer 0 Trigger Event/Watchdog      ;
  8024h        0000 0000 FFFF R/W Timer 0 Reload value, bit0-15       ; Timer 0
  8026h        0000 0000 FFFF R/W Timer 0 Reload value, bit16-31      ;
  8028h        0000 0000 0000 R   Timer 0 Counter value, bit0-15      ;
  802Ah        0000 0000 0000 R   Timer 0 Counter value, bit16-31     ;
  802Ch        0000 0000 FFFF R/W Timer 0 PWM Reload value, bit0-15   ;
  802Eh        0000 0000 FFFF R/W Timer 0 PWM Reload value, bit16-31  ;/
  8030h        0200 0200 7xDF R/W Timer 1 Control (bit11=DANGER)      ;\
  8032h        0000 0000 0000 W   Timer 1 Trigger Event/Watchdog      ;
  8034h        0000 0000 FFFF R/W Timer 1 Reload value, bit0-15       ; Timer 1
  8036h        0000 0000 FFFF R/W Timer 1 Reload value, bit16-31      ;
  8038h        0000 0000 0000 R   Timer 1 Counter value, bit0-15      ;
  803Ah        0000 0000 0000 R   Timer 1 Counter value, bit16-31     ;
  803Ch        0000 0000 FFFF R/W Timer 1 PWM Reload value, bit0-15   ;
  803Eh        0000 0000 FFFF R/W Timer 1 PWM Reload value, bit16-31  ;/
  8040h..804Eh 3300 3300 3300 R   Mirror of Port 80D6h
8050h Serial Port (SIO)
  8050h        7000 0000 F03F R/W SIO Control
  8052h        0000 0000 7F7F R/W SIO Clock Divider
  8054h        0000 0000 0000 R+W SIO Data (R) and (W)
  8056h        0000 0000 0001 R/W SIO Enable
  8058h        0000 0000 0000 R   SIO Status
  805Ah..805Eh F03F F03F F03F R   Mirror of port 8050h
8060h Debug (OCEM, On-chip Emulation Module)
  8060h        0105 0105 0105 R   OCEM Program Flow Trace Buffer, bit0-15
  8061h        0000 0000 0000 R   OCEM Program Flow Trace Buffer, bit16-31
  8062h        FFFF 0000 FFFF R/W OCEM Program Break Address 1, bit0-15
  8063h        0F03 0000 0F03 R/W OCEM Program Break Address 1, bit16-31
  8064h        FFFF 0000 FFFF R/W OCEM Program Break Address 2, bit0-15
  8065h        0F03 0000 0F03 R/W OCEM Program Break Address 2, bit16-31
  8066h        FFFF 0000 FFFF R/W OCEM Program Break Address 3, bit0-15
  8067h        0F03 0000 0F03 R/W OCEM Program Break Address 3, bit16-31
  8068h        00FF 0000 00FF R/W OCEM Program Break Counter 1
  8069h        00FF 0000 00FF R/W OCEM Program Break Counter 2
  806Ah        00FF 0000 00FF R/W OCEM Program Break Counter 3
  806Bh        FFFF 0000 FFFF R/W OCEM Data Break Mask
  806Ch        FFFF 0000 FFFF R/W OCEM Data Break Address
  806Dh        0000 0000      R/W OCEM Breakpoint Enable Flags (DANGER)
  806Eh        3001 0000 FFFF R/W OCEM Mode/Indication?
  806Fh        0000 0000 BFFF R/W OCEM Breakpoint Status Flags
  8070h        0000 0000 0001 R/W OCEM Program Flow Trace Update Disable
  8072h        0000 0000 FFFF R/W Unknown 16bit?
  8074h        C000 C000 C000 R   OCEM Boot/Debug Mode
  8076h..807Eh 0105 0105 0105 R   Mirror of port 8060h
8080h PLL and Power (PMU, Power Management Unit)
  8080h        C00E 0000 FFFF R/W PMU PLL Multiplier
  8082h        0001 0000 0001 R/W PMU PLL Power-on config
  8084h        8000           R/W PMU PLL Divider/Bypass (DANGER)
  8086h        0000           R/W PMU Wake/Shutdown Module(s)
  8088h        0000 0000 07BF R/W PMU Recover Module(s) on interrupt 0
  808Ah        0000 0000 07BF R/W PMU Recover Module(s) on interrupt 1
  808Ch        0000 0000 07BF R/W PMU Recover Module(s) on interrupt 2
  808Eh        0000 0000 07BF R/W PMU Recover Module(s) on vectored interrupt
  8090h        0000 0000 06BF R/W PMU Recover Module(s) on Timer 0 (no bit8)
  8092h        0000 0000 05BF R/W PMU Recover Module(s) on Timer 1 (no bit9)
  8094h        0000 0000 07BF R/W PMU Recover Module(s) on NMI
  8096h        0000 0000 0002 R/W PMU Recover DMA on external signal (bit1)
  8098h        0000 0000 0302 R/W PMU Breakpoint mask module(s) (bit1,8,9 only)
  809Ah        0000 0000 0003 R/W PMU Wake/Shutdown BTDMP(s)
  809Ch        0000 0000 0003 R/W PMU Recover BTDMP(s) on interrupt 0
  809Eh        0000 0000 0003 R/W PMU Recover BTDMP(s) on interrupt 1
  80A0h        0000 0000 0003 R/W PMU Recover BTDMP(s) on interrupt 2
  80A2h        0000 0000 0003 R/W PMU Recover BTDMP(s) on vectored interrupt
  80A4h        0000 0000 0003 R/W PMU Recover BTDMP(s) on Timer 0
  80A6h        0000 0000 0003 R/W PMU Recover BTDMP(s) on Timer 1
  80A8h        0000 0000 0003 R/W PMU Recover BTDMP(s) on NMI (undoc?)
  80AAh        0000 0000 FFFF R/W Unknown 16bit
  80ACh        0000 0000 FFFF R/W Unknown 16bit
  80AEh        0000 0000 FFFF R/W Unknown 16bit
  80B0h..80BEh FFFF FFFF FFFF R   Mirror of port 8080h
80C0h APBP (aka HPI Host Port Interface)
  80C0h        xxxx xxxx xxxx R/W APBP DSP-to-ARM Reply 0
  80C2h        4300 4300 4300 R   APBP ARM-to-DSP Command 0
  80C4h        0000 0000 FFFF R/W APBP DSP-to-ARM Reply 1
  80C6h        3123 3123 3123 R   APBP ARM-to-DSP Command 1
  80C8h        0000 0000 FFFF R/W APBP DSP-to-ARM Reply 2
  80CAh        3223 3223 3223 R   APBP ARM-to-DSP Command 2
  80CCh        0000 0000 FFFF R/W APBP DSP-to-ARM Semaphore Set Flags
  80CEh        0000           R/W APBP ARM-to-DSP Semaphore Interrupt Mask
  80D0h        0000           W?  APBP ARM-to-DSP Semaphore Ack Flags
  80D2h        AFFE AFFE AFFE R   APBP ARM-to-DSP Semaphore Get Flags
  80D4h        0000           R/W APBP Control (DANGER: can crash cpu)
  80D6h        03C0 03C0 03C0 R   APBP DSP-side Status
  80D8h        3B00 3B00 3B00 R   APBP ARM-side Status (mirror of 400430Ch)
  80DAh..80DEh 0000 0000 0000 R   Fixed 0000h
80E0h Bus Config for DMA to external ARM-bus (AHBM)
  80E0h        0000 0000 0000 R   AHBM Status
  80E2h+N*6    0000 0000 0FBF R/W AHBM Channel 0..2 Configure Burst/Data
  80E4h+N*6    0000 0000 03FF R/W AHBM Channel 0..2 Configure Whatever
  80E6h+N*6    0000 0000 00FF R/W AHBM Channel 0..2 Configure DMA
  80F4h        0000 0000 FC00 R/W Unknown 6bit? bit10-15 are used
  80F6h        0000 0000 0000 R?  AHBM Internal FIFO (R) and maybe also (W?)
  80F8h        0000 0000 0000 R?  Unknown always zero?
  80FAh        0000 0000 FFFF R/W Read/write-able(!) mirror of MMIO[80FCh]
  80FCh        FFFF 0000 FFFF R/W Unknown 16bit?
  80FEh        0000 0000 FFFF R/W Unknown 16bit?
8100h MIU (memory limits for X-,Y-,Z-Space, and Memory Mapped I/O base)
  8100h        FFFF 0000 FFFF R/W MIU Waitstate Settings, bit0-15
  8102h        0FFF 0000 0FFF R/W MIU Waitstate Settings, bit16-31
  8104h        0000 0000 FFFF R/W MIU Waitstate Area Z0
  8106h        0000 0000 FFFF R/W MIU Waitstate Area Z1
  8108h        0000 0000 FFFF R/W MIU Waitstate Area Z2
  810Ah        0000 0000 FFFF R/W MIU Waitstate Area Z3
  810Ch        0014 0014 0014 R   Mirror of port 811Ah
  810Eh        0000 0000 FFFF R/W MIU X Page (16bit) (or unused)
  8110h        0000 0000 00FF R/W MIU Y Page (8bit)  (or unused)
  8112h        0000           R/W MIU Z Page (16bit) (or absolute page)(DANGER)
  8114h        1E20           R/W MIU X/Y Page Size for Page 0 (or all pages)
  8116h        1E20 0100 403F R/W MIU X/Y Page Size for Page 1 (or unused)
  8118h        1E20 0100 403F R/W MIU X/Y Page Size for Off-chip (or unused)
  811Ah        0014 00x4      R/W MIU Config for Misc stuff (DANGER)
  811Ch        0004 0000 007F R/W MIU Config for Program Page and Download Mem
  811Eh        8000           R/W MIU Base Address for MMIO Registers (DANGER)
  8120h        0000 0000 000F R/W MIU Observability Mode
  8122h        0000 0000 007F R/W MIU Pin Config?
  8124h..813Eh 0014 0014 0014 R   Mirror of port 811Ah
8140h Patch (CRU, Code Replacement Unit)
  8140h+N*4    0000 0000 FFFF R/W CRU Entry 0..14 Offset, bit0-15
  8142h+N*4    0000 0000 803F R/W CRU Entry 0..14 Offset, bit16-31
  817Ch        0000 0000 FFFF R/W CRU Entry 15 Offset, bit0-15  ;\with control
  817Eh        0000 0000 C03F R/W CRU Entry 15 Offset, bit16-31 ;/status bits
8180h DMA (eight channels, port 81C0h..81Exh are bank-switched via 81BEh)
  8180h        0000 0000 0000 R   DMA Internal: Channel Size0 Busy or so?
  8182h        0000 0000 0000 R   DMA Internal: Channel Size1 Busy or so?
  8184h        0001 0000 00FF R/W DMA Channel Start Flags (1=Start/Busy)
  8186h        0000 0000 00FF R/W DMA Channel Pause Flags (1=Pause)
  8188h        0000 0000 0000 R   DMA Channel End Flags for Size0
  818Ah        0000 0000 0000 R   DMA Channel End Flags for Size1
  818Ch        0000 0000 0000 R   DMA Channel End Flags for Size2 (all done)
  818Eh        3210 0000 7777 R/W DMA Whatever Slot Config, bit0-15
  8190h        7654 0000 7777 R/W DMA Whatever Slot Config, bit16-31
  8192h        0000 0000 7C03 R/W Unknown, R/W mask 7C03h
  8194h        0000 0000 0000 R   DMA Internal: contains SRC_ADDR_L after DMA
  8196h        0000 0000 0000 R   DMA Internal: contains DST_ADDR_L after DMA
  8198h..81B4h 0000 0000 0000 R   Fixed 0000h
  81B6h        0000 0000 FFFF R/W Unknown, 16bit
  81B8h        0000 0000 FFFF R/W Unknown, 16bit
  81BAh        0000 0000 FFFF R/W Unknown, 16bit
  81BCh        0000 0000 FFFF R/W Unknown, 16bit
  81BEh        0000 0000 0007 R/W DMA Select Channel (bank for 81C0h-81Exh)
  81C0h:0..7   0000 0000 FFFF R/W DMA Channel: Source Address, bit0-15
  81C2h:0..7   0000 0000 FFFF R/W DMA Channel: Source Address, bit16-31
  81C4h:0..7   0000 0000 FFFF R/W DMA Channel: Destination Address, bit0-15
  81C6h:0..7   0000 0000 FFFF R/W DMA Channel: Destination Address, bit16-31
  81C8h:0..7   FFFF 0001 FFFF R/W DMA Channel: Size0 (usually total len)
  81CAh:0..7   0001 0001 FFFF R/W DMA Channel: Size1 (usually 1)
  81CCh:0..7   0001 0001 FFFF R/W DMA Channel: Size2 (usually 1)
  81CEh:0..7   0001 0000 FFFF R/W DMA Channel: Source Step0      ;-2,4,2,1
  81D0h:0..7   0001 0000 FFFF R/W DMA Channel: Source Step1      ;-4,2,2,1
  81D2h:0..7   0001 0000 FFFF R/W DMA Channel: Source Step2      ;-2,4,0,1
  81D4h:0..7   0001 0000 FFFF R/W DMA Channel: Destination Step0 ;-4,2,0,1
  81D6h:0..7   0001 0000 FFFF R/W DMA Channel: Destination Step1 ;-0,0,0,1
  81D8h:0..7   0001 0000 FFFF R/W DMA Channel: Destination Step2 ;-0,0,0,1
  81DAh:0..7   F200 0000 F7FF R/W DMA Channel: Memory Area Config
  81DCh:0..7   0000 0000 1FF7 R/W DMA Channel: Unknown, usually set to 0300h?
  81DEh:0..7   0000 0000 00FF R/W DMA Channel: Start/Stop/Control
  81E0h:0..7   0000 0000 0000 R   DMA Internal: contains SRC_ADDR_L after DMA
  81E2h:0..7   0000 0000 0000 R   DMA Internal: contains DST_ADDR_L after DMA
  81E4h:0..7   0000 0000 0000 R   DMA Internal: contains SRC_ADDR_H after DMA
  81E6h:0..7   0000 0000 0000 R   DMA Internal: contains DST_ADDR_H after DMA
  81E8h..81FEh 0000 0000 0000 R   Fixed 0000h
8200h ICU (interrupts)
  8200h        4020 4020 4020 R   ICU Interrupt Pending Flags  (1=Pending)
  8202h        0000 0000 0000 W   ICU Interrupt Acknowledge    (1=Clear)
  8204h        0000 0000 FFFF R/W ICU Interrupt Manual Trigger (1=Set)
  8206h        0000 0000 FFFF R/W ICU Enable Interrupt as int0 (1=Enable)
  8208h        0000 0000 FFFF R/W ICU Enable Interrupt as int1 (1=Enable)
  820Ah        0000 0000 FFFF R/W ICU Enable Interrupt as int2 (1=Enable)
  820Ch        0000 0000 FFFF R/W ICU Enable Interrupt as vint (1=Enable)
  820Eh        2000 0000 FFFF R/W ICU Interrupt Trigger mode (0=Level, 1=Edge)
  8210h        2000 0000 FFFF R/W ICU Interrupt Polarity (0=Normal, 1=Invert)
  8212h+N*4    0003 0000 8003 R/W ICU Vectored Interrupt 0..15 Addr, bit16-31
  8214h+N*4    FC00 0000 FFFF R/W ICU Vectored Interrupt 0..15 Addr, bit0-15
  8252h        0000 0000 FFFF R/W ICU Interrupt Master Disable (1=Off/undoc)
  8254h        0000 0000 5555 R/W Unknown, R/W mask 5555h
  8256h        0000 0000 5555 R/W Unknown, R/W mask 5555h
  8258h..827Eh 0000 0000 0000 R   Mirror of Port 8200h
8280h BTDMP Audio (two channels N=0..1, each with speaker out and mic in)
  8280h+N*80h  0005 0000 FFFF R/W BTDMP Receive Control         ;\
  8282h+N*80h  0000 0000 7FE7 R/W BTDMP Receive Period          ;
  8284h+N*80h  0000 0000 0FE7 R/W BTDMP Receive Usually 0004h   ;
  8286h+N*80h  0000 0000 0003 R/W BTDMP Receive Usually 0021h   ; RX
  8288h+N*80h  1FFF 0000 1FFF R/W BTDMP Receive Usually 0000h   ; (microphone)
  828Ah+N*80h  0000 0000 0FFF R/W BTDMP Receive Usually 0000h   ;
  828Ch+N*80h  0000 0000 3FFF R/W BTDMP Receive Usually 0000h   ;
  828Eh+N*80h  0000 0000 FFFF R/W BTDMP Receive Usually unused  ;
  8290h+N*80h  0000 0000 FFFF R/W BTDMP Receive Usually unused  ;
  8292h+...    0000 0000 0000 R   Fixed 0000h                   ;
  829Eh+N*80h  0000 0000 8000 R/W BTDMP Receive Enable          ;/
  82A0h+N*80h  0005 0000 FFFF R/W BTDMP Transmit Control        ;\
  82A2h+N*80h  0000 0000 7FE7 R/W BTDMP Transmit Period         ;
  82A4h+N*80h  0000 0000 0FE7 R/W BTDMP Transmit Usually 0004h  ;
  82A6h+N*80h  0000 0000 0003 R/W BTDMP Transmit Usually 0021h  ; TX
  82A8h+N*80h  1FFF 0000 1FFF R/W BTDMP Transmit Usually 0000h  ; (audio out)
  82AAh+N*80h  0000 0000 0FFF R/W BTDMP Transmit Usually 0000h  ;
  82ACh+N*80h  0000 0000 3FFF R/W BTDMP Transmit Usually 0000h  ;
  82AEh+N*80h  0000 0000 FFFF R/W BTDMP Transmit Usually unused ;
  82B0h+N*80h  0000 0000 FFFF R/W BTDMP Transmit Usually unused ;
  82B2h+...    0000 0000 0000 R   Fixed 0000h                   ;
  82BEh+N*80h  0000 0000 8000 R/W BTDMP Transmit Enable         ;/
  82C0h+N*80h  001x 001F 001F R   BTDMP Receive FIFO Status     ;\
  82C2h+N*80h  0057 005x 0057 R   BTDMP Transmit FIFO Status    ;
  82C4h+N*80h  E0A1 FFFF E0A1 R   BTDMP Receive FIFO Data       ; RX/TX
  82C6h+N*80h  0000 0000 0000 W   BTDMP Transmit FIFO Data      ;
  82C8h+N*80h  0000 0000 0003 R/W BTDMP Receive FIFO Control    ;
  82CAh+N*80h  0000 0000 0003 R/W BTDMP Transmit FIFO Control   ;/
  82CCh+...    0000 0000 0000 R   Fixed 0000h
  8380h..867Eh 03C0 03C0 03C0 R   Mirror of Port 80D6h
8680h ? (listed in "xpert_offsets_tbl", but there are just mirrors)
  8680h..87FEh 03C0 03C0 03C0 R   Mirror of Port 80D6h
8800h ? (listed in "perxteak.per", but seems to be always 0) (dbg aka H2C)
  (this is called "Host-to-Core JAM protocol" and consists of 11bit values)
  (not sure if that are MMIO registers, or some 11bit data transfer protocol)
  8800h..8807h 0000 0000 0000 R?  Fixed 0 (reportedly H2C aka dbg stuff?)

xpert_offsets_tbl: (with baseIO=8000h)
The DSi's aac.a file contains a "xpert_offsets_tbl" with three sets of I/O regions, which are apparently related to different hardware versions:
     ?    JAM  GLUE TMR  SIO  OCEM PMU  APBP AHBM MIU  CRU  DMA  ICU AUDIO ?
  #0 3333 0000 0010 0020 0050 0060 0080 00A0 3333 00C0 3333 0100 0180 0200 3333
  #1 0000 0004 0010 0020 0050 0060 0080 00C0 00E0 0100 0140 0180 0200 0280 0680
  #2 3333 0004 0010 3333 3333 0020 0040 3333 3333 0060 3333 3333 0120 3333 3333
All addresses are relative to the MMIO base (usually 8000h), 3333h is apparently some dummy value for unsupported I/O areas.
The DSi does use set #1. The other two sets are probably relicts for older Teak hardware that was never used in DSi consoles (for example, set #2 doesn't event support the APBP region for cmd/reply/semaphore).


DSi Teak MMIO[8000h] - Misc Registers (JAM/GLUE)

MMIO[8004h] - JAM Unknown (R/W)
  0-10  Unknown (R/W) (0..7FFh=?)
  11-14 Unused (0)
  15    Unknown (R/W) (0..1=?)
Maybe this is for the 11bit "Host-to-Core JAM protocol"?

MMIO[8006h] - JAM Unknown/Crash, DANGER (crashes on read)
Crashes on read.

MMIO[8010h] - GLUE CFG0 (R/W)
GLUE_CFG0 - Number of wait-states for Z-space transactions in predefined zones
Uh, the above name does not match up with below descriptions?
  0     Timer 1 clock source (0=107MHz/Core, 1=Timer0_TOUT)
  1     Timer 0 force restart upon Timer 1 output (0=No, 1=Yes)
  2-15  Unused (0)

MMIO[8012h] - GLUE Unknown 2bit (R/W)
  0-1   Unknown (R/W) (0..3=?)
  2-15  Unused (0)

MMIO[8014h] - GLUE Unknown 16bit (R/W)
  0-15  Unknown (R/W) (0..FFFFh=?)

MMIO[8016h] - GLUE Unknown, DSi=0000h or New3DS=00BAh (R)
  0-15  Unknown (DSi: always 0000h, New3DS: always 00BAh)

MMIO[8018h] - GLUE Whatever Parity/Shuffle (R/W)
  0-3   Value A                                         (R/W)
  4     All four bits in Value A XORed together         (R)
  5-8   Value B                                         (R/W)
  9     All four bits in Value B XORed together         (R)
  10-13 Value C                                         (R/W)
  14    All four bits in Value C XORed together         (R)
  15    Value D                                         (R/W)
Unknown purpose, might be a randomizer/maths feature, or an interactive chip-detection feature, or something completely different, like memory-control function, or whatever.

MMIO[801Ah] - GLUE Chip config ID (R)
  0-15  Fixed, always C902h on DSi and New3DS
Used for chip detect (for xpert_offsets_tbl).

More Unknown Registers
XpertTeak was announced to support GPIO, unknown where those registers are located. Probably consist of 16bit direction and 16bit data registers (if it's similar as in older Oak chips). A few GPIO-style bits seem to be in st2/mod0/mod3 CPU registers.

Unknown what below is... maybe MMIO[8800h..8807h] or maybe 11bit values for JAM registers at MMIO[8004h..8006h]... and/or Input-only direction GPIO?

[dbg:800h] - H2C Host-to-Core JAM protocol h2c_0
  0     Reset                                           (0=No, 1=Yes)
  1     Boot                                            (0=No, 1=Yes)
  2     Debug                                           (0=No, 1=Yes)
  4     URST (user reset)                               (0=No, 1=Yes)
  5     -
  6     Internal Program (Load code to on-chip memory)  (0=No, 1=Yes)
  7-10  -

[dbg:801h] - H2C Host-to-Core JAM protocol h2c_1
  0-6   -
  7     Continue core's clock after stopped by software (0=No, 1=Yes)
  8     Stop (Stop core's clock)                        (0=No, 1=Yes)
  9     NMI                                             (0=No, 1=Yes)
  10    Abort                                           (0=No, 1=Yes)

[dbg:802h] - H2C Host-to-Core JAM protocol h2c_2
  0-10  Interrupt 0..10                                 (0=No, 1=Yes)

[dbg:803h] - H2C Host-to-Core JAM protocol h2c_3
  0-10  GPI (General Purpose Input) 0..10               (0=Low, 1=High)

[dbg:804h] - H2C Host-to-Core JAM protocol h2c_4
  0-4   GPI (General Purpose Input) 11..15              (0=Low, 1=High)
  5-8   -
  9-10  UI (User Input) 0..1                            (0=Low, 1=High)

[dbg:805h] - H2C Host-to-Core JAM protocol h2c_5
  0-10  Interrupt external/internal control 0..10       (0=Ext, 1=Int)

[dbg:806h] - H2C Host-to-Core JAM protocol h2c_6
  0-10  GPI Enable Control 0..10                        (0=Disable, 1=Enable)

[dbg:807h] - H2C Host-to-Core JAM protocol h2c_7
  0-4   GPI Enable Control 11..15                       (0=Disable, 1=Enable)
  5-8
  9-10  User Input Enable Control 0..1                  (0=Disable, 1=Enable)


DSi Teak MMIO[8020h] - Timers (TMR)

MMIO[8020h/8030h] - Timer 0/1 Control (R/W)
  0-1   Time prescaler (0=Div1, 1=Div2, 2=Div4, 3=Div16)
  2-4   Count mode
         0h: single count     Stop at zero
         1h: auto restart     Wrap from zero to Reload value
         2h: free running     Wrap from zero to FFFFFFFFh
         3h: event count      Decrement manually, and stop at zero
         4h: watchdog mode 1  Trigger Teak Reset at zero
         5h: watchdog mode 2  Trigger Teak NMI at zero
         6h: watchdog mode 3  Trigger Unacknowledgeable-Timer-IRQ at zero?
         7h: reserved         Same as mode 0 (stop at zero)
  5     Unused (0)
  6     Output signal polarity                (0=Normal, 1=Invert/Buggy?)
  7     Clear output signal; when bit14-15=0  (0=No change, 1=Clear)   (W)
  8     Pause the counter                     (0=Unpause, 1=Pause)
  9     Freeze COUNTER_L/H register value     (0=Freeze, 1=Update)
         Note: Bit8/Bit9 can be forced to always 1 via other Timer's Bit13
  10    Restart/Reload the counter            (0=No change, 1=Restart) (W)
  11    Breakpoint requests enable   (0=Disable, 1=Enable) (DANGER/TRAP)
  12    Clock source (0=InternalClk=134MHz/107MHz, 1=ExternalClk=None)
  13    General Purpose (somehow interact between Timer 0 and 1)
         Timer0: Force Timer1.Control.Bit9=1  (0=No, 1=Yes/ForceUpdate)
         Timer1: Force Timer0.Control.Bit8=1  (0=No, 1=Yes/ForcePause)
  14-15 Clear output signal automatically (0=No, 1/2/3=After 2/4/8 cycles)
The InternalClk is different for Timer 0 and 1, and depends on GLUE setting:
  For Timer 0 (no "waitstates")   --> 134.055928MHz
  For Timer 1 (with "waitstates") --> 107.244742MHz (aka 134.055928MHz/1.25)
  For Timer 1 (if GLUE_CFG0.bit0) --> Timer0_TOUT (bugs if Timer0_Reload<3)
  Unknown what "waitstates" refers to, probably not the Z0/Z1/Z2/Z3 waits?
Bit10 is automatically cleared after writing - however, when using prescaler other than Div1, it may take a few cycles until bit10 gets cleared (and perhaps also takes time until it is processed??? if so, one shouldn't clear bit10 in that timeslot).
Bit7 is usually cleared after writing - but not always, still unknown what/when that happens?

MMIO[8022h/8032h] - Timer 0/1 Trigger Event/Watchdog (W)
  0     In Event Mode: Decrement Counter (0=No change, 1=Decrement)
        In Watchdog Mode: Reload Counter (0=No change, 1=Reload)
  1-15  Unused (0)

MMIO[8024h/8034h] - Timer 0/1 Reload value, bit0-15 (R/W)
MMIO[8026h/8036h] - Timer 0/1 Reload value, bit16-31 (R/W)
  0-31  Start/Reload value for decrementing counter
Used as start/reload value; copied to counter when setting Control.bit10, or after reaching 0 in auto-restart mode, or when writting trigger bit in watchdog mode.
Not used in free-run mode (which starts at current counter value, and wraps from 0 to FFFFFFFFh).

MMIO[8028h/8038h] - Timer 0/1 Counter value, bit0-15 (R)
MMIO[802Ah/803Ah] - Timer 0/1 Counter value, bit16-31 (R)
  0-31  Current (or frozen) decrementing counter value
When using freeze, counter keeps decreasing in background, but reading the counter register returns the frozen value (latched when changing Control.bit9 from 1-to-0).

MMIO[802Ch/803Ch] - Timer 0/1 PWM Reload value, bit0-15 (R/W)
MMIO[802Eh/803Eh] - Timer 0/1 PWM Reload value, bit16-31 (R/W)
  0-31  Restart value for PWM counter (uh, maybe PWM duty?)
Unknown if/when/how this is used (maybe just goes to an unimplemented PWM output pin).


DSi Teak MMIO[8050h] - Serial Port (SIO)

This is a SPI-style serial I/O interface, allowing to connect some peripheral or debugging hardware (unused in DSi/3DS).

MMIO[8050h] - SIO Control (R/W)
  0     Chip Select Polarity       (0=Active High, 1=Active Low)
  1     Chip Select Output         (0=Disable/Hangs, 1=Enable) (for Master)
  2     Master/Slave Clock         (0=FromClkDivider, 1=ExternalClk/Hangs)
  3     Clock Polarity             (0=Idle Low, 1=Idle High)
  4     Clock Edge Phase           (0=InputOnRising, 1=OutputOnRising)
  5     Transfer End Interrupt     (0=Enable, 1=Disable/Hangs/NoStatusDone)
  6-11  Unused (0)
  12-15 Num data bits per transfer (0=Hangs, 1..15=2bit..16bit)

MMIO[8052h] - SIO Clock Divider (R/W)
  0-6   Clock Divider 1            (1..7Fh = Div1..Div127) (0=Div1, too)
  7     Unused (0)
  8-14  Clock Divider 2            (1..7Fh = Div1..Div127) (0=Div1, too)
  15    Unused (0)
The transfer shift clock is 134MHz/(Divider1*Divider2).

MMIO[8054h] - SIO Data (R) and (W)
  0-15  Transfer data (probably using only LSBs when NumBits<16)
Writing the transmit data starts the transfer, the reply data can be read when Transfer Done status flag gets set.

MMIO[8056h] - SIO Enable (R/W)
  0     Enable SIO operation       (0=Disable/Hangs, 1=Enable)
  1-15  Unused (0)

MMIO[8058h] - SIO Status (R)
  0     Transfer done   (0=No, 1=Done, Data can be read now)
  1     Overrun error   (0=No, 1=New data arrived before reading old data)
  2-15  Unused (0)
Bit0,1 are automatically cleared after reading the status register.

SIO Transfer Timing Bugs
After transfer end, one must apparently wait at least "Divider1*Divider2/2" cycles before starting another transfer, else the new transfer won't start.
There are two dummy transfer clocks inserted (so transferring 2..16 bits does actually take "(4..18)*Divider1*Divider2" cycles).
And, transfer start doesn't seem to take place until next clock boundary (that may take between "0 and 0.999*Divider1*Divider2" extra cycles).


DSi Teak MMIO[8060h] - Debug (OCEM, On-chip Emulation Module)

MMIO[8060h] - OCEM Program Flow Trace Buffer (PFT), bit0-15 (R)
MMIO[8061h] - OCEM Program Flow Trace Buffer (PFT), bit16-31 (R)
This buffer contains addresses of the 16 most recent jump opcodes, reading returns the oldest of those 16 addresses (or 16 random address/page values if read after reset). One can disable buffer updating via MMIO[8070h] (eg. to avoid jumps inside of a debug handler to be written to the buffer). There is "buffer full" condition that gets set 16 jumps after reset, and that can trap an optional buffer full exception.
  0-17   Program Flow Trace Address
  18-23  Unused (0)
  24-27  Program Flow Trace Page
  28-31  Unused (0)
Unknown if there is any way to "make the buffer empty", either by clearing the buffer, or by removing entries until it gets empty. Also, there is no known way to read the next buffer entry, except for one trick: temporarily re-enable buffer updates via MMIO[8070h] and issue a dummy jump; this will add a new entry, and reading will then return the next oldest entry; by that, the buffer won't get empty (but, when ignoring the address of the dummy jump, one can extract the actual non-dummy data from the buffer).

MMIO[8062h/8064h/8066h] - OCEM Program Break Address 1/2/3, bit0-15 (R/W)
MMIO[8063h/8065h/8067h] - OCEM Program Break Address 1/2/3, bit16-31 (R/W)
  0-17   Program Break Address
  18-23  Unused (0)
  24-27  Program Break Page (should be usually 00h)
  28-31  Unused (0)

MMIO[8068h/8069h/806Ah] - OCEM Program Break Counter 1/2/3 (R/W)
  0-7    Program Address Break Counter (decrements upon PC=break.addr)
  8-15   Unused (0)
Break triggers upon count zero. Writing count=NNh will trap after program counter had hit the break address NNh times (writing count=00h will trigger immediately, without even hitting the break address).

MMIO[806Bh] - OCEM Data Break Mask (R/W)
MMIO[806Ch] - OCEM Data Break Address (R/W)
  0-15   Mask/Address

MMIO[806Dh] - OCEM Breakpoint Enable Flags DANGER (0=Disable, 1=Enable/Trap)
  0      Data value break point on data write transaction
  1      Data value break point on data read transaction
  2      Data address break point as a result on data write transaction
  3      Data address break point as a result on data read transaction
  4      Simultaneous data address and data value match
  5      External register write transaction  ;\(aka ext0/1/2/3?)
  6      External register read transaction   ;/
  7      Program Address break 1 count zero
  8      Program Address break 2 count zero
  9      Program Address break 3 count zero
  10     Break on any program jumps instead of executing the next address
  11     Break on detection of interrupt service routine
  12     Break as a result of program flow trace buffer full
  13     Break when returning to the beginning of block repeat loop
  14     Break on illegal condition (uh, are that... illegal opcodes?)
  15     Single Step
Note: Data value refers to the "dvm" CPU-core register. Data write matches can occur on things like "mov r0,1234h" or "addv r0,1" (when r0 becomes equal to dvm).

MMIO[806Eh] - OCEM Mode/Indication? (R/W)
  0      Program Flow Trace Buffer full (0=Not full/OldestIsGarbage, 1=Full)
  1-11   Unknown (R/W)
  12     MOVD instruction detected (uh, usually 1, even when not using movd?)
  13     User reset activated while in break point service routine
  14     Boot mode   (0=No, 1=Yes)
  15     Debug mode  (0=No, 1=Yes)
Unknown if this is a mode or status register, or mixup thereof?

MMIO[806Fh] - OCEM Breakpoint Status Flags (R/W)
  0      Break caused by Data value match
  1      Break caused by Data address match
  2      Break caused by Data value and data address match
  3      Break caused by User defined register transaction (aka ext0/1/2/3?)
  4      Break caused by an external event (aka what?)
  5      Break caused by Program address break 1 count zero
  6      Break caused by Program address break 2 count zero
  7      Break caused by Program address break 3 count zero
  8-10   Unknown (R/W)
  11     Break caused by Branch break point
  12     Break caused by Interrupt break point
  13     Break caused by Program Flow Trace Buffer full
  14     Break caused by Illegal break point
  15     Break caused by Software trap
Uh, R/W mask is BFFFh, ie. bit14 is always 0, that doesn't match up with above description?

MMIO[8070h] - OCEM Program Flow Trace Update Disable (R/W)
  0      Disable Program Flow Buffer Updating (0=Enable, 1=Disable)
  1-15   Unused (0)

MMIO[8072h] - Unknown 16bit? (R/W)
  0-15   Unknown (R/W)
Maybe be "programming model signature" mentioned in perxteak.per (though that is claimed to use only upper 8bit)? That signature might be some general purpose value to notify the debugger what kind of code is executed?

MMIO[8074h] - OCEM Boot/Debug Mode (R)
  0-13   Unused? (0)
  14     Boot mode   (0=No, 1=Yes)
  15     Debug mode  (0=No, 1=Yes)
Usually contains the same mode bits as written to MMIO[806Eh].bit14/bit15 (maybe one of the registers contains the OLD mode bits; when entering a debug handler or so).


DSi Teak MMIO[8080h] - PLL and Power (PMU, Power Management Unit)

MMIO[8080h] - PMU PLL Multiplier (R/W)
  0-15  Configuration of the PLL clock multiplication (0..FFFFh=what?)
Power-up: C00Eh. Unknown what that does... multiplying clock by 16bit seems unlikely. Maybe alike CCR2 register in files peroak.per and pertklc.per?
Or maybe 0Ch and 0Eh translate to (14+1):12 ratio (ie. the 134MHz/1.25 divider; though changing this register doesn't seem to affect that)?

MMIO[8082h] - PMU PLL Power-on config (R/W)
  0     PLL power-on configuration value for PLL use (0..1=what)
  1-15  Unused (0)
Power-up: 0001h. Unknown what that is. Default value for PLB bit in next register? Or maybe something needed for powering-up the PLL (when clearing bypass flag)?

MMIO[8084h] - PMU PLL Divider/Bypass (R/W?)
  0-6   Clock Divider (0 or 1=Div1) (2..7Fh=Crashes?)
  7-14  Unused (0)
  15    Bypass PLL    (0=Use PLL/Crashes, 1=Bypass; works only if Div1)
Power-up: 8000h. Ie. PLL bypassed, and using 134MHz clock from DSi as is.
Unknown how to change/enable the PLL without crashing.

MMIO[8086h,809Ah] - PMU Wake/Shutdown module(s) (0=Wake-up, 1=Shutdown) (R/W)
MMIO[8088h,809Ch] - PMU Recover module(s) on interrupt 0 (R/W)
MMIO[808Ah,809Eh] - PMU Recover module(s) on interrupt 1 (R/W)
MMIO[808Ch,80A0h] - PMU Recover module(s) on interrupt 2 (R/W)
MMIO[808Eh,80A2h] - PMU Recover module(s) on vectored interrupt (R/W)
MMIO[8090h,80A4h] - PMU Recover module(s) on Timer 0 (except bit8) (R/W)
MMIO[8092h,80A6h] - PMU Recover module(s) on Timer 1 (except bit9) (R/W)
MMIO[8094h,80A8h] - PMU Recover module(s) on non-maskable interrupt (R/W)
MMIO[8096h] - PMU Recover DMA module on external signal (bit1 only) (R/W)
 For registers MMIO[8086h..8096h]:
  0     Core     ;aka cpu?
  1     DMA
  2     SIO
  3     GLUE
  4     APBP/HPI
  5     AHBM
  6     Unused (0)
  7     OCEM
  8     Timer 0
  9     Timer 1
  10    JAM
  11-15 Unused (0)
 For registers MMIO[809Ah..80A8h]:
  0     BTDMP 0
  1     BTDMP 1
  2-15  Unused (0)
Register 8090h.bit8 and 8092h.bit9 are unused, always 0 (ie. a disabled timer cannot wakeup itself).
Register 8096h supports bit1 only (DMA), all other bits are unused, always 0.

MMIO[8098h] - BM: PMU Breakpoint mask module(s) (bit1,8,9 only) (R/W)
  0     Unused (0)
  1     DMA
  2-7   Unused (0)
  8     Timer 0
  9     Timer 1
  10-15 Unused (0)
Unknown what this does. It looks similar to the "Recover" registers, but, going by the description, it is "breakpoink masking" something instead of "recovering".

MMIO[80AAh] - 16bit R/W ?
MMIO[80ACh] - 16bit R/W ?
MMIO[80AEh] - 16bit R/W ?


DSi Teak MMIO[80C0h] - Host Port Interface (APBP aka HPI)

The APBP (aka HPI Host Port Interface) registers are used to communicate between ARM and DSP.

MMIO[80C0h/80C4h/80C8h] - APBP DSP-to-ARM Reply 0/1/2 (R/W)
MMIO[80C2h/80C6h/80CAh] - APBP ARM-to-DSP Command 0/1/2 (R)
  0-15   Command/Reply Data

MMIO[80CCh] - APBP DSP-to-ARM Semaphore Set Flags (0=Clear, 1=Set) (R/W)
MMIO[80CEh] - APBP ARM-to-DSP Semaphore Interrupt Mask (?=On/Off) (R/W)
MMIO[80D0h] - APBP ARM-to-DSP Semaphore Ack Flags (0=No change, 1=Clear) (W?)
MMIO[80D2h] - APBP ARM-to-DSP Semaphore Get Flags (R)
  0-15   Semaphore Flag 0..15

MMIO[80D4h] - APBP Control (R/W)
  0-1    Unused (0)
  2      ARM-side register endianness (0=Normal, 1=Big-Endian/DANGER)
  3-7    Unused (0)
  8      Interrupt when CMD0 is written by ARM (0=Enable, 1=Disable)
  9-11   Unused (0)
  12     Interrupt when CMD1 is written by ARM (0=Enable, 1=Disable)
  13     Interrupt when CMD2 is written by ARM (0=Enable, 1=Disable)
  14-15  Unused (0)

MMIO[80D6h] - APBP DSP-side Status (R)
  0-4    Unused? (usually 0)
  5      Reply Register 0 Read Flag     (0=Was Read by ARM?, 1=No)
  6      Reply Register 1 Read Flag     (0=Was Read by ARM?, 1=No)
  7      Reply Register 2 Read Flag     (0=Was Read by ARM?, 1=No)
  8      Command Register 0 Update Flag (0=Was Written by ARM?, 1=No)
  9      Semaphore IRQ Flag             (0=No, 1=[80D2h] AND NOT [80CEh])
  10-11  Unused? (usually 0)
  12     Command Register 1 Update Flag (0=Was Written by ARM?, 1=No)
  13     Command Register 2 Update Flag (0=Was Written by ARM?, 1=No)
  14-15  Unused? (usually 0)

MMIO[80D8h] - APBP ARM-side Status (mirror of ARM9 Port 400430Ch) (R)
  0      Read Transfer Underway Flag    (0=No, 1=Yes/From DSP Memory)
  1      Write Transfer Underway Flag   (0=No, 1=Yes/To DSP Memory)
  2      Peripheral Reset Flag          (0=No/Ready, 1=Reset/Busy)
  3-4    Unused (0)
  5      Read FIFO Full Flag            (0=No, 1=Yes/Full)
  6      Read FIFO Not-Empty Flag       (0=No, 1=Yes, ARM9 may read PDATA)
  7      Write FIFO Full Flag           (0=No, 1=Yes/Full)
  8      Write FIFO Empty Flag          (0=No, 1=Yes/Empty)
  9      Semaphore IRQ Flag             (0=None, 1=IRQ)
  10     Reply Register 0 Update Flag   (0=Was Written by DSP, 1=No)
  11     Reply Register 1 Update Flag   (0=Was Written by DSP, 1=No)
  12     Reply Register 2 Update Flag   (0=Was Written by DSP, 1=No)
  13     Command Register 0 Read Flag   (0=Was Read by DSP, 1=No)
  14     Command Register 1 Read Flag   (0=Was Read by DSP, 1=No)
  15     Command Register 2 Read Flag   (0=Was Read by DSP, 1=No)


DSi Teak MMIO[80E0h] - AHBM - Advanced High Performance Bus Master

AHBM does allow the Teak CPU to access the ARM-side memory (in combination with DMA interface at MMIO[8180h]).

Supported ARM-side memory areas
DSi allows to access most of the ARM9 address space:
  02000000h/Main RAM     --> works
  03000000h/Shared RAM   --> works (maybe also New Shared RAM, if any mapped?)
  04000000h/ARM9 I/O     --> works
  05000000h/Palette      --> works
  06000000h/VRAM         --> works
  07000000h/OAM          --> works
  08000000h/GBA SLOT ROM --> works (with dummy FFFFFFFFh values)
  0A000000h/GBA SLOT RAM --> works (with dummy FFFFFFFFh values)
  FFFF0000h/ARM9 BIOS    --> works (lower 32K only, upper 32K is zerofilled)
  DTCM/ITCM              --> probably ignored?
  Any other              --> returns zero (but without MMIO[80E0h] error flag)
3DS in 3DS mode is more restrictive:
  20000000h/FCRAM        --> works
  1FF80000h/AXI          --> works
  1FF40000h/DSP/DATA     --> oddly mirrors to 1FF80000h/AXI
  Any other              --> rejected (and sets MMIO[80E0h].bit4 error flag)

MMIO[80E0h] - AHBM Status (R)
  0-1   Usually/always 0 ?
  2     Burst queue not empty  (0=Empty, 1=Not-empty)
  3     Usually/always 0 ?
  4     Busy/stuck/error?  (0=Normal, 1=Invalid ARM address)  ;3DS only?
  5-15  Usually/always 0 ?
"Applications wait for all bits to be 0 before connecting AHBM to DMA."

MMIO[80E2h+(0..2)*6] - AHBM Channel 0..2 Configure Burst/Data (R/W)
  0     Applications set this to 1 if BURST is non-zero, uh?
  1-2   Burst type     (0=x1, 1=x4, 2=x8, 3=?)
  3     Unknown (R/W)  (0=Normal, 1=Dunno/NoTransfer?)
  4-5   Data type      (0=8bit, 1=16bit, 2=32bit, 3=?)
  6     Unused (0)
  7     Unknown (R/W)  (0=Normal, 1=Dunno/TransferHangs/crashes?)
  8-11  Unknown (R/W)  (0..Fh=?) (usually 0)
  12-15 Unused (0)
Used values: 0010h=?,0020h=?,0025h=dma?

MMIO[80E4h+(0..2)*6] - AHBM Channel 0..2 Configure Whatever (R/W)
  0-7   Unknown (R/W)      (0..FFh=?) (usually 0)
  8     Transfer direction (0=Read external memory, 1=Write external memory)
  9     Applications always set this (usually 1=set) (but also works when 0)
  10-15 Unused (0)
Used values: 0200h=read, 0300h=write

MMIO[80E6h+(0..2)*6] - AHBM Channel 0..2 Configure DMA (R/W)
  0-7   Connect to DMA channel 0..7   (0=No, 1=Connect)
  8-15  Unused (0)
Used values: bit0-7=dma0..7, 0000h=All off.

MMIO[80F4h] - Unknown 6bit? bit10-15 are used (R/W)
MMIO[80F6h] - AHBM Internal FIFO (R) and maybe also (W?)
MMIO[80F8h] - Unknown always zero? (R?)
MMIO[80FAh] - Read/write-able(!) mirror of MMIO[80FCh] (R/W)
MMIO[80FCh] - Unknown 16bit? (R/W)
MMIO[80FEh] - Unknown 16bit? (R/W)
Unknown registers, normally left unused. The FIFO register seems to contain the most recent 8x16bit values that were transferred via AHBM. Unknown if that FIFO (and whatever address setting) could be used for manual (non-DMA) AHBM transfers.


DSi Teak MMIO[8100h] - Memory Interface Unit (MIU)

MMIO[8100h] - MIU Waitstate Settings, bit0-15 (R/W)
MMIO[8102h] - MIU Waitstate Settings, bit16-31 (R/W)
  0-3    Number of wait-states for off-chip Z0 block
  4-7    Number of wait-states for off-chip Z1 block
  8-11   Number of wait-states for off-chip Z2 block
  12-15  Number of wait-states for off-chip Z3 block
  16-19  Number of wait-states for off-chip Z blocks outside Z0/Z1/Z2/Z3
  20-23  Number of wait-states for off-chip X/Y memory transactions
  24-27  Number of wait-states for off-chip Program-memory transactions
  28-31  Unused (0)
Uh, what means "off-chip" exactly, what kind of memory, on what "chip"?

MMIO[8104h] - MIU Waitstate Area Z0 (R/W)
MMIO[8106h] - MIU Waitstate Area Z1 (R/W)
MMIO[8108h] - MIU Waitstate Area Z2 (R/W)
MMIO[810Ah] - MIU Waitstate Area Z3 (R/W)
  0-5    Wait-state block Start address in 1K-word units
  6-11   Wait-state block End address in 1K-word units
  12-15  Wait-state block Page (lower 4bit of page)

MMIO[810Eh] - MIU X Page (or unused) (16bit) (R/W)
MMIO[8110h] - MIU Y Page (or unused) (8bit) (R/W)
MMIO[8112h] - MIU Z Page (or "absolute" page) (16bit) (R/W)
The X/Z pages are 16bit wide:
  0-15   Memory Page (...base or so, in WHAT-units?)
The Y page is only 8bit wide:
  0-7    Memory Page (...base or so, in WHAT-units?)
  8-15   Unused (0)
The register meaning depends on the PGM paging mode:
  When PGM=0 --> MMIO[8112h] is the "absolute" data memory page
  When PGM=1 --> MMIO[810Eh/8110h/8112h] are the X/Y/Z pages

MMIO[8114h] - MIU X/Y Page Size for Page 0 (or all pages) (R/W)
MMIO[8116h] - MIU X/Y Page Size for Page 1 (or unused) (R/W)
MMIO[8118h] - MIU X/Y Page Size for Off-chip Pages (or unused) (R/W)
  0-5    X memory size (0..3Fh)
  6-7    Unused (0)
  8-14   Y memory size (1..40h)
  15     Unused (0)
The register meaning depends on the PGM paging mode:
  When PGM=0?--> MMIO[8114h,8116h,8118h] used for Page 0, 1, and Off-chip pages
  When PGM=1?--> MMIO[8114h] used for all pages
For Y memory size, the hardware does automatically replace the written value by min=01h or max=40h when trying to to write 00h or 41h-7Fh.

MMIO[811Ah] - MIU Config for Misc stuff (R/W)
  0      Program protection mechanism, uh, what is that? (0=Disable, 1=Enable)
  1      Program page for entire program space (from Test pin) (1=offchip)
  2      Program page for breakpoint handler (0=Page1/offchip, 1=Page0/onchip)
  3      Unknown (R/W)  (0..1=?)
  4      Core/DMA data use only Z-even address bus (single? PGM=0?) (1=Enable)
  5      Unknown (R/W)  (0..1=?)
  6      Paging mode (PGM) (for X/Y/Z pages)  (0=Normal, 1=DANGER)
  7-15   Unused (0)
Power-on default is 0014h. Bit1-2 are read-only (always bit1=0, bit2=1).

MMIO[811Ch] - MIU Config for Program Page and Download Memory (R/W)
  0      Select Z-space data memory (0=Regular Memory, 1=Download memory)
  1      Download mem is/was selected (bit1 can be cleared during Trap only)
  2-5    Alternative Program Page for movd/movp opcodes (PDLPAGE) (4bit)
  6      Select program page for movd/movp (0=2bit/movpd, 1=4bit/PDLPAGE)
  7-15   Unused (0)
Bit1 gets set when setting bit0=1 (bit1 is usually readonly, except, trap handler may clear bit1 by writing to it). Unknown what Download means, maybe off-chip data memory?

MMIO[811Eh] - MIU Base Address for MMIO Registers (R/W)
  0-9    Unused (0)
  10-15  MMIO Base Address (in 400h-word units)
Power-on default is 8000h, ie. mapping MMIO[8000h..87FFh] to 8000h..87FFh.

MMIO[8120h] - MIU Observability Mode (R/W)
  0      Observability Enable (0=Disable, 1=Enable)
  1-3    Observability Mode   (0..4=Mode, see below)
  4-15   Unused (0)
Observability modes (defines which Core/DMA address/data buses are reflected on the off-chip XZ buses):
  00h: Core XZ address/data buses
  01h: Core Y address/data buses
  02h: Core P address/data buses
  03h: DMA DST address/data buses
  04h: DMA SRC address/data buses

MMIO[8122h] - MIU Pin Config? (R/W)
  0     Z Read Polarity Bit   - for DRZON/DRZEN
  1     Z Write Polarity Bit  - for DWZON/DWZEN
  2     Z Strobe Polarity Bit - for ZSTRB
  3     X Strobe Polarity Bit - for XSTRB
  4     X Select Polarity Bit - for XS
  5     Z Select Polarity Bit - for ZS
  6     Signal Polarity Bit   - for RD_WR
  7-15  Unused (0)


DSi Teak MMIO[8140h] - Code Replacement Unit (CRU)

The CRU is intended to fix bugs in ROM-based programs (rather useless for RAM-based DSi code).

MMIO[8140h+(0..15)*4] - CRU Entry 0..15 Offset, bit0-15 (R/W)
MMIO[8142h+(0..15)*4] - CRU Entry 0..15 Offset, bit16-31 (R/W)
  0-17   Program Address                           (0..3FFFFh)            (R/W)
  18-21  Program Page (usually 0)                  (0..Fh)                (R/W)
  22-30  Unused (0) (except bit25-30 in entry 15)
  25-28  Entry 15: Match entry number              (0..15=Entry 0..15)    (R)
  29     Entry 15: Match flag (cleared after read) (0=None, 1=Yes/match)  (R)
  30     Entry 15: Master enable for all entries   (0=Disable, 1=Enable)  (R/W)
  31     Enable Entry                              (0=Disable, 1=Enable)  (R/W)
There are sixteen identical entries, resembling OCEM program breaks, with some extra control/status bits in last entry.
The feature is working in so far that the read-only status bits get set upon matches, but the match should reportedly insert "a branch instruction" or trigger a "trap" exception, which doesn't happen.
Unknown if there are further config/mode/enable bits elsewhere for activating that behaviour. To bypass ROM code, it might redirect to data RAM, or external AHBM memory?


DSi Teak MMIO[8180h] - Direct Memory Access (DMA)

 _____________________________ DMA Control/Status _____________________________

MMIO[8184h] - DMA Channel Start Flags (0=Stop/Done, 1=Start/Busy) (R/W)
MMIO[8186h] - DMA Channel Pause Flags (0=Normal, 1=Pause) (R/W)
  0-7    Channel 0..7 flags
  8-15   Unused (0)
Transfer start/stop should be done via [81DEh].bit14/15 (using RMW to change [8184h] directly could mess up other channels; if they finish during the RMW).
Channel 0 is automatically enabled on power up, because it is used for ARM-side data transfers via DSP_PDATA (Port 4004300h).

MMIO[8188h] - DMA Channel End Flags for Size0 (R)
MMIO[818Ah] - DMA Channel End Flags for Size1 (R)
MMIO[818Ch] - DMA Channel End Flags for Size2 (R) (all done)
  0-7    Channel 0..7 end flags (0=No, 1=End)
  8-15   Unused (0)
The COFF labels refer to these three registers as "seox", whatever that means.
The 3rd register can be used to check for transfer completion (transfer end does also clear the Start/Enable bit in MMIO[8184h]).

MMIO[818Eh] - DMA Whatever Slot Config, bit0-15 (R/W)
MMIO[8190h] - DMA Whatever Slot Config, bit16-31 (R/W)
  0-2    Whatever (0..7) (initially 0 on reset)
  4-6    Whatever (0..7) (initially 1 on reset)
  8-10   Whatever (0..7) (initially 2 on reset)
  12-14  Whatever (0..7) (initially 3 on reset)
  16-18  Whatever (0..7) (initially 4 on reset)
  20-22  Whatever (0..7) (initially 5 on reset)
  24-24  Whatever (0..7) (initially 6 on reset)
  28-30  Whatever (0..7) (initially 7 on reset)
  Bit3,7,11,15,19,23,25,31 are unused (always 0)
Reportedly "some sort of slots for channel 0..7" maybe priority for DMA 0..7?
transfer can hang (eg. when changing 1st word to 4444h or higher)?

 ________________________________ DMA Channels ________________________________

MMIO[81BEh] - DMA Select Channel (R/W)
  0-2    Select the channel to be mapped to MMIO[81C0h..81Exh] (0..7)
  3-15   Unused (0)

MMIO[81C0h:0..7] - DMA Channel: Source Address, bit0-15 (R/W)
MMIO[81C2h:0..7] - DMA Channel: Source Address, bit16-31 (R/W)
MMIO[81C4h:0..7] - DMA Channel: Destination Address, bit0-15 (R/W)
MMIO[81C6h:0..7] - DMA Channel: Destination Address, bit16-31 (R/W)
  0-31   Address (within the selected memory area, see MMIO[81DAh])
Unknown how/what works exactly...
DSP/data probably uses only lower 18bit & probably ignores X/Y/Z and MMIOBASE
DSP/code probably uses only lower 18bit & probably ignores prpage/movpd
DSP/mmio probably uses only lower 11bit & probably ignores MMIOBASE
ARM/ahbm uses full 32bit address, counted in BYTE-units (not 16bit-units)

MMIO[81C8h:0..7] - DMA Channel: Size0 (inner dimension) (R/W)
MMIO[81CAh:0..7] - DMA Channel: Size1 (middle dimension) (R/W)
MMIO[81CCh:0..7] - DMA Channel: Size2 (outer dimension) (R/W)
  0-15   Length (for each array dimension)   (0001h..FFFFh)
Trying to write size=0000h is automatically replaced by size=0001h.
Total transfer length is Size0*Size1*Size2 (that is always counted in 16bit units; Size0 should contain an even number when using 32bit mode).
Normal 1-dimensional transfer would use Size0=Len, Size1=Size2=1. Size1 can be useful for 2-dimensional arrays. Size2 was announced to be useful for re-ordering things like RGB values (uh, but that may require 8bit-addressing, and negative step values, or separate step-direction flags?).

MMIO[81CEh:0..7] - DMA Channel: Source Step0 (R/W)
MMIO[81D0h:0..7] - DMA Channel: Source Step1 (R/W)
MMIO[81D2h:0..7] - DMA Channel: Source Step2 (R/W)
MMIO[81D4h:0..7] - DMA Channel: Destination Step0 (R/W)
MMIO[81D6h:0..7] - DMA Channel: Destination Step1 (R/W)
MMIO[81D8h:0..7] - DMA Channel: Destination Step2 (R/W)
  0-15   Step (... in 8bit/16bit/32bit units?) (signed or unsigned?)

MMIO[81DAh:0..7] - DMA Channel: Memory Area Config (R/W)
  0-3    Source Memory Area      (0..0Fh, see below)
  4-7    Destination Memory Area (0..0Fh, see below)
  8      Unknown?                (0=Normal, 1=No Irq, No end, maybe repeat?)
  9      Different Memory Areas  (0=No/Slow, 1=Yes/Simultaneous Read+Write)
  10     Transfer Unit size      (0=16bit/Slow, 1=32bit/Fast)
  11     Unused (0)
  12-13  Unknown?                (0..3=?)
  12-15  Transfer Speed          (0=Slow, 1/2=Medium, 3=Fast) (or burst size?)
Source/Destination Memory Areas can be:
  00h DSP/Data memory                                 ;\
  01h DSP/MMIO registers                              ; 16bit-address units
  05h DSP/Code memory (only for DST_SPACE) (untested) ;/
  07h ARM/AHBM external memory (via AHBM registers)   ;-8bit-address units
Used values: 670h,607h,400h,250h. Reset value is F200h (and kept so for channel 0).

MMIO[81DCh:0..7] - DMA Channel: Unknown, usually set to 0300h? (R/W)
  0-2    Unknown (R/W)  (0..07h=?) (usually 0)
  3      Unused (0)
  4-7    Unknown (R/W)  (0..0Fh=?) (usually 0h)
  8-9    Unknown (R/W)  (0/1/2=Hangs?, 3=Normal)
  10-12  Unknown (R/W)  (0..07h=?) (usually 0h)
  13-15  Unused (0)
Usually set to 0300h or 0700h (or, set to 0011h for DSP_PDATA transfer for channel 0, though that does also work with reset value 0000h).

MMIO[81DEh:0..7] - DMA Channel: Start/Stop/Control (R/W)
  0-2   Interrupt upon Size 0..2 End (0=Disable, 1=Enable)                (R/W)
  3-5   Never set Size2 End flag? (0=Normal, 1=No end, maybe repeat?)     (R/W)
  6-7   Unknown (0..3)                                                    (R/W)
  8-13  Unused? (0)
  14-15 Start/Stop Transfer (0=No change, 1=Start, 2=Stop, 3=Same as 1)     (W)

 ______________________ DMA Unknown/Internal Registers ________________________

MMIO[8192h] - Unknown, one register with RW-mask 7C03h (R/W)
Unknown/internal stuff. Writing 0000h, 0001h, 0002h, 0800h, 1000h, 4000h, FFFFh passes okay, however, writing 0400h or 2000h causes TRAP exception. Note: Don't remember how that had happened; it might have been caused indirectly by dvm data matches.

MMIO[81B6h..81BCh] - Unknown, four registers with RW-mask FFFFh (R/W)
Unknown/internal stuff. The four 16bit R/W registers might be general purpose fill values (if they have no other purpose)?

MMIO[8180h] - DMA Internal: Channel Size0 Busy or so? (R)
MMIO[8182h] - DMA Internal: Channel Size1 Busy or so? (R)
Unknown, can contain similar busy flags as in [8184h], although in read-only form, and not exactly the same value (eg. bit0 tends to be zero despite of channel being enabled for DSP_PATA transfers). Maybe related to Size0/1, or maybe indicating which channel is RIGHT NOW transferring data (if so, only one bit should be seen set at a time; or maybe bits go off one after another during processing of multiple channels).

MMIO[8194h] - DMA Internal: initially 0, contains SRC_ADDR_L after DMA (R)
MMIO[8196h] - DMA Internal: initially 0, contains DST_ADDR_L after DMA (R)
MMIO[8198h..81B4h] - Unknown, fixed 0 (R)
MMIO[81E0h:0..7] - DMA Internal: initially 0, but SRC_ADDR_L(n) after DMA (R)
MMIO[81E2h:0..7] - DMA Internal: initially 0, but DST_ADDR_L(n) after DMA (R)
MMIO[81E4h:0..7] - DMA Internal: initially 0, but SRC_ADDR_H(n) after DMA (R)
MMIO[81E6h:0..7] - DMA Internal: initially 0, but DST_ADDR_H(n) after DMA (R)
MMIO[81E8h..81FEh] - Unknown, fixed 0 (R)
Unknown/internal stuff.

 _________________________________ DMA Notes _________________________________

STEP0, STEP1 and STEP2 specify the address stepping between elements for each dimension. Below is an example showing how it works.
With the source address configuration:
  SRC_ADDR = 0
  SIZE0 = 3
  SIZE1 = 5
  SIZE2 = 2
  SRC_STEP0 = 2
  SRC_STEP1 = 1
  SRC_STEP2 = 7
The data transfer copies data from the following addresses:
  <--------------------------size1-------------------------->
  <--size0--> <--size0--> <--size0--> <--size0--> <--size0-->
   0,  2,  4,  5,  7,  9, 10, 12, 14, 15, 17, 19, 20, 22, 24  <-- size2 (1st)
  31, 33, 35, 36, 38, 40, 41, 43, 45, 46, 48, 50, 51, 53, 55  <-- size2 (2nd)

The 32bit double word mode also automatically aligns down the addresses to 32bit boundaries.

When the memory space is specified as 7 (AHBM), it performs data transfer from/to external ARM memory.
The external memory has 8-bit addressing. Keep in mind that the STEP value is also added to the address as-is, so STEP = 1 means stepping 8-bit for FCRAM, while stepping 16-bit for DSP memory.
There are also more alignment requirement on the external memory address, but it is handled by AHBM.


DSi Teak MMIO[8200h] - Interrupt Control Unit (ICU)

MMIO[8200h] - ICU Interrupt Pending Flags (0=No, 1=IRQ Pending) (R)
MMIO[8202h] - ICU Interrupt Acknowledge (0=No change, 1=Set) (W)
MMIO[8204h] - ICU Interrupt Manual Trigger (0=Release, 1=Set) (R/W)
MMIO[8206h] - ICU Enable Interrupt routing to core interrupt 0 (R/W)
MMIO[8208h] - ICU Enable Interrupt routing to core interrupt 1 (R/W)
MMIO[820Ah] - ICU Enable Interrupt routing to core interrupt 2 (R/W)
MMIO[820Ch] - ICU Enable Interrupt routing to vectored interrupt (R/W)
MMIO[820Eh] - ICU Interrupt Trigger mode (0=Level, 1=Edge) (R/W)
MMIO[8210h] - ICU Interrupt Polarity (0=Normal, 1=Invert) (R/W)
  0-8   No hardware IRQs (but can be used as Software IRQs via Manual Trigger)
  9     Timer 1
  10    Timer 0
  11    BTDMP 0
  12    BTDMP 1
  13    SIO
  14    APBP
  15    DMA

MMIO[8212h+(0..15)*4] - ICU Vectored Interrupt 0..15 Address, bit16-31 (R/W)
MMIO[8214h+(0..15)*4] - ICU Vectored Interrupt 0..15 Address, bit0-15 (R/W)
  0-17  Address of interrupt handler for vectored interrupt 0..15
  18-30 Unused (0)
  31    Context switch on vectored interrupt 0..15 (0=Disable, 1=Enable)
Observe that upper/lower 16bit are arranged in BIG-ENDIAN style (unlike other registers with lower/upper 16bit).
Default values on reset are 0003FC00h.
Interrupt vector address for Interrupt 0..15, when using "vectored interrupt".
The core interrupts and NMI have fixed vector addresses.

MMIO[8252h] - ICU Interrupt Master Disable (0=Normal, 1=Off/undoc) (R/W)
  0-15  Master Disable for interrupt 0..15 (0=Normal, 1=Off, don't set pending)

MMIO[8254h] - Unknown, R/W mask 5555h (R/W)
MMIO[8256h] - Unknown, R/W mask 5555h (R/W)
Unknown.

Interrupt related CPU registers
DSi Teak CPU Control/Status Registers

teak exception vectors
  code:00000h    start (from reset or timer watchdog)
  code:00002h    trap_handler (trap/break) (from OCEM or Timers)
  code:00004h    nmi_handler (non-maskable interrupt) (from timer watchdog)
  code:00006h    int0_handler
  code:0000Eh    int1_handler
  code:00016h    int2_handler
  code:variable  vint_handler(s) (with context switch, instead of push/pop?)

Interrupt Behaviour
Pending flags are set somewhat as so:
  new_state=incoming_hw_signal             ;always 0 for interrupt 0..8
  if polarity=1 then new_state=new_state xor 1
  new_state=new_state OR manual_trigger    ;done AFTER above polarity invert
  new_state=new_state AND NOT master_disable
  if new_state=1 and old_state=0 then pending=1
  old_state=new_state
Acknowlege is required for clearing pending bits, this is required in both Egde- and Level-triggered modes (the difference is that Level-triggered mode will ignore the acknowledge if new_state is still on).
Manual Trigger won't appear in Pending until after two NOP opcodes (or similar delay).

IRQ-to-interrupt translator
The main job of ICU is to translate 16 IRQ signals to 4 processor interrupt signals (int0, int1, int2 and vint), specified by I0x, I1x, I2x and IVx registers. When an IRQ is signaled, ICU will generate interrupt signal and the processor starts to execute interrupt handling procedure if the core interrupt is enabled. The procedure is supposed check IPx reigster to know the exact IRQ index, and to set IAx registers to clear the IRQ signal.

Software interrupt
The processor can writes to ITx to generate a software interrupt manually. A use case for this in many 3DS games is that IRQ 0 is used as the reschedule procedure for multithreading. When a thread wants to yield, it triggers IRQ 0, which switches thread context and resume another thread.


DSi Teak MMIO[8280h] - Audio (Buffered Time Division Multiplexing Port)

There are two BTDMP units. The weird name "Buffered Time Division Multiplexing Port" does essentially mean "FIFO with sample rate timer".
  BTDMP 0 is used for Receive (microphone) and Transmit (audio out).
  BTDMP 1 isn't actually used for anything.

MMIO[8280h/82A0h+(0..1)*80h] - BTDMP Receive/Transmit Control (R/W)
  0-3    Unknown (0..Fh) (usually 0Dh/0Fh)
  4-7    Unknown (0..Fh) (usually 00h)
  8-11   Enable BTDMP Interrupt when non-zero (0=Off, AnyOther=On?)
  12-15  Unknown (0..Fh) (usually 00h)
DSi sets this to 020Dh (receive) or 010Fh (transmit).

MMIO[8282h/82A2h+(0..1)*80h] - BTDMP Receive/Transmit Period (R/W)
  0-2    Clock Divider? (0..7)    (usually 4)   (affects timing when bit13=1)
  3-4    Unused (0)
  5-12   Clock Divider? (0..FFh)  (usually 80h) (affects timing when bit13=1)
  13     Clock Select   (0=ExternalDSiAudioClk, 1=InternalClkDivider?)
  14     Unknown        (0..1)    (usually 0)
  15     Unused (0)
Usually set to 1004h, which does select ExternalClk (32.73kHz or 47.61kHz, as selected in SNDEXCNT on ARM side; per 2x16bit stereo data).
Unknown how InternalClk works exactly. Increasing the "dividers" doesn't consistently increase FIFO transfer time; it seems as if the max time gets truncated somehow; maybe that's caused by InternalClk being ANDed with still running ExternalClk.

MMIO[8284h/82A4h+(0..1)*80h] - BTDMP Receive/Transmit Usually 0004h (R/W)
  0-2    Unknown (0..7) (R/W)                                        (R/W)
  3-4    Unused? (0)
  5-11   Unknown (0..7Fh) (R/W)                                      (R/W)
  12-15  Unused? (0)
Hmmmm, the write-ability of bit0-11 resembles the Period register...?

MMIO[8286h/82A6h+(0..1)*80h] - BTDMP Receive/Transmit Usually 0021h (R/W)
  0-1    Unknown (0..3) (R/W)                                        (R/W)
  2-4    Unused? (0)
  5      Unknown/writeonly? (read=0) (code writes 1 here)            (W?)
  6-15   Unused? (0)

MMIO[8288h/82A8h+(0..1)*80h] - BTDMP Receive/Transmit Usually 0000h'a (R/W)
  0-12   Unknown (0..1FFFh) (R/W) (initially=1FFFh on reset)
  13-15  Unused (0)

MMIO[828Ah/82AAh+(0..1)*80h] - BTDMP Receive/Transmit Usually 0000h'b (R/W)
  0-11   Unknown (0..0FFFh) (R/W)
  12-15  Unused (0)

MMIO[828Ch/82ACh+(0..1)*80h] - BTDMP Receive/Transmit Usually 0000h'c (R/W)
  0-13   Unknown (0..3FFFh) (R/W)
  14-15  Unused (0)

MMIO[828Eh/82AEh+(0..1)*80h] - BTDMP Receive/Transmit Usually unused'a (R/W)
MMIO[8290h/82B0h+(0..1)*80h] - BTDMP Receive/Transmit Usually unused'b (R/W)
  0-15   Unknown (0..FFFFh) (R/W)

Some of the above unknown stuff might be... volume, bias, sample.size, mono/stereo, dummy-value-when-fifo-empty, beep generator, filter/equalizer, sample rate interpolation, whatever...?

MMIO[829Eh/82BEh+(0..1)*80h] - BTDMP Receive/Transmit Enable (R/W)
  0-14   Unused (0)
  15     Enable Transfer  (0=Off, 1=On, allow Transfer+IRQ's)

 ________________________________ BTDMP FIFOs _________________________________

MMIO[82C0h/82C2h+(0..1)*80h] - BTDMP Receive/Transmit FIFO Status (R)
  0      usually 0
  1      If transfer ENABLED usually set, sometimes 0
  2      If transfer ENABLED usually set
  3      FIFO Full  (0=No, 1=Full, 16x16bit words)
  4      FIFO Empty (0=No, 1=Empty, 0x16bit words)
  5      If transfer ENABLED usually set
  6      usually 0
  7      For TX: gets set when FIFO contains ONE word?
  8-15   usually 0

MMIO[82C4h/82C6h+(0..1)*80h] - BTDMP Receive/Transmit FIFO Data (R) and (W)
  0-15      Signed 16bit audio sample.
FIFO size is 16x16bit. The data is stereo, ie. one needs to write 2x16bit for a full stereo sample (the write-order for left/right is still unknown).
Software seems to be directly writing to the FIFO (rather than using DMA). If DMA is also supported, that would probably require whatever special settings in the BTDMP and/or DMA registers (ie. so that the DMA knows when it needs to transfer new FIFO data).

MMIO[82C8h/82CAh+(0..1)*80h] - BTDMP Receive/Transmit FIFO Control (R/W)
  0-1    Unknown     (0..3=?)                                          (R/W)
  2      Flush FIFO  (0=No change, 1=Clear FIFO)                       (W)
  3-15   Unused (0)


DSi Teak CPU Registers

36bit/40bit Accumulators: a0,a1,b0,b1
  a0e:a0h:a0l (4:16:16 bits) = a0 (36bit)    ;TL2: 40bit (8:16:16)
  a1e:a1h:a1l (4:16:16 bits) = a1 (36bit)    ;TL2: 40bit (8:16:16)
  b0e:b0h:b0l (4:16:16 bits) = b0 (36bit)    ;TL2: 40bit (8:16:16)
  b1e:b1h:b1l (4:16:16 bits) = b1 (36bit)    ;TL2: 40bit (8:16:16)
4bit snippets (bit32-35) of a0/a1 can be found in status registers (st0,st1). On TL2, the whole upper 8bit (bit32-39) of a0/a1/b0/b1 can be additionally accessed via push/pop (a0e,a1e,b0e,b1e).

Teak General Registers: r0,r1,r2,r3,r4,r5,r6,r7
  r0     ;TL  ;16bit  ;\
  r1     ;TL  ;16bit  ;
  r2     ;TL  ;16bit  ; old TL1 registers
  r3     ;TL  ;16bit  ;
  r4     ;TL  ;16bit  ;
  r5     ;TL  ;16bit  ;/
  r6     ;TL2 ;16bit  ;<-- new TL2 register
  r7     ;TL  ;16bit  ;<-- aka rb (with optional immediate, MemR7Imm)

32bit Multiply Result and 16bit Muliply Parameters: p0,p1, and x0,y0,x1,y1
  x0     ;TL  ;16bit  ;-
  y0     ;TL  ;16bit  ;-
  x1     ;TL2 ;16bit  ;-
  y1     ;TL2 ;16bit  ;-
  p0     ;TL  ;33bit! ;\Px   ;TL2: 33bit p0e:p0 ?  ;TL1: 32bit?
  p1     ;TL2 ;33bit! ;/     ;TL2: 33bit p1e:p1 ?  ;TL1: N/A
  p0h    ;TL  ;16bit  ; ;<-- aka ph ;<-- called "p0" (aka "p") in "RegisterP0"
The "load ps" and "load ps01" opcodes allow to specify a multiply shifter, this is useful when dealing with signed/unsigned parameters:
  Unsigned = Unsigned * Unsigned       ;use shift 0
  Unsigned = Unsigned * Signed         ;use shift +1
  Unsigned = Signed * Signed           ;use shift +2
  Signed = Unsigned * Unsigned         ;use shift -1
  Signed = Unsigned * Signed           ;use shift 0
  Signed = Signed * Signed             ;use shift +1

TeakLite Misc
  pc     ;TL  ;18bit! ;-program counter (TL2: 18bit, TL1: 16bit)
  sp     ;TL  ;16bit  ;-stack pointer (decreasing on push/call)
  sv     ;TL  ;16bit  ;-shift value (negative=right) (for shift-by-register)
  mixp   ;TL  ;16bit  ;-related to min/max/mind/maxd
  lc     ;TL  ;16bit  ;-Loop Counter (of block repeat)
  repc   ;TL  ;16bit  ;-Repeat Counter (for "rep" opcode)
  dvm    ;TL  ;16bit  ;-Data Value Match (OCEM data breakpoints) (and for trap)

TeakLiteII Misc: vtr0,vtr1,prpage
  vtr0   ;TL2 16bit   ;\related to vtrshr,vtrmov,vtrclr
  vtr1   ;TL2 16bit   ;/(saved C/C1 carry flags for Viterby decoding)
  prpage ;TL2 4bit    ;-??? (bit0-3 used/dangerous, bit4-15 always 0)
vtr0,vtr1 are related to vtrshr,vtrmov,vtrclr opcodes (and multi-function opcodes with "vtrshr" suffix).
prpage isn't used by existing DSi code, setting the four write-able bits to nonzero seems to screw-up opcode fetching, causing code to crash (unless one of the next 1-2 prefetched opcodes restores prpage=0, which causes opcode fetching to recover; after skipping some following prefetched opcodes, until prpage=0 is applied). Maybe it's related to code access rights or waitstates... it doesn't seem to be related to upper 2bit of the 18bit program counter (prpage is zero even when executing code above address 0FFFFh).

Old Control/Status registers (TeakLite): st0,st1,st2,icr
New Control/Status registers (TeakLiteII): stt0,stt1,stt2,mod0,mod1,mod2,mod3
DSi Teak CPU Control/Status Registers

Address Config (TeakLiteII): ar0,ar1,arp0,arp1,arp2,arp3
Address Step/Modulo: cfgi,cfgj (and TL2 stepi0,stepj0)
DSi Teak CPU Address Config/Step/Modulo

User-defined registers (optional off-core): ext0,ext1,ext2,ext3
The four ext registers are intended for custom hardware extensions (where they could be used as I/O ports, with faster & more direct access than memory mapped I/O).
  ext0   ;TL  ;16bit
  ext1   ;TL  ;16bit
  ext2   ;TL  ;16bit
  ext3   ;TL  ;16bit
In the DSi, the four register do exist (they are fully read/write-able), but unknown if they do have any special functions - or if they are just general-purpose data registers (existing DSi software isn't using the ext registers, and hardware is solely accessed via memory mapped I/O).

Bitfields for Control/Status registers and cfgi/cfgj registers
  page   ;TL  ;8bit "load" st1.bit0-7   (page for MemImm8)    ;aka "lpg"
  ps     ;TL  ;2bit "load" st1.bit10-11 (product shifter for multiply?)
  ps01   ;TL2 ;4bit "load" mod0...?     (maybe separate "ps" for p0 and p1 ?)
  movpd  ;TL2 ;2bit "load" stt2.bit6-7  (page for reading DATA from ProgMem)
  modi   ;TL  ;9bit "load" cfgi.bit7-15 =imm9
  modj   ;TL  ;9bit "load" cfgj.bit7-15 =imm9
  stepi  ;TL  ;7bit "load" cfgi.bit0-6  =imm7
  stepj  ;TL  ;7bit "load" cfgj.bit0-6  =imm7

Shadow Registers
Some registers (or in case of st0-st2: fractions thereof) exist as "shadows"... related to "cntx", "swap", "banke" (and maybe "bankr"?) opcodes, and "reti/retid" opcodes with "context" suffix, and interrupts with context switching enabled.
  st0  bit0,2-11                        ;\control/status (cntx)
  st1  bit10-11 (and "swap": bit0-7)    ; (TL2: probably also SttMod)
  st2  bit0-7                           ;/
  a0 <--> b0    manualswap only?        ;\accumulators (swap)
  a1 <--> b1    autoswapped?            ;/
  r0 <--> r0b                           ;\
  r1 <--> r1b                           ;
  r4 <--> r4b                           ; BankFlags (banke)
  r7 <--> r7b     ;TL2                  ;
  cfgi <--> cfgib                       ;
  cfgj <--> cfgjb ;TL2                  ;/
  Ar,Arp <--> ?   ;TL2                  ;-? (bankr and/or cntx)
Registers b0/b1 can be used as normal opcode operands, the other shadow registers are used only when doing bank/cntx stuff.

Suffix codes: dmod,dmodi,dmodj,dmodij,context,eu,dbrv,ebrv,s,r
Non-register assembler keywords.
  dmod   ;TL  ;suffix ;\
  dmodi  ;TL2 ;suffix ;
  dmodj  ;TL2 ;suffix ;
  dmodij ;TL2 ;suffix ;/
  context;TL  ;suffix ;<-- (related to "cntx")
  eu     ;TL  ;suffix ;<-- (aka "Axheu", now "Axh,eu")
  dbrv   ;TL2 ;suffix ;\for "bitrev"
  ebrv   ;TL2 ;suffix ;/
  s      ;TL  ;suffix ;\param for "cntx" opcode  ;"s" also for opcode 88D1h
  r      ;TL  ;suffix ;/

Condition codes: true,eq,neq,gt,ge,lt,le,nn,c,v,e,l,nr,niu0,iu0,iu1
The 16 condition codes can be used for all opcodes with "Cond" operand, whereas "true" can be omitted (as it means always/non-conditional), the four conditions "gt,ge,lt,le" can be also used with "min/max/maxd/cbs" opcodes.

Old pre-TeakLiteII keyword names (renamed in TeakLiteII)
  TL:   x    y    p    ph   rb   lpg   a0heu   a1heu
  TL2:  x0   y0   p0   p0h  r7   page  a0h,eu  a1h,eu


DSi Teak CPU Control/Status Registers

There are two sets of Control/Status registers
  Old registers (for TeakLite):   st0/st1/st2, and icr
  New registers (for TeakLiteII): stt0/stt1/stt2, and mod0/mod1/mod2/mod3
The new registers do contain only a few new bits, apart from that they are basically same as the old registers (with the old bits rearranged to different locations in the new registers).
The old registers do still exist on TeakLiteII, so one could use either old or new registers (all reads/writes will be mirrored to both register sets).
However, there are a few cases where writing the old registers may smash bits in new registers (writing the old "limit" bit will change BOTH of the new "limit" bits, changing "ps" versus "ps01" may also involve strange effects, and... changing "a0e/a1e" bits seems to have "weird" effects on a0l/a0h/a1l/a1h, or maybe that's some "wanted" saturation effect?).

CPU Flags (for Cond opcodes)
CPU Flags are stored in st0 register (with mirrors in stt0/stt1). The flags can be used for conditional opcodes (with "Cond" operand). According to TeakLite datasheet, the flags are affected somewhat like this:
  ZMNVCEL- add, addh, addl, cmp, cmpu, sub, subh, subl, inc, dec, neg
  ZMNVCEL- maa, maasu, mac, macsu, macus, macuu, msu, sqra, rnd, pacr, movr
  ZMN-C--- or
  ZM--C--- addv, cmpv, subv, and
  ZMN--E-- clr, clrr, copy, divs, swap, not, xor
  ZMN--0L- lim
  ZMNVCELR norm
  ZMN-CE-- rol, ror
  ZMN-CE-- movs, movsi, shfc, shfi, shl, shl4, shr, shr4  ;for logical shift
  ZMNVCEL- movs, movsi, shfc, shfi, shl, shl4, shr, shr4  ;for arithmetic shift
  ZMN--E-- mov, movp, pop        ;when dst=ac,bc (whut?)         ;\
  xxxxxxxx mov, movp, pop        ;when dst=st0                   ; mov etc.
  ------L- mov, push             ;when src=aXL,aXH,bXL,bXH       ;
  -------- mov, movp, pop, push  ;when src/dst neither of above  ;/
  ZMN--E-- cntx s  ;store shadows (new flags for a1)             ;\cntx
  ZMNVCELR cntx r  ;restore shadows (old flags)                  ;/
  ZM------ set, rst, chng
  Z------- tst0, tst1, tstb
  -M------ max, maxd, min
  -------R modr
  -------- mpy, mpyi, mpysu, sqr, exp
  -------- banke, dint, eint, load, nop, bkrep, rep, break, trap, movd
  -------- br, brr, call, calla, callr, ret, retd, reti, retid, rets
Flags for new TL2 opcodes aren't officially documented; some might follow the above rules (eg. the new "r6" register should act as old "r0-r5"), but other new opcodes might do this or that.

 __________________________ Old registers (TeakLite) __________________________

st0 - Old TL1 Status/Control Register st0
  0     SAT  R/W Saturation Mode  (0=Off, 1=Saturate "Ax to data") ;mod0.0
  1     IE   R/W Interrupt Enable (0=Disable, 1=Enable) ;dint/eint ;mod3.7
  2     IM0  R/W Interrupt INT0 Mask (0=Disable, 1=Enable if IE=1) ;mod3.8
  3     IM1  R/W Interrupt INT1 Mask (0=Disable, 1=Enable if IE=1) ;mod3.9
  4     R    R/W Flag: rN is Zero   ;see Cond nr                   ;stt1.4
  5     L    R/W Flag: Limit        ;see Cond l      ;L=(LM or VL) ;stt0.0+1
  6     E    R/W Flag: Extension    ;see Cond e                    ;stt0.2
  7     C    R/W Flag: Carry        ;see Cond c                    ;stt0.3
  8     V    R/W Flag: Overflow     ;see Cond v                    ;stt0.4
  9     N    R/W Flag: Normalized   ;see Cond nn                   ;stt0.5
  10    M    R/W Flag: Minus        ;see Cond gt,ge,lt,le          ;stt0.6
  11    Z    R/W Flag: Zero         ;see Cond eq,neq,gt,le         ;stt0.7
  12-15 a0e  R/W Accumulator 0 Extension Bits                      ;a0.32-35

st1 - Old TL1 Status/Control Register st1
  0-7   PAGE R/W Data Memory Page (for MemImm8) (see "load page")  ;mod1.0-7
  8-9   -    -   Reserved (read: always set)                       ;-
  10-11 PS   R/W Product Shifter for P0 (see "load ps")(multiply?) ;mod0.10-11
                   (0=No Shift, 1=SHR1, 2=SHL1, 3=SHL2)
  12-15 a1e  R/W Accumulator 1 Extension Bits                      ;a1.32-35

st2 - Old TL1 Status/Control Register st2
  0-3   MDn  R/W Enable cfgi.modi modulo for R0..R3 (0=Off, 1=On)  ;mod2.0-3
  4-5   MDn  R/W Enable cfgj.modj modulo for R4..R5 (0=Off, 1=On)  ;mod2.4-5
  6     IM2  R/W Interrupt INT2 Mask (0=Disable, 1=Enable if IE=1) ;mod3.10
  7     S    R/W Shift Mode (0=Arithmetic, 1=Logic)                ;mod0.7
  8     OU0  R/W OUSER0 User Output Pin                            ;mod0.8
  9     OU1  R/W OUSER1 User Output Pin                            ;mod0.9
  10    IU0  R   IUSER0 User Input Pin (zero)  ;see Cond iu0,niu0  ;stt1.??
  11    IU1  R   IUSER1 User Input Pin (zero)  ;see Cond iu1       ;stt1.??
  12    -    -   Reserved (read: always set)                       ;-
  13    IP2  R   Interrupt Pending INT2 (0=No, 1=IRQ)              ;stt2.2
  14    IP0  R   Interrupt Pending INT0 (0=No, 1=IRQ)              ;stt2.0
  15    IP1  R   Interrupt Pending INT1 (0=No, 1=IRQ)              ;stt2.1

icr - Old TL1 Interrupt Context and Repeat Nesting
  0     NMIC R/W NMI Context switching enable  (0=Off, 1=On)       ;mod3.0
  1     IC0  R/W INT0 Context switching enable (0=Off, 1=On)       ;mod3.1
  2     IC1  R/W INT1 Context switching enable (0=Off, 1=On)       ;mod3.2
  3     IC2  R/W INT2 Context switching enable (0=Off, 1=On)       ;mod3.3
  4     LP   R   InLoop (when inside one or more "bkrep" loops)    ;stt2.15
  5-7   BCn  R   Block repeat nest. counter ;see "bkrep"           ;stt2.12-14
  8-15  -    -   Reserved (read: always set)                       ;-

 _________________________ New registers (TeakLiteII) _________________________

stt0 - New TL2 Status/Control Register stt0 (CPU Flags)
  0     LM   R/W Flag: Limit, set if saturation has/had occured    ;st0.5
  1     VL   R/W Flag: LatchedV, set if overflow has/had occurred  ;st0.5, too
  2     E    R/W Flag: Extension    ;see Cond e                    ;st0.6
  3     C    R/W Flag: Carry        ;see Cond c                    ;st0.7
  4     V    R/W Flag: Overflow     ;see Cond v                    ;st0.8
  5     N    R/W Flag: Normalized   ;see Cond nn                   ;st0.9
  6     M    R/W Flag: Minus        ;see Cond gt,ge,lt,le          ;st0.10
  7     Z    R/W Flag: Zero         ;see Cond eq,neq,gt,le         ;st0.11
  8-10  -    -   Unknown (reads as zero)
  11    C1   R/W Flag: Carry1 (2nd carry, for dual-operation opcodes)
  12-15 -    -   Unknown (reads as zero)

stt1 - New TL2 Status/Control Register stt1 (whatever)
  0-3   -    -   Unknown (reads as zero)
  4     R    R/W Flag: rN is Zero   ;see Cond nr                   ;st0.4
  5-13  -    -   Unknown (reads as zero)  (IU1 and IU0 should be here!)
  14    P0E  R/W Upper bit of 33bit P0 register  ;\shifted-in on        ;p0.32
  15    P1E  R/W Upper bit of 33bit P1 register  ;/arith right shifts   ;p1.32
Note: bit14/bit15 are automatically sign-expanded when moving data to p0/p0h/p1.

stt2 - New TL2 Status/Control Register stt2 (Interrupt/ProgBank/Bkrep)
  0     IP0  R   Interrupt Pending INT0 (0=No, 1=IRQ)              ;st2.14
  1     IP1  R   Interrupt Pending INT1 (0=No, 1=IRQ)              ;st2.15
  2     IP2  R   Interrupt Pending INT2 (0=No, 1=IRQ)              ;st2.13
  3     IPV  R   Interrupt Pending VINT                            ;-
  4-5   -    -   Unknown (reads as zero)                           ;-
  6-7  PCMhi R/W Program Memory Bank (for ProgMemRn/ProgMemAxl) ("load movpd")
  8-11  -    -   Unknown (reads as zero)                           ;-
  12-14 BCn  R   Block repeat nest. counter ;see "bkrep"           ;icr.5-7
  15    LP   R   InLoop (when inside one or more "bkrep" loops)    ;icr.4

mod0 - New TL2 Status/Control Register mod0 (Misc)
  0     SAT  R/W Saturation Mode (0=Off, 1=Saturate "Ax to data"?) ;st0.0
  1     SATA R/W Saturation Mode on store (0=Off, 1="(Ax op data) to Ax"?)
  2     ?    R   Unknown (reads as one)
  3     -    -   Unknown (reads as zero)
  4     -    -   Unknown (reads as zero)
  5-6   HWM  R/W Halfword Multiply    ... Modify y0 (and y1?)
                  0=read y0/y1 directly (full 16bit words)
                  1=Takes y0>>8 and y1>>8 (logic shift)
                  2=Takes y0&0xFF and y1&0xFF
                  3=Takes y0>>8 and y1&&0xFF
  7     S    R/W Shift Mode (0=Arithmetic, 1=Logic)                ;st2.7
  8     OU0  R/W OUSER0 User Output Pin                            ;st2.8
  9     OU1  R/W OUSER1 User Output Pin                            ;st2.9
  10-11 PS0  R/W Product Shifter for P0 (see "load ps")(multiply?) ;st1.10-11
  12    -    -   Unknown (reads as zero)
  13-14 PS1  R/W Product Shifter for P1 (see "load ps")(multiply?)
  15    -    -   Unknown (reads as zero)

mod1 - New TL2 Status/Control Register mod1 (Data Page)
  0-7   PAGE R/W Data Memory Page (for MemImm8) (see "load page")  ;st1.0-7
  8-11  -    -   Unknown (reads as zero)
  12   STP16 R/W banke opcode (0=exchange cfgi/cfgj, 1=cfgi/cfgj+stepi0/stepj0)
                  1=use stepi0/j0 instead of stepi/j for stepping Rn registers
  13    CMD  R/W Change Modulo mode (0=New TL2 style, 1=TL1 style)
  14    EPI  R/W Unknown (1=Set R3=0 after any "modr R3" or "access[R3]"?)
  15    EPJ  R/W Unknown (1=Set R7=0 after any "modr R7" or "access[R7]"?)

mod2 - New TL2 Status/Control Register mod2 (Modulo Enable)
  0-3   MDn  R/W Enable cfgi.modi modulo for R0..R3 (0=Off, 1=On)  ;st2.0-3
  4-5   MDn  R/W Enable cfgj.modj modulo for R4..R5 (0=Off, 1=On)  ;st2.4-5
  6-7   MDn  R/W Enable cfgj.modj modulo for R6..R7 (0=Off, 1=On) ;TL2 only
  8-11  BRn  R/W Step +s for R0..R3 (0=cfgi.stepi, 1=stepi0)
  12-15 BRn  R/W Step +s for R4..R7 (0=cfgj.stepi, 1=stepj0)
XXX... bit8-9 seem to mess up my code (that uses r0/r1, but only with +0 step).
"When BRn=1, memory access through Rn will use the bit-reversed value of Rn as the address. Note that this also implies that stepi0/j0 will be used, regardless of what STP16 says."

mod3 - New TL2 Status/Control Register mod3 (Interrupt Control)
  0     NMIC R/W NMI Context switching enable  (0=Off, 1=On)       ;icr.0
  1     IC0  R/W INT0 Context switching enable (0=Off, 1=On)       ;icr.1
  2     IC1  R/W INT1 Context switching enable (0=Off, 1=On)       ;icr.2
  3     IC2  R/W INT2 Context switching enable (0=Off, 1=On)       ;icr.3
  4     OU2  R/W Unknown (R/W)
  5     OU3  R/W Unknown (R/W)
  6     OU4  ?   ---DANGER BIT--- (1=hangs/crashes when set)
  7     IE   R/W Interrupt Enable (0=Disable, 1=Enable) ;dint/eint ;st0.1
  8     IM0  R/W Interrupt INT0 Mask (0=Disable, 1=Enable if IE=1) ;st0.2
  9     IM1  R/W Interrupt INT1 Mask (0=Disable, 1=Enable if IE=1) ;st0.3
  10    IM2  R/W Interrupt INT2 Mask (0=Disable, 1=Enable if IE=1) ;st2.6
  11    IMV  R/W Interrupt VINT Mask (0=Disable, 1=Enable if IE=1?)
  12    -    -   Unknown (reads as zero)
  13   CCNTA R/W Unknown (R/W)
  14    CPC  R/W Stack word order for PC on call/ret (0=Normal, 1=Reversed)
  15    CREP R/W Unknown (R/W)
Bit14=0: push lowword then push highword on call; pop highword then pop lowword on ret.


DSi Teak CPU Address Config/Step/Modulo

 _______________________________ Address Config _______________________________

These registers allow to reconfigure opcodes. For example, opcodes with operand MemR45 can normally use only R4/R5 operands; if desired that can be changed to anything else like R3/R0. The selection if Offset/Step operands can be changed in similar way.
  Unknown which settings affect which opcodes exactly.
The DSi Sound code is using a default configuration for most of its code, but it does also have some functions with alternate configurations.

ar0/ar1
  0-2   R/W PM1/PM3 Post Modify Step    (0..7 = +0,+1,-1,+s,+2,-2,+2,-2)
  3-4   R/W CS1/CS3 Offset              (0..3 = +0,+1,-1,-1)
  5-7   R/W PM0/PM2 Post Modify Step    (0..7 = +0,+1,-1,+s,+2,-2,+2,-2)
  8-9   R/W CS0/CS2 Offset              (0..3 = +0,+1,-1,-1)
  10-12 R/W RN1/RN3 Register            (0..7 = R0..R7)
  13-15 R/W RN0/RN2 Register            (0..7 = R0..R7)

arp0/arp1/arp2/arp3
  0-2   R/W PIn     Post Modify Step I  (0..7 = +0,+1,-1,+s,+2,-2,+2,-2)
  3-4   R/W CIn     Offset I            (0..3 = +0,+1,-1,-1)
  5-7   R/W PJn     Post Modify Step J  (0..7 = +0,+1,-1,+s,+2,-2,+2,-2)
  8-9   R/W CJn     Offset J            (0..3 = +0,+1,-1,-1)
  10-11 R/W RIn     Register I          (0..3 = R0..R3)
  12    -   -       Unused              (always zero)
  13-14 R/W RJn     Register J          (0..3 = R4..R7)
  15    -   -       Unused              (always zero)

 ________________________________ Step/Modulo ________________________________

cfgi - Step and Mod I (for R0..R3)
cfgj - Step and Mod J (for R4..R7)
  0-6   stepi/stepj  (7bit) (see "load stepi/stepj")  ;step "Rn+s" ?
  7-15  modi/modj    (9bit) (see "load modi/modj")
The modulos can be enabled in Control/Status registers. Some opcodes do also allow to disable modulos via "dmod" suffix.
On TL2, the above 7bit stepi/stepj can be optionally replaced by new 16bit stepi0/stepj0 registers (via flags in mod2 register).

stepi0 ;TL2 16bit
stepj0 ;TL2 16bit
  0-16  stepi0/stepj0
more steps, probably for "modr" with "+s0" (stepII2D2S0)
and for STP16 and BRn?


DSi TeakLite II Instruction Set Encoding

The opcodes are 16bits wide (some followed by an additional 16bit parameter word, namely those with "@16" operands). The encoding is very messy (fixed opcode bits randomly mixed/interleaved with variable parameter bits, and with new TL2 opcodes squeezed in formerly unused locations), making it pretty much impossible to decode that unpleasant stuff by software/logic.
The only reasonable decoding way is using a huge table with 65536 entries (which could be generated temporarily from the information in below table, using the Base number plus all variable bit combinations, for example, "6100h TL mov MemImm8@0, Ab@11" has variable bits in bit0-7 and bit11-12, so the opcode would be mapped at 6100h-61FFh, 6900h-69FFh, 7100h-71FFh, 7900h-79FFh).

TeakLite I (TL) and TeakLite II (TL2) Opcodes
  Base  Ver Opcode (with parameter bits located at @bitnumber and up)
  D4FBh TL  add  MemImm16@16, Ax@8
  A600h TL  add  MemImm8@0, Ax@8
  86C0h TL  add  Imm16@16, Ax@8
  C600h TL  add  Imm8u@0, Ax@8
  D4DBh TL  add  MemR7Imm16@16, Ax@8
  4600h TL  add  MemR7Imm7s@0, Ax@8
  8680h TL  add  MemRn@0, Ax@8 || Rn@0stepZIDS@3
  86A0h TL  add  RegisterP0@0, Ax@8
  D2DAh TL2 add  Ab@10, Bx@0
  5DF0h TL2 add  Bx@1, Ax@0
  9070h TL2 add  MemR01@8, sv, Abh@2 || sub MemR01@8offsZI@0, sv, Abl@2
             || mov Abl@2, MemR45@8 || R01@8stepII2@0, R45@8stepII2@1
  5DB0h TL2 add  MemR04@1, sv, Abh@2 || sub MemR04@1offsZI@0, sv, Abl@2
             || R04@1stepII2@0
  6F80h TL2 add  MemR45@2, MemR01@2, Abh@3
             || add MemR45@2offsZI@1, MemR01@2offsZI@0, Abl@3
             || R01@2stepII2@0, R45@2stepII2@1
  6FA0h TL2 add  MemR45@2, MemR01@2, Abh@3
             || sub MemR45@2offsZI@1, MemR01@2offsZI@0, Abl@3
             || R01@2stepII2@0, R45@2stepII2@1
  5E30h TL2 add  MemR45@8, sv, Abh@2 || sub MemR45@8offsZI@1, sv, Abl@2
             || mov Abl@2, MemR01@8 || R01@8stepII2@0, R45@8stepII2@1
  5DC0h TL2 add  p0, p1, Ab@2
  D782h TL2 add  p1, Ax@0
  5DF8h TL2 add  Px@1, Bx@0
  D38Bh TL2 add  r6, Ax@4
  4590h TL2 add3 p0, p1, Ab@2
  4592h TL2 add3a p0, p1, Ab@2
  4593h TL2 add3aa p0, p1, Ab@2
  5DC1h TL2 adda p0, p1, Ab@2
  B200h TL  addh MemImm8@0, Ax@8
  9280h TL  addh MemRn@0, Ax@8 || Rn@0stepZIDS@3
  92A0h TL  addh Register@0, Ax@8
  9464h TL2 addh r6, Ax@0
  90E0h TL2 addhp MemR0425@2, Px@4, Ax@8 || R0425@2stepII2D2S@0 ;p=ProgMem? Px?
  B400h TL  addl MemImm8@0, Ax@8
  9480h TL  addl MemRn@0, Ax@8 || Rn@0stepZIDS@3
  94A0h TL  addl Register@0, Ax@8
  9466h TL2 addl r6, Ax@0
  906Ch TL2 addsub  p0, p1, Ab@0
  49C2h TL2 addsub  p1, p0, Ab@4
  916Ch TL2 addsuba p0, p1, Ab@0
  49C3h TL2 addsuba p1, p0, Ab@4
  E700h TL  addv Imm16@16, MemImm8@0
  86E0h TL  addv Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  87E0h TL  addv Imm16@16, Register@0
  47BBh TL2 addv Imm16@16, r6
  D4F9h TL  and  MemImm16@16, Ax@8
  A200h TL  and  MemImm8@0, Ax@8
  82C0h TL  and  Imm16@16, Ax@8
  C200h TL  and  Imm8u@0, Ax@8
  D4D9h TL  and  MemR7Imm16@16, Ax@8
  4200h TL  and  MemR7Imm7s@0, Ax@8
  8280h TL  and  MemRn@0, Ax@8 || Rn@0stepZIDS@3
  82A0h TL  and  RegisterP0@0, Ax@8
  6770h TL2 and  Ab@2, Ab@0, Ax@12                ;TL2 only
  D389h TL2 and  r6, Ax@4
  4B80h TL  banke BankFlags6@0  ;{r0}{,r1}{,r4}{,cfgi}{,r7}{,cfgj}
  8CDFh TL2 bankr       ;without operand ?
  8CDCh TL2 bankr Ar@0
  8CD0h TL2 bankr Ar@2, Arp@0
  8CD8h TL2 bankr Arp@0
  5EB8h TL2 bitrev Rn@0
  D7E8h TL2 bitrev Rn@0, dbrv
  D7E0h TL2 bitrev Rn@0, ebrv
  5C00h TL  bkrep NoReverse, Imm8u@0, Address16@16
  5D00h TL  bkrep NoReverse, Register@0, Address18@16and5
  8FDCh TL2 bkrep NoReverse, r6, Address18@16and0
  DA9Ch TL2 bkreprst MemR0425@0
  5F48h TL2 bkreprst MemSp, Unused2@0
  DADCh TL2 bkrepsto MemR0425@0, Unused1@10
  9468h TL2 bkrepsto MemSp, Unused3@0
  4180h TL  br   Address18@16and4, Cond@0
  D3C0h TL  break               ;break
  5000h TL  brr  RelAddr7@4, Cond@0
  41C0h TL  call Address18@16and4, Cond@0
  D480h TL  calla Axl@8
  D381h TL2 calla Ax@4
  1000h TL  callr RelAddr7@4, Cond@0
  9068h TL2 cbs  Axh@0, Axh@not0, r0, ge
  9168h TL2 cbs  Axh@0, Axh@not0, r0, gt
  D49Eh TL2 cbs  Axh@8, Bxh@5, r0, ge
  D49Fh TL2 cbs  Axh@8, Bxh@5, r0, gt
  D5C0h TL2 cbs  MemR01@2, MemR45@2, ge || R01@2stepII2@0, R45@2stepII2@1
  D5C8h TL2 cbs  MemR01@2, MemR45@2, gt || R01@2stepII2@0, R45@2stepII2@1
  E500h TL  chng Imm16@16, MemImm8@0
  84E0h TL  chng Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  85E0h TL  chng Imm16@16, Register@0
  47BAh TL2 chng Imm16@16, r6
  0038h TL2 chng Imm16@16, SttMod@0
  6760h TL  clr  Implied ConstZero, Ax@12, Cond@0  ;aX=0
  6F60h TL  clr  Implied ConstZero, Bx@12, Cond@0  ;bX=0
  8ED0h TL2 clr  Implied ConstZero, Ab@2, Ab@0
  5DFEh TL2 clrp p0
  5DFFh TL2 clrp p0, p1
  5DFDh TL2 clrp p1
  67C0h TL  clrr Implied Const8000h, Ax@12, Cond@0 ;aX=8000h
  6F70h TL2 clrr Implied Const8000h, Bx@12, Cond@0 ;bX=8000h
  8DD0h TL2 clrr Implied Const8000h, Ab@2, Ab@0
  D4FEh TL  cmp  MemImm16@16, Ax@8
  AC00h TL  cmp  MemImm8@0, Ax@8
  8CC0h TL  cmp  Imm16@16, Ax@8
  CC00h TL  cmp  Imm8u@0, Ax@8
  D4DEh TL  cmp  MemR7Imm16@16, Ax@8
  4C00h TL  cmp  MemR7Imm7s@0, Ax@8
  8C80h TL  cmp  MemRn@0, Ax@8 || Rn@0stepZIDS@3
  8CA0h TL  cmp  RegisterP0@0, Ax@8
  4D8Ch TL2 cmp  Ax@1, Bx@0
  D483h TL2 cmp  b0, b1
  D583h TL2 cmp  b1, b0
  DA9Ah TL2 cmp  Bx@10, Ax@0
  8B63h TL2 cmp  p1, Ax@4
  D38Eh TL2 cmp  r6, Ax@4
  BE00h TL  cmpu MemImm8@0, Ax@8
  9E80h TL  cmpu MemRn@0, Ax@8 || Rn@0stepZIDS@3
  9EA0h TL  cmpu Register@0, Ax@8
  8A63h TL2 cmpu r6, Ax@3
  ED00h TL  cmpv Imm16@16, MemImm8@0
  8CE0h TL  cmpv Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  8DE0h TL  cmpv Imm16@16, Register@0
  47BEh TL2 cmpv Imm16@16, r6
  D390h TL  cntx r  ;restore shadows
  D380h TL  cntx s  ;store shadows
  67F0h TL  copy Implied Ax@not12,   Ax@12, Cond@0 ;aX=aY
  67E0h TL  dec  Implied Const1,     Ax@12, Cond@0 ;aX=aX-1
  43C0h TL  dint        ;IE=0, interrupt disable
  0E00h TL  divs MemImm8@0, Ax@8
  4380h TL  eint        ;IE=1, interrupt enable
  9460h TL  exp  Bx@0, Implied sv
  9060h TL  exp  Bx@0, Implied sv, Ax@8
  9C40h TL  exp  MemRn@0, Implied sv || Rn@0stepZIDS@3
  9840h TL  exp  MemRn@0, Implied sv, Ax@8 || Rn@0stepZIDS@3
  9040h TL  exp  RegisterP0@0, Implied sv, Ax@8
  9440h TL  exp  RegisterP0@0, Implied sv
  D7C1h TL2 exp  r6, Implied sv
  D382h TL2 exp  r6, Implied sv, Ax@4
  67D0h TL  inc  Implied Const1,     Ax@12, Cond@0 ;aX=aX+1
  49C0h TL  lim  a0     ;aka a0,a0
  49D0h TL  lim  a0, a1
  49F0h TL  lim  a1     ;aka a1,a1
  49E0h TL  lim  a1, a0
  4D80h TL  load Imm2u@0, ps               ;st1.bit11-10=imm2
  DB80h TL  load Imm7s@0, stepi            ;cfgi.LSB=imm7
  DF80h TL  load Imm7s@0, stepj            ;cfgj.LSB=imm7
  0400h TL  load Imm8u@0, page             ;st1.LSBs=imm8 ;aka "lpg"
  0200h TL  load Imm9u@0, modi             ;cfgi.MSB=imm9
  0A00h TL  load Imm9u@0, modj             ;cfgj.MSB=imm9
  D7D8h TL2 load Imm2u@1, movpd, Unused1@0 ;stt2.bit6.7 (page for ProgMem)
  0010h TL2 load Imm4u@0, ps01             ;mod0.bit10-11,13-14 and st1.10-11 ?
  D400h TL  maa  MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8400h TL  maa  MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  8420h TL  maa  y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8440h TL  maa  y0, Register@0, Ax@11
  E400h TL  maa  y0, MemImm8@0, Ax@11
  5EA8h TL2 maa  y0, r6, Ax@0
  D700h TL  maasu MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8700h TL  maasu MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  8720h TL  maasu y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8740h TL  maasu y0, Register@0, Ax@11
  5EAEh TL2 maasu y0, r6, Ax@0
  D200h TL  mac  MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8200h TL  mac  MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  8220h TL  mac  y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8240h TL  mac  y0, Register@0, Ax@11
  E200h TL  mac  y0, MemImm8@0, Ax@11
  5EA4h TL2 mac  y0, r6, Ax@0
  4D84h TL2 mac  y0, x1, Ax@1, Unused1@0
  5E28h TL2 mac1 MemR45@2, MemR01@2, Ax@8 || R01@2stepII2@0, R45@2stepII2@1
  D600h TL  macsu MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8600h TL  macsu MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  E600h TL  macsu y0, MemImm8@0, Ax@11
  8620h TL  macsu y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8640h TL  macsu y0, Register@0, Ax@11
  5EACh TL2 macsu y0, r6, Ax@0
  D300h TL  macus MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8300h TL  macus MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  8320h TL  macus y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8340h TL  macus y0, Register@0, Ax@11
  5EA6h TL2 macus y0, r6, Ax@0
  D500h TL  macuu MemR45@2, MemR0123@0, Ax@11
             || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8500h TL  macuu MemRn@0, Imm16@16, Ax@11 || Rn@0stepZIDS@3
  8520h TL  macuu y0, MemRn@0, Ax@11 || Rn@0stepZIDS@3
  8540h TL  macuu y0, Register@0, Ax@11
  5EAAh TL2 macuu y0, r6, Ax@0
  8460h TL  max  NoReverse, Ax@8, Implied Ax@not8, Bogus MemR0, ge,
             Implied mixp, Implied r0 || R0stepZIDS@3   ;when aY >= aX
  8660h TL  max  NoReverse, Ax@8, Implied Ax@not8, Bogus MemR0, gt,
             Implied mixp, Implied r0 || R0stepZIDS@3   ;when aY > aX
  5E21h TL2 max  a0h, a1h || max a0l, a1l || vtrshr
  5F21h TL2 max  a1h, a0h || max a1l, a0l || vtrshr
  D784h TL2 max  Axh@1, Bxh@0 || max Axl@1, Bxl@0 || vtrshr
  4A40h TL2 max  Axh@3, Bxh@4 || max Axl@3, Bxl@4 || mov Axl@not3, MemR04@1
             || vtrshr || R04@1stepII2@0
  4A44h TL2 max  Axh@3, Bxh@4 || max Axl@3, Bxl@4 || mov Axh@not3, MemR04@1
             || vtrshr || R04@1stepII2@0
  45A0h TL2 max  Axh@4, Bxh@3 || max Axl@4, Bxl@3 || mov Axh@not4, MemR45@2
             || mov Axl@not4, MemR01@2 || vtrshr
             || R01@2stepII2@0, R45@2stepII2@1
  D590h TL2 max  Axh@6, Bxh@5 || max Axl@6, Bxl@5 || mov Axh@not6, MemR01@2
             || mov Axl@not6, MemR45@2 || vtrshr
             || R01@2stepII2@0, R45@2stepII2@1
  4A60h TL2 max  Bxh@4, Axh@3 || max Bxl@4, Axl@3 || mov Bxl@not4, MemR04@1
             || vtrshr || R04@1stepII2@0
  4A64h TL2 max  Bxh@4, Axh@3 || max Bxl@4, Axl@3 || mov Bxh@not4, MemR04@1
             || vtrshr || R04@1stepII2@0
  8060h TL  maxd NoReverse, Ax@8, MemR0, ge, Implied mixp, Implied r0
             || R0stepZIDS@3   ;when (r0) >= aX
  8260h TL  maxd NoReverse, Ax@8, MemR0, gt, Implied mixp, Implied r0
             || R0stepZIDS@3   ;when (r0) > aX
  8860h TL  min  NoReverse, Ax@8, Implied Ax@not8, Bogus MemR0, le,
             Implied mixp, Implied r0 || R0stepZIDS@3   ;when aY <= aX
  8A60h TL  min  NoReverse, Ax@8, Implied Ax@not8, Bogus MemR0, lt,
             Implied mixp, Implied r0 || R0stepZIDS@3   ;when aY < aX
  43C2h TL2 min  Axh@0, Axh@not0 || min Axl@0, Axl@not0 || vtrshr
  D2B8h TL2 min  Axh@11, Bxh@10 || min Axl@11, Bxl@10
             || mov Axh@not11, MemR01@2 || mov Axl@not11, MemR45@2
             || vtrshr || R01@2stepII2@0, R45@2stepII2@1
  4A00h TL2 min  Axh@3, Bxh@4 || min Axl@3, Bxl@4 || mov Axl@not3, MemR04@1
             || vtrshr || R04@1stepII2@0
  4A04h TL2 min  Axh@3, Bxh@4 || min Axl@3, Bxl@4 || mov Axh@not3, MemR04@1
             || vtrshr || R04@1stepII2@0
  45E0h TL2 min  Axh@4, Bxh@3 || min Axl@4, Bxl@3 || mov Axh@not4, MemR45@2
             || mov Axl@not4, MemR01@2 || vtrshr
             || R01@2stepII2@0, R45@2stepII2@1
  D4BAh TL2 min  Axh@8, Bxh@0 || min Axl@8, Bxl@0 || vtrshr
  4A20h TL2 min  Bxh@4, Axh@3 || min Bxl@4, Axl@3 || mov Bxl@not4, MemR04@1
             || vtrshr || R04@1stepII2@0
  4A24h TL2 min  Bxh@4, Axh@3 || min Bxl@4, Axl@3 || mov Bxh@not4, MemR04@1
             || vtrshr || R04@1stepII2@0
  47A0h TL2 mind NoReverse, Ax@3, MemR0, le, Implied mixp, Implied r0
             || R0stepZIDS@0
  47A4h TL2 mind NoReverse, Ax@3, MemR0, lt, Implied mixp, Implied r0
             || R0stepZIDS@0
  0080h TL  modr MemRn@0stepZIDS@3
  00A0h TL  modr MemRn@0stepZIDS@3, dmod  ;Disable modulo
  D294h TL2 modr MemR0123@10stepII2D2S0@0 || modr MemR4567@10stepII2D2S0@5
  0D80h TL2 modr MemR0123@5stepII2D2S0@1  || modr MemR4567@5stepII2D2S0@3, dmod
  0D81h TL2 modr MemR0123@5stepII2D2S0@1, dmod
             || modr MemR4567@5stepII2D2S0@3, dmod
  8464h TL2 modr MemR0123@8stepII2D2S0@0, dmod || modr MemR4567@8stepII2D2S0@3
  5DA0h TL2 modr MemRn@0stepD2
  5DA8h TL2 modr MemRn@0stepD2, dmod
  4990h TL2 modr MemRn@0stepI2
  4998h TL2 modr MemRn@0stepI2, dmod
  D290h TL  mov  Ab@10, Ab@5
  D298h TL  mov  Abl@10, dvm
  D2D8h TL  mov  Abl@10, x0
  3000h TL  mov  Ablh@9, MemImm8@0
  D4BCh TL  mov  Axl@8, MemImm16@16
  D49Ch TL  mov  Axl@8, MemR7Imm16@16
  DC80h TL  mov  Axl@8, MemR7Imm7s@0
  D4B8h TL  mov  MemImm16@16, Ax@8
  6100h TL  mov  MemImm8@0, Ab@11
  6200h TL  mov  MemImm8@0, Ablh@10
  6500h TL  mov  MemImm8@0, Axh@12, eu   ;aka Axheu
  6000h TL  mov  MemImm8@0, R0123457y0@10
  6D00h TL  mov  MemImm8@0, sv
  D491h TL  mov  dvm, Ab@5
  D492h TL  mov  icr, Ab@5
  5E20h TL  mov  Imm16@16, Bx@8
  5E00h TL  mov  Imm16@16, Register@0
  4F80h TL  mov  Imm5u@0, icr    ;uh, but icr is 8bit wide (only 4bit are R/W)?
  2500h TL  mov  Imm8s@0, Axh@12         ;signed!
  2900h TL  mov  Imm8s@0, ext0
  2D00h TL  mov  Imm8s@0, ext1
  3900h TL  mov  Imm8s@0, ext2
  3D00h TL  mov  Imm8s@0, ext3
  2300h TL  mov  Imm8s@0, R0123457y0@10  ;signed!
  0500h TL  mov  Imm8s@0, sv
  2100h TL  mov  Imm8u@0, Axl@12         ;unsigned!
  D498h TL  mov  MemR7Imm16@16, Ax@8
  D880h TL  mov  MemR7Imm7s@0, Ax@8
  98C0h TL  mov  MemRn@0, Bx@8 || Rn@0stepZIDS@3
  1C00h TL  mov  MemRn@0, Register@5 || Rn@0stepZIDS@3
  47E0h TL  mov  MemSp, Register@0
  47C0h TL  mov  mixp, Register@0
  2000h TL  mov  R0123457y0@9, MemImm8@0
  4FC0h TL  mov  Register@0, icr
  5E80h TL  mov  Register@0, mixp
  1800h TL  mov  Register@5, MemRn@0 || Rn@0stepZIDS@3
  5EC0h TL  mov  RegisterP0@0, Bx@5
  5800h TL  mov  RegisterP0@0, Register@5
  D490h TL  mov  repc, Ab@5
  7D00h TL  mov  sv, MemImm8@0
  D493h TL  mov  x0, Ab@5
  D49Bh TL2 mov  a0h, stepi0
  D59Bh TL2 mov  a0h, stepj0
  4390h TL2 mov  a0h, MemR0425@2 || mov y0, MemR0425@2offsZIDZ@0
             || R0425@2stepII2D2S@0
  43D0h TL2 mov  a1h, MemR0425@2 || mov y0, MemR0425@2offsZIDZ@0
             || R0425@2stepII2D2S@0
  8FD4h TL2 mov  Ab@0, p0
  43A0h TL2 mov  Abh@3, MemR01@2 || mov Abl@3, MemR45@2
             || R01@2stepII2@0, R45@2stepII2@1
  43E0h TL2 mov  Abh@3, MemR45@2 || mov Abl@3, MemR01@2
             || R01@2stepII2@0, R45@2stepII2@1
  9D40h TL2 mov  Abh@4, MemR04@1 || mov Abh@2, MemR04@1offsZI@0
             || R04@1stepII2@0
  9164h TL2 mov  Abl@0, prpage
  9064h TL2 mov  Abl@0, repc
  D394h TL2 mov  Abl@0, x1
  D384h TL2 mov  Abl@0, y1
  9540h TL2 mov  Abl@3, ArArp@0
  9C60h TL2 mov  Abl@3, SttMod@0
  9560h TL2 mov  ArArp@0, Abl@3
  D488h TL2 mov  ArArp@0, MemR04@8 || R04@8stepII2@5
  5F50h TL2 mov  ArArpSttMod@0, MemR7Imm16@16
  886Bh TL2 mov  Ax@8, pc
  8C60h TL2 mov  Axh@4, MemR4567@8 || mov MemR0123@8, Axh@4
             || R0123@8stepII2D2S@0, R4567@8stepII2D2S@2
  4800h TL2 mov  Axh@6, MemR0123@4 || movr MemR4567@4, Axh@6
             || R0123@4stepII2D2S@0, R4567@4stepII2D2S@2
  4900h TL2 mov  Axh@6, MemR0123@4 || mov  MemR4567@4, Axh@6
             || R0123@4stepII2D2S@0, R4567@4stepII2D2S@2
  7F80h TL2 mov  Axh@6, MemR4567@4 || movr MemR0123@4, Axh@6
             || R0123@4stepII2D2S@0, R4567@4stepII2D2S@2
  8863h TL2 mov  Bx@8, pc
  0008h TL2 mov  Imm16@16, ArArp@0
  0023h TL2 mov  Imm16@16, r6
  0001h TL2 mov  Imm16@16, repc
  8971h TL2 mov  Imm16@16, stepi0
  8979h TL2 mov  Imm16@16, stepj0
  0030h TL2 mov  Imm16@16, SttMod@0
  5DD0h TL2 mov  Imm4u@0, prpage
  80C4h TL2 mov  MemR01@9, Abh@10 || mov MemR45@9, Abl@10
             || R01@9stepII2@0, R45@9stepII2@8
  D292h TL2 mov  MemR0425@10_MemR0425@10offsZIDZ@5, Px@0
             || R0425@10stepII2D2S@5
  D7D4h TL2 mov  MemR04@1, repc || R04@1stepII2@0
  5F4Ch TL2 mov  MemR04@1, sv || sub3 MemR04@1, p0, p1, b0 || R04@1stepII2@0
  D4B4h TL2 mov  MemR04@1, sv || sub3rnd MemR04@1, p0, p1, b1 || R04@1stepII2@0
  DE9Ch TL2 mov  MemR04@1, sv || sub3rnd MemR04@1, p0, p1, b0 || R04@1stepII2@0
  4B40h TL2 mov  MemR04@3, sv || addsub    MemR04@3, p1, p0, Bx@0
             || R04@3stepII2@2
  4B42h TL2 mov  MemR04@3, sv || addsubrnd MemR04@3, p1, p0, Bx@0
             || R04@3stepII2@2
  8062h TL2 mov  MemR04@4, ArArp@8  || R04@4stepII2@3
  8063h TL2 mov  MemR04@4, SttMod@8 || R04@4stepII2@3
  9960h TL2 mov  MemR04@4, sv || addsub    MemR04@4, p1, p0, Bx@2
             || R04@4stepD2S@3  ;<-- ordered p1, p0 here !
  99E0h TL2 mov  MemR04@4, sv || addsubrnd MemR04@4, p1, p0, Bx@2
             || R04@4stepD2S@3  ;<-- ordered p1, p0 here !
  9860h TL2 mov  MemR04@4, sv || sub3      MemR04@4, p0, p1, Bx@2
             || R04@4stepD2S@3
  98E0h TL2 mov  MemR04@4, sv || sub3rnd   MemR04@4, p0, p1, Bx@2
             || R04@4stepD2S@3
  8873h TL2 mov  MemR04@8, sv || sub3 MemR04@8, p0, p1, b1 || R04@8stepII2@3
  D4C0h TL2 mov  MemR45@5, Abh@2 || mov MemR01@5, Abl@2
             || R01@5stepII2@0, R45@5stepII2@1
  4D90h TL2 mov  MemR7Imm16@16, ArArpSttMod@0
  D2DCh TL2 mov  MemR7Imm16@16, repc, Unused2@0, Unused1@10
  1B20h TL2 mov  MemRn@0, r6 || Rn@0stepZIDS@3 ;override 1800h (mov a1,MemRn@0)
  D29Ch TL2 mov  MemSp, r6, Unused2@0, Unused1@10
  8A73h TL2 mov  mixp, Bx@3
  4381h TL2 mov  mixp, r6
  4382h TL2 mov  p0h, Bx@0
  D3C2h TL2 mov  p0h, r6
  4B60h TL2 mov  p0h, Register@0     ;<-- here "p0h" as source
  8FD8h TL2 mov  p1, Ab@0
  88D0h TL2 mov  Px@1, MemR0425@8_MemR0425@8offsZIDZ@2   || R0425@8stepII2D2S@2
  88D1h TL2 mov  Px@1, MemR0425@8_MemR0425@8offsZIDZ@2,s || R0425@8stepII2D2S@2
  D481h TL2 mov  r6, Bx@8
  1B00h TL2 mov  r6, MemRn@0 || Rn@0stepZIDS@3 ;override 1800h (mov a0,MemRn@0)
  43C1h TL2 mov  r6, mixp
  5F00h TL2 mov  r6, Register@0
  5F60h TL2 mov  Register@0, r6
  D2D9h TL2 mov  repc, Abl@10
  D7D0h TL2 mov  repc, MemR04@1 || R04@1stepII2@0
  D3C8h TL2 mov  repc, MemR7Imm16@16, Unused3@0
  D482h TL2 mov  stepi0, a0h
  D582h TL2 mov  stepj0, a0h
  D2F8h TL2 mov  SttMod@0, Abl@10
  49C1h TL2 mov  x1, Ab@4
  D299h TL2 mov  y1, Ab@10
  5EB0h TL2 mov  prpage, Abl@0
  49A0h TL2 mov  SttMod@0, MemR04@4 || R04@4stepII2@3
  4DC0h TL2 mova Ab@4, MemR0425@2_MemR0425@2offsZIDZ@0 || R0425@2stepII2D2S@0
  4BC0h TL2 mova MemR0425@2_MemR0425@2offsZIDZ@0, Ab@4 || R0425@2stepII2D2S@0
  5F80h TL  movd MemR0123@0,ProgMemR45@2 || R0123@0stepZIDS@3, R45@2stepZIDS@5
  0040h TL  movp ProgMemAxl@5, Register@0
  0D40h TL2 movp ProgMemAx@5, Register@0
  0600h TL  movp ProgMemRn@0, MemR0123@5 || R0123@5stepZIDS@7, Rn@0stepZIDS@3
  D499h TL2 movpdw ProgMemAx@8_ProgMemAx@8offsI, pc
  8864h TL  movr MemR0425@3, Abh@8 || R0425@3stepII2D2S@0   ;op*10000h+8000h
  9CE0h TL  movr MemRn@0, Ax@8 || Rn@0stepZIDS@3
  9CC0h TL  movr RegisterP0@0, Ax@8
  5DF4h TL2 movr Bx@1, Ax@0
  8961h TL2 movr r6, Ax@3
  6300h TL  movs Implied sv, MemImm8@0, Ab@11
  0180h TL  movs Implied sv, MemRn@0, Ab@5 || Rn@0stepZIDS@3
  0100h TL  movs Implied sv, RegisterP0@0, Ab@5
  5F42h TL2 movs Implied sv, r6, Ax@0
  4080h TL  movsi Implied Imm5s@0, R0123457y0@9, Ab@5, Bogus Imm5s@0
  D000h TL  mpy  MemR45@2, MemR0123@0 || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8000h TL  mpy  MemRn@0, Imm16@16    || Rn@0stepZIDS@3
  8020h TL  mpy  y0, MemRn@0          || Rn@0stepZIDS@3
  8040h TL  mpy  y0, Register@0
  E000h TL  mpy  y0, MemImm8@0
  5EA0h TL2 mpy  y0, r6
  CB00h TL2 mpy  MemR45@5, MemR01@5 || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3   p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB01h TL2 mpy  MemR45@5, MemR01@5 || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3   p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB02h TL2 mpy  MemR45@5, MemR01@5 || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB03h TL2 mpy  MemR45@5, MemR01@5 || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB04h TL2 mpy  MemR45@5, MemR01@5 || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3   p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB05h TL2 mpy  MemR45@5, MemR01@5 || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3   p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB06h TL2 mpy  MemR45@5, MemR01@5 || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CB07h TL2 mpy  MemR45@5, MemR01@5 || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  D5E0h TL2 mpy  MemR04@1, x1 || mpy y1, x0 || sub3 p0, p1, Ax@3
             || R04@1stepII2@0
  D5E4h TL2 mpy  MemR04@1, x1 || mpy y1, x0 || add3 p0, p1, Ax@3
             || R04@1stepII2@0
  C800h TL2 mpy  MemR4567@4, MemR0123@4
             || mpy MemR4567@4offsZIDZ@2, MemR0123@4offsZIDZ@0
             || add3 p0, p1, Ab@6 || R0123@4stepII2D2S@0, R4567@4stepII2D2S@2
  C900h TL2 mpy  MemR4567@4, MemR0123@4
             || mpy MemR4567@4offsZIDZ@2, MemR0123@4offsZIDZ@0
             || sub3 p0, p1, Ab@6 || R0123@4stepII2D2S@0, R4567@4stepII2D2S@2
  80C2h TL2 mpy  MemR45@0, MemR01@0 || mpy MemR45@0offsZI@9, MemR01@0offsZI@8
             || add3a p0, p1, Ab@10 || R01@0stepII2@8, R45@0stepII2@9
  49C8h TL2 mpy  MemR45@2, MemR01@2 || mpy MemR45@2offsZI@1, MemR01@2offsZI@0
             || sub3a p0, p1, Ab@4 || R01@2stepII2@0, R45@2stepII2@1
  80C8h TL2 mpy  MemR45@2, MemR01@2 || mpy MemR45@2offsZI@1, MemR01@2offsZI@0
             || addsub  p0, p1, Ab@10 || R01@2stepII2@0, R45@2stepII2@1
  81C8h TL2 mpy  MemR45@2, MemR01@2 || mpy MemR45@2offsZI@1, MemR01@2offsZI@0
             || addsuba p0, p1, Ab@10 || R01@2stepII2@0, R45@2stepII2@1
  82C8h TL2 mpy  MemR45@2, MemR01@2 || mpy MemR45@2offsZI@1, MemR01@2offsZI@0
             || add     p0, p1, Ab@10 || R01@2stepII2@0, R45@2stepII2@1
  83C8h TL2 mpy  MemR45@2, MemR01@2 || mpy MemR45@2offsZI@1, MemR01@2offsZI@0
             || adda    p0, p1, Ab@10 || R01@2stepII2@0, R45@2stepII2@1
  00C0h TL2 mpy  MemR45@3, MemR01@3 || mpy MemR45@3offsZI@2, MemR01@3offsZI@1
             || sub  p0, p1, Ab@4 || R01@3stepII2@1, R45@3stepII2@2
  00C1h TL2 mpy  MemR45@3, MemR01@3 || mpy MemR45@3offsZI@2, MemR01@3offsZI@1
             || suba p0, p1, Ab@4 || R01@3stepII2@1, R45@3stepII2@2
  0D20h TL2 mpy  MemR45@3, MemR01@3 || mpyus MemR45@3offsZI@2, MemR01@3offsZI@1
             || add3a p0, p1, Ax@0, dmodi || R01@3stepII2@1, R45@3stepII2@2
  0D30h TL2 mpy  MemR45@3, MemR01@3 || mpyus MemR45@3offsZI@2, MemR01@3offsZI@1
             || add3a p0, p1, Ax@0, dmodj || R01@3stepII2@1, R45@3stepII2@2
  4B50h TL2 mpy  MemR45@3, MemR01@3 || mpyus MemR45@3offsZI@2, MemR01@3offsZI@1
             || add3a p0, p1, Ax@0, dmodij || R01@3stepII2@1, R45@3stepII2@2
  D7A0h TL2 mpy  MemR45@3, MemR01@3 || mpy MemR45@3offsZI@2, MemR01@3offsZI@1
             || add3    sv, p0, p1, Ax@4 || R01@3stepII2@1, R45@3stepII2@2
  D7A1h TL2 mpy  MemR45@3, MemR01@3 || mpy MemR45@3offsZI@2, MemR01@3offsZI@1
             || add3rnd sv, p0, p1, Ax@4 || R01@3stepII2@1, R45@3stepII2@2
  9861h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3  p0, p1, Ax@8, dmodj  || R01@4stepII2@2, R45@4stepII2@3
  9862h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3  p0, p1, Ax@8, dmodi  || R01@4stepII2@2, R45@4stepII2@3
  9863h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3  p0, p1, Ax@8, dmodij || R01@4stepII2@2, R45@4stepII2@3
  98E1h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3a p0, p1, Ax@8, dmodj  || R01@4stepII2@2, R45@4stepII2@3
  98E2h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3a p0, p1, Ax@8, dmodi  || R01@4stepII2@2, R45@4stepII2@3
  98E3h TL2 mpy  MemR45@4, MemR01@4 || mpy MemR45@4offsZI@3, MemR01@4offsZI@2
             || add3a p0, p1, Ax@8, dmodij || R01@4stepII2@2, R45@4stepII2@3
  4DA0h TL2 mpy  y0, MemR04@3 || mpyus y1, MemR04@3offsZI@2
             || sub3  p0, p1, Ax@4 || R04@3stepII2@2
  4DA1h TL2 mpy  y0, MemR04@3 || mpyus y1, MemR04@3offsZI@2
             || sub3a p0, p1, Ax@4 || R04@3stepII2@2
  4DA2h TL2 mpy  y0, MemR04@3 || mpyus y1, MemR04@3offsZI@2
             || add3  p0, p1, Ax@4 || R04@3stepII2@2
  4DA3h TL2 mpy  y0, MemR04@3 || mpyus y1, MemR04@3offsZI@2
             || add3a p0, p1, Ax@4 || R04@3stepII2@2
  94E0h TL2 mpy  y0, MemR04@4 || mpy   y1, MemR04@4offsZI@3
             || sub3  p0, p1, Ax@8 || R04@4stepII2@3
  94E2h TL2 mpy  y0, MemR04@4 || mpy   y1, MemR04@4offsZI@3
             || sub3a p0, p1, Ax@8 || R04@4stepII2@3
  94E4h TL2 mpy  y0, MemR04@4 || mpy   y1, MemR04@4offsZI@3
             || add3  p0, p1, Ax@8 || R04@4stepII2@3
  94E6h TL2 mpy  y0, MemR04@4 || mpy   y1, MemR04@4offsZI@3
             || add3a p0, p1, Ax@8 || R04@4stepII2@3
  94E1h TL2 mpy  y0, MemR04@4 || mpysu y1, MemR04@4offsZI@3
             || sub3  p0, p1, Ax@8 || R04@4stepII2@3
  94E3h TL2 mpy  y0, MemR04@4 || mpysu y1, MemR04@4offsZI@3
             || sub3a p0, p1, Ax@8 || R04@4stepII2@3
  94E5h TL2 mpy  y0, MemR04@4 || mpysu y1, MemR04@4offsZI@3
             || add3  p0, p1, Ax@8 || R04@4stepII2@3
  94E7h TL2 mpy  y0, MemR04@4 || mpysu y1, MemR04@4offsZI@3
             || add3a p0, p1, Ax@8 || R04@4stepII2@3
  8862h TL2 mpy  y0, x1 || mpy   MemR04@4, x0 || sub3  p0, p1, Ax@8
             || R04@4stepII2@3
  8A62h TL2 mpy  y0, x1 || mpy   MemR04@4, x0 || add3  p0, p1, Ax@8
             || R04@4stepII2@3
  4D88h TL2 mpy  y0, x1 || mpy   y1, x0 || sub p0, p1, Ax@1
  5E24h TL2 mpy  y0, x1 || mpy   y1, x0 || add p0, p1, Ab@0
  8061h TL2 mpy  y0, x1 || mpy   y1, x0 || add3  p0, p1, Ab@8
  8071h TL2 mpy  y0, x1 || mpy   y1, x0 || add3a p0, p1, Ab@8
  8461h TL2 mpy  y0, x1 || mpy   y1, x0 || sub3  p0, p1, Ab@8
  8471h TL2 mpy  y0, x1 || mpy   y1, x0 || sub3a p0, p1, Ab@8
  D484h TL2 mpy  y0, x1 || mpy   y1, x0 || add3aa p0, p1, Ab@0
  D49Dh TL2 mpy  y0, x1 || mpy   y1, x0 || sub p0, p1, Bx@5
  D4A0h TL2 mpy  y0, x1 || mpy   y1, x0 || addsub p0, p1, Ab@0
  4FA0h TL2 mpy  y0, x1 || mpy y1, x0 || add3 p0, p1, Ab@3
             || mov Axh@6, MemR04@1 || mov Bxh@2, MemR04@1offsZI@0
             || R04@1stepII2@0
  5818h TL2 mpy  y0, x1 || mpy y1, x0 || addsub    sv, p0, p1, Ax@0
             || mov Axh@0, MemR0425@7 || mov Axh@not0, MemR0425@7offsZI@6
             || R0425@7stepII2@6  ;override 5800h+18h (mov a0, Register)
  5838h TL2 mpy  y0, x1 || mpy y1, x0 || addsubrnd sv, p0, p1, Ax@0
             || mov Axh@0, MemR0425@7 || mov Axh@not0, MemR0425@7offsZI@6
             || R0425@7stepII2@6  ;override 5800h+38h (mov a1, Register)
  80D0h TL2 mpy  y0, x1 || mpy y1, x0 || addsub    sv, p0, p1, Ax@10
             || mov Axh@9, MemR04@3 || mov Bxh@8, MemR04@3offsZI@2
             || R04@3stepII2@2
  80D1h TL2 mpy  y0, x1 || mpy y1, x0 || addsubrnd sv, p0, p1, Ax@10
             || mov Axh@9, MemR04@3 || mov Bxh@8, MemR04@3offsZI@2
             || R04@3stepII2@2
  80D2h TL2 mpy  y0, x1 || mpy y1, x0 || add3      sv, p0, p1, Ax@10
             || mov Axh@9, MemR04@3 || mov Bxh@8, MemR04@3offsZI@2
             || R04@3stepII2@2
  80D3h TL2 mpy  y0, x1 || mpy y1, x0 || add3rnd   sv, p0, p1, Ax@10
             || mov Axh@9, MemR04@3 || mov Bxh@8, MemR04@3offsZI@2
             || R04@3stepII2@2
  D3A0h TL2 mpy  y0, x1 || mpy y1, x0 || addsub p0, p1, Ab@3
             || mov Axh@6, MemR04@1 || mov Bxh@2, MemR04@1offsZI@0
             || R04@1stepII2@0
  4D89h TL2 mpy  y0, x1 || mpyus y1, x0 || sub p0, p1, Ax@1
  5F24h TL2 mpy  y0, x1 || mpyus y1, x0 || add p0, p1, Ab@0
  8069h TL2 mpy  y0, x1 || mpyus y1, x0 || add3  p0, p1, Ab@8
  8079h TL2 mpy  y0, x1 || mpyus y1, x0 || add3a p0, p1, Ab@8
  8469h TL2 mpy  y0, x1 || mpyus y1, x0 || sub3  p0, p1, Ab@8
  8479h TL2 mpy  y0, x1 || mpyus y1, x0 || sub3a p0, p1, Ab@8
  D584h TL2 mpy  y0, x1 || mpyus y1, x0 || add3aa p0, p1, Ab@0
  D59Dh TL2 mpy  y0, x1 || mpyus y1, x0 || sub p0, p1, Bx@5
  D5A0h TL2 mpy  y0, x1 || mpyus y1, x0 || addsub p0, p1, Ab@0
  0800h TL  mpyi NoReverse, Implied p0, y0, Imm8s@0   ;multiply  ;aka "mpys"
  D100h TL  mpysu MemR45@2, MemR0123@0 || R0123@0stepZIDS@3, R45@2stepZIDS@5
  8100h TL  mpysu MemRn@0, Imm16@16    || Rn@0stepZIDS@3
  8120h TL  mpysu y0, MemRn@0          || Rn@0stepZIDS@3
  8140h TL  mpysu y0, Register@0
  CA00h TL2 mpysu MemR45@5, MemR01@5
             || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA01h TL2 mpysu MemR45@5, MemR01@5
             || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA02h TL2 mpysu MemR45@5, MemR01@5
             || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3aa p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA03h TL2 mpysu MemR45@5, MemR01@5
             || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || sub3aa p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA04h TL2 mpysu MemR45@5, MemR01@5
             || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA05h TL2 mpysu MemR45@5, MemR01@5
             || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3a  p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA06h TL2 mpysu MemR45@5, MemR01@5
             || mpysu MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3aa p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  CA07h TL2 mpysu MemR45@5, MemR01@5
             || mpyus MemR45@5offsZI@4, MemR01@5offsZI@3
             || add3aa p0, p1, Ab@6 || R01@5stepII2@3, R45@5stepII2@4
  5EA2h TL2 mpysu y0, r6
  D080h TL  msu  MemR45@2,MemR0123@0,Ax@8 || R0123@0stepZIDS@3, R45@2stepZIDS@5
  90C0h TL  msu  MemRn@0, Imm16@16,  Ax@8 || Rn@0stepZIDS@3 ;multiply, subtract
  9080h TL  msu  y0, MemRn@0, Ax@8 || Rn@0stepZIDS@3
  90A0h TL  msu  y0, Register@0, Ax@8
  B000h TL  msu  y0,MemImm8@0, Ax@8
  9462h TL2 msu  y0, r6, Ax@0
  8264h TL2 msusu y0, MemR0425@3, Ax@8 || R0425@3stepII2D2S@0
  6790h TL  neg  Ax@12, Cond@0 ;aX=0-aX
  0000h TL  nop
  94C0h TL  norm Ax@8, Bogus MemRn@0 || Rn@0stepZIDS@3  ;if N=0 (aX=aX*2,rN+/-)
  6780h TL  not  Ax@12, Cond@0 ;aX=not aX
  D4F8h TL  or   MemImm16@16, Ax@8
  A000h TL  or   MemImm8@0, Ax@8
  80C0h TL  or   Imm16@16, Ax@8
  C000h TL  or   Imm8u@0, Ax@8
  D4D8h TL  or   MemR7Imm16@16, Ax@8
  4000h TL  or   MemR7Imm7s@0, Ax@8
  8080h TL  or   MemRn@0, Ax@8 || Rn@0stepZIDS@3
  80A0h TL  or   RegisterP0@0, Ax@8
  D291h TL2 or   Ab@10, Ax@6, Ax@5
  D4A4h TL2 or   Ax@8, Bx@1, Ax@0
  D3C4h TL2 or   b0, Bx@1, Ax@0
  D7C4h TL2 or   b1, Bx@1, Ax@0
  D388h TL2 or   r6, Ax@4
  67B0h TL  pacr Implied Const8000h, Implied p0, Ax@12, Cond@0 ;aX=shfP+8000h
  D7C2h TL2 pacr1 Implied Const8000h, Implied p1, Ax@0
  5E60h TL  pop  Register@0
  47B4h TL2 pop  Abe@0
  80C7h TL2 pop  ArArpSttMod@8
  0006h TL2 pop  Bx@5, Unused1@0
  D7F4h TL2 pop  prpage, Unused2@0
  D496h TL2 pop  Px@0
  0024h TL2 pop  r6, Unused1@0
  D7F0h TL2 pop  repc, Unused2@0
  D494h TL2 pop  x0
  D495h TL2 pop  x1
  0004h TL2 pop  y1, Unused1@0
  47B0h TL2 popa Ab@0
  5F40h TL  push Imm16@16
  5E40h TL  push Register@0
  D7C8h TL2 push Abe@1, Unused1@0
  D3D0h TL2 push ArArpSttMod@0
  D7FCh TL2 push prpage, Unused2@0
  D78Ch TL2 push Px@1, Unused1@0
  D4D7h TL2 push r6, Unused1@5
  D7F8h TL2 push repc, Unused2@0
  D4D4h TL2 push x0, Unused1@5
  D4D5h TL2 push x1, Unused1@5
  D4D6h TL2 push y1, Unused1@5
  4384h TL2 pusha Ax@6, Unused2@0
  D788h TL2 pusha Bx@1, Unused1@0
  0C00h TL  rep  Imm8u@0    ;repeat next opcode N+1 times
  0D00h TL  rep  Register@0 ;repeat next opcode N+1 times
  0002h TL2 rep  r6, Unused1@0
  4580h TL  ret  Cond@0      ;=pop pc
  D780h TL  retd    ;delayed return (after 2 clks)
  45C0h TL  reti Cond@0          ;Don't context switch
  45D0h TL  reti Cond@0, context ;Do context switch
  D7C0h TL  retid   ;delayed, from interrupt
  D3C3h TL2 retid context
  0900h TL  rets Imm8u@0          ;ret+dealloc sp (for INCOMING pushed params)
  67A0h TL  rnd  Implied Const8000h, Ax@12, Cond@0 ;aX=aX+8000h
  6750h TL  rol  Implied Const1,     Ax@12, Cond@0 ;aX=aX rcl 1 (37bit rotate)
  6F50h TL  rol  Implied Const1,     Bx@12, Cond@0 ;bX=bX rcl 1 (37bit rotate)
  6740h TL  ror  Implied Const1,     Ax@12, Cond@0 ;aX=aX rcr 1 (37bit rotate)
  6F40h TL  ror  Implied Const1,     Bx@12, Cond@0 ;bX=bX rcr 1 (37bit rotate)
  E300h TL  rst  Imm16@16, MemImm8@0
  82E0h TL  rst  Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  83E0h TL  rst  Imm16@16, Register@0
  47B9h TL2 rst  Imm16@16, r6
  4388h TL2 rst  Imm16@16, SttMod@0
  E100h TL  set  Imm16@16, MemImm8@0
  80E0h TL  set  Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  81E0h TL  set  Imm16@16, Register@0
  47B8h TL2 set  Imm16@16, r6
  43C8h TL2 set  Imm16@16, SttMod@0
  D280h TL  shfc Implied sv, Ab@10, Ab@5, Cond@0
  9240h TL  shfi Implied Imm6s@0, Ab@10, Ab@7, Bogus Imm6s@0
  6720h TL  shl  Implied Const1,     Ax@12, Cond@0 ;aX=aX*2
  6F20h TL  shl  Implied Const1,     Bx@12, Cond@0 ;bX=bX*2
  6730h TL  shl4 Implied Const4,     Ax@12, Cond@0 ;aX=aX*10h
  6F30h TL  shl4 Implied Const4,     Bx@12, Cond@0 ;bX=bX*10h
  6700h TL  shr  Implied Const1,     Ax@12, Cond@0 ;aX=aX/2
  6F00h TL  shr  Implied Const1,     Bx@12, Cond@0 ;bX=bX/2
  6710h TL  shr4 Implied Const4,     Ax@12, Cond@0 ;aX=aX/10h
  6F10h TL  shr4 Implied Const4,     Bx@12, Cond@0 ;bX=bX/10h
  BA00h TL  sqr  MemImm8@0
  9A80h TL  sqr  MemRn@0 || Rn@0stepZIDS@3
  9AA0h TL  sqr  Register@0
  D790h TL2 sqr  Abh@2 || sqr Abl@2 || add3 p0, p1, Ab@0
  49C4h TL2 sqr  Abh@4 || mpysu Abh@4, Abl@4 || add3a p0, p1, Ab@0
  4B00h TL2 sqr  MemR0425@4 || sqr MemR0425@4offsZIDZ@2 || add3 p0, p1, Ab@0
             || R0425@4stepII2D2S@2
  5F41h TL2 sqr  r6
  BC00h TL  sqra MemImm8@0, Ax@8
  9C80h TL  sqra MemRn@0, Ax@8 || Rn@0stepZIDS@3
  9CA0h TL  sqra Register@0, Ax@8
  9062h TL2 sqra r6, Ax@8, Unused1@0
  D4FFh TL  sub  MemImm16@16, Ax@8
  AE00h TL  sub  MemImm8@0, Ax@8
  8EC0h TL  sub  Imm16@16, Ax@8
  CE00h TL  sub  Imm8u@0, Ax@8
  D4DFh TL  sub  MemR7Imm16@16, Ax@8
  4E00h TL  sub  MemR7Imm7s@0, Ax@8
  8E80h TL  sub  MemRn@0, Ax@8 || Rn@0stepZIDS@3
  8EA0h TL  sub  RegisterP0@0, Ax@8
  8A61h TL2 sub  Ab@3, Bx@8
  8861h TL2 sub  Bx@4, Ax@3
  8064h TL2 sub  MemR01@8, sv, Abh@3 || add MemR01@8offsZI@0, sv, Abl@3
             || mov MemR45@8, sv || R01@8stepII2@0, R45@8stepII2@1
  5DE0h TL2 sub  MemR04@1, sv, Abh@2 || add MemR04@1offsZI@0, sv, Abl@2
             || R04@1stepII2@0
  6FC0h TL2 sub  MemR45@2, MemR01@2, Abh@3
             || add MemR45@2offsZI@1, MemR01@2offsZI@0, Abl@3
             || R01@2stepII2@0, R45@2stepII2@1
  6FE0h TL2 sub  MemR45@2, MemR01@2, Abh@3
             || sub MemR45@2offsZI@1, MemR01@2offsZI@0, Abl@3
             || R01@2stepII2@0, R45@2stepII2@1
  5D80h TL2 sub  MemR45@2, sv, Abh@3 || add MemR45@2offsZI@1, sv, Abl@3
             || mov MemR01@2, sv || R01@2stepII2@0, R45@2stepII2@1
  5DC2h TL2 sub  p0, p1, Ab@2
  D4B9h TL2 sub  p1, Ax@8
  8FD0h TL2 sub  Px@1, Bx@0
  D38Fh TL2 sub  r6, Ax@4
  80C6h TL2 sub3 p0, p1, Ab@10
  82C6h TL2 sub3a p0, p1, Ab@10
  83C6h TL2 sub3aa p0, p1, Ab@10
  5DC3h TL2 suba p0, p1, Ab@2
  B600h TL  subh MemImm8@0, Ax@8
  9680h TL  subh MemRn@0, Ax@8 || Rn@0stepZIDS@3
  96A0h TL  subh Register@0, Ax@8
  5E23h TL2 subh r6, Ax@8
  B800h TL  subl MemImm8@0, Ax@8
  9880h TL  subl MemRn@0, Ax@8 || Rn@0stepZIDS@3
  98A0h TL  subl Register@0, Ax@8
  5E22h TL2 subl r6, Ax@8
  EF00h TL  subv Imm16@16, MemImm8@0
  8EE0h TL  subv Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  8FE0h TL  subv Imm16@16, Register@0
  47BFh TL2 subv Imm16@16, r6
  4980h TL  swap SwapTypes4@0
  0020h TL  trap                  ;software interrupt
  A800h TL  tst0 Axl@8, MemImm8@0
  8880h TL  tst0 Axl@8, MemRn@0 || Rn@0stepZIDS@3
  88A0h TL  tst0 Axl@8, Register@0
  E900h TL  tst0 Imm16@16, MemImm8@0
  88E0h TL  tst0 Imm16@16, MemRn@0 || Rn@0stepZIDS@3
  89E0h TL  tst0 Imm16@16, Register@0
  D38Ch TL2 tst0 Axl@4, r6
  47BCh TL2 tst0 Imm16@16, r6
  9470h TL2 tst0 Imm16@16, SttMod@0
  AA00h TL  tst1 Axl@8, MemImm8@0 Implied Not
  8A80h TL  tst1 Axl@8, MemRn@0 Implied Not || Rn@0stepZIDS@3
  8AA0h TL  tst1 Axl@8, Register@0 Implied Not
  EB00h TL  tst1 Imm16@16, MemImm8@0 Implied Not
  8AE0h TL  tst1 Imm16@16, MemRn@0 Implied Not || Rn@0stepZIDS@3
  8BE0h TL  tst1 Imm16@16, Register@0 Implied Not
  D38Dh TL2 tst1 Axl@4, r6 Implied Not
  47BDh TL2 tst1 Imm16@16, r6 Implied Not
  9478h TL2 tst1 Imm16@16, SttMod@0 Implied Not
  80C1h TL2 tst4b a0l, MemR0425@10 || R0425@10stepII2D2S@8
  4780h TL2 tst4b a0l, MemR0425@2, Ax@4 || R0425@2stepII2D2S@0
  F000h TL  tstb NoReverse, Implied Not MemImm8@0, Imm4bitno@8
  9020h TL  tstb NoReverse, Implied Not MemRn@0, Imm4bitno@8 || Rn@0stepZIDS@3
  9000h TL  tstb NoReverse, Implied Not Register@0, Imm4bitno@8
  9018h TL2 tstb NoReverse, Implied Not r6, Imm4bitno@8  ;override tstb a0,Imm4
  0028h TL2 tstb NoReverse, Implied Not SttMod@0, Imm4bitno@16, Unused12@20
  5F45h TL2 vtrclr vtr0         ;vtr0=0           ;for Viterbi decoding...
  5F47h TL2 vtrclr vtr0, vtr1   ;vtr0=0, vtr1=0   ;(saved C/C1 carry flags)
  5F46h TL2 vtrclr vtr1         ;vtr1=0
  D383h TL2 vtrmov Axl@4        ;Axl=(vtr1 and FF00h)+(vtr0/100h)
  D29Ah TL2 vtrmov vtr0, Axl@0  ;Axl=vtr0
  D69Ah TL2 vtrmov vtr1, Axl@0  ;Axl=vtr1
  D781h TL2 vtrshr              ;vtr0=vtr0/2+C*8000h, vtr1=vtr1/2+C1*8000h
  D4FAh TL  xor  MemImm16@16, Ax@8
  A400h TL  xor  MemImm8@0, Ax@8
  84C0h TL  xor  Imm16@16, Ax@8
  C400h TL  xor  Imm8u@0, Ax@8
  D4DAh TL  xor  MemR7Imm16@16, Ax@8
  4400h TL  xor  MemR7Imm7s@0, Ax@8
  8480h TL  xor  MemRn@0, Ax@8 || Rn@0stepZIDS@3
  84A0h TL  xor  RegisterP0@0, Ax@8
  D38Ah TL2 xor  r6, Ax@4
  8800h TL  undefined Unused5@0, Unused1@8 ;(mpy/mpys without A in bit11)
  8820h TL  undefined Unused5@0, Unused1@8 ;(mpy/mpys without A in bit11)
  8840h TL  undefined Unused5@0, Unused1@8 ;(mpy/mpys without A in bit11)
  D800h TL  undefined Unused7@0, Unused1@8 ;(mpy/mpys without A in bit11)
  9B80h TL  undefined Unused6@0  ;(sqr without A in bit8)
  BB00h TL  undefined Unused8@0  ;(sqr without A in bit8)
  E800h TL  undefined Unused8@0  ;(mpy without A in bit11)
  5EA1h TL2 undefined Unused1@1  ;(mpy/mpys without A in bit11)
  5DFCh TL2 undefined
  8CDEh TL2 undefined
  D3C1h TL2 undefined
  5EB4h TL2 undefined Unused2@0


DSi TeakLite II Operand Encoding

Syntax Notes
The official Teak syntax specifies all operands in "source,dest" order, that's opposite of most other ASM languages which use "dest,source" order (except 68000 processors, which the Teak is apparently inspired on). One exception are instructions tagged "NoReverse" in the opcode list: These ones do have the operands ordered as how one would usually expect them.
Operands tagged as "Implied xx" are effectively used by the hardware, although the official syntax doesn't specify them in source code. On the other hand, operands tagged as "Bogus xx" are specified in official source code syntax, although the hardware doesn't actually use that operands in that form.
The nocash (dis-)assembler syntax reverses the operand order (except those flagged as NoReverse), removes Bogus operands, and inserts Implied operands. Moreover, immediates and memory operands are specified differently...

Memory Operands
  name          native                  nocash
  MemRn         (Rn)                    [Rn]
  MemSp         (sp)                    [sp]
  ProgMemRn     (Rn)                    [code:movpd:Rn]
  ProgMemAxl    (Axl)                   [code:movpd:Axl]
  ProgMemAx     (Ax)                    [code:Ax]
  ProgMemAx_..  (Ax),(Ax+)              [code:Ax]:[code:Ax+]
  MemImm8       0xNN                    [page:NNh]
  MemImm16      [##0xNNNN]              [NNNNh]
  MemR7Imm7s    (r7+#0xNN), (r7+#-NNN)  [r7+/-NNh]
  MemR7Imm16    (r7+##0xNNNN)           [r7+NNNNh]

Immediates/Addresses
  Address18     0xNNNNN                 NNNNNh         ;for bkrep/br/call
  Address16     0xNNNN                  NNNNh          ;for bkrep
  RelAddr7      0xNNNN                  NNNNh          ;for jmp
  ImmN:         #0xNNNN                 NNNNh
  ImmNs:        #0xNN, #-NNN            +/-NNh
  Imm16:        ##0xNNNN                NNNNh
  Imm4bitno:    ...                     1 shl N
  ConstZero     <implied>               0000h
  Const1        <implied>               0001h
  Const4        <implied>               0004h
  Const8000h    <implied>               8000h

Operand Encoding
Below shows the binary encoding for registers/conditions. For example, "Ab@10" in the opcode list can be "b0,b1,a0,a1" encoded in bit10-11. Some instructions re-use the same bitfield for multiple operands (eg. when performing two operations on the SAME operand, or when expecting DIFFERENT operands: for "Ax@12,Ax@not12" one of the registers must "a0", and the other must be "a1").

  Register:  RegisterP0:  Ax:     Axl:    Axh:            Px:
  00: r0     00: r0       0: a0   0: a0l  0: a0h          0: p0
  01: r1     01: r1       1: a1   1: a1l  1: a1h          1: p1
  02: r2     02: r2
  03: r3     03: r3       Bx:     Bxl:    Bxh:            Ablh:
  04: r4     04: r4       0: b0   0: b0l  0: b0h          0: b0l
  05: r5     05: r5       1: b1   1: b1l  1: b1h          1: b0h
  06: r7     06: r7                                       2: b1l
  07: y0     07: y0       Ab:     Abl:    Abh:    Abe:    3: b1h
  08: st0    08: st0      0: b0   0: b0l  0: b0h  0: b0e  4: a0l
  09: st1    09: st1      1: b1   1: b1l  1: b1h  1: b1e  5: a0h
  0A: st2    0A: st2      2: a0   2: a0l  2: a0h  2: a0e  6: a1l
  0B: p0h !! 0B: p0 !!    3: a1   3: a1l  3: a1h  3: a1e  7: a1h
  0C: pc     0C: pc
  0D: sp     0D: sp       Cond:
  0E: cfgi   0E: cfgi     0: true  ;Always                    ;always
  0F: cfgj   0F: cfgj     1: eq    ;Equal to zero             ;Z=1
  10: b0h    10: b0h      2: neq   ;Not equal to zero         ;Z=0
  11: b1h    11: b1h      3: gt    ;Greater than zero         ;M=0 and Z=0
  12: b0l    12: b0l      4: ge    ;Greater or equal to zero  ;M=0
  13: b1l    13: b1l      5: lt    ;Less than zero            ;M=1
  14: ext0   14: ext0     6: le    ;Less or equal to zero     ;M=1 or Z=1
  15: ext1   15: ext1     7: nn    ;Normalize flag is cleared ;N=0
  16: ext2   16: ext2     8: c     ;Carry flag is set         ;C=1
  17: ext3   17: ext3     9: v     ;Overflow flag is set      ;V=1
  18: a0     18: a0       A: e     ;Extension flag is set     ;E=1
  19: a1     19: a1       B: l     ;Limit flag is set         ;L=1
  1A: a0l    1A: a0l      C: nr    ;R flag is cleared         ;R=0
  1B: a1l    1B: a1l      D: niu0  ;Input user pin 0 cleared  ;IUSER0=0
  1C: a0h    1C: a0h      E: iu0   ;Input user pin 0 set      ;IUSER0=1
  1D: a1h    1D: a1h      F: iu1   ;Input user pin 1 set      ;IUSER1=1
  1E: lc     1E: lc
  1F: sv     1F: sv

  R0123457y0:       Rn:                 ArArpSttMod:  ArArp:       SttMod:
  0: r0             0: r0               0: ar0        0: ar0       0: stt0
  1: r1             1: r1               1: ar1        1: ar1       1: stt1
  2: r2             2: r2               2: arp0       2: arp0      2: stt2
  3: r3             3: r3               3: arp1       3: arp1      3: reserved
  4: r4             4: r4               4: arp2       4: arp2      4: mod0
  5: r5             5: r5               5: arp3       5: arp3      5: mod1
  6: r7  ;aka rb    6: r6 ;TL2 only     6: reserved   6: reserved  6: mod2
  7: y0  ;aka y     7: r7 ;TL2 only     7: reserved   7: reserved  7: mod3
                                        8: stt0
  R01:     R04:     R45:                9: stt1       Ar:       BankFlags:
  0: r0    0: r0    0:r4                A: stt2       0: ar0    01h: cfgi
  1: r1    1: r4    1:r5                B: reserved   1: ar1    02h: r4
                                        C: mod0                 04h: r1
  R0123:   R0425:   R4567:              D: mod1       Arp:      08h: r0
  0: r0    0: r0    0: r4               E: mod2       0: arp0   10h: r7   ;TL2
  1: r1    1: r4    1: r5               F: mod3       1: arp1   20h: cfgj ;TL2
  2: r2    2: r2    2: r6                             2: arp2
  3: r3    3: r5    3: r7                             3: arp3

  SwapTypes:
  val native           nocash         ;meaning
  0:  (a0,b0)          a0,b0          ;a0 <--> b0                ;flags(a0)
  1:  (a0,b1)          a0,b1          ;a0 <--> b1                ;flags(a0)
  2:  (a1,b0)          a1,b0          ;a1 <--> b0                ;flags(a1)
  3:  (a1,b1)          a1,b1          ;a1 <--> b1                ;flags(a1)
  4:  (a0,b0),(a1,b1)  a0:a1,b0:b1    ;a0 <--> b0 and a1 <--> b1 ;flags(a0)
  5:  (a0,b1),(a1,b0)  a0:a1,b1:b0    ;a0 <--> b1 and a1 <--> b0 ;flags(a0)
  6:  (a0,b0,a1)       a1,b0,a0       ;a0 --> b0 --> a1          ;flags(a1)
  7:  (a0,b1,a1)       a1,b1,a0       ;a0 --> b1 --> a1          ;flags(a1)
  8:  (a1,b0,a0)       a0,b0,a1       ;a1 --> b0 --> a0          ;flags(a0)
  9:  (a1,b1,a0)       a0,b1,a1       ;a1 --> b1 --> a0          ;flags(a0)
  A:  (b0,a0,b1)       b1,a0,b0       ;b0 --> a0 --> b1          ;flags(a0)!
  B:  (b0,a1,b1)       b1,a1,b0       ;b0 --> a1 --> b1          ;flags(a1)!
  C:  (b1,a0,b0)       b0,a0,b1       ;b1 --> a0 --> b0          ;flags(a0)!
  D:  (b1,a1,b0)       b0,a1,b1       ;b1 --> a1 --> b0          ;flags(a1)!
  E:  reserved         reserved       ;-                         ;-
  F:  reserved         reserved       ;-                         ;-

offs and step
Memory operands with "offs" allow to read from [Rn], [Rn+1], or [Rn-1]. Operands with "step" allow to increment/decrement registers (for old TL opcodes this is usually specified alongsides with memory operands, for new TL2 opcodes it's typically specified as separate "||" instruction (eg. "|| Rn@0stepZIDS@3"; which can be omitted if the step is zero).
The official syntax wants "+1,-1" abbreviated to "+,-" in some cases (but not abbreviated in other cases). step "+s" does probably refer to "stepi or stepj", but it's rather unclear which one, maybe stepi is used for r0..r3, and stepj for r4..r7, or vice versa... or maybe it depends on each opcode (particulary opcodes that allow to use "Rn" (r0..r7) might use the same step in ALL cases).
 offsZI:                           ;maybe offsAr01 ?
  0: ''         ;Z  (zero)
  1: '+'        ;I  (increment)
 offsI:
  0: '+'        ;I  (increment)
 offsZIDZ:                         ;aka offsAr0123
  0: ''         ;Z  (zero)
  1: '+'        ;I  (increment)
  2: '-'        ;D  (decrement)
  3: ''         ;Z  (zero)
 stepZIDS:
  0: ''         ;Z  (zero)
  1: '+1'       ;I  (increment)
  2: '-1'       ;D  (decrement)
  3: '+s'       ;S  (add step)           ;XXX ?   see "stepi" and "stepj"
 modrstepZIDS:
  0: ''         ;Z  (zero)
  1: '+'        ;I  (increment)
  2: '-'        ;D  (decrement)
  3: '+s'       ;S  (add step)           ;XXX ?   see "stepi" and "stepj"
 stepII2D2S:                      ;aka stepAr0123@
  0: '+1'       ;I  (increment)
  1: '+2'       ;I2 (increment twice)
  2: '-2'       ;D2 (decrement twice)
  3: '+s'       ;S  (add step)           ;XXX ?   see "stepi" and "stepj"
 stepD2S:
  0: '-2'       ;D2 (decrement twice)
  1: '+s'     ' ;S  (add step)           ;XXX ?   see "stepi" and "stepj"
 modrstepII2D2S0:
  0: '+'        ;I  (increment)
  1: '+2'       ;I2 (increment twice)
  2: '-2'       ;D2 (decrement twice)
  3: '+s0'      ;S0 (add step0 ?)        ;XXX ??  see "stepi0" and "stepj0"
 stepII2:
  0: '+1'       ;I  (increment)
  1: '+2'       ;I2 (increment twice)
 modrstepI2:
  0: '+2'       ;I2 (increment twice)
 modrstepD2:
  0: '-2'       ;D2 (decrement twice)

Note: The "modr" opcodes are probably just incrementing/decrementing registers (with optional "modulo"), although the official syntax specifies their operands in brackets, ie. as if they were doing memory accesses.


DSi New Shared WRAM (for ARM7, ARM9, DSP)

Shared WRAM (total 800Kbytes)
  Old WRAM-0/1 32Kbytes (2x16K), mappable to ARM7, or ARM9
  New WRAM-A  256Kbytes (4x64K), mappable to ARM7, or ARM9
  New WRAM-B  256Kbytes (8x32K), mappable to ARM7, ARM9, or DSP-program memory
  New WRAM-C  256Kbytes (8x32K), mappable to ARM7, ARM9, or DSP-data memory
New WRAM mapping is done in three steps: First, releasing Slot Write Protect (on ARM7 side). Then, mapping the physical banks to logical slots (on ARM9 side). And finally, mapping those slots to actual memory addresses (on ARM7 and ARM9 sides). As an extra step, one may set Slot Write Protect flags (on ARM7 side) to prevent ARM9 from applying further changes.

 ____________________________ Slot Write Protect ______________________________

MBK9 is READ/WRITE-ABLE only on ARM7 side (and READ-ONLY on ARM9).

4004060h - DSi9 - MBK9, WRAM-A/B/C Slot Write Protect (undocumented) (R)
4004060h - DSi7 - MBK9, WRAM-A/B/C Slot Write Protect (undocumented) (R/W)
  0-3   WRAM-A, Port 4004040h-4004043h Write (0=Writeable by ARM9, 1=Read-only)
  4-7   Unknown/Unused (0)
  8-15  WRAM-B, Port 4004044h-400404Bh Write (0=Writeable by ARM9, 1=Read-only)
  16-23 WRAM-C, Port 400404Ch-4004053h Write (0=Writeable by ARM9, 1=Read-only)
  24-31 Unknown/Unused (0)   ;but, carthdr has nonzero data for it?
Selects whether ARM9 may write to WRAM slot registers at 4004040h-4004053h (in Read-only mode neither ARM7 nor ARM9 can write to those registers; that applies only to that registers, ie. the memory itself isn't write-protected).

 ______________________________ Slot Allocation ______________________________

MBK1-MBK5 are READ-ONLY on ARM7 side, and either READ-ONLY or READ/WRITE-ABLE on ARM9 side (depending on the MBK9 setting).

4004040h - DSi - MBK1.0, WRAM-A0 - 64K, mappable to ARM7, or ARM9
4004041h - DSi - MBK1.1, WRAM-A1 - 64K, mappable to ARM7, or ARM9
4004042h - DSi - MBK1.2, WRAM-A2 - 64K, mappable to ARM7, or ARM9
4004043h - DSi - MBK1.3, WRAM-A3 - 64K, mappable to ARM7, or ARM9
  0    Master (0=ARM9, 1=ARM7)
  1    Not used
  2-3  Offset (0..3) (slot 0..3) (LSB of address in 64Kbyte units)
  4-6  Not used
  7    Enable (0=Disable, 1=Enable)
In Cooking Coach, above four bytes are locked via MBK9 (not write-able, always 81h,85h,89h,8Dh).

4004044h - DSi - MBK2.0, WRAM-B0 - 32K, mappable to ARM7, ARM9, or DSP/code
4004045h - DSi - MBK2.1, WRAM-B1 - 32K, mappable to ARM7, ARM9, or DSP/code
4004046h - DSi - MBK2.2, WRAM-B2 - 32K, mappable to ARM7, ARM9, or DSP/code
4004047h - DSi - MBK2.3, WRAM-B3 - 32K, mappable to ARM7, ARM9, or DSP/code
4004048h - DSi - MBK3.0, WRAM-B4 - 32K, mappable to ARM7, ARM9, or DSP/code
4004049h - DSi - MBK3.1, WRAM-B5 - 32K, mappable to ARM7, ARM9, or DSP/code
400404Ah - DSi - MBK3.2, WRAM-B6 - 32K, mappable to ARM7, ARM9, or DSP/code
400404Bh - DSi - MBK3.3, WRAM-B7 - 32K, mappable to ARM7, ARM9, or DSP/code
  0-1  Master (0=ARM9, 1=ARM7, 2 or 3=DSP/code)
  2-4  Offset (0..7) (slot 0..7) (LSB of address in 32Kbyte units)
  5-6  Not used (0)
  7    Enable (0=Disable, 1=Enable)

400404Ch - DSi - MBK4.0, WRAM-C0 - 32K, mappable to ARM7, ARM9, or DSP/data
400404Dh - DSi - MBK4.1, WRAM-C1 - 32K, mappable to ARM7, ARM9, or DSP/data
400404Eh - DSi - MBK4.2, WRAM-C2 - 32K, mappable to ARM7, ARM9, or DSP/data
400404Fh - DSi - MBK4.3, WRAM-C3 - 32K, mappable to ARM7, ARM9, or DSP/data
4004050h - DSi - MBK5.0, WRAM-C4 - 32K, mappable to ARM7, ARM9, or DSP/data
4004051h - DSi - MBK5.1, WRAM-C5 - 32K, mappable to ARM7, ARM9, or DSP/data
4004052h - DSi - MBK5.2, WRAM-C6 - 32K, mappable to ARM7, ARM9, or DSP/data
4004053h - DSi - MBK5.3, WRAM-C7 - 32K, mappable to ARM7, ARM9, or DSP/data
  0-1  Master (0=ARM9, 1=ARM7, 2 or 3=DSP/data)
  2-4  Offset (0..7) (slot 0..7) (LSB of address in 32Kbyte units)
  5-6  Not used (0)
  7    Enable (0=Disable, 1=Enable)

 ______________________________ Address Mapping ______________________________

MBK6-8 exist as separate READ/WRITE-ABLE registers on ARM7 and ARM9 side (making it six registers in total).

4004054h - DSi - MBK6, WRAM-A, 64K..256K mapping (R/W)
  0-3   Not used (0)
  4-11  Start Address (3000000h+N*10000h)     ;=3000000h..3FF0000h
  12-13 Image Size (0 or 1=64KB/Slot0, 2=128KB/Slot0+1+2??, 3=256KB/Slot0..3)
  14-19 Not used (0)
  20-28 End Address   (3000000h+N*10000h-1)   ;=2FFFFFFh..4FEFFFFh
  29-31 Not used (0)

4004058h - DSi - MBK7, WRAM-B (R/W)
400405Ch - DSi - MBK8, WRAM-C (R/W)
  0-2   Not used (0)
  3-11  Start Address (3000000h+N*8000h)      ;=3000000h..3FF8000h
  12-13 Image Size (0=32K/Slot0,1=64KB/Slot0-1,2=128KB/Slot0-3,3=256KB/Slot0-7)
  14-18 Not used (0)
  19-28 End Address   (3000000h+N*8000h-1)    ;=2FFFFFFh..4FF7FFFh
  29-31 Not used (0)

Uh, but, ARM7 3800000h..3FFFFFFh contains OTHER memory (ARM7-WRAM) !?

 ___________________________________ Notes ___________________________________

Slots and Image Size vs Start/End Addresses
When using Image Size of 4 slots, then Memory at 3000000h..3FFFFFFh is:
  Slots  0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,etc.
When start=6, and End=12, then (with above example), only following is mapped:
  Slots  -,-,-,-,-,-,2,3,0,1,2,3,-,-,-,-,etc.
Observe that the mapped region starts with Slot 2 (not Slot 0) in that case.
Moreover, some slots may be empty (disabled, or mapped to another CPU), so, if Slot 3 is empty (disabled or mapped to another CPU), then memory appears to look somewhat as so:
  Slots  -,-,-,-,-,-,2,z,0,1,2,z,-,-,-,-,etc.
Whereas, the "z" areas seem to read as zerofilled memory blocks (rather than mirroring to underlaying WRAM's of lower priority).

Overlapping WRAM regions
  New Shared-WRAM-A   Highest Priority
  New Shared-WRAM-B   High Priority
  New Shared-WRAM-C   Low Priority
  Old Shared-WRAM-0/1 Lowest Priority
  Old ARM7-WRAM       Whatever Priority (unknown...)
  I/O ports 4xxxxxxh  Whatever Priority (unknown...)
Overlapping WRAM slots
  Unknown what happens when selecting multiple WRAM blocks to the same slot?

The initial MBK values are derived from carthdr.
Exploits for DSi cartridges & DSiware usually have ARM7.MBK registers disabled via SCFG_EXT7, making it impossible to change that ARM7 registers; the ARM9.MBK registers are usually kept enabled, nethertheless, the ARM7.MBK9 setting can apply some restrictions to ARM9 side (for example, in Cooking Coach, WRAM-A is controlled via ARM7.MBK1, so ARM9 can control WRAM-B and WRAM-C via ARM9.MBK2-5 only).


DSi New DMA (NDMA)

The DSi has four New DMA channels for ARM7 and ARM9 each (eight New DMA channels in total). The old NDS-style DMA channels do still exist, too [though unknown which priority they have in relation to new channels].

4004100h - DSi - NDMAGCNT NewDMA Global Control (R/W) [00000000h]
  0-15  Unused (0)
  16-19 Cycle Selection (0=None, 1..15=1..16384 clks) ;1 SHL (N-1)
  20-30 Unused (0)
  31    DMA Arbitration Mode (0=NDMA0=HighestPriority, 1=RoundRobinPriority)
CycleSelection is used ONLY in RoundRobin mode; if so... then it does specify the number of cycles that can be executed by ARM9 and DSP <CPUs?> during NDMA?

4004104h+x*1Ch - NDMAxSAD - NewDMAx Source Address (R/W) [00000000h]
4004108h+x*1Ch - NDMAxDAD - NewDMAx Destination Address (R/W) [00000000h]
  0-1   Unused (0)
  2-31  DMA Source/Destination Address, in 4-byte steps

400410Ch+x*1Ch - NDMAxTCNT - NewDMAx Total Length for Repeats (R/W) [0]
  0-27  Total Number of Words to Transfer (1..0FFFFFFFh, or 0=10000000h)
  28-31 Unused (0)
Not used in "Start immediately" mode (which doesn't repeat).
Not used in "Repeat infinitely" mode (which repeats forever).
Used only in "Repeat until NDMAxTCNT" mode (for example, to define the total size of the Camera picture).
Total Length isn't required to be a multiple of the Logical or Physical Block Sizes (for example the DSi launcher uses Total=64h with Log=8/Phys=8; in that case only 4 words (instead of 8 words) are transferred for the last block).

4004110h+x*1Ch - NDMAxWCNT - NewDMAx Logical Block Size
  0-23  Number of Words to Transfer       (1..00FFFFFFh, or 0=01000000h)
  24-31 Unused (0)
Should be a multiple of the Physical Block Size specified in NDMAxCNT.Bit16-19.
The bus will be monopolized until the selected number of words for (physical) block transfers has completed, a single (physical) block transfer cycle will never be split up.

4004114h+x*1Ch - NDMAxBCNT - NewDMAx Block Transfer Timing/Interval
  0-15  Interval Timer (1..FFFFh, or 0=Infinite/TillTransferEnd)
  16-17 Prescaler (33.514MHz SHR (n*2)) ;0=33MHz, 1=8MHz, 2=2MHz, 3=0.5MHz
  18-31 Unused (0)
Allows to insert a delay after each (Physical?) Block.

4004118h+x*1Ch - NDMAxFDATA - NewDMAx Fill Data
  0-31  Fill Data (can be used as Fixed Source Data for memfill's)
This value is used when setting NDMAxCNT.Bit13-14=3, which causes the source data to be read directly (within 0 clock cycles) from the NDMAxFDATA (instead of from the address specified in NDMAxSAD; in this case, the NDMAxSAD is ignored/don't care).

400411Ch+x*1Ch - NDMAxCNT - NewDMAx Control
  0-9   Unused (0)
  10-11 Dest Address Update   (0=Increment, 1=Decrement, 2=Fixed, 3=Reserved)
  12    Dest Address Reload   (0=No, 1=Reload at (logical blk?) transfer end)
  13-14 Source Address Update (0=Increment, 1=Decrement, 2=Fixed, 3=FillData)
  15    Source Address Reload (0=No, 1=Reload at (logical blk?) transfer end)
  16-19 Physical Block Size   (0..0Fh=1..32768 words, aka (1 SHL n) words)
  20-23 Unused (0)
  24-28 DMA Startup Mode      (00h..1Fh, see ARM7/ARM9 startup lists below)
  29    DMA Repeat Mode       (0=Repeat until NDMAxTCNT, 1=Repeat infinitely)
  30    DMA Interrupt Enable  (0=Disable, 1=Enable)
  31    DMA Enable/Busy       (0=Disable, 1=Enable/Busy)

Startup Modes for ARM9:
  00h      Timer0                       ;\
  01h      Timer1                       ; new NDMA-specific modes
  02h      Timer2                       ;
  03h      Timer3                       ;/
  04h      DS Cartridge Slot 4100010h
  05h      Reserved (maybe 2nd DS-Cart Slot 4102010h, or GBA slot relict?)
  06h      V-Blank
  07h      H-Blank (but not during V-blank)
  08h      Display Sync (sync to H-blank drawing) ;Uh, what is BLANK-DRAWING ??
  09h      Work RAM (what?) (=probably Main memory display, as on NDS)
  0Ah      Geometry Command FIFO
  0Bh      Camera                       ;-new NDMA-specific mode
  0Ch..0Fh Reserved
  10h..1Fh Start immediately (without repeat)

Startup Modes for ARM7:
  00h      Timer0                       ;\
  01h      Timer1                       ; new NDMA-specific modes
  02h      Timer2                       ;
  03h      Timer3                       ;/
  04h      DS Cartridge Slot 4100010h
  05h      Reserved? (maybe 2nd DS-Cart Slot 4102010h, or GBA slot relict?)
  06h      V-Blank
  07h      NDS-Wifi
  08h      SD/MMC   (SD_DATA32_FIFO)    ;\
  09h      DSi-Wifi (SDIO_DATA32_FIFO)  ;
  0Ah      AES in   (AES_WRFIFO)        ; new NDMA-specific modes
  0Bh      AES out  (AES_RDFIFO)        ;
  0Ch      Microphone (MIC_DATA)        ;/
  0Dh..0Fh Reserved?
  10h..1Fh Start immediately (without repeat)

Start/repeat modes
There are three different transfer modes.
1) Start immediately (without repeat):
the transfer ends after one Logical Block, without repeat. With single IRQ (after last/only block).
2) Start by Hardware events, Repeat until NDMAxTCNT:
the transfer repeats Logical Blocks until reaching the Total Length. With single IRQ (after last block).
3) Start by Hardware events, Repeat infinitely:
the transfer repeats Logical Blocks infinitely. With multiple IRQs (one IRQ after EACH logical block).

Read-only Effect
There is something that can make port 4004104h..4004173h read-only. For example, when FFh-filling all DSi registers, and then 00h-filling them, then most DMA bits stay set (00h-filling them another time does clear them).
Maybe, during enabled transfers, ONLY the enable/busy bit is writeable?


DSi Microphone and SoundExt

4004600h - DSi7 - MIC_CNT - Microphone Control (can be 0000E10Fh)
  0-1   Data Format    (0=MakeStereo, 1=SameAsNormal?, 2=Normal, 3=None)  (R/W)
  2-3   Sampling Rate  (0..3=F/1, F/2, F/3, F/4)                          (R/W)
  4-7   Unused (0)                                                          (-)
  8     FIFO Empty     (0=No, 1=Empty)           ;0 words                   (R)
  9     FIFO Half-Full (0=No, 1=Half-Full)       ;8 or more words           (R)
  10    FIFO Full      (0=No, 1=Full)            ;16 words                  (R)
  11    FIFO Overrun   (0=No, 1=Overrun/Stopped) ;more than 16 words        (R)
  12    Clear FIFO     (0=No change, 1=Clear)    ;works only if bit15 was 0 (W)
  13-14 IRQ Enable     (0=Off, 1=Same as 3, 2=When Full, 3=When Half-Full)(R/W)
  15    Enable         (0=Disable, 1=Enable)                              (R/W)
The Sampling Rate depends on the I2S frequency in SNDEXCNT.Bit13,
  I2S=32.73kHz --> F/1=32.73kHz, F/2=16.36kHz, F/3=10.91kHz, F/4=8.18kHz
  I2S=47.61kHz --> F/1=47.61kHz, F/2=23.81kHz, F/3=15.87kHz, F/4=11.90kHz
The Sampling Rate becomes zero (no data arriving) when SNDEXCNT.Bit15=0, or when MIC_CNT.bit0-1=3, or when MIC_CNT.bit15=0, or when Overrun has occurred.

4004604h - DSi7 - MIC_DATA - Microphone Data (R)
The internal (and external) microphones are mono only. However, the "MakeStereo" data format can convert "mono to stereo" (ie. each sample is output twice, and 1st/2nd sample contain the same value; accordingly, the FIFO is getting full twice as fast).
MIC_DATA can be read by software, or via NDMA (with startup mode 0Ch and Blocksize 8 words).
  0-15  Signed 16bit Data, 1st sample    ;\16 words FIFO, aka 32 halfwords
  16-31 Signed 16bit Data, 2nd sample    ;/
Overrun Caution: If data isn't read fast enough then the Overrun flag will get set, and FIFO updates will be stopped. At that point one can still read the remaining 16 words from the FIFO, but no further words will be added to the FIFO (until clearing the FIFO and Overrun flag via MIC_CNT.bit12; which requires bit15=0 before setting bit12).

Microphone Touchscreen/sound control
DSi Touchscreen/Sound Init Flowcharts
The Sample Data tends to be 0000h or FFFFh if the microphone related TSC-registers aren't unmuted.

4004700h - DSi7 - SNDEXCNT (R/W)
  0-3     NITRO/DSP ratio                   (valid range is 0 to 8)       (R/W)
  4-12    Unknown/Unused (0)                                               (0?)
  13      Sound/Microphone I2S frequency (0=32.73 kHz, 1=47.61 kHz)  (R or R/W)
  14      Mute status (does NOT affect mic)          (?=Mute WHAT?)       (R/W)
  15      Enable Microphone (and Sound Output!)          (1=Enable)       (R/W)
Bit13 is write-able only if bit15 was zero before the write.
NITRO/DSP ratio
The DSP can generate sound output aswell, alongside the old NITRO sound mixer. The following settings configure the ratio between DSP and NITRO mixer output:
  00h      DSP sound 8/8, NITRO sound 0/8 (=DSP sound only)
  01h      DSP sound 7/8, NITRO sound 1/8
  02h      DSP sound 6/8, NITRO sound 2/8
  03h      DSP sound 5/8, NITRO sound 3/8
  04h      DSP sound 4/8, NITRO sound 4/8 (=half volume for DSP and NITRO each)
  05h      DSP sound 3/8, NITRO sound 5/8
  06h      DSP sound 2/8, NITRO sound 6/8
  07h      DSP sound 1/8, NITRO sound 7/8
  08h      DSP sound 0/8, NITRO sound 8/8 (=NITRO sound only)
  09h..0Fh Reserved
Uh, what is that? Hopefully, a volume-ratio? Preferably, no time-ratio!


DSi Advanced Encryption Standard (AES)

AES I/O Ports
DSi AES I/O Ports

AES Pseudo Code
Little Endian Code (as used in DSi hardware):
DSi AES Little-Endian High Level Functions
DSi AES Little-Endian Core Function and Key Schedule
DSi AES Little-Endian Tables and Test Values
Big Endian Code (as used more commonly, in non-DSi implementations):
DSi AES Big-Endian High Level Functions
DSi AES Big-Endian Core Function and Key Schedule
DSi AES Big-Endian Tables and Test Values
Most AES values are endian-free byte-strings, so different "endianness" does just mean to reverse the byte order of the 16/24/32-byte KEYs, the 16-byte data chunks, and the 16-byte CTR/CFB/CBC/MAC registers (in some of the latter cases it's also referring to actual endiannes, eg. for CTR increments).

AES Usage in DSi
AES-CCM is used for several SD/MMC files (using a custom Nintendo-specific CCM variant; consisting of 128K-byte data blocks with 32-byte footers):
DSi ES Block Encryption
AES-CTR is used for the Modcrypt areas defined in Cartridge Header, and for eMMC Boot Sectors and for eMMC MBR/Partitions.

AES Usage in DSi-Wifi
DSi Wifi is also supporting AES (and TKIP and WEP) encryption, the Wifi unit contains additional AES hardware for data packet encryption (however, Wifi EAPOL handshakes do require AES key unwrap implemented in software).

AES Usage in DSi-Shop
DSi Shop downloads (and system updates) are using big-endian AES-CBC, this does require an AES software implementation because the DSi's AES hardware couldn't decrypt that AES variant.


DSi AES I/O Ports

4004400h - DSi7 - AES_CNT (parts R/W)
  0-4   Write FIFO Count    (00h..10h words) (00h=Empty, 10h=Full)          (R)
  5-9   Read FIFO Count     (00h..10h words) (00h=Empty, 10h=Full)          (R)
  10    Write FIFO Flush    (0=No change, 1=Flush)                   (N/A or W)
  11    Read FIFO Flush     (0=No change, 1=Flush)                   (N/A or W)
  12-13 Write FIFO DMA Size (0..3 = 16,12,8,4 words) (2=Normal=8)    (R or R/W)
  14-15 Read FIFO DMA Size  (0..3 = 4,8,12,16 words) (1=Normal=8)    (R or R/W)
  16-18 CCM MAC Size, max(4,(N*2+2)) bytes, usually 7=16 bytes       (R or R/W)
  19    CCM Pass Associated Data to RDFIFO (0=No/Normal, 1=Yes)      (R or R/W)
          Bit19=1 is a bit glitchy: The data should theoretically arrive in
          RDFIFO immediately after writing 4 words to WRFIFO, but actually,
          Bit19=1 seems to cause 4 words held hidden in neither FIFO, until
          the first Payload block is written (at that point, the hidden
          associated words are suddenly appearing in RDFIFO)
  20    CCM MAC Verify Source (0=From AES_WRFIFO, 1=From AES_MAC)    (R or R/W)
  21    CCM MAC Verify Result (0=Invalid/Busy, 1=Verified/Okay)             (R)
  22-23 Unknown/Unused (0)                                                  (0)
  24    Key Select        (0=No change, 1=Apply key selected in Bit26-27)   (W)
  25    Key Schedule Busy (uh, always 0=ready?) (rather sth else busy?)     (R)
  26-27 Key Slot          (0..3=KEY0..KEY3, applied via Bit24)       (R or R/W)
  28-29 Mode (0=CCM/decrypt, 1=CCM/encrypt, 2=CTR, 3=Same as 2)      (R or R/W)
  30    Interrupt Enable  (0=Disable, 1=Enable IRQ on Transfer End)  (R or R/W)
  31    Start/Enable      (0=Disable/Ready, 1=Enable/Busy)                (R/W)
Bit31 gets cleared automatically shortly after all data (as indicated in AES_BLKCNT) is written to WRFIFO, and the IRQ is generated alongsides; the transfer isn't fully completed at that point since there may be still data (and CCM/encrypt MAC result) in RDFIFO.

4004404h - DSi7 - AES_BLKCNT (W)
Specifies the transfer length, counted in 16-byte blocks.
  0-15  Number of Extra associated data blocks for AES-CCM (unused for AES-CTR)
  16-31 Number of Payload data blocks (0..FFFFh = 0..FFFF0h bytes)
The length values are copied to internal counter registers on transfer start (the value in AES_BLKCNT is left unchanged during/after transfer).

4004408h - DSi7 - AES_WRFIFO (W)
400440Ch - DSi7 - AES_RDFIFO (R)
  0-31  Data
Writing to WRFIFO works even when AES_CNT.bit31=0 (the data does then stay in WRFIFO though, and doesn't arrive in RDFIFO).

4004420h - DSi7 - AES_IV (16 bytes) (W)
This contains the Initialization Vector (aka IV aka Nonce). The hardware does use that value to automatically initialize the internal CTR/CBC registers when starting encryption/decryption:
  For AES-CTR mode:  CTR[00h..0Fh] = AES_IV[00h..0Fh]
                     CBC[00h..0Fh] = not used by AES-CTR mode
  For AES-CCM mode:  CTR[00h..0Fh] = 00h,00h,00h,AES_IV[00h..0Bh],02h
                     CBC[00h..0Fh] = x0h,xxh,0xh,AES_IV[00h..0Bh],flg
The initial CTR/CBC values for AES-CCM mode are following the CCM specifications, but WITHOUT encoding the "extra associated data size" in upper bytes of first block (see CCM pseudo code chapter for details).
The CTR/CBC registers are manipulated during transfer, however, the AES_IV content is kept unchanged during/after transfer.

4004430h - DSi7 - AES_MAC (16 bytes) (W)
The MAC (Message Authentication Code) is an encrypted checksum, computed alongsides with the actual data encryption/decryption, and used only in AES-CCM mode. There are three ways how the DSi deals with MAC values:
  AES-CCM Encryption: MAC is returned in AES_RDFIFO after transfer
  AES-CCM Decryption, AES_CNT.20=0: MAC written to AES_WRFIFO after transfer
  AES-CCM Decryption, AES_CNT.20=1: MAC written to AES_MAC before transfer
The AES_MAC register and the RDFIFO/WRFIFO blocks are always 16-byte wide; when selecting a smaller MAC size in AES_CNT, then the lower bytes of that 16-byte value are 00h-padded (eg. a 6-byte MAC would appear as 00000000h, 00000000h, xxxx0000h, xxxxxxxxh), for ENCRYPT those 00h-bytes are returned in RDFIFO, for DECRYPT those padding bytes MUST be 00h (else the verification will fail).
The minimum MAC size is 4 bytes (trying to use 2 byte by setting AES_CNT.16-18 to 00h is producing the exact same result as when setting it to 01h, ie. 4-bytes)

4004440h - DSi7 - AES_KEY0 (48 bytes) (W)
4004470h - DSi7 - AES_KEY1 (48 bytes) (W)
40044A0h - DSi7 - AES_KEY2 (48 bytes) (W)
40044D0h - DSi7 - AES_KEY3 (48 bytes) (W)
  Byte 00h-0Fh  Normal 128bit Key      ;\use either normal key,
  Byte 10h-1Fh  Special 128bit Key_X   ; or special key_x/y
  Byte 20h-2Fh  Special 128bit Key_Y   ;/
Writing the last word of "Key_Y" (or any of its last four bytes, ie. byte(s) 2Ch..2Fh) causes the Normal Key to be overwritten by following values:
  Key = ((Key_X XOR Key_Y) + FFFEFB4E295902582A680F5F1A4F3E79h) ROL 42
After changing a key, one must (re-)apply it via AES_CNT.Bits 24,26-27.

DMA
The AES data would be usually transferred via two NDMA channels, one for WRFIFO, one for RDFIFO. The NDMAs should be started BEFORE setting AES_CNT.31 (else the DMA will miss the first WRFIFO data request; and DMA won't start). The DMAs 'Logical Block' sizes should match up with the block sizes selected in AES_CNT (a bigger logical block size would cause FIFO overruns/underruns, a smaller logical block size could work theoretically, but it practice it causes the DMA to hang after the first data request; apparently data requests are somewhat generated upon "empty-not-empty" transitions, rather than upon "enough data/space" status).

Reading Write-Only Values
The AES_IV register and the AES_KEY registers are fully write-able, including 8bit STRB writes; this allows to 'read' the write-only values via brute-force without any noticeable delay (ie. encrypt 16 bytes with original values, then change one byte to values 00h..FFh, and check which of those values gives same encryption result). AES_BLKCNT can be also dumped by simple counting.

Cartheader Key Request Byte
The firmware is usually destroying the AES_KEY registers before starting DSi programs. However, bits in CartHeader[1B4h] allow to "request" certain keys to be left intact.

DSi BIOS & Firmware Keys
The DSi BIOS contains several AES keys in the non-dumpable upper 32K halves; most of that keys are relocated to RAM/TCM, so they can be dumped via main memory hacks (there might be some further keys that cannot be dumped, in case they exist only in early boot stages).


DSi AES Little-Endian High Level Functions

AES-CTR (Counter)
aes_crypt_ctr(src,dst,len,nc_off,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [ctr+0..15] = [iv+0..15]                                         ;-init ctr
  n=[nc_off]
  while len>0   ;code is 100% same for ENCRYPT and DECRYPT         ;\
    if n=0                                                         ; encrypt
      aes_crypt_block(ENCRYPT,ctr,tmp)                             ; or decrypt
      littleendian(ctr)=littleendian(ctr)+1   ;increment counter   ; message
    [dst] = [src] xor [tmp+n]                                      ;
    src=src+1, dst=dst+1, len=len-1, n=(n+1) and 0Fh               ;/
  [nc_off]=n

AES-CCM (Counter with CBC-MAC)
aes_ccm_crypt(mode,src,dst,msg_len,iv,iv_len,xtra,xtra_len,mac,mac_len)
  if mac_len<4 or mac_len>16 or (mac_len and 1)=1 then error       ;\limits
  if iv_len<7 or iv_len>13 then error                              ;/
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  ctr_len = 15-iv_len                                              ;\
  [ctr+15]=ctr_len-1          ;bit3..7=zero   ;1 byte (ctr_len)    ; init ctr
  [ctr+(15-iv_len)..14] = [iv+0..(iv_len-1)]  ;7..13 bytes (iv)    ;
  [ctr+0..(14-iv_len)]=littleendian(0)  ;8..2 bytes (counter=0)    ;/
  [cbc+0..15]=littleendian(msg_len)  ;-[(iv_len+1)..15]=msg_len    ;\
  if [cbc+15..15-iv_len]<>0 then error  ;msg_len overlaps iv/flags ;
  [cbc+(15-iv_len)..14]=[iv+0..iv_len-1] ;-[1..iv_len]=iv/nonce    ;
  [cbc+15].bit7=0  ;reserved/zero   ;\                             ; init cbc
  [cbc+15].bit6=(xtra_len>0)        ; [15]=flags                   ;
  [cbc+15].bit5..3=(mac_len/2-1)    ;                              ;
  [cbc+15].bit2..0=(ctr_len-1)      ;/                             ;
  aes_crypt_block(ENCRYPT,cbc,cbc)      ;UPDATE_CBC_MAC            ;/
  if NintendoDSi then                                              ;\
    a=0 ;the DSi hardware doesn't support xtra_len encoding at all ;
  elseif xtra_len<0FF00h then                                      ;
    [cbc+14..15]=[cbc+14..15] xor littleendian(xtra_len), a=2      ; weird
  elseif xtra_len<100000000h then                                  ; encoding
    [cbc+14..15]=[cbc+14..15] xor littleendian(FFFEh)              ; for
    [cbc+10..13]=[cbc+10..13] xor littleendian(xtra_len), a=6      ; xtra_len
  else                                                             ;
    [cbc+14..15]=[cbc+14..15] xor littleendian(FFFFh)              ;
    [cbc+6..13] =[cbc+6..13]  xor littleendian(xtra_len), a=10     ;/
  while xtra_len>0                                                 ;\scatter
    z=min(xtra_len,16-a)                                           ; cbc by
    [cbc+16-a-z..(15-a)]=[cbc+16-a-z..(15-a)] xor [xtra+0..(z-1)]  ; xtra
    aes_crypt_block(ENCRYPT,cbc,cbc)    ;UPDATE_CBC_MAC            ; (if any)
    xtra=xtra+z, xtra_len=xtra_len-z, a=0                          ;/
  while msg_len>0                                                  ;\
    littleendian(ctr)=littleendian(ctr)+1   ;increment counter     ;
    aes_crypt_block(ENCRYPT,ctr,tmp)    ;CTR_CRYPT                 ;
    z=min(msg_len,16)                                              ; encrypt
    if mode=ENCRYPT                                                ; or decrypt
      [cbc+(16-z)..15] = [cbc+(16-z)..15] xor [src+0..(z-1)]       ; message
    [dst+0..(z-1)] = [src+0..(z-1)] xor [tmp+(16-z)..15]           ; body
    if mode=DECRYPT                                                ;
      [cbc+(16-z)..15] = [cbc+(16-z)..15] xor [dst+0..(z-1)]       ;
    aes_crypt_block(ENCRYPT,cbc,cbc)    ;UPDATE_CBC_MAC            ;
    src=src+z, dst=dst+z, msg_len=msg_len-z                        ;/
  [ctr+0..(14-iv_len)]=littleendian(0)  ;reset counter=0           ;\
  aes_crypt_block(ENCRYPT,ctr,tmp)      ;CTR_CRYPT                 ; message
  [cbc+0..15] = [cbc+0..15] xor [tmp+0..15]                        ; auth code
  z=mac_len                                                        ; (mac)
  IF mode=ENCRYPT then [mac+0..(z-1)] = [cbc+(16-z)..15]           ;
  IF mode=DECRYPT and [mac+0..(z-1)] <> [cbc+(16-z)..15] then error;/

AES-Key-Wrap/Unwrap
This is used for EAPOL Key Data in WPA2 Wifi packets, however, neither DSi-ARM7 nor DSi-Wifi do support that by hardware, so the unwrap (decrypt) must be implemented by software. For details see:
DS Wifi WPA/WPA2 Encryption

Below are some other AES variants (just for curiosity - those variants aren't used in DSi):

AES-CBC (Cipher-block chaining)
aes_crypt_cbc(mode,src,dst,len,iv)
  aes_setkey(mode,key,key_size]                                    ;-init key
  [cbc+0..15] = [iv+0..15]                                         ;-init cbc
  if (len AND 0Fh)>0 then error
  while len>0                                                      ;\
    if mode=ENCRYPT                                                ;
      [dst+0..15] = [src+0..15] xor [cbc+0..15]                    ;
      aes_crypt_block(mode,dst,dst)                                ; encrypt
      [cbc+0..15] = [dst+0..15]                                    ; or decrypt
    if mode=DECRYPT                                                ; message
      [tmp+0..15] = [src+0..15]                                    ;
      aes_crypt_block(mode,src,dst)                                ;
      [dst+0..15] = [dst+0..15] xor [cbc+0..15]                    ;
      [cbc+0..15] = [tmp+0..15]                                    ;
    src=src+16, dst=dst+16, len=len-16                             ;/

AES-CFB128 (Cipher feedback on 128bits, aka 16 bytes)
aes_crypt_cfb128(mode,src,dst,len,iv_off,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [cfb+0..15] = [iv+0..15]                                         ;-init cfb
  n=[iv_off]
  while len>0                                                      ;\
    if n=0 then aes_crypt_block(ENCRYPT,cfb,cfb)                   ; encrypt
    if mode=DECRYPT then c=[src], [dst]=c xor [cfb+n], [cfb+n]=c   ; or decrypt
    if mode=ENCRYPT then c=[cfb+n] xor [src], [cfb+n]=c, [dst]=c   ; message
    src=src+1, dst=dst+1, len=len-1, n=(n+1) and 0Fh               ;/
  [iv_off]=n

AES-CFB8 (Cipher feedback on 8bits, aka 1 byte, very inefficient)
aes_crypt_cfb8(mode,src,dst,len,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [cfb+0..15] = [iv+0..15]                                         ;-init cfb
  n=[iv_off]
  while len>0                                                      ;\
    aes_crypt_block(ENCRYPT,cfb,tmp)                               ;
    [cfb+1..15] = [cfb+0..14]   ;shift with 8-bit step             ; encrypt
    if mode=DECRYPT then [cfb+0] = [src+(n xor 0Fh)]               ; or decrypt
    [dst+(n xor 0Fh)] = [src+(n xor 0Fh)] xor [tmp+15]  ;shift-in  ; message
    if mode=ENCRYPT then [cfb+0] = [dst+(n xor 0Fh)]               ;
    len=len-1, n=n+1                                               ;/
  [iv_off]=n

AES-ECB (Electronic codebook, very basic, very insecure)
aes_crypt_ecb(mode,src,dst,len)
  aes_setkey(mode,key,key_size]                                    ;-init key
  if (len AND 0Fh)>0 then error
  while len>0                                                      ;\encrypt
    aes_crypt_block(mode,src,dst)                                  ; or decrypt
    src=src+16, dst=dst+16, len=len-16                             ;/message


DSi AES Little-Endian Core Function and Key Schedule

 aes_crypt_block(mode,src,dst):
  Y0 = RK[0] xor [src+00h]
  Y1 = RK[1] xor [src+04h]
  Y2 = RK[2] xor [src+08h]
  Y3 = RK[3] xor [src+0Ch]
  ;below code depending on mode:      <---ENCRYPT--->  -or-  <---DECRYPT--->
  for i=1 to nr-1
    X0      = RK[i*4+0] xor scatter32(FT,Y1,Y2,Y3,Y0)  -or-  (RT,Y3,Y2,Y1,Y0)
    X1      = RK[i*4+1] xor scatter32(FT,Y2,Y3,Y0,Y1)  -or-  (RT,Y0,Y3,Y2,Y1)
    X2      = RK[i*4+2] xor scatter32(FT,Y3,Y0,Y1,Y2)  -or-  (RT,Y1,Y0,Y3,Y2)
    X3      = RK[i*4+3] xor scatter32(FT,Y0,Y1,Y2,Y3)  -or-  (RT,Y2,Y1,Y0,Y3)
    Y0=X0, Y1=X1, Y2=X2, Y3=X3
  [dst+00h] = RK[nr*4+0] xor scatter8(FSb,Y1,Y2,Y3,Y0) -or-  (RSb,Y3,Y2,Y1,Y0)
  [dst+04h] = RK[nr*4+1] xor scatter8(FSb,Y2,Y3,Y0,Y1) -or-  (RSb,Y0,Y3,Y2,Y1)
  [dst+08h] = RK[nr*4+2] xor scatter8(FSb,Y3,Y0,Y1,Y2) -or-  (RSb,Y1,Y0,Y3,Y2)
  [dst+0Ch] = RK[nr*4+3] xor scatter8(FSb,Y0,Y1,Y2,Y3) -or-  (RSb,Y2,Y1,Y0,Y3)

 scatter32(TAB,a,b,c,d):              scatter8(TAB,a,b,c,d):
  w=      (TAB[a.bit0..7] ror 24)      w.bit0..7   = TAB[a.bit0..7]
  w=w xor (TAB[b.bit8..15] ror 16)     w.bit8..15  = TAB[b.bit8..15]
  w=w xor (TAB[c.bit16..23] ror 8)     w.bit16..23 = TAB[c.bit16..23]
  w=w xor (TAB[d.bit24..31])           w.bit24..31 = TAB[d.bit24..31]
  return w                             return w

 aes_setkey(mode,key,keysize):  ;out: RK[0..43/51/59], nr=10/12/14
  aes_generate_tables   ;<-- unless tables are already initialized
  if keysize<>128 and keysize<>192 and keysize<>256 then error  ;size in bits
  rc=01h, j=0, jj=keysize/32, nr=jj+6   ;jj=4,6,8      ;\
  for i=0 to (nr+1)*4-1                 ;nr=10,12,14   ; copy 16/24/32-byte key
    if i<jj then w=[key+(jj-1-i)*4+0..3]               ; to RK[0..3/5/7]
    else w=w xor RK[(i-jj) xor 3]                      ; and, make
    RK[i xor 3]=w, j=j+1                               ; RK[4/6/8..43/51/59]
    if j=jj then                                       ;
      w=scatter8(FSb,w,w,w,w)                          ;
      w=(w rol 8) xor (rc shl 24)                      ;
      j=0, rc=rc*2, if rc>0FFh then rc=rc xor 11Bh     ;
    if j=4 and jj=8 then w=scatter8(FSb,w,w,w,w)       ;/
  if mode=DECRYPT then
    for i=0 to nr/2-1     ;swap entries (except middle one)
      for j=0 to 3
        w=RK[i*4+j], v=RK[nr*4-i*4+j]
        RK[i*4+j]=v, RK[nr*4-i*4+j]=w
    for i=4 to nr*4-1     ;modify entries (except RK[0..3] and RK[nr*4+0..3])
      w=RK[i], w=scatter8(FSb,w,w,w,w), RK[i]=scatter32(RT,w,w,w,w)


DSi AES Little-Endian Tables and Test Values

 aes_generate_tables:
  for i=0 to 0FFh               ;compute pow and log tables...
    if i=0 then x=01h, else x=x xor x*2, if x>0FFh then x=x xor 11Bh
    pow[i]=x, log[x]=i
  for i=0 to 0FFh               ;generate the forward and reverse S-boxes...
    x=pow[0FFh-log[i]]
    x=x xor (x rol 1) xor (x rol 2) xor (x rol 3) xor (x rol 4) xor 63h
    if i=0 then x=63h
    FSb[i]=x, RSb[x]=i
  for i=0 to 0FFh               ;generate the forward and reverse tables...
    x=FSb[i]*2, if x>0FFh then x=x xor 11Bh
    FT[i]=(FSb[i]*00010101h) xor (x*01000001h)
    w=00000000h, x=RSb[i]
    if x<>00h then   ;ie. not at i=63h
      w=w+pow[(log[x]+log[0Eh]) mod 00FFh]*1000000h
      w=w+pow[(log[x]+log[09h]) mod 00FFh]*10000h
      w=w+pow[(log[x]+log[0Dh]) mod 00FFh]*100h
      w=w+pow[(log[x]+log[0Bh]) mod 00FFh]*1h
    RT[i]=w

 aes_generate_tables_results:
  pow[00h..FFh] = 01,03,05,0F,11,..,C7,52,F6,01   ;pow  ;\needed temporarily
  log[00h..FFh] = 00,FF,19,01,32,..,C0,F7,70,07   ;log  ;/for table creation
  FSb[00h..FFh] = 63,7C,77,7B,F2,..,B0,54,BB,16   ;Forward S-box
  RSb[00h..FFh] = 52,09,6A,D5,30,..,55,21,0C,7D   ;Reverse S-box
  FT[00h..FFh] = C66363A5,F87C7C84,..,2C16163A    ;Forward Table
  RT[00h..FFh] = 51F4A750,7E416553,..,D0B85742    ;Reverse Table

 aes_setkey_results:
  key = "AES-Test-Key-Str-1234567-Abcdefg"  ;use only 1st bytes for 128/192bit
  128bit ENCRYPT --> RK[0..9..30..43] = 2D534541..2783080F..93AF7DF0..827EE10D
  192bit ENCRYPT --> RK[0..9..30..51] = 79654B2D..9708FA95..2529372B..C66C19FA
  256bit ENCRYPT --> RK[0..9..30..59] = 3332312D..DF5C92A5..74174E2E..3C8ADAE6
  128bit DECRYPT --> RK[0..9..30..43] = AEABCD4D..ECD33F19..8C87B246..7274532D
  192bit DECRYPT --> RK[0..9..30..51] = AFA9796F..72A3EFE5..455646C7..37363534
  256bit DECRYPT --> RK[0..9..30..59] = 0ED52830..4601F929..415A7D65..67666564

 aes_crypt_results:
  [key+0..15]    = "AES-Test-Key-Str-1234567-Abcdefg"
  [iv+0..15]     = "Nonce/InitVector"
  [xtra+0..20]   = "Extra-Associated-Data"  ;\for CCM
  iv_len=12, mac_len=16, xtra_len=xx        ;/
  Unencrypted:   [dta+0..113Fh] = "Unencrypted-Data", 190h x "TestPadding"
  AES-ECB:       [dta+0..113Fh] = 20,24,73,88,..,44,A8,D6,A8  ;\
  AES-CBC:       [dta+0..113Fh] = A4,6F,7A,F2,..,58,C9,02,B4  ;
  AES-CFB128:    [dta+0..113Fh] = 20,C6,DB,35,..,9A,83,7F,DB  ; keysize=128
  AES-CFB8:      [dta+0..113Fh] = 55,C7,75,1C,..,24,6E,A6,D1  ;
  AES-CTR:       [dta+0..113Fh] = 20,C6,DB,35,..,AB,09,0C,75  ;
  AES-CCM:       [dta+0..113Fh] = C8,37,D7,F1,..,7B,EF,FC,12  ;
  AES-CCM (ori): [mac+0..0Fh]   = xx,xx,xx,xx,..,xx,xx,xx,xx  ;
  AES-CCM (DSi): [mac+0..0Fh]   = xx,xx,xx,xx,..,xx,xx,xx,xx  ;/
  AES-ECB:       [dta+0..113Fh] = CC,B6,4D,17,..,D3,56,3E,64  ;-keysize=192
  AES-ECB:       [dta+0..113Fh] = A9,A9,9B,3E,..,8A,C6,13,A1  ;-keysize=256


DSi AES Big-Endian High Level Functions

AES-CTR (Counter)
aes_crypt_ctr(src,dst,len,nc_off,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [ctr+0..15] = [iv+0..15]                                         ;-init ctr
  n=[nc_off]
  while len>0   ;code is 100% same for ENCRYPT and DECRYPT         ;\
    if n=0                                                         ; encrypt
      aes_crypt_block(ENCRYPT,ctr,tmp)                             ; or decrypt
      bigendian(ctr)=bigendian(ctr)+1     ;increment counter       ; message
    [dst] = [src] xor [tmp+n]                                      ;
    src=src+1, dst=dst+1, len=len-1, n=(n+1) and 0Fh               ;/
  [nc_off]=n

AES-CCM (Counter with CBC-MAC)
aes_ccm_crypt(mode,src,dst,msg_len,iv,iv_len,xtra,xtra_len,mac,mac_len)
  if mac_len<4 or mac_len>16 or (mac_len and 1)=1 then error       ;\limits
  if iv_len<7 or iv_len>13 then error                              ;/
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  ctr_len = 15-iv_len                                              ;\
  [ctr+0]=ctr_len-1     ;bit3..7=zero   ;1 byte (ctr_len)          ; init ctr
  [ctr+1..iv_len] = [iv+0..(iv_len-1)]  ;7..13 bytes (iv)          ;
  [ctr+(iv_len+1)..15]=bigendian(0)     ;8..2 bytes (counter=0)    ;/
  [cbc+0..15]=bigendian(msg_len)   ;-[(iv_len+1)..15]=msg_len      ;\
  if [cbc+0..iv_len]<>0 then error ;errif msg_len overlaps iv/flags;
  [cbc+1..iv_len]=[iv+0..iv_len-1] ;-[1..iv_len]=iv (aka nonce)    ;
  [cbc+0].bit7=0  ;reserved/zero   ;\                              ; init cbc
  [cbc+0].bit6=(xtra_len>0)        ; [0]=flags                     ;
  [cbc+0].bit5..3=(mac_len/2-1)    ;                               ;
  [cbc+0].bit2..0=(ctr_len-1)      ;/                              ;
  aes_crypt_block(ENCRYPT,cbc,cbc)      ;UPDATE_CBC_MAC            ;/
  if NintendoDSi then                                              ;\
    a=0 ;the DSi hardware doesn't support xtra_len encoding at all ;
  elseif xtra_len<0FF00h then                                      ;
    [cbc+0..1]=[cbc+0..1] xor bigendian(xtra_len), a=2             ; weird
  elseif xtra_len<100000000h then                                  ; encoding
    [cbc+0..1]=[cbc+0..1] xor bigendian(FFFEh)                     ; for
    [cbc+2..5]=[cbc+2..5] xor bigendian(xtra_len), a=6             ; xtra_len
  else                                                             ;
    [cbc+0..1]=[cbc+0..1] xor bigendian(FFFFh)                     ;
    [cbc+2..9]=[cbc+2..9] xor bigendian(xtra_len), a=10            ;/
  while xtra_len>0                                                 ;\scatter
    z=min(xtra_len,16-a)                                           ; cbc by
    [cbc+a..(a+z-1)]=[cbc+a..(a+z-1)] xor [xtra+0..(z-1)]          ; xtra
    aes_crypt_block(ENCRYPT,cbc,cbc)    ;UPDATE_CBC_MAC            ; (if any)
    xtra=xtra+z, xtra_len=xtra_len-z, a=0                          ;/
  while msg_len>0                                                  ;\
    bigendian(ctr)=bigendian(ctr)+1     ;increment counter         ;
    aes_crypt_block(ENCRYPT,ctr,tmp)    ;CTR_CRYPT                 ;
    z=min(msg_len,16)                                              ; encrypt
    if mode=ENCRYPT                                                ; or decrypt
      [cbc+0..(z-1)] = [cbc+0..(z-1)] xor [src+0..(z-1)]           ; message
    [dst+0..(z-1)] = [src+0..(z-1)] xor [tmp+0..(z-1)]             ; body
    if mode=DECRYPT                                                ;
      [cbc+0..(z-1)] = [cbc+0..(z-1)] xor [dst+0..(z-1)]           ;
    aes_crypt_block(ENCRYPT,cbc,cbc)    ;UPDATE_CBC_MAC            ;
    src=src+z, dst=dst+z, msg_len=msg_len-z                        ;/
  [ctr+(iv_len+1)..15]=bigendian(0)     ;reset counter=0           ;\
  aes_crypt_block(ENCRYPT,ctr,tmp)      ;CTR_CRYPT                 ; message
  [cbc+0..15] = [cbc+0..15] xor [tmp+0..15]                        ; auth code
  z=mac_len                                                        ; (mac)
  IF mode=ENCRYPT then [mac+0..(z-1)] = [cbc+0..(z-1)]             ;
  IF mode=DECRYPT and [mac+0..(z-1)] <> [cbc+0..(z-1)] then error  ;/

AES-Key-Wrap/Unwrap
This is used for EAPOL Key Data in WPA2 Wifi packets, however, neither DSi-ARM7 nor DSi-Wifi do support that by hardware, so the unwrap (decrypt) must be implemented by software. For details see:
DS Wifi WPA/WPA2 Encryption

Below are some other AES variants (just for curiosity - those variants aren't used in DSi):

AES-CBC (Cipher-block chaining)
aes_crypt_cbc(mode,src,dst,len,iv)
  aes_setkey(mode,key,key_size]                                    ;-init key
  [cbc+0..15] = [iv+0..15]                                         ;-init cbc
  if (len AND 0Fh)>0 then error
  while len>0                                                      ;\
    if mode=ENCRYPT                                                ;
      [dst+0..15] = [src+0..15] xor [cbc+0..15]                    ;
      aes_crypt_block(mode,dst,dst)                                ; encrypt
      [cbc+0..15] = [dst+0..15]                                    ; or decrypt
    if mode=DECRYPT                                                ; message
      [tmp+0..15] = [src+0..15]                                    ;
      aes_crypt_block(mode,src,dst)                                ;
      [dst+0..15] = [dst+0..15] xor [cbc+0..15]                    ;
      [cbc+0..15] = [tmp+0..15]                                    ;
    src=src+16, dst=dst+16, len=len-16                             ;/

AES-CFB128 (Cipher feedback on 128bits, aka 16 bytes)
aes_crypt_cfb128(mode,src,dst,len,iv_off,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [cfb+0..15] = [iv+0..15]                                         ;-init cfb
  n=[iv_off]
  while len>0                                                      ;\
    if n=0 then aes_crypt_block(ENCRYPT,cfb,cfb)                   ; encrypt
    if mode=DECRYPT then c=[src], [dst]=c xor [cfb+n], [cfb+n]=c   ; or decrypt
    if mode=ENCRYPT then c=[cfb+n] xor [src], [cfb+n]=c, [dst]=c   ; message
    src=src+1, dst=dst+1, len=len-1, n=(n+1) and 0Fh               ;/
  [iv_off]=n

AES-CFB8 (Cipher feedback on 8bits, aka 1 byte, very inefficient)
aes_crypt_cfb8(mode,src,dst,len,iv)
  aes_setkey(ENCRYPT,key,key_size]                                 ;-init key
  [cfb+0..15] = [iv+0..15]                                         ;-init cfb
  while len>0                                                      ;\
    aes_crypt_block(ENCRYPT,cfb,tmp)                               ;
    [cfb+0..14] = [cfb+1..15]   ;shift with 8-bit step             ; encrypt
    if mode=DECRYPT then [cfb+15] = [src]                          ; or decrypt
    [dst] = [src] xor [tmp+0]   ;shift-in new 8-bits               ; message
    if mode=ENCRYPT then [cfb+15] = [dst]                          ;
    src=src+1, dst=dst+1, len=len-1                                ;/

AES-ECB (Electronic codebook, very basic, very insecure)
aes_crypt_ecb(mode,src,dst,len)
  aes_setkey(mode,key,key_size]                                    ;-init key
  if (len AND 0Fh)>0 then error
  while len>0                                                      ;\encrypt
    aes_crypt_block(mode,src,dst)                                  ; or decrypt
    src=src+16, dst=dst+16, len=len-16                             ;/message


DSi AES Big-Endian Core Function and Key Schedule

 aes_crypt_block(mode,src,dst):
  Y0 = RK[0] xor [src+00h]
  Y1 = RK[1] xor [src+04h]
  Y2 = RK[2] xor [src+08h]
  Y3 = RK[3] xor [src+0Ch]
  ;below code depending on mode:      <---ENCRYPT--->  -or-  <---DECRYPT--->
  for i=1 to nr-1
    X0      = RK[i*4+0] xor scatter32(FT,Y0,Y1,Y2,Y3)  -or-  (RT,Y0,Y3,Y2,Y1)
    X1      = RK[i*4+1] xor scatter32(FT,Y1,Y2,Y3,Y0)  -or-  (RT,Y1,Y0,Y3,Y2)
    X2      = RK[i*4+2] xor scatter32(FT,Y2,Y3,Y0,Y1)  -or-  (RT,Y2,Y1,Y0,Y3)
    X3      = RK[i*4+3] xor scatter32(FT,Y3,Y0,Y1,Y2)  -or-  (RT,Y3,Y2,Y1,Y0)
    Y0=X0, Y1=X1, Y2=X2, Y3=X3
  [dst+00h] = RK[nr*4+0] xor scatter8(FSb,Y0,Y1,Y2,Y3) -or-  (RSb,Y0,Y3,Y2,Y1)
  [dst+04h] = RK[nr*4+1] xor scatter8(FSb,Y1,Y2,Y3,Y0) -or-  (RSb,Y1,Y0,Y3,Y2)
  [dst+08h] = RK[nr*4+2] xor scatter8(FSb,Y2,Y3,Y0,Y1) -or-  (RSb,Y2,Y1,Y0,Y3)
  [dst+0Ch] = RK[nr*4+3] xor scatter8(FSb,Y3,Y0,Y1,Y2) -or-  (RSb,Y3,Y2,Y1,Y0)

 scatter32(TAB,a,b,c,d):              scatter8(TAB,a,b,c,d):
  w=      (TAB[a.bit0..7])             w.bit0..7   = TAB[a.bit0..7]
  w=w xor (TAB[b.bit8..15] rol 8)      w.bit8..15  = TAB[b.bit8..15]
  w=w xor (TAB[c.bit16..23] rol 16)    w.bit16..23 = TAB[c.bit16..23]
  w=w xor (TAB[d.bit24..31] rol 24)    w.bit24..31 = TAB[d.bit24..31]
  return w                             return w

 aes_setkey(mode,key,keysize):  ;out: RK[0..43/51/59], nr=10/12/14
  aes_generate_tables   ;<-- unless tables are already initialized
  if keysize<>128 and keysize<>192 and keysize<>256 then error  ;size in bits
  rc=01h, j=0, jj=keysize/32, nr=jj+6   ;jj=4,6,8      ;\
  for i=0 to (nr+1)*4-1                 ;nr=10,12,14   ; copy 16/24/32-byte key
    if i<jj then w=[key+i*4+0..3]                      ; to RK[0..3/5/7]
    else w=w xor RK[i-jj]                              ; and, make
    RK[i]=w, j=j+1                                     ; RK[4/6/8..43/51/59]
    if j=jj then                                       ;
      w=scatter8(FSb,w,w,w,w)                          ;
      w=(w ror 8) xor (rc)                             ;
      j=0, rc=rc*2, if rc>0FFh then rc=rc xor 11Bh     ;
    if j=4 and jj=8 then w=scatter8(FSb,w,w,w,w)       ;/
  if mode=DECRYPT then
    for i=0 to nr/2-1     ;swap entries (except middle one)
      for j=0 to 3
        w=RK[i*4+j], v=RK[nr*4-i*4+j]
        RK[i*4+j]=v, RK[nr*4-i*4+j]=w
    for i=4 to nr*4-1     ;modify entries (except RK[0..3] and RK[nr*4+0..3])
      w=RK[i], w=scatter8(FSb,w,w,w,w), RK[i]=scatter32(RT,w,w,w,w)


DSi AES Big-Endian Tables and Test Values

 aes_generate_tables:
  for i=0 to 0FFh               ;compute pow and log tables...
    if i=0 then x=01h, else x=x xor x*2, if x>0FFh then x=x xor 11Bh
    pow[i]=x, log[x]=i
  for i=0 to 0FFh               ;generate the forward and reverse S-boxes...
    x=pow[0FFh-log[i]]
    x=x xor (x rol 1) xor (x rol 2) xor (x rol 3) xor (x rol 4) xor 63h
    if i=0 then x=63h
    FSb[i]=x, RSb[x]=i
  for i=0 to 0FFh               ;generate the forward and reverse tables...
    x=FSb[i]*2, if x>0FFh then x=x xor 11Bh
    FT[i]=(FSb[i]*01010100h) xor (x*01000001h)
    w=00000000h, x=RSb[i]
    if x<>00h then   ;ie. not at i=63h
      w=w+pow[(log[x]+log[0Eh]) mod 00FFh]*1h
      w=w+pow[(log[x]+log[09h]) mod 00FFh]*100h
      w=w+pow[(log[x]+log[0Dh]) mod 00FFh]*10000h
      w=w+pow[(log[x]+log[0Bh]) mod 00FFh]*1000000h
    RT[i]=w

 aes_generate_tables_results:
  pow[00h..FFh] = 01,03,05,0F,11,..,C7,52,F6,01   ;pow  ;\needed temporarily
  log[00h..FFh] = 00,FF,19,01,32,..,C0,F7,70,07   ;log  ;/for table creation
  FSb[00h..FFh] = 63,7C,77,7B,F2,..,B0,54,BB,16   ;Forward S-box
  RSb[00h..FFh] = 52,09,6A,D5,30,..,55,21,0C,7D   ;Reverse S-box
  FT[00h..FFh] = A56363C6,847C7CF8,..,3A16162C    ;Forward Table
  RT[00h..FFh] = 50A7F451,5365417E,..,4257B8D0    ;Reverse Table

 aes_setkey_results:
  key = "AES-Test-Key-Str-1234567-Abcdefg"  ;use only 1st bytes for 128/192bit
  128bit ENCRYPT --> RK[0..9..30..43] = 2D534541..ED0DC6FA..43DAC81C..0F5026BB
  192bit ENCRYPT --> RK[0..9..30..51] = 2D534541..4AAB3D82..29CA38D2..CA4DFE3B
  256bit ENCRYPT --> RK[0..9..30..59] = 2D534541..1AA51359..CCB886C8..88956C9C
  128bit DECRYPT --> RK[0..9..30..43] = F653079B..47DD8A1C..1C2070A7..7274532D
  192bit DECRYPT --> RK[0..9..30..51] = 3CEC6AFF..C4F96B6F..AE36B4AE..7274532D
  256bit DECRYPT --> RK[0..9..30..59] = DE7ADCD9..8C559ADD..067A387E..7274532D

 aes_crypt_results:
  [key+0..15]    = "AES-Test-Key-Str-1234567-Abcdefg"
  [iv+0..15]     = "Nonce/InitVector"
  [xtra+0..20]   = "Extra-Associated-Data"  ;\for CCM
  iv_len=12, mac_len=16, xtra_len=21        ;/
  Unencrypted:   [dta+0..113Fh] = "Unencrypted-Data", 190h x "TestPadding"
  AES-ECB:       [dta+0..113Fh] = 5F,BD,04,DB,..,E4,07,F4,B6  ;\
  AES-CBC:       [dta+0..113Fh] = 0B,BB,53,FA,..,DD,28,6D,AE  ;
  AES-CFB128:    [dta+0..113Fh] = F4,75,4F,0E,..,73,B5,D7,E7  ; keysize=128
  AES-CFB8:      [dta+0..113Fh] = F4,10,6A,83,..,BF,1B,16,3E  ;
  AES-CTR:       [dta+0..113Fh] = F4,75,4F,0E,..,04,DF,EB,BA  ;
  AES-CCM:       [dta+0..113Fh] = FD,1A,6D,98,..,EE,FD,68,F6  ;
  AES-CCM (ori): [mac+0..0Fh]   = FD,F9,FE,85,..,4F,50,3C,AF  ;
  AES-CCM (DSi): [mac+0..0Fh]   = xx,xx,xx,xx,..,xx,xx,xx,xx  ;/
  AES-ECB:       [dta+0..113Fh] = 0E,69,F5,1A,..,9A,5F,7A,9A  ;-keysize=192
  AES-ECB:       [dta+0..113Fh] = C6,FB,68,C1,..,14,89,6C,E0  ;-keysize=256


DSi ES Block Encryption

ES Block Encryption, for lack of a better name, is a Nintendo DSi specific data encryption method. It's used for some SD/MMC files:
  FAT16:\sys\dev.kp
  FAT16:\ticket\000300tt\4ggggggg.tik (tickets)
  SD Card: .bin files (aka Tad Files) (contains multiple blocks)
  .twl-*.der files (within the "verdata" NARC file)

Block Layout
  00000h      BLKLEN   Data Block      (AES-CCM encrypted)
  BLKLEN+00h  10h      Data Checksum   (AES-CCM MAC value on above Data)
  BLKLEN+10h  1        Fixed 3Ah       (AES-CTR encrypted)
  BLKLEN+11h  0Ch      Nonce           (unencrypted)
  BLKLEN+1Dh  1        BLKLEN.bit16-23 (AES-CTR encrypted)
  BLKLEN+1Eh  1        BLKLEN.bit8-15  (AES-CTR encrypted)
  BLKLEN+1Fh  1        BLKLEN.bit0-7   (AES-CTR encrypted)
BLKLEN can be max 20000h. If the Data is bigger than 128Kbytes, then it's split into multiple block(s) with BLKLEN=20000h (the last block can have smaller BLKLEN).

Data Block Encryption/Decryption (AES-CCM)
  IV[00h..0Bh]=[BLKLEN+11h..1Ch]  ;Nonce
  IV[0Ch..0Fh]=Don't care (not used for CCM)
With that IV value, apply AES-CCM on the Data Block:
  00000h      BLKLEN   Data Block      (AES-CCM)
Observe that some DSi files have odd BLKLEN values, so you may need to append padding bytes to the Data Block (the DSi hardware requires full 16-byte chunks for encryption/decryption).
Alternately, one could use AES-CTR for decryption (this may be faster/easier, and allows random access, though without MAC verify), using this IV value:
  IV[00h..02h]=offset/10h + 1     ;CTR value for desired 16-byte block
  IV[03h..0Eh]=[BLKLEN+11h..1Ch]  ;Nonce for CTR
  IV[0Fh]=02h                     ;Indicate 3-byte wide CTR (fixed on DSi)

Data Block Padding (16-byte alignment)
For encryption, it's simple: Just append 00h byte(s) as padding value.
For decryption, it's more complicated: The padding values should be ENCRYPTED 00h-bytes (required to get the same MAC result as for encryption). If you don't want to verify the MAC, then you could append whatever dummy bytes. If you want to verify the MAC, then you could pre-calculate the padding values as so:
  IV[00h..02h]=BLKLEN/10h + 1     ;CTR value for last 16-byte block
  IV[03h..0Eh]=[BLKLEN+11h..1Ch]  ;Nonce
  IV[0Fh]=02h                     ;Indicate 3-byte wide CTR (fixed on DSi)
Then, use AES-CTR (not CCM) to encrypt sixteen 00h-bytes, the last byte(s) of the result can be then used as padding value(s). The padding values should be pre-calculated BEFORE starting the CCM decryption (the DSi hardware allows only one AES task at once, so they cannot be calculated via AES-CTR when AES-CCM decryption is in progress).

Verifying the Footer values (AES-CTR)
This step is needed only for verification purposes (encryption tools should create these values, but decryption tools may or may not verify them).
  IV[00h]=00h                     ;Zero
  IV[01h..0Ch]=[BLKLEN+11h..1Ch]  ;Nonce
  IV[0Dh..0Fh]=00h,00h,00h        ;Zero
With that IV value (and same Key as for AES-CCM), apply AES-CTR on the last 16 bytes of the block:
  BLKLEN+10h  1        Fixed 3Ah       (AES-CTR encrypted)
  BLKLEN+11h  0Ch      Nonce           (unencrypted)
  BLKLEN+1Dh  1        BLKLEN.bit16-23 (AES-CTR encrypted)
  BLKLEN+1Eh  1        BLKLEN.bit8-15  (AES-CTR encrypted)
  BLKLEN+1Fh  1        BLKLEN.bit0-7   (AES-CTR encrypted)
AES-CTR is XORing the data stream (encrypted bytes will turn into unencrypted bytes, and vice-versa), so the result would look as so:
  BLKLEN+10h  1        Fixed 3Ah       (unencrypted)       (to be verified)
  BLKLEN+11h  0Ch      Nonce           (AES-CTR encrypted) (useless/garbage)
  BLKLEN+1Dh  1        BLKLEN.bit16-23 (unencrypted)       (to be verified)
  BLKLEN+1Eh  1        BLKLEN.bit8-15  (unencrypted)       (to be verified)
  BLKLEN+1Fh  1        BLKLEN.bit0-7   (unencrypted)       (to be verified)
Mind that BLKLEN can be odd, so data at BLKLEN+00h..1Fh isn't necessarily located at 4-byte aligned addresses.


DSi Cartridge Header

Old NDS Header Entries
The first 180h bytes of the DSi Header are essentially same as on NDS:
DS Cartridge Header
New/changed entries in DSi carts are:
  012h 1    Unitcode (00h=NDS, 02h=NDS+DSi, 03h=DSi) (bit1=DSi)
  01Ch 1    NDS:Reserved, DSi:Flags (03h=Normal, 0Bh=Sys, 0Fh=Debug/Sys)
              bit0 Has TWL-Exclusive Region      ;MUST be 1 for DSi titles?
              bit1 Modcrypted (0=No, 1=Yes, see [220h..22Fh])
              bit2 Modcrypt key select (0=Retail, 1=Debug)
              bit3 Disable Debug ?
  01Dh 1    NDS:Region,   DSi:Permit jump (00h=Normal, 01h=System Settings)
                             bit0 jump (always include title at [2FFD800h..])
                             bit1 tmpjump (?)
  068h 4    Icon/Title offset (same as NDS, but with new extra entries)
  080h 4    Total Used ROM size, EXCLUDING DSi area
  088h 4    NDS:Unknown,  DSi:ARM9 Parameters Table Offset ???  ;base=[028h]
  08Ch 4    NDS:Reserved, DSi:ARM7 Parameters Table Offset ???  ;base=[038h]
  090h 2    NDS:Reserved, DSi:NTR ROM Region End/80000h   ;\usually both same
  092h 2    NDS:Reserved, DSi:TWL ROM Region Start/80000h ;/(zero for DSiware)
NDS carts (that don't use DSi features, but are manufactured after DSi release) contain these extra entries:
 (012h)1    Unitcode (must be 00h for non-DSi carts)
 (020h)16   Changed ARM9/ARM7 areas (DSi-in-NDS-mode more restricted than NDS)
  088h 4    Unknown (B8h,4Bh,00h,00h) (similar as in DSi carts)
  1BFh 1    Flags (40h=RSA+TwoHMACs, 60h=RSA+ThreeHMACs)
  33Ch 14   HMAC for Icon/Title (only if [1BFh]=60h)      ;as Whitelist Phase 3
  378h 14   HMAC for 160h-byte header and ARM9+ARM7 areas ;as Whitelist Phase 1
  38Ch 14   HMAC for OverlayARM9+NitroFAT (zero if no overlay)      ;as Phase 2
  F80h 128  RSA signature
All other entries at 160h..FFFh are zerofilled in non-DSi carts.

Changed ARM9/ARM7 areas (and new ARM9i/ARM7i areas)
NDS allowed ARM9 or ARM7 to occupy about 3.8MB of main RAM. On DSi this is restriced to 2.5MB for ARM9 and 0.25MB for ARM7, ie. 2.75MB in total, this restriction applies even in NDS-mode, thus making DSi not fully backwards compatible with NDS games (officially licensed NDS titles hopefully don't conflict with that new restriction). In DSi mode, one can additionally load 2.5MB for ARM9i and 1MB for ARM7i, ie. 6.25MB in total for all four areas.
The DSi loading is a bit complicated, the areas are first loaded to DEDICATED areas:
  ARM9  2004000h..227FFFFh (siz=27C000h) (for NDS mode: 2000000h and up)
  ARM7  2380000h..23BFFFFh (siz=40000h)
  ARM9i 2400000h..267FFFFh (siz=280000h)
  ARM7i 2E80000h..2F87FFFh (siz=108000h)
If the cart header does match with those DEDICATED areas then the data is left in place, otherwise it gets relocated to GENERAL areas (shortly before jumping to the entrypoint). The GENERAL areas are allowed to be:
  Main  2000000h..2FFC000h (excluding bootstrap at 23FEE00h..23FF000h)
  WRAM  3000000h..380F000h (excluding bootstrap at 3FFF600h..3FFF800h)
The GENERAL areas may not overlap with another DEDICATED area (eg. ARM7 cannot be relocated to the ARM9+ARM9i+ARM7i areas). Concerning the 16K at 2000000h..2003FFFh: ARM7+ARM9i+ARM7i aren't allow to use that, but ARM9 seems to be relocatable to that address (usually that shouldn't be done as it would destroy some DSi system variables).
ARM9i+ARM7i areas can have "Size" and "ROM offset" set to zero (but still need to have a valid nonzero "RAM Load address").
ARM9/ARM7 entrypoints MUST be within ARM9/ARM7 area respectively (NDS allowed entrypoints being anywhere).

New DSi Header Entries
  180h 20   Global MBK1..MBK5 Settings, WRAM Slots
  194h 12   Local MBK6..MBK8 Settings, WRAM Areas for ARM9
  1A0h 12   Local MBK6..MBK8 Settings, WRAM Areas for ARM7
  1ACh 3    Global MBK9 Setting, WRAM Slot Write Protect
  1AFh 1    Global WRAMCNT Setting (usually 03h) (FCh/00h in SysMenu/Settings)
  1B0h 4    Region flags (bit0=JPN, bit1=USA, bit2=EUR, bit3=AUS, bit4=CHN,
              bit5=KOR, bit6-31=Reserved) (FFFFFFFFh=Region Free)
  1B4h 4    Access control (AES Key Select)
              bit0 Common Client Key ;want 380F000h=3FFC600h+00h "common key"
              bit1 AES Slot B  ;380F010h=3FFC400h+180h and KEY1=unchanged
              bit2 AES Slot C  ;380F020h=3FFC400h+190h and KEY2.Y=3FFC400h+1A0h
              bit3 SD Card            ;want Device I
              bit4 NAND Access        ;want Device A-H and KEY3=intact
              bit5 Game Card Power On                 ;tested with bit8
              bit6 Shared2 File                       ;used... but WHAT for?
              bit7 Sign JPEG For Launcher (AES Slot B);select 1 of 2 jpeg keys?
              bit8 Game Card NTR Mode                 ;tested with bit5
              bit9 SSL Client Cert (AES Slot A) ;KEY0=3FFC600h+30h (twl-*.der)
              bit10 Sign JPEG For User (AES Slot B) ;\
              bit11 Photo Read Access               ; seems to be unused
              bit12 Photo Write Access              ; (and, usually ZERO,
              bit13 SD Card Read Access             ; even if the stuff is
              bit14 SD Card Write Access            ; accessed)
              bit15 Game Card Save Read Access      ; (bit11 set in flipnote)
              bit16 Game Card Save Write Access     ;/
              bit31 Debugger Common Client Key  ;want 380F000h=3FFC600h+10h
  1B8h 4    ARM7 SCFG_EXT7 setting (bit0,1,2,10,18,31)
  1BCh 3    Reserved/flags? (zerofilled)
  1BFh 1    Flags (usually 01h) (DSiware Browser: 0Bh)
              bit0: TSC Touchscreen/Sound Controller Mode (0=NDS, 1=DSi)
              bit1: Require EULA Agreement (see hdr[20Eh] for version)
              bit2: Custom Icon  (0=No/Normal, 1=Use banner.sav)
              bit3: Show Nintendo Wi-Fi Connection icon in Launcher
              bit4: Show DS Wireless icon in Launcher
              bit5: NDS cart with icon SHA1  (DSi firmware v1.4 and up)
              bit6: NDS cart with header RSA (DSi firmware v1.0 and up)
              bit7: Developer App
  1C0h 4    ARM9i ROM Offset (usually XX03000h, XX=1MB-boundary after NDS area)
  1C4h 4    Reserved (zero)
  1C8h 4    ARM9i RAM Load address
  1CCh 4    ARM9i Size
  1D0h 4    ARM7i ROM Offset
  1D4h 4    SD/MMC Device List ARM7 RAM Addr; 400h-byte initialized by firmware
  1D8h 4    ARM7i RAM Load address
  1DCh 4    ARM7i Size
  1E0h 4    Digest NTR region offset (usually same as ARM9 rom offs, 0004000h)
  1E4h 4    Digest NTR region length
  1E8h 4    Digest TWL region offset (usually same as ARM9i rom offs, XX03000h)
  1ECh 4    Digest TWL region length
  1F0h 4    Digest Sector Hashtable offset ;\SHA1-HMAC's on all sectors
  1F4h 4    Digest Sector Hashtable length ;/in above NTR+TWL regions
  1F8h 4    Digest Block Hashtable offset  ;\SHA1-HMAC's on each N entries
  1FCh 4    Digest Block Hashtable length  ;/in above Sector Hashtable
  200h 4    Digest Sector size       (eg. 400h bytes per sector)
  204h 4    Digest Block sectorcount (eg. 20h sectors per block)
  208h 4    Icon/Title size (usually 23C0h for DSi) (older 840h-byte works too)
  20Ch 1    SD/MMC size of "shared2\0000" file in 32Kbyte units? (dsi sound)
  20Dh 1    SD/MMC size of "shared2\0001" file in 32Kbyte units?
                ;or are shared2 sizes rather counted in 16Kbyte cluster units?
  20Eh 1    EULA Version (01h)  ?   ;used when hdr[1BFh].bit1=1       !
  20Fh 1    Use Ratings  (00h)  ?                                     !
  210h 4    Total Used ROM size, INCLUDING DSi area (optional, can be 0)
  214h 1    SD/MMC size of "shared2\0002" file in 32Kbyte units?
  215h 1    SD/MMC size of "shared2\0003" file in 32Kbyte units?
  216h 1    SD/MMC size of "shared2\0004" file in 32Kbyte units?
  217h 1    SD/MMC size of "shared2\0005" file in 32Kbyte units?
  218h 4    ARM9i Parameters Table Offset (84 D0 04 00) ???  ;base=[028h]
  21Ch 4    ARM7i Parameters Table Offset (2C 05 00 00) ???  ;base=[038h]
  220h 4    Modcrypt area 1 offset ;usually same as ARM9i rom offs (XX03000h)
  224h 4    Modcrypt area 1 size   ;usually min(4000h,ARM9iSize+Fh AND not Fh)
  228h 4    Modcrypt area 2 offset (0=None)
  22Ch 4    Modcrypt area 2 size   (0=None)
  230h 4    Title ID, Emagcode (aka Gamecode spelled backwards)
  234h 1    Title ID, Filetype (00h=Cartridge, 04h=DSiware, 05h=System Fun
              Tools, [0Fh=Non-executable datafile without cart header],
              15h=System Base Tools, 17h=System Menu)
  235h 1    Title ID, Zero     (00h=Normal)
  236h 1    Title ID, Three    (03h=DSi) (as opposed to Wii or 3DS)
  237h 1    Title ID, Zero     (00h=Normal)
  238h 4    SD/MMC (DSiware) "public.sav" filesize in bytes  (0=none)
  23Ch 4    SD/MMC (DSiware) "private.sav" filesize in bytes (0=none)
  240h 176  Reserved (zero-filled)
Parental Control Age Ratings (set all entries to 80h to allow any age)
  2F0h 10h  Parental Control Age Ratings (for different countries/areas)
             Bit7: Rating exists for local country/area
             Bit6: Game is prohibited in local country/area?
             Bit5: Unused
             Bit4-0: Age rating for local country/area (years)
  2F0h 1    CERO (Japan)       (0=None/A, 12=B, 15=C, 17=D, 18=Z)
  2F1h 1    ESRB (US/Canada)   (0=None, 3=EC, 6=E, 10=E10+, 13=T, 17=M)
  2F2h 1    Reserved           (0=None)
  2F3h 1    USK (Germany)      (0=None, 6=6+, 12=12+, 16=16+, 18=18+)
  2F4h 1    PEGI (Pan-Europe)  (0=None, 3=3+, 7=7+, 12=12+, 16=16+, 18=18+)
  2F5h 1    Reserved           (0=None)
  2F6h 1    PEGI (Portugal)    (0=None, 4=4+, 6=6+, 12=12+, 16=16+, 18=18+)
  2F7h 1    PEGI and BBFC (UK) (0=None, 3, 4=4+/U, 7, 8=8+/PG, 12, 15, 16, 18)
  2F8h 1    AGCB (Australia)   (0=None/G, 7=PG, 14=M, 15=MA15+, plus 18=R18+?)
  2F9h 1    GRB (South Korea)  (0=None, 12=12+, 15=15+, 18=18+)  (aka "BG"?)
  2FAh 6    Reserved (6x)      (0=None)
  ?    ?    OFLC (NZ) (unknown, exists in DSi System Settings rom:layout\cmn)
  N/A? -    DEJUS (Brazil) (L, 10, 12, 14, 16, 18)
  N/A? -    GSRMR (Taiwan) (formerly CSRR) (0,6,12,18) (and GSRMR: 15)
  N/A? -    PEGI (Finland) (discontinued 2007, shortly before DSi launch)
             bit0-4 Rating (0..18)
             bit6   Pending
             bit7   Enabled
SHA1-HMAC's and RSA-SHA1
  300h 20   SHA1-HMAC hash ARM9 (with encrypted secure area)     ;[020h,02Ch]
  314h 20   SHA1-HMAC hash ARM7                                  ;[030h,03Ch]
  328h 20   SHA1-HMAC hash Digest master                         ;[1F8h,1FCh]
  33Ch 20   SHA1-HMAC hash Icon/Title (also in newer NDS titles) ;[068h,208h]
  350h 20   SHA1-HMAC hash ARM9i (decrypted)                     ;[1C0h,1CCh]
  364h 20   SHA1-HMAC hash ARM7i (decrypted)                     ;[1D0h,1DCh]
  378h 20   Reserved (zero-filled) (but used for non-whitelisted NDS titles)
  38Ch 20   Reserved (zero-filled) (but used for non-whitelisted NDS titles)
  3A0h 20   SHA1-HMAC hash ARM9 (without 16Kbyte secure area)    ;[020h,02Ch]
  3B4h 2636 Reserved (zero-filled)
  E00h 180h Reserved and unchecked region, always zero. Used for passing
              arguments in debug environment.
  F80h 80h  RSA-SHA1 signature across header entries [000h..DFFh]
Reserved Area
  1000h..3FFFh  Non-Load area in ROMs... but contains sth in DSiWare files!?!

DSiware/System Utilities
Files saved on SD card or internal eMMC memory are having the same header as ROM carts, with some differences:
  No need for NDS backwards compatibility (since DSiware is DSi only)
  Entry 3A0h can be zero-filled (in LAUNCHER)
DSiware files are usually marked as [012h]=03h=DSi (exceptions are the DS Download Play and PictoChat utilities, which are marked [012h]=00h=NDS, since they are actually running in NDS mode (yet having at least two DSi-specific features: 1st is allowing to reboot into DSi menu via Powerman SPI, 2nd is requiring enabled wifi channels in 2FFFCFAh)).

SHA1-HMAC
The SHA1-HMAC's in cart header and Digest tables are SHA1 checksums with a 40h-byte HMAC key (values 21h, 06h, C0h, DEh, BAh, ..., 24h), the key is contained in the Launcher, and it's also stored in most DSi cartridges (probably used for verifying Digest values when loading additional data after booting). The key can be used for verifying checksums, but (due to the RSA signature) not for changing them. See BIOS chapter for SHA1/HMAC pseudo code.

RSA-SHA1
The RSA-SHA1 value is a normal SHA1 (not SHA1-HMAC) across header entries [000h..DFFh], the 20-byte value is padded to 127-byte size (01h, 105xFFh, 00h, followed by the 20 SHA1 bytes). It can be decrypted (via SWI 22h) using the 80h-byte RSA public keys located in ARM9BIOS (note that there are at least four different RSA keys, one is used for games, and others for system files), and can be then verfied against the SHA1 checksum (computed via SWI 27h).
BIOS RSA Functions (DSi only)
The private key needed for encryption is unknown, which is unfortunately preventing to boot unlicensed (homebrew) software.

Modcrypt (AES-CTR) (optional, carthdr[220h..22Fh] can be all zero)
Modcrypt is a new additional way of encrypting parts of the NDS ROM executable binary modules using AES CTR. It is mostly being used to encrypt the ARM9i and ARM7i binaries. DSi cartridges are usually having only the ARM9i binary encrypted (as area 1), while NAND based applications have both the ARM9i and ARM7i binaries encrypted (as area 1 and 2).
The initial AES Counter value (IV) is:
  Modcrypt Area 1 IV[0..F]: First 16 bytes of the ARM9 SHA1-HMAC   [300h..30Fh]
  Modcrypt Area 2 IV[0..F]: First 16 bytes of the ARM7 SHA1-HMAC   [314h..323h]
The AES key depends of flags in the cartridge header:
 IF header[01Ch].Bit1=0
  None (modcrypt disabled)
 ELSEIF header[01Ch].Bit2 OR header[1BFh].Bit7 THEN (probably for prototypes)
  Debug KEY[0..F]: First 16 bytes of the header                    [000h..00Fh]
 ELSE (commonly used for retail software)
  Retail KEY_X[0..7]: Fixed 8-byte ASCII string                    ("Nintendo")
  Retail KEY_X[8..B]: The 4-byte gamecode, forwards                [00Ch..00Fh]
  Retail KEY_X[C..F]: The 4-byte gamecode, backwards               [00Fh..00Ch]
  Retail KEY_Y[0..F]: First 16 bytes of the ARM9i SHA1-HMAC        [350h..35Fh]
Above does describe how modcrypted areas should look like. However, there are several circumstances where the firmware can't actually decrypt that areas...
Theoretically, the modcrypt areas can span over any of the ARM9i/ARM7i and ARM9/ARM7 areas (in practice, cartridges should never use modcrypt for the ARM9/ARM7 areas because NDS consoles would leave them undecrypted; that restriction doesn't apply to DSiware though).
Theoretically, a large modcrypt area could contain several data areas, but the launcher does decrypt only the first matching data area (areas are processed in order ARM9, ARM7, ARM9i, ARM7i). Moreover, matching data areas must be INSIDE of the modcrypt area (ie. the data area must be same size, or smaller than the modrypt area) (whereas, the launcher is weirdly rounding-up the data size to a multiple of 20h-bytes when checking that matches) (as a side-effect, each data area can be decrypted starting with "IV+0", rather than needing "IV+(offset_within_modcrypt_area/10h").
Theoretically, AES decryption could be done byte-wise, however, the AES hardware is doing it in 10h-byte chunks, unknown if the launcher does require 10h-byte alignments; however, in fact, the launcher seems to be rounding the modcrypt END address to 20h-byte boundary - so it's safest to stick with 20h-byte aligned start+size values for modcrypt areas, as well as for corresponding data areas.
Note: The size of the modcrypt areas can exceed the AES hardware's size limit of max FFFF0h bytes (eg. in DSi Sound utility), in such cases decryption must be split to smaller AES chunks; with manually increased IV.
Modcrypt area 1 and 2 can overlap each other (whereas, it doesn't matter which of them is processed first, since the encryption/decryption is done by XORing).
Note: The ARM9 code for modcrypt/data areas is at 26A6BB8h in Launcher v1.4E.

Digests (optional, carthdr[1E0h..207h] can be all zero)
The NDS format has been extended with a hash tree to verify the entire contents of an NDS ROM. The NDS ROM is divided into sectors, and each sector will be hashed and have its hash stored in the digest sector hashtable. The size of a sector is defined in the header aswell. Furthermore, the sector hashtable is partitioned and hashed again to form block hashes. This block hashtable is hashed again into a single hash called the digest master hash. These hashtables can be used to verify that the sectors of a NDS ROM have not been tampered with, since the integrity of a sector hash can be verified by a block hash, which in turn can be verified by the master hash. And this hash is part of the header, which is signed with RSA.
The sector hashtable reaches over the NTR and TWL regions, respectively.

Cartridge Protocol
The DSi cartridge protocol is same as on NDS; with one new command (3Dh) for unlocking DSi specific memory regions. For details,
DS Cartridge Protocol


DSi Touchscreen/Sound Controller

DSi Touchscreen Access
DSi Touchscreen/Sound Init Flowcharts

AIC3000D Registers
DSi TSC, Register Summary
DSi TSC[0:00h..1Ah], Basic PLL and Timing Control
DSi TSC[0:1Bh..23h], Codec Control
DSi TSC[0:24h..32h], Status and Interrupt Flags
DSi TSC[0:33h..3Bh], Pin Control
DSi TSC[0:3Ch..55h], DAC/ADC and Beep
DSi TSC[0:56h..7Fh], AGC and ADC
DSi TSC[1:xxh], DAC and ADC Routing, PGA, Power-Controls and MISC Logic
DSi TSC[3:xxh], Touchscreen/SAR Control and TSC[FCh:xxh], Buffer
DSi TSC[04h..05h:xxh], ADC Digital Filter Coefficient RAM
DSi TSC[08h..0Fh:xxh], DAC Digital Filter Coefficient RAM
DSi TSC[20h..2Bh:xxh], TSC[40h..5Fh:xxh] ADC/DAC Instruction RAM


DSi Touchscreen Access

The Touch Screen Controller (for lower LCD screen) is accessed via SPI bus,
DS Serial Peripheral Interface Bus (SPI)
so far, it's same as on NDS, but the SPI touchscreen commands are having an entirely different format in DSi mode:
The DSi touchscreen registers are selected via a combination of a PAGE byte and an INDEX byte. The PAGE byte is located at INDEX=00h, and it does somewhat 'bankswitch' the contents of INDEX=01h..7Fh. And INDEX can be incremented manually, or automatically (but, confusingly, the manual increment doesn't work for reading Y coordinates).
SPI clock should be set to 4MHz for DSi Mode touchscreen access (unlike NDS, which used 2MHz). The PENIRQ bit in port 4000136h is always zero in DSi mode.
When reading data: Write dummy 00h-bytes in output direction.

AIC3000D

DSi Touchscreen PAGE:INDEX values
The INDEX/Direction byte is written as first byte after SPI chip select:
  0     Direction for following data bytes (0=Write, 1=Read)
  1-7   INDEX (00h..7Fh) for following data bytes (auto-increasing)
However, the chip has more than 128 registers, stored in multiple pages.
  TSC[00h]=PAGE         ;<-- change page (at INDEX=0)
  TSC[PAGE:INDEX]       ;<-- access registers in select page

Pen Down Testing
  if (TSC[3:09h] AND 40h)<>0 then return(not_pressed)   ;ADC Ready Flag
  if (TSC[3:0Eh] AND 03h)<>0 then return(not_pressed)   ;Undocumented Flags?
  return(pressed)
Note: On NDS, this would be done by reading port 4000136h.bit6, which isn't supported in DSi mode.

X/Y Coordinate Reading
  touchdata[0..19] = TSC[FCh:01h..14h]     ;read page FCh, index(1..20)
  rawx=0, rawy=0
  for i=0 to 8 step 2
    x = touchdata[i+0]*100h+touchdata[i+1]
    y = touchdata[i+10]*100h+touchdata[i+11]
    if (x or y) and F000h then return(not_pressed)
    rawx=rawx+x, rawy=rawy+y
  return(rawx/5, rawy/5)
The resulting 12bit coordinates are same as on NDS (ie. they need to be further processed using the Calibration Points from User Settings).
Reading TSC[FCh:01h..14h] must be done in a single SPI transfer (reading them separatedly as TSC[FCh:01h], TSC[FCh:02h], etc. doesn't work).

Touchscreen X/Y Coordinates
  0-11   Coordinate (0..FFFh) (usually 000h when not pressed)
  12-14  State (0=Pressed, 7=Released) (or sometimes also 1 or 3=Released)
  15     State Changed (0=No, 1=Newly pressed/released; cleared after read)
Bit12-14 are usually set to 7 when releasing the screen (though sometimes they become 1 or 3 when releasing the screen, and do stay so until newly pressing it).
Bit15 is cleared after reading (so it will be usually seen only in the first MSB, ie. at INDEX=01h) (though maybe it can also occur elsewhere if it becomes newly set during the SPI transfer).

Microphone
The microphone input was part of the TSC on NDS. In DSi mode it is reportedly somehow changed, using a new "CODEC" (aka the DSi's newer TSC touchscreen/sound controller).

NDS Backwards Compatibility Mode
The DSi hardware can emulate the NDS-style touchscreen protocol (with X/Y/MIC channels and with additional PENIRQ flag; but without Pressure or Temperature channels).
DS Touch Screen Controller (TSC)
DSi enhanced games should implement both modes, and use the new mode on DSi consoles, and the old mode on NDS consoles (alternately, CartHdr[1BFh].bit0=0 will activate the old mode for both NDS+DSi).
If the backwards compatibility mode isn't enabled, then trying to read the touchscreen in NDS fashion will return nothing but zeroes for all TSC channels (and also zero for the PENIRQ bit).


DSi Touchscreen/Sound Init Flowcharts

touch_enable_tsc_init_list:
  TSC[3:0Eh]=00h  ;Undoc (RMW: bit7=0)
  TSC[3:02h]=18h  ;SAR ADC clk divider, Div8 (12bit mode) (RMW bit34=3, bit7=?)
  TSC[3:0Fh]=A0h  ;Scan Mode Timer
  TSC[3:0Eh].28h  ;Undoc (RNW: bit345=5)
  TSC[3:0Eh].28h  ;Undoc (RMW: bit6=0)
  TSC[3:03h]=87h  ;SAR ADC Control 2 (SelfByPenDown, ScanXY, /PENIRQ)
  TSC[3:05h].04h  ;Stabilization time = 30us (RMW bit012=4)
  TSC[3:04h].02h  ;Sense time = 3us          (RMW bit012=2)
  TSC[3:04h].22h  ;Precharge time = 3us      (RMW bit456=2)
  TSC[3:12h].00h  ;Debounce Time = 0us       (RMW bit012=0)
  TSC[3:0Eh].A8h  ;Undoc                     (RMW bit7=1)

mic_enable_tsc_init_list:
This is needed to unmute the microphone (otherwise microphone will return only 0000h or FFFFh.
  TSC[1:2Eh]=03h  ;MICBIAS=AVDD
  TSC[0:51h]=80h  ;ADC Digital Mic, on
  TSC[0:52h]=00h  ;ADC Digital Volume Control Fine Adjust, unmute
  TSC[1:2Fh]=37h  ;MIC PGA=27.5dB (or use other value, if desired)

mic_disable_tsc_init_list:
  TSC[0:52h]=80h  ;ADC Digital Volume Control Fine Adjust, mute
  TSC[0:51h]=00h  ;ADC Digital Mic, off
  TSC[1:2Eh]=00h  ;MICBIAS=Off

basic_tsc_init_list:
This is done by DSi Launcher/Unlaunch (and other titles usually won't need to do this).
  TSC[0:01h]=01h  ;Software Reset
  TSC[0:39h]=66h  ;ADC DC Measurement 1
  TSC[1:20h]=16h  ;Class-D Speaker Amplifier (RMW:bit4=1)
  TSC[0:04h]=00h  ;Clock-Gen Muxing
  TSC[0:12h]=81h  ;ADC NADC Value
  TSC[0:13h]=82h  ;ADC MADC Value
  TSC[0:51h]=82h  ;ADC Digital Mic
  TSC[0:51h]=00h  ;ADC Digital Mic again
  TSC[0:04h]=03h  ;Clock-Gen Muxing
  TSC[0:05h]=A1h  ;PLL P and R-Values
  TSC[0:06h]=15h  ;PLL J-Value
  TSC[0:0Bh]=87h  ;DAC NDAC Value
  TSC[0:0Ch]=83h  ;DAC MDAC Value
  TSC[0:12h]=87h  ;ADC NADC Value
  TSC[0:13h]=83h  ;ADC MADC Value
  TSC[3:10h]=88h  ;Scan Mode Timer Clock (RMW:bit0-6)
  TSC[4:08h..0Dh]=7Fh,E1h,80h,1Fh,7Fh,C1h  ;some coeff's
  TSC[0:41h]=08h  ;DAC Left Volume Control
  TSC[0:42h]=08h  ;DAC Right Volume Control
  TSC[0:3Ah]=00h  ;GPI3 Pin Control
  TSC[4:08h..0Dh]=7Fh,E1h,80h,1Fh,7Fh,C1h  ;some coeff's ;again?
  TSC[1:2Fh]=2Bh  ;MIC PGA
  TSC[1:30h]=40h  ;P-Terminal Delta-Sigma Mono ADC Channel Fine-Gain Input
  TSC[1:31h]=40h  ;M-Terminal ADC Input Selection
  TSC[1:32h]=60h  ;Input CM Settings
  TSC[0:74h]=82h  ;VOL/MICDET-Pin SAR ADC - Volume Control (RMW)
  TSC[0:74h]=92h  ;VOL/MICDET-Pin SAR ADC - Volume Control (RMW)
  TSC[0:74h]=D2h  ;VOL/MICDET-Pin SAR ADC - Volume Control (RMW)
  TSC[1:21h]=20h  ;HP Output Drivers POP Removal Settings
  TSC[1:22h]=F0h  ;Output Driver PGA Ramp-Down Period Control
  TSC[0:3Fh]=D4h  ;DAC Data-Path Setup (RMW)
  TSC[1:23h]=44h  ;DAC_L and DAC_R Output Mixer Routing
  TSC[1:1Fh]=D4h  ;Headphone Drivers
  TSC[1:28h]=4Eh  ;HPL Driver (Left Headphone)
  TSC[1:29h]=4Eh  ;HPR Driver (Right Headphone)
  TSC[1:24h]=9Eh  ;Analog Volume to HPL (Left Headphone)
  TSC[1:25h]=9Eh  ;Analog Volume to HPR (Right Headphone)
  TSC[1:20h]=D4h  ;Class-D Speaker Amplifier
  TSC[1:2Ah]=14h  ;SPL Driver (Left Speaker)
  TSC[1:2Bh]=14h  ;SPR Driver (Right Speaker)
  TSC[1:26h]=A7h  ;Analog Volume to SPL (Left Speaker)
  TSC[1:27h]=A7h  ;Analog Volume to SPR (Right Speaker)
  TSC[0:40h]=00h  ;DAC Volume Control
  (should set DSi.GPIO.data.bit7 here, but can be also done elsewhere)
  TSC[0:3Ah]=60h  ;GPI3 Pin Control

nds_mode_tsc_init_list:
Switches to NDS Touchscreen/sound mode. Usually done when starting NDS titles (or DSi titles that request NDS-TSC mode in carthdr[1BFh]).
  TSC[1:26h]=ACh  ;\special setting (when found special gamecode)
  TSC[1:27h]=ACh  ;/
  TSC[1:26h]=A7h  ;\normal setting (for any other gamecodes)
  TSC[1:27h]=A7h  ;/
  TSC[1:2Eh]=03h  ;MICBIAS=AVDD
  TSC[3:03h]=00h  ;SAR ADC Control 2
  TSC[1:21h]=20h  ;HP Output Drivers POP Removal Settings
  TSC[1:22h]=F0h  ;Output Driver PGA Ramp-Down Period Control (70h OR 80h)
  TSC[1:22h]=70h  ;Output Driver PGA Ramp-Down Period Control (bit7=0)
  TSC[0:52h]=80h  ;ADC Digital Volume Control Fine Adjust
  TSC[0:51h]=00h  ;ADC Digital Mic
  READ[3:02h] (returns 00h)
  TSC[3:02h].Bit7=1 ;SAR ADC Control 1 (set to 80h) (or 98h?) (RMW)
  TSC[FFh:05h]=00h ;TSC final enter NDS mode
And, set powerman[0].bit0=1 (bit0=sound amplifier on) (this is actually part of TSC chip, accessed via "POWERMAN" SPI chipselect signal).


DSi TSC, Register Summary

The DSi's Touchscreen/Sound controller (AIC3000D) is essentially a Texas Instruments TSC2117 chip (possibly with some customizations for NDS backwards compatibility mode).

TSC[page:index] registers are accessed via SPI bus with 15bit address space:
  7bit index: selected via the first SPI byte, with direction flag in bit0
  8bit page:  selected by writing to index 00h, ie. to TSC[xxh:00h]

TSC page select (for "TSC[page:index]" addressing)
  TSC[xxh:00h] - Page Select Register (00h)
TSC Basic PLL and Timing Control
  TSC[0:01h] - Software Reset (00h)
  TSC[0:02h] - Reserved (xxh) (R)
  TSC[0:03h] - Overtemperature OT Flag (02h..FFh) (R)
  TSC[0:04h] - Clock-Gen Muxing (00h)
  TSC[0:05h] - PLL P and R-Values (11h)
  TSC[0:06h] - PLL J-Value (04h)
  TSC[0:07h,08h] - PLL D-Value MSB,LSB (0000h)
  TSC[0:09h,0Ah] - Reserved (xxh)
  TSC[0:0Bh] - DAC NDAC Value (01h)
  TSC[0:0Ch] - DAC MDAC Value (01h)
  TSC[0:0Dh,0Eh] - DAC DOSR Value MSB,LSB (0080h)
  TSC[0:0Fh] - DAC IDAC Value (80h)
  TSC[0:10h] - DAC miniDSP Engine Interpolation (08h)
  TSC[0:11h] - Reserved (xxh)
  TSC[0:12h] - ADC NADC Value (01h)
  TSC[0:13h] - ADC MADC Value (01h)
  TSC[0:14h] - ADC AOSR Value (80h)
  TSC[0:15h] - ADC IADC Value (80h)
  TSC[0:16h] - ADC miniDSP Engine Decimation (04h)
  TSC[0:17h,18h] - Reserved (xxh)
  TSC[0:19h] - CLKOUT MUX (00h)
  TSC[0:1Ah] - CLKOUT Divider M Value (01h)
TSC Codec Control
  TSC[0:1Bh] - Codec Interface Control 1 (00h) (R/W)
  TSC[0:1Ch] - Data-Slot Offset Programmability (00h)
  TSC[0:1Dh] - Codec Interface Control 2 (00h)
  TSC[0:1Eh] - BCLK Divider N Value (01h)
  TSC[0:1Fh] - Codec Secondary Interface Control 1 (00h)
  TSC[0:20h] - Codec Secondary Interface Control 2 (00h)
  TSC[0:21h] - Codec Secondary Interface Control 3 (00h)
  TSC[0:22h] - I2C Bus Condition (00h)
  TSC[0:23h] - Reserved (xxh)
TSC Status and Interrupt Flags
  TSC[0:24h] - ADC Flag Register (0xh) (R)
  TSC[0:25h] - DAC Flag Register (00h) (R)
  TSC[0:26h] - DAC Flag Register (00h) (R)
  TSC[0:27h] - Overflow Flags (00h) (R)
  TSC[0:28h..2Bh] - Reserved (xxh)
  TSC[0:2Ch] - Interrupt Flags DAC, sticky (00h..30h) (R)
  TSC[0:2Dh] - Interrupt Flags ADC, sticky (00h..18h) (R)
  TSC[0:2Eh] - Interrupt Flags DAC, non-sticky? (00h..30h) (R)
  TSC[0:2Fh] - Interrupt Flags ADC, non-sticky? (00h..18h) (R)
  TSC[0:30h] - INT1 Control Register (Select INT1 Sources) (00h)
  TSC[0:31h] - INT2 Control Register (Select INT2 Sources) (00h)
  TSC[0:32h] - INT1 and INT2 Control Register (00h)
TSC Pin Control
  TSC[0:33h] - GPIO1 In/Out Pin Control (00h..C2h)
  TSC[0:34h] - GPIO2 In/Out Pin Control (00h..C2h)
  TSC[0:35h] - SDOUT (OUT Pin) Control (12h)
  TSC[0:36h] - SDIN (IN Pin) Control (02h or 03h)
  TSC[0:37h] - MISO (OUT Pin) Control (02h)
  TSC[0:38h] - SCLK (IN Pin) Control (02h..03h)
  TSC[0:39h] - GPI1 and GPI2 Pin Control (00h..11h)
  TSC[0:3Ah] - GPI3 Pin Control (00h..10h)
  TSC[0:3Bh] - Reserved (xxh)
TSC DAC/ADC and Beep
  TSC[0:3Ch] - DAC Instruction Set (01h)
  TSC[0:3Dh] - ADC Instruction Set (04h)
  TSC[0:3Eh] - Programmable Instruction Mode-Control Bits (00h)
  TSC[0:3Fh] - DAC Data-Path Setup (14h)
  TSC[0:40h] - DAC Volume Control (0Ch)
  TSC[0:41h] - DAC Left Volume Control (00h)
  TSC[0:42h] - DAC Right Volume Control (00h)
  TSC[0:43h] - Headset Detection (00h..60h)
  TSC[0:44h] - DRC Control 1 (0Fh)
  TSC[0:45h] - DRC Control 2 (38h)
  TSC[0:46h] - DRC Control 3 (00h)
  TSC[0:47h] - Beep Generator and Left Beep Volume (00h)
  TSC[0:48h] - Beep Generator and Right Beep Volume (00h)
  TSC[0:49h,4Ah,4Bh] - Beep Length MSB,MID,LSB (0000EEh)
  TSC[0:4Ch,4Dh] - Beep Frequency Sin(x) MSB,LSB (10D8h)
  TSC[0:4Eh,4Fh] - Beep Frequency Cos(x) MSB,LSB (7EE3h)
  TSC[0:50h] - Reserved (xxh)
  TSC[0:51h] - ADC Digital Mic (00h)
  TSC[0:52h] - ADC Digital Volume Control Fine Adjust (80h)
  TSC[0:53h] - ADC Digital Volume Control Coarse Adjust (00h)
  TSC[0:54h,55h] - Reserved (xxh)
TSC AGC and ADC (Auto-Gain-Control & Analog-to-Digital Converter)
  TSC[0:56h] - AGC Control 1 (00h)
  TSC[0:57h] - AGC Control 2 (00h)
  TSC[0:58h] - AGC Maximum Gain (7Fh, uh that's 7Fh=Reserved?)
  TSC[0:59h] - AGC Attack Time (00h)
  TSC[0:5Ah] - AGC Decay Time (00h)
  TSC[0:5Bh] - AGC Noise Debounce (00h)
  TSC[0:5Ch] - AGC Signal Debounce (00h)
  TSC[0:5Dh] - AGC Gain-Applied Reading (xxh) (R)
  TSC[0:5Eh...65h] - Reserved (xxh)
  TSC[0:66h] - ADC DC Measurement 1 (00h)
  TSC[0:67h] - ADC DC Measurement 2 (00h)
  TSC[0:68h,69h,6Ah] - ADC DC Measurement Output MSB,MID,LSB (R) (000000h)
  TSC[0:6Bh...73h] - Reserved (xxh)
  TSC[0:74h] - VOL/MICDET-Pin SAR ADC - Volume Control (00h)
  TSC[0:75h] - VOL/MICDET-Pin Gain (xxh) (R)
  TSC[0:76h...7Fh] - Reserved (xxh)
TSC TSC, DAC and ADC Routing, PGA, Power-Controls and MISC Logic
  TSC[1:01h..1Dh] - Reserved (xxh)
  TSC[1:1Eh] - Headphone and Speaker Amplifier Error Control (00h)
  TSC[1:1Fh] - Headphone Drivers (04h)
  TSC[1:20h] - Class-D Speaker Amplifier (06h)
  TSC[1:21h] - HP Output Drivers POP Removal Settings (3Eh)
  TSC[1:22h] - Output Driver PGA Ramp-Down Period Control (00h)
  TSC[1:23h] - DAC_L and DAC_R Output Mixer Routing (00h)
  TSC[1:24h] - Analog Volume to HPL (Left Headphone) (7Fh)
  TSC[1:25h] - Analog Volume to HPR (Right Headphone) (7Fh)
  TSC[1:26h] - Analog Volume to SPL (Left Speaker) (7Fh)
  TSC[1:27h] - Analog Volume to SPR (Right Speaker) (7Fh)
  TSC[1:28h] - HPL Driver (Left Headphone) (02h)
  TSC[1:29h] - HPR Driver (Right Headphone) (02h)
  TSC[1:2Ah] - SPL Driver (Left Speaker) (00h)
  TSC[1:2Bh] - SPR Driver (Right Speaker) (00h)
  TSC[1:2Ch] - HP Driver Control (00h)
  TSC[1:2Dh] - Reserved (xxh)
  TSC[1:2Eh] - MICBIAS (00h)
  TSC[1:2Fh] - MIC PGA (80h)
  TSC[1:30h] - P-Terminal Delta-Sigma Mono ADC Channel Fine-Gain Input (00h)
  TSC[1:31h] - M-Terminal ADC Input Selection (00h)
  TSC[1:32h] - Input CM Settings (00h)
  TSC[1:33h..FFh] - Reserved (xxh)
Reserved Page
  TSC[2:01h..FFh] - Reserved (00h)
TSC Touchscreen/SAR Control
  TSC[3:01h] - Reserved (xxh)
  TSC[3:02h] - SAR ADC Control 1 (00h)
  TSC[3:03h] - SAR ADC Control 2 (00h)
  TSC[3:04h] - Precharge and Sense (00h)
  TSC[3:05h] - Panel Voltage Stabilization (00h)
  TSC[3:06h] - Voltage Reference (20h)
  TSC[3:07h,08h] - Reserved (xxh)
  TSC[3:09h] - Status Bits 1 (40h) (R)
  TSC[3:0Ah] - Status Bits 2 (00h) (R)
  TSC[3:0Bh,0Ch] - Reserved (xxh)
  TSC[3:0Dh] - Buffer Mode (03h)  ;DSi: Unused,seems to use TSC[3:0Eh] instead
  TSC[3:0Eh] - Reserved / Undocumented (read by DSi for Pen Down Test) (0Fh)
  TSC[3:0Fh] - Scan Mode Timer (40h)
  TSC[3:10h] - Scan Mode Timer Clock (81h)
  TSC[3:11h] - SAR ADC Clock (81h)
  TSC[3:12h] - Debounce Time for Pen-Up Detection (00h)
  TSC[3:13h] - Auto AUX Measurement Selection (00h)
  TSC[3:14h] - Touch-Screen Pen Down (00h)
  TSC[3:15h] - Threshold Check Flags Register (00h) (R)
  TSC[3:16h,17h] - AUX1 Maximum Value Check MSB,LSB (0000h)
  TSC[3:18h,19h] - AUX1 Minimum Value Check MSB,LSB (0000h)
  TSC[3:1Ah,1Bh] - AUX2 Maximum Value Check MSB,LSB (0000h)
  TSC[3:1Ch,1Dh] - AUX2 Minimum Value Check MSB,LSB (0000h)
  TSC[3:1Eh,1Fh] - Temperature(TEMP1/TEMP2) Maximum Value Check MSB,LSB (0000h)
  TSC[3:20h,21h] - Temperature(TEMP1/TEMP2) Minimum Value Check MSB,LSB (0000h)
  TSC[3:22h...29h] - Reserved (xxh)
  TSC[3:2Ah,2Bh] - Touchscreen X-Coordinate Data MSB,LSB (0000h) (R)
  TSC[3:2Ch,2Dh] - Touchscreen Y-Coordinate Data MSB,LSB (0000h) (R)
  TSC[3:2Eh,2Fh] - Touchscreen Z1-Pressure Register MSB,LSB (0000h) (R)
  TSC[3:30h,31h] - Touchscreen Z2-Pressure Register MSB,LSB (0000h) (R)
  TSC[3:32h...35h] - Reserved (xxh)
  TSC[3:36h,37h] - AUX1 Data MSB,LSB (0000h) (R)
  TSC[3:38h,39h] - AUX2 Data MSB,LSB (0000h) (R)
  TSC[3:3Ah,3Bh] - VBAT Data MSB,LSB (0000h) (R)
  TSC[3:3Ch...41h] - Reserved (xxh)
  TSC[3:42h,43h] - Temperature TEMP1 Data Register MSB,LSB (0000h) (R)
  TSC[3:44h,45h] - Temperature TEMP2 Data Register MSB,LSB (0000h) (R)
  TSC[3:46h...7Fh] - Reserved (xxh)
TSC Coefficient RAM and Instruction RAM for ADC/DAC
  TSC[04h..05h:xxh] - ADC Coefficient RAM (126 x 16bit)
  TSC[06h..07h:xxh] - Reserved (00h)
  TSC[08h:01h]      - DAC Coefficient RAM Control (00h)
  TSC[08h..0Bh:xxh] - DAC Coefficient RAM, DAC Buffer A (252 x 16bit)
  TSC[0Ch..0Fh:xxh] - DAC Coefficient RAM, DAC Buffer B (252 x 16bit)
  TSC[10h..1Fh:xxh] - Reserved (00h)
  TSC[20h..2Bh:xxh] - ADC DSP Engine Instruction RAM (384 x 24bit)
  TSC[2Ch..3Fh:xxh] - Reserved (00h)
  TSC[40h..5Fh:xxh] - DAC DSP Engine Instruction RAM (1024 x 24bit)
  TSC[60h..FBh:xxh] - Reserved (00h)
TSC Additional 3DS Registers (3DS only, and only on the 2nd SPI bus)
  TSC[64h:01h..xxh] - 3DS Config Registers for Sound (and Microphone?)
  TSC[65h:01h..xxh] - 3DS Config Registers for Sound (and Microphone?)
  TSC[67h:01h..xxh] - 3DS Config Registers for Touchscreen and Circle Pad
  TSC[FBh:01h..xxh] - 3DS Buffer Mode Data for Touchscreen and Circle Pad
TSC Touchscreen/SAR Buffer
  TSC[FCh:01h..xxh] - Buffer Mode Data MSB,LSB (xxxxh) (R)
  TSC[FCh:xxh..7Fh] - Reserved (xxh)
TSC Undocumented Registers
  TSC[FDh:xxh] - Contains some undocumented non-zero values (DSi specific?)
  TSC[FEh:xxh] - Reserved (00h)
  TSC[FFh:xxh] - Accessing this page changes operation (DSi specific?)


DSi TSC[0:00h..1Ah], Basic PLL and Timing Control

TSC[xxh:00h] - Page Select Register (00h)
  7-0   Page Select (00h..FEh) (FFh=Undocumented, enter special mode?)
Selects the "page" for the TSC[page:index] addresses.

TSC[0:01h] - Software Reset (00h)
  7-1   Reserved. Write only zeros to these bits.
  0     Software Reset (0=No change, 1=Reset)

TSC[0:02h] - Reserved (xxh) (R)
  7-0   Reserved. Do not write to this register.

TSC[0:03h] - Overtemperature OT Flag (02h..FFh) (R)
  7-2   Reserved. Do not write to these bits. (R)
  1     Overtemperature protection flag (0=Alert, 1=Normal) (R)
  0     Reserved. Do not write to these bits. (R/W?)
Bit1 is valid only if speaker amplifier is powered up. Initial value varies per console:
  Old3DS    = 16h
  New3DS XL = 36h
Maybe the upper bits contain a Chip ID.

TSC[0:04h] - Clock-Gen Muxing (00h)
  7-4   Reserved. Write only zeros to these bits.
  3-2   Select PLL_CLKIN   (0=MCLK, 1=BCLK, 2=GPIO1, 3=SDIN)
  1-0   Select CODEC_CLKIN (0=MCLK, 1=BCLK, 2=GPIO1, 3=PLL_CLK)
See Section 5.8 for more details on clock generation mutiplexing and dividers.

TSC[0:05h] - PLL P and R-Values (11h)
  7     PLL Enable        (0=Power down, 1=Power up)
  6-4   PLL Divider P     (1..7=Div1..7, or 0=Div8)
  3-0   PLL Multiplier R  (1..15=Mul1..15, or 0=Mul16)

TSC[0:06h] - PLL J-Value (04h)
  7-6   Reserved. Write only zeros to these bits.
  5-0   PLL Multiplier J  (1..63=Mul1..63, or 0=Reserved)

TSC[0:07h,08h] - PLL D-Value MSB,LSB (0000h)
  15-14 Reserved. Write only zeros to these bits.
  13-0  PLL fractional multiplier D-Val (14bit)
Note that LSB register must be written to immediately after writing to MSB.

TSC[0:09h,0Ah] - Reserved (xxh)
  7-0   Reserved. Write only zeros to these bits.

TSC[0:0Bh] - DAC NDAC Value (01h)
  7     DAC NDAC Divider Enable (0=Power down, 1=Power up)
  6-0   DAC NDAC Divider (1..127=Div1..127, or 0=Div128)

TSC[0:0Ch] - DAC MDAC Value (01h)
  7     DAC MDAC Divider Enable (0=Power down, 1=Power up)
  6-0   DAC MDAC Divider (1..127=Div1..127, or 0=Div128)

TSC[0:0Dh,0Eh] - DAC DOSR Value MSB,LSB (0080h)
  15-10 Reserved
  9-0   DAC OSR value "DOSR" (1..1023, or 0=1024)
DOSR should be an integral multiple of the interpolation ratio in TSC[0:10h].
Note that LSB register must be written to immediately after writing to MSB.

TSC[0:0Fh] - DAC IDAC Value (80h)
  7-0   Number of instructions for DAC miniDSP engine (IDAC=N*4)
        (1..255 = 4..1020 (N*4), or 0=1024)
IDAC should be an integral multiple of the interpolation ratio in TSC[0:10h].

TSC[0:10h] - DAC miniDSP Engine Interpolation (08h)
  7-4   Reserved. Do not write to these registers.
  3-0   Interpolation ratio in DAC miniDSP engine (1..15, or 0=16)

TSC[0:11h] - Reserved (xxh)
  7-0   Reserved. Do not write to this register.

TSC[0:12h] - ADC NADC Value (01h)
  7     ADC NADC divider is powered
          0: ADC NADC divider is powered down and ADC_DSP_CLK = DAC_DSP_CLK.
          1: ADC NADC divider is powered up.
  6-0   ADC NADC divider  (1..127, or 0=128)

TSC[0:13h] - ADC MADC Value (01h)
  7     ADC MADC divider is powered
          0: ADC MADC divider is powered down and ADC_MOD_CLK = DAC_MOD_CLK.
          1: ADC MADC divider is powered up.
  6-0   ADC MADC divider  (1..127, or 0=128)

TSC[0:14h] - ADC AOSR Value (80h)
  7-0   ADC OSR "AOSR" divider  (1..255, or 0=256)
AOSR should be an integral multiple of the decimation ratio in TSC[0:16h].

TSC[0:15h] - ADC IADC Value (80h)
  7-0   Number of instruction for ADC miniDSP engine (IADC=N*2)
        (1..192 = 2..384 (N*2), or 0,193..255=Reserved)
IADC should be an integral multiple of the decimation ratio in TSC[0:16h].

TSC[0:16h] - ADC miniDSP Engine Decimation (04h)
  7-4   Reserved
  3-0   Decimation ratio in ADC miniDSP engine  (1..15, or 0=16)

TSC[0:17h,18h] - Reserved (xxh)
  7-0   Reserved. Do not write to these registers.

TSC[0:19h] - CLKOUT MUX (00h)
  7-3   Reserved
  2-0   CDIV_CLKIN (0=MCLK, 1=BCLK, 2=SDIN, 3=PLL_CLK, 4=DAC_CLK(DSP),
        5=DAC_MOD_CLK, 6=ADC_CLK(DSP), 7=ADC_MOD_CLK)

TSC[0:1Ah] - CLKOUT Divider M Value (01h)
  7     CLKOUT divider M Enable (0=Powered down, 1=Powered up)
  6-0   CLKOUT divider M        (1..127, or 0=128)


DSi TSC[0:1Bh..23h], Codec Control

TSC[0:1Bh] - Codec Interface Control 1 (00h) (R/W)
  7-6   Codec interface type        (0=I2S, 1=DSP, 2=RJF, 3=LJF)
  5-4   Codec interface word length (0..3=16,20,24,32 bits)
  3     BCLK Direction              (0=Input, 1=Output)
  2     WCLK Direction              (0=Input, 1=Output)
  1     Reserved
  0     Driving SDOUT to High-Impedance for the Extra BCLK cycle when
         data is not being transferred (0=Disabled, 1=Enabled)

TSC[0:1Ch] - Data-Slot Offset Programmability (00h)
  7-0   Offset (0..255 = 0..255 BCLKs)
Note: Measured with respect to WCLK Rising Edge in DSP Mode.

TSC[0:1Dh] - Codec Interface Control 2 (00h)
  7-6   Reserved
  5     SDIN-to-SDOUT loopback (0=Disable, 1=Enable)
  4     ADC-to-DAC loopback    (0=Disable, 1=Enable)
  3     BCLK Invert            (0=No, 1=Invert)
  2     BCLK and WCLK active even with Codec powered down (0=No, 1=Yes)
  1-0   BDIV_CLKIN     (0=DAC_CLK, 1=DAC_MOD_CLK, 2=ADC_CLK, 3=ADC_MOD_CLK)
The BCLK settings in Bit2,3 do apply to both Primary and Secondary BCLK.

TSC[0:1Eh] - BCLK Divider N Value (01h)
  7     BCLK divider N Enable (0=Powered down, 1=Powered up)
  6-0   BCLK divider N        (1..127, or 0=128)

TSC[0:1Fh] - Codec Secondary Interface Control 1 (00h)
  7-5   Secondary BCLK is obtained from    ;\(0=GPIO1, 1=SCLK, 2=MISO, 3=SDOUT,
  4-2   Secondary WCLK is obtained from    ;/ 4=GPIO2, 5=GPI1, 6=GPI2, 7=GPI3)
  1-0   Secondary SDIN is obtained from (0=GPIO1, 1=SCLK, 2=GPIO2, 3=GPI1)

TSC[0:20h] - Codec Secondary Interface Control 2 (00h)
  7-5   ADC_WCLK is obtained from  (0=GPIO1, 1=SCLK, 2=MISO, 3=Reserved,
  4     Reserved                        4=GPIO2, 5=GPI1, 6=GPI2, 7=GPI3)
  3     Codec/ClockGen BCLK source (0=Primary BCLK, 1=Secondary BCLK)
  2     Codec WCLK source          (0=Primary WCLK, 1=Secondary WCLK)
  1     Codec ADC_WCLK source      (0=DAC_WCLK, 1=ADC_WCLK)
  0     Codec SDIN source          (0=Primary SDIN, 1=Secondary SDIN)

TSC[0:21h] - Codec Secondary Interface Control 3 (00h)
  7     Primary BCLK output   (0=Internally generated BCLK, 1=Secondary BCLK)
  6     Secondary BCLK output (0=Primary BCLK, 1=Internally generated BCLK)
  5-4   Primary WCLK output  (0=DAC_fS, 1=ADC_fS, 2=Secondary WCLK, 3=Reserved)
  3-2   Secondary WCLK output (0=Primary WCLK, 1=DAC_fS, 2=ADC_fS, 3=Reserved)
  1     Primary SDOUT         (0=SDOUT from codec, 1=Secondary SDIN)
  0     Secondary SDOUT       (0=Primary SDIN, 1=SDOUT from codec)

TSC[0:22h] - I2C Bus Condition (00h)
  7-6   Reserved. Write only the reset value to these bits.
  5     Accept I2C general-call address  (0=No/Ignore, 1=Yes/Accept)
  4-0   Reserved. Write only zeros to these bits.

TSC[0:23h] - Reserved (xxh)
  7-0   Reserved. Write only zeros to these bits.


DSi TSC[0:24h..32h], Status and Interrupt Flags

TSC[0:24h] - ADC Flag Register (0xh) (R)
  7     ADC PGA applied gain = programmed gain (0=Differs, 1=Equal) (R)
  6     ADC powered                  (0=Powered down, 1=Powered up) (R)
  5     AGC saturated        (0=No/inrange, 1=Yes/saturated to max) (R)
  4-0   Reserved. Write only zeros to these bits.
Note on D5(?): Sticky flag bIts. These are read-only bits. They are automatically cleared once they are read and are set only if the source trigger occurs again.

TSC[0:25h] - DAC Flag Register (00h) (R)
  7     Left-channel DAC powered             (0=Powered down, 1=Powered up) (R)
  6     Reserved. Write only zero to this bit.
  5     Left Headphone HPL driver powered    (0=Powered down, 1=Powered up) (R)
  4     Left-channel class-D driver powered  (0=Powered down, 1=Powered up) (R)
  3     Right-channel DAC powered            (0=Powered down, 1=Powered up) (R)
  2     Reserved. Write only zero to this bit.
  1     Right Headphone HPR driver powered   (0=Powered down, 1=Powered up) (R)
  0     Right-channel class-D driver powered (0=Powered down, 1=Powered up) (R)

TSC[0:26h] - DAC Flag Register (00h) (R)
  7-5   Reserved. Do not write to these bits.
  4     Left-channel DAC PGA applied gain=programmed gain  (0=Differs, 1=Equal)
  3-1   Reserved. Write only zeros to these bits.
  0     Right-channel DAC PGA applied gain=programmed gain (0=Differs, 1=Equal)

TSC[0:27h] - Overflow Flags (00h) (R)
  7     Left-Channel DAC Overflow Flag           (0=None, 1=Overflow) (R)
  6     Right-Channel DAC Overflow Flag          (0=None, 1=Overflow) (R)
  5     DAC Barrel Shifter Output Overflow Flag  (0=None, 1=Overflow) (R)
  4     Reserved. Write only zeros to these bits.
  3     Delta-Sigma Mono ADC Overflow Flag       (0=None, 1=Overflow) (R)
  2     Reserved. Write only zero to this bit.
  1     ADC Barrel Shifter Output Overflow Flag  (0=None, 1=Overflow) (R)
  0     Reserved. Write only zero to this bit.
Sticky flag bIts. These are read-only bits. They are automatically cleared once they are read and are set only if the source trigger occurs again.

TSC[0:28h..2Bh] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.

TSC[0:2Ch] - Interrupt Flags DAC, sticky (00h..30h) (R)
  7     Short-circuit detected at HPL/left class-D driver         (0=No, 1=Yes)
  6     Short-circuit detected at HPR/right class-D driver        (0=No, 1=Yes)
  5     Headset button pressed                                    (0=No, 1=Yes)
  4     Headset insertion/removal is detected                     (0=No, 1=Yes)
  3     Left DAC signal power vs signal threshold of DRC (0=Less/Equal,1=Above)
  2     Right DAC signal power vs signal threshold of DRC(0=Less/Equal,1=Above)
  1     DAC miniDSP Engine Standard Interrupt-Port Output  (0=Read 0, 1=Read 1)
  0     DAC miniDSP Engine Auxiliary Interrupt-Port Output (0=Read 0, 1=Read 1)
Sticky flag bIts. These are read-only bits. They are automatically cleared once they are read and are set only if the source trigger occurs again.

TSC[0:2Dh] - Interrupt Flags ADC, sticky (00h..18h) (R)
  7     Reserved. Write only zero to this bit.
  6     ADC signal power vs noise threshold for AGC (0=Greater, 1=Less)
  5     Reserved. Write only zeros to these bits.
  4     ADC miniDSP Engine Standard Interrupt Port Output  (0=Read 0, 1=Read 1)
  3     ADC miniDSP Engine Auxiliary Interrupt Port Output (0=Read 0, 1=Read 1)
  2     DC measurement using Delta Sigma Audio ADC
          (0=Not available, 1=Not available, too, uh?)
  1-0   Reserved. Write only zeros to these bits.
Sticky flag bIts. These are read-only bits. They are automatically cleared once they are read and are set only if the source trigger occurs again.

TSC[0:2Eh] - Interrupt Flags DAC, non-sticky? (00h..30h) (R)
  7     Short circuit detected at HPL/left class-D driver         (0=No, 1=Yes)
  6     Short circuit detected at HPR/right class-D driver        (0=No, 1=Yes)
  5     Headset button pressed                                    (0=No, 1=Yes)
  4     Headset removal/insertion detected             (0=Removal, 1=Insertion)
  3     Left DAC signal power vs signal threshold of DRC     (0=Below, 1=Above)
  2     Right DAC signal power vs signal threshold of DRC    (0=Below, 1=Above)
  1     DAC miniDSP Engine Standard Interrupt Port Output  (0=Read 0, 1=Read 1)
  0     DAC miniDSP Engine Auxiliary Interrupt Port Output (0=Read 0, 1=Read 1)
This is (almost?) same as TSC[0:2Ch]. Maybe this is current state (non-sticky)?

TSC[0:2Fh] - Interrupt Flags ADC, non-sticky? (00h..18h) (R)
  7     Reserved
  6     Delta-sigma mono ADC signal power vs noise threshold for left AGC
  5     Reserved                                       (0=Greater, 1=Less)
  4     ADC miniDSP Engine Standard Interrupt Port Output  (0=Read 0, 1=Read 1)
  3     ADC miniDSP Engine Auxiliary Interrupt Port Output (0=Read 0, 1=Read 1)
  2     DC measurement using Delta Sigma Audio ADC
          (0=Not available, 1=Not available, too, uh?)
  1-0   Reserved. Write only zeros to these bits.
This is (almost?) same as TSC[0:2Dh]. Maybe this is current state (non-sticky)?

TSC[0:30h] - INT1 Control Register (Select INT1 Sources) (00h)
TSC[0:31h] - INT2 Control Register (Select INT2 Sources) (00h)
  7     Headset-insertion detect                                  (0=Off, 1=On)
  6     Button-press detect                                       (0=Off, 1=On)
  5     DAC DRC signal-power                                      (0=Off, 1=On)
  4     ADC AGC noise                                             (0=Off, 1=On)
  3     Short-circuit                                             (0=Off, 1=On)
  2     Engine-generated                                          (0=Off, 1=On)
  1     DC measurement using Delta Sigma Audio ADC data-available (0=Off, 1=On)
  0     INT duration (0=Pulse Once, 1=Pulse Repeatedly until Acknowledge)
Bit1-7 select which sources shall trigger INT1/INT2, a few more sources can be selected in TSC[0:32h].Bit5-7.
Bit0 selects how the INT1/INT2 signal shall be pulsed (once with 2ms length, or repeating every 4ms with 50% duty, until it gets acknowledged by reading TSC[0:2Ch,2Dh,32h]).

TSC[0:32h] - INT1 and INT2 Control Register (00h)
  7     INT1 upon SAR measurement data-out-of-threshold range   (0=Off, 1=Off?)
  6     INT1 upon Pen touch/SAR data-available                    (0=Off, 1=On)
  5     INT2 upon SAR measurement data-out-of-threshold range   (0=Off, 1=Off?)
  4     Reserved
  3     Pen touch detected                          (0=No, 1=Touch)     (R)
  2     Data available for read                     (0=No, 1=Available) (R)
  1     SAR data out of programmed threshold range  (0=No, 1=Out)       (R)
  0     Reserved. Write only the default value to this bit.             (R)


DSi TSC[0:33h..3Bh], Pin Control

TSC[0:33h] - GPIO1 In/Out Pin Control (00h..C2h)
TSC[0:34h] - GPIO2 In/Out Pin Control (00h..C2h)
  7-6   Reserved. Do not write any value other than reset value.
  5-2   GPIOx Mode                                                 (R/W)
          0 = GPIOx disabled (input and output buffers powered down)
          1 = GPIOx input mode (as secondary BCLK/WCLK/SDIN input, or
                   as ADC_WCLK input, Dig_Mic_In or in ClockGen block)
          2 = GPIOx input mode (as GPI general-purpose input)
          3 = GPIOx output = general-purpose output
          4 = GPIOx output = CLKOUT output
          5 = GPIOx output = INT1 output
          6 = GPIOx output = INT2 output
          7 = GPIOx output = ADC_WCLK output for codec interface
          8 = GPIOx output = secondary BCLK output for codec interface
          9 = GPIOx output = secondary WCLK output for codec interface
          10 = GPIOx output = ADC_MOD_CLK output for the digital microphone
          11 = GPIOx output = secondary SDOUT for codec interface
          12 = GPIOx output = TouchScreen/SAR ADC interrupt (active-low),
          13-15 = Reserved                              as PINTDAV signal
  1     GPIOx input buffer value (0 or 1)                         (R)
  0     GPIOx general-purpose output value (0 or 1)               (R/W)

TSC[0:35h] - SDOUT (OUT Pin) Control (12h)
  7-5   Reserved
  4     SDOUT bus keeper (0=Enabled, 1=Disabled)
  3-1   SDOUT Mode
          0 = SDOUT disabled (output buffer powered down)
          1 = SDOUT = primary SDOUT output for codec interface
          2 = SDOUT = general-purpose output
          3 = SDOUT = CLKOUT output
          4 = SDOUT = INT1 output
          5 = SDOUT = INT2 output
          6 = SDOUT = secondary BCLK output for codec interface
          7 = SDOUT = secondary WCLK output for codec interface
  0     SDOUT general-purpose output value (0 or 1)

TSC[0:36h] - SDIN (IN Pin) Control (02h or 03h)
  7-3   Reserved
  2-1   SDIN Mode
          0 = SDIN disabled (input buffer powered down)
          1 = SDIN enabled (as codec SDIN, Dig_Mic_In, or in ClockGen block)
          2 = SDIN enabled (as GPI general-purpose input)
          3 = Reserved
  0     SDIN input-buffer value (0 or 1)                          (R)

TSC[0:37h] - MISO (OUT Pin) Control (02h)
  7-5   Reserved
  4-1   MISO Mode
          0 = MISO disabled (output buffer powered down)
          1 = MISO = MISO output for SPI interface (or disabled for I2C)
          2 = General-purpose output
          3 = MISO = CLKOUT output
          4 = MISO = INT1 output
          5 = MISO = INT2 output
          6 = MISO = ADC_WCLK output for codec interface
          7 = MISO = ADC_MOD_CLK output for the digital microphone
          8 = MISO = secondary SDOUT for codec interface
          9 = MISO = secondary BCLK output for codec interface
          10 = MISO = secondary WCLK output for codec interface
          11-15 = Reserved
  0     MISO general-purpose output value (0 or 1)

TSC[0:38h] - SCLK (IN Pin) Control (02h..03h)
  7-3   Reserved
  2-1   SCLK Mode
          0 = SCLK disabled (input buffer powered down)
          1 = SCLK enabled (for the SPI interface)
          2 = SCLK enabled (as a GPI general-purpose input)
          3 = SCLK enabled (as secondary SDIN/BCLK/WCLK input,
                            or as ADC_WCLK input, or Dig_Mic_In)
  0     SCLK input buffer value (0 or 1)                         (R)

TSC[0:39h] - GPI1 and GPI2 Pin Control (00h..11h)
  7     Reserved. Write only zero to this bit.
  6-5   GPI1 Mode
          0 = GPI1 disabled (input buffer powered down)
          1 = GPI1 enabled (as secondary SDIN/BCLK/WCLK input, or ADC_WCLK inp)
          2 = GPI1 enabled (as a GPI general-purpose input)
          3 = Reserved (unlike below GPI2)
  4     GPI1 pin value (0 or 1)         (R)
  3     Reserved. Write only zero to this bit.
  2-1   GPI2 Mode
          0 = GPI2 disabled (input buffer powered down)
          1 = GPI2 enabled (as secondary BCLK/WCLK input, or ADC_WCLK input)
          2 = GPI2 enabled (as a GPI general-purpose input)
          3 = GPI2 enabled (as an HP_SP input)
  0     GPI2 pin value (0 or 1)         (R)
The DSi has GPI1 wired to VCNT5.
The DSi has GPI2 wired to HP#SP (headphone/speaker switch).

TSC[0:3Ah] - GPI3 Pin Control (00h..10h)
  7     Reserved. Write only zero to this bit.
  6-5   GPI3 Mode
          0 = GPI3 disabled (input buffer powered down)
          1 = GPI3 enabled (as secondary BCLK/WCLK input, or ADC_WCLK input)
          2 = GPI3 enabled (as a GPI general purpose input)
          3 = Reserved (Undocumented - used by DSi?)
  4     GPI3 pin value (0 or 1)         (R)
  3-0   Reserved. Write only zeros to these bits.
The DSi has the GPI3 pin wired to Headphone Mute logic.

TSC[0:3Bh] - Reserved (xxh)
  7-0   Reserved. Write only zeros to these bits.


DSi TSC[0:3Ch..55h], DAC/ADC and Beep

TSC[0:3Ch] - DAC Instruction Set (01h)
  7-5   Reserved. Write only default value.
  4-0   DAC Signal Processing Block
          0      = DAC miniDSP is used for signal processing
          1..25  = DAC Signal Processing Block PRB_P1 .. PRB_P25
          26..31 = Reserved. Do not use.

TSC[0:3Dh] - ADC Instruction Set (04h)
  7-5   Reserved. Write only default values.
  4-0   ADC Signal Processing Block
          0      = ADC miniDSP is used for signal processing
          1..3   = Reserved
          4..6   = ADC Signal Processing Block PRB_R4 .. PRB_R6
          7..9   = Reserved
          10..12 = ADC Signal Processing Block PRB_R10 .. PRB_R12
          13..15 = Reserved
          16..18 = ADC Signal Processing Block PRB_R16 .. PRB_R18
          19..31 = Reserved. Do not write these sequences to these bits.

TSC[0:3Eh] - Programmable Instruction Mode-Control Bits (00h)
  7     Reserved
  6     ADC miniDSP Engine Auxiliary Control bit A (0 or 1)
  5     ADC miniDSP Engine Auxiliary Control bit B (0 or 1)
  4     Reset ADC miniDSP instruction counter at start of new frame (0=Yes)
  3     Reserved
  2     DAC miniDSP Engine Auxiliary Control bit A (0 or 1)
  1     DAC miniDSP Engine Auxiliary Control bit B (0 or 1)
  0     Reset DAC miniDSP instruction counter at start of new frame (0=Yes)
Above DAC/ADC bit A and B can be used for conditional instructions like JMP.

TSC[0:3Fh] - DAC Data-Path Setup (14h)
  7     Left-channel DAC            (0=Powered down, 1=Powered up)
  6     Right-channel DAC           (0=Powered down, 1=Powered up)
  5-4   Left-channel DAC data path  (0=Off, 1=Left Data, 2=Right Data, 3=Both)
  3-2   Right-channel DAC data path (0=Off, 1=Right Data, 2=Left Data, 3=Both)
  1-0   DAC channel volume control soft-stepping (0=One step per sample,
         1=One step per 2 samples, 2=Disabled, 3=Reserved)
Wheras, Both=((L+R)/2).

TSC[0:40h] - DAC Volume Control (0Ch)
  7-4   Reserved. Write only zeros to these bits.
  3     Left-channel DAC  (0=Not muted, 1=Muted)
  2     Right-channel DAC (0=Not muted, 1=Muted)
  1-0   DAC Mono/Stereo Volume
          0: Use Left/Right volume control for Left/Right channels ("stereo")
          1: Use Right volume control for Both channels            ("mono")
          2: Use Left volume control for Both channels             ("mono")
          3: Same as 0                                             ("stereo")

TSC[0:41h] - DAC Left Volume Control (00h)
TSC[0:42h] - DAC Right Volume Control (00h)
  7-0  Digital gain in 0.5dB units (-127..+48 = -63.5dB..+24dB, Other=Reserved)

TSC[0:43h] - Headset Detection (00h..60h)
  7     Headset detection Enable (0=Disabled, 1=Enabled)
  6-5   Headset detection (0=None, 1=Headset, 2=Reserved, 3=Headset+Mic) (R)
  4-2   Debounce for Glitch Rejection During Headset Detection
          (0..5 = 16ms, 32ms, 64ms, 128ms, 256ms, 512ms, 6..7=Reserved)
          (when TSC[3:10h] set to 1MHz)
  1-0   Debounce for Glitch Rejection During Headset Button-Press Detection
          (0..3 = 0ms, 8ms, 16ms, 32ms) (when TSC[3:10h] set to 1MHz)
Sampling is 8x faster than above timings (eg. time=32ms uses 4ms sampling).

TSC[0:44h] - DRC Control 1 (0Fh)
  7     Reserved. Write only the reset value to these bits.
  6     DRC for left channel  (0=Disabled, 1=Enabled)
  5     DRC for right channel (0=Disabled, 1=Enabled)
  4-2   DRC threshold  (0..7 = -3dB,-6dB,-9dB,-12dB,-15dB,-18dB,-21dB,-24dB)
  1-0   DRC hysteresis (0..3 = +0dB,+1dB,+2dB,+3dB)

TSC[0:45h] - DRC Control 2 (38h)
  7     Reserved. Write only the reset value to these bits.
  6-3   DRC Hold Time
          0  = DRC Hold Disabled        ;-disable
          1  = 32 DAC Word Clocks       ;\
          2  = 64 DAC Word Clocks       ;
          3  = 128 DAC Word Clocks      ;
          4  = 256 DAC Word Clocks      ; powers of 2
          5  = 512 DAC Word Clocks      ;
          6  = 1024 DAC Word Clocks     ;
          7  = 2048 DAC Word Clocks     ;
          8  = 4096 DAC Word Clocks     ;
          9  = 8192 DAC Word Clocks     ;
          10 = 16384 DAC Word Clocks    ;/
          11 = 1*32768 DAC Word Clocks  ;\
          12 = 2*32768 DAC Word Clocks  ;
          13 = 3*32768 DAC Word Clocks  ; multiples of 32768
          14 = 4*32768 DAC Word Clocks  ;
          15 = 5*32768 DAC Word Clocks  ;/
  2-0   Reserved. Write only the reset value to these bits.

TSC[0:46h] - DRC Control 3 (00h)
  7-4   DRC attack rate, "(4 SHR N) dB per DAC Word Clock"
        (0=4dB, 1=2dB, 2=1dB, ..., 15=0.000122dB per DAC Word Clock)
  3-0   DRC decay rate, "(1 SHR (N+6)) dB per DAC Word Clock"
        (0=0.0156dB, 1=0.00781dB, ..., 15=0.000000476dB per DAC Word Clock)

TSC[0:47h] - Beep Generator and Left Beep Volume (00h)
  7     Beep Generator Enable (0=Disabled/Duration ended, 1=Enabled/Busy)
          (self-clearing based on beep duration)
  6     Auto beep generator on pen touch (0=Disabled, 1=Enabled)
          (CODEC_CLKIN should be available for this and is
          used whenever touch is detected).
  5-0   Left-channel beep volume control "(2-N)dB" (0..63 = +2dB .. -61dB)
The beep generator is only available in PRB_P25 DAC processing mode.

TSC[0:48h] - Beep Generator and Right Beep Volume (00h)
  7-6   Beep Mono/Stereo Volume
          0: Use Left/Right volume control for Left/Right channels ("stereo")
          1: Use Right volume control for Both channels            ("mono")
          2: Use Left volume control for Both channels             ("mono")
          3: Same as 0                                             ("stereo")
  5-0   Right-channel beep volume control "(2-N)dB" (0..63 = +2dB .. -61dB)
The beep generator is only available in PRB_P25 DAC processing mode.

TSC[0:49h,4Ah,4Bh] - Beep Length MSB,MID,LSB (0000EEh)
  23-0  Number of samples for which beep need to be generated (24bit)

TSC[0:4Ch,4Dh] - Beep Frequency Sin(x) MSB,LSB (10D8h)
TSC[0:4Eh,4Fh] - Beep Frequency Cos(x) MSB,LSB (7EE3h)
  15-0  Beep Frequency sin/cos values (16bit, each)
These registers should be set to sin(2pi*fin/fS) and cos(2pi*fin/fS) accordingly; where fin is the beep frequency and fS is the DAC sample rate.

TSC[0:50h] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.

TSC[0:51h] - ADC Digital Mic (00h)
  7     ADC channel   (0=Powered Down, 1=Powered Up)
  6     Reserved
  5-4   Digital microphone input  (0=GPIO1, 1=SCLK, 2=SDIN, 3=GPIO2)
  3     Digital microphone for delta-sigma mono ADC channel (0=Off, 1=On)
  2     Reserved
  1-0   ADC channel volume control soft-stepping (0=One step per sample,
         1=One step per 2 samples, 2=Disabled, 3=Reserved)

TSC[0:52h] - ADC Digital Volume Control Fine Adjust (80h)
  7     ADC channel   (0=Not muted, 1=Muted)
  6-4   Delta-Sigma Mono ADC Channel Volume Control Fine Gain
        (0=0dB, 1=-0.1dB, 2=-0.2dB, 3=-0.3dB, 4=-0.4dB, 5..7=Reserved)
  3-0   Reserved. Write only zeros to these bits.

TSC[0:53h] - ADC Digital Volume Control Coarse Adjust (00h)
  7     Reserved
  6-0   Delta-Sigma Mono ADC Channel Volume Control Coarse Gain
          00h..27h = 0..39    = Reserved
          28h..xxh = 40       = -12 dB
          29h      = 39       = -11.5 dB
          ...        ...
          67h      = 103      = +19.5 dB
          68h      = 104      = +20 dB
          69h..7Fh = 105..127 = Reserved

TSC[0:54h,55h] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.


DSi TSC[0:56h..7Fh], AGC and ADC

Auto-Gain-Control & Analog-to-Digital Converter

TSC[0:56h] - AGC Control 1 (00h)
  7     AGC (0=Disabled, 1=Enabled)
  6-4   AGC target level     (0=-5.5dB, 1=-8dB, 2=-10dB, 3=-12dB,
                              4=-14dB, 5=-17dB, 6=-20dB, 7=-24dB)
  3-0   Reserved. Write only zeros to these bits.

TSC[0:57h] - AGC Control 2 (00h)
  7-6   AGC hysterysis setting (0=1dB, 1=2dB, 2=4dB, 3=Disable AGC hysterysis)
  5-1   AGC noise threshold (and silence detection)
          0   = AGC noise/silence detection is disabled.
          1   = AGC noise threshold = -30dB
          2   = AGC noise threshold = -32dB
          3   = AGC noise threshold = -34dB
          ...
          29  = AGC noise threshold = -86dB
          30  = AGC noise threshold = -88dB
          31  = AGC noise threshold = -90dB
  0     Reserved. Write only zero to this bit.

TSC[0:58h] - AGC Maximum Gain (7Fh, uh that's 7Fh=Reserved?)
  7     Reserved. Write only zero to this bit.
  6-0   AGC maximum gain in 0.5dB units (0..119=0..+59.5dB, 120..127=Reserved)

TSC[0:59h] - AGC Attack Time (00h)
TSC[0:5Ah] - AGC Decay Time (00h)
  7-3   AGC attack/decay time, (N*2+1)*32/fS (0..31 = 1*32/fS .. 63*32/fS)
  2-0   AGC attack/decay time Multiply factor, 1 SHL N (0..7 = 1..128)
Whereas, fS is the ADC sample rate.

TSC[0:5Bh] - AGC Noise Debounce (00h)
  7-5   Reserved. Write only zeros to these bits.
  4-0   AGC noise debounce
          0..5   = 0/fS, 4/fS, 8/fS, 16/fS, 32/fS, 64/fS     ;\powers of 2
          6..10  = 128/fS, 256/fS, 512/fS, 1024/fS, 2048/fS  ;/
          11..14 = 1*4096/fS, 2*4096/fS, 3*4096/fS           ;\multiples
          14..31 = 4*4096/fS, .., 20*4096/fS, 21*4096/fS     ;/of 4096

TSC[0:5Ch] - AGC Signal Debounce (00h)
  7-4   Reserved. Write only zeros to these bits.
  3-0   AGC signal debounce
          0..5   = 0/fS, 4/fS, 8/fS, 16/fS, 32/fS, 64/fS     ;\powers of 2
          6..9   = 128/fS, 256/fS, 512/fS, 1024/fS           ;/
          10..13 = 1*2048/fS, 2*2048/fS, 3*2048/fS           ;\multiples
          13..15 = 4*2048/fS, 5*2048/fS, 6*2048/fS           ;/of 2048

TSC[0:5Dh] - AGC Gain-Applied Reading (xxh) (R)
  7-0   Gain applied by AGC in 0.5dB units (-24..+119 = -12dB..+59.5dB)   (R)

TSC[0:5Eh...65h] - Reserved (xxh)
  7-0   Reserved. Do not write to these registers.

TSC[0:66h] - ADC DC Measurement 1 (00h)
  7     DC measurement for mono ADC channel (0=Disabled, 1=Enabled)
  6     Reserved. Write only reset value.
  5     DC measurement is done based on
          0: 1st order sinc filter with averaging of 2^D.
          1: 1st order low-pass IIR filter whose coefficients
              are calculated based on D value.
  4-0   DC Meaurement D setting (1..20 = D=1 .. D=20) (0 or 21..31=Reserved)

TSC[0:67h] - ADC DC Measurement 2 (00h)
  7     Reserved. Write only reset value.
  6     DC measurement data update (0=Enabled, 1=Disabled/allow stable reading)
        (Disabled: user can read the last updated data without corruption)
  5     For IIR based DC measurement, the measurment value is
          0: the instantaneous output of the IIR filter
          1: update before periodic clearing of the IIR filter
  4-0   IIR based DC measurment, average time setting:
          0       Infinite average is used
          1       Averaging time is 2^1 ADC modulator clock periods
          2       Averaging time is 2^2 ADC modulator clock periods
          ...
          19      Averaging time is 2^19 ADC modulator clock periods
          20      Averaging time is 2^20 ADC modulator clock periods
          21..31  Reserved. Don't use.

TSC[0:68h,69h,6Ah] - ADC DC Measurement Output MSB,MID,LSB (R) (000000h)
  23-0  ADC DC Measurement Output (24bit)

TSC[0:6Bh...73h] - Reserved (xxh)
  7-0   Reserved. Do not write to these registers.

TSC[0:74h] - VOL/MICDET-Pin SAR ADC - Volume Control (00h)
  7     DAC volume control is controlled by,
          0: controlled by control register (7-bit Vol ADC is powered down)
          1: controlled by pin (analog volume input)
  6     Clock for the 7-bit Vol ADC for pin volume control,
          0: Internal on-chip RC oscillator
          1: External MCLK
  5-4   Hysteresis
          0: No hysteresis for volume control ADC output
          1: Hysteresis of +/-1 bit
          2: Hysteresis of +/-2 bits
          3: Reserved. Do not write this sequence to these bits.
  3     Reserved. Write only reset value.
  2-0   Throughput of the 7-bit Vol ADC for pin volume control,
        When Bit6=1 and external MCLK is 12MHz:
          (0..7=15.625Hz, 31.25Hz, 62.5Hz, 125Hz, 250Hz, 500Hz, 1000Hz, 2000Hz)
        When Bit6=0 (use Internal oscillator):
          (0..7=10.68Hz, 21.35Hz, 42.71Hz, 85Hz?, 170Hz, 340Hz, 680Hz, 1370Hz)

TSC[0:75h] - VOL/MICDET-Pin Gain (xxh) (R)
  7     Reserved. Write only zero to this bit.
  6-0   Gain applied by pin volume control
          0   = +18 dB
          1   = +17.5 dB
          2   = +17 dB
          ...
          35  = +0.5 dB
          36  = 0 dB
          37  = -0.5 dB
          ...
          89  = -26.5 dB
          90  = -27 dB    ;below in 1dB steps instead of 0.5dB steps !
          91  = -28 dB
          ...
          125 = -62 dB
          126 = -63 dB
          127 = Reserved

TSC[0:76h...7Fh] - Reserved (xxh)
  7-0   Reserved. Do not write to these registers.


DSi TSC[1:xxh], DAC and ADC Routing, PGA, Power-Controls and MISC Logic

TSC[1:01h..1Dh] - Reserved (xxh)
  7-0  Reserved. Do not write to these registers.

TSC[1:1Eh] - Headphone and Speaker Amplifier Error Control (00h)
  7-2  Reserved
  1    Reset HPL/HPR power-up bits upon short-circuit detect (0=Yes, 1=No)
  0    Reset SPL/SPR power-up bits upon short-circuit detect (0=Yes, 1=No)
The HPL/HPR auto-reset occurs only if TSC[1:1Fh].Bit1=1 (action=power down).

TSC[1:1Fh] - Headphone Drivers (04h)
  7    HPL output driver (0=Powered down, 1=Powered up)
  6    HPR output driver (0=Powered down, 1=Powered up)
  5    Reserved. Write only zero to this bit.
  4-3  Output common-mode voltage (0=1.35V, 1=1.5V, 2=1.65V, 3=1.8V)
  2    Reserved. Write only 1 to this bit. (!!!)
  1    Action when short-circuit protection is enabled/detected,
           0=Limit the maximum current to the load.
           1=Power down the output driver.
  0    Short-circuit detected on the headphone driver (0=No, 1=Yes) (R)

TSC[1:20h] - Class-D Speaker Amplifier (06h)
  7    Left-channel class-D output driver  (0=Powered down, 1=Powered up)
  6    Right-channel class-D output driver (0=Powered down, 1=Powered up)
  5-1  Reserved. Write only the reset value (00011b) to these bits (!!!)
  0    Short-circuit is detected on the class-D driver (0=No, 1=Yes) (R)
Bit0 is Valid only if class-D amplifier is powered up. For short-circuit flag sticky bit, see TSC[0:2Ch].

TSC[1:21h] - HP Output Drivers POP Removal Settings (3Eh)
  7    If power down sequence is activated by device software power down
       using TSC[1:2Eh].Bit7 then power down DAC,
         0: simultaneously with the HP and SP amplifiers.
         1: after HP and SP amplifiers are completely powered down.
         (the latter setting is to optimize power-down POP).
  6-3  Driver power-on time (at 8.2MHz) (1=15.3us, 2=153us, 3=1.53ms,
         4=15.3ms,5=76.2ms, 6=153ms, 7=304ms, 8=610ms, 9=1.22s, 10=3.04s,
         11=6.1s, 12..15=Reserved)
  2-1  Driver ramp-up step time (8.2MHz) (0=0ms, 1=0.98ms, 2=1.95ms, 3=3.9ms)
  0    Weakly driven output common-mode voltage is generated from,
         0=resistor divider of the AVDD supply.
         1=band-gap reference.

TSC[1:22h] - Output Driver PGA Ramp-Down Period Control (00h)
  7    Reserved. Write only the reset value to this bit.    (USED on DSi!)
  6-4  Speaker Power-Up Wait Time (at 8.2MHz) (0=0 ms, 1=3.04 ms, 2=7.62 ms,
         3=12.2 ms, 4=15.3 ms, 5=19.8 ms, 6=24.4 ms, 7=30.5 ms)
  3-0  Reserved. Write only the reset value to these bits.

TSC[1:23h] - DAC_L and DAC_R Output Mixer Routing (00h)
  7-6  DAC_L route      (0=Nowhere, 1=To L-Mixer, 2=Direct to HPL, 3=Reserved)
  5    MIC input routed to the left-channel mixer amplifier      (0=No, 1=Yes)
  4    AUX1 input routed to the left-channel mixer amplifier     (0=No, 1=Yes)
  3-2  DAC_R route      (0=Nowhere, 1=To R-Mixer, 2=Direct to HPR, 3=Reserved)
  1    AUX1 input routed to the right-channel mixer amplifier    (0=No, 1=Yes)
  0    HPL driver output routed to HPR driver (for differential) (0=No, 1=Yes)

TSC[1:24h] - Analog Volume to HPL (Left Headphone) (7Fh)
TSC[1:25h] - Analog Volume to HPR (Right Headphone) (7Fh)
TSC[1:26h] - Analog Volume to SPL (Left Speaker) (7Fh)
TSC[1:27h] - Analog Volume to SPR (Right Speaker) (7Fh)
  7    Analog volume control routed to HPx/SPx output driver (0=No, 1=Yes)
  6-0  Analog volume control gain (non-linear) (0 dB to -78 dB)
See Table 5-37 and Table 5-38, uh?

TSC[1:28h] - HPL Driver (Left Headphone) (02h)
TSC[1:29h] - HPR Driver (Right Headphone) (02h)
  7    Reserved. Write only zero to this bit.
  6-3  HPx driver PGA  (0..9 = 0dB..9dB, 10..15=Reserved)
  2    HPx driver      (0=Muted, 1=Not muted)
  1    HPx driver during power down (0=Weakly driven to a common mode,
        1=High-impedance)
  0    All programmed gains to HPx have been applied (0=Not yet, 1=Yes/all) (R)

TSC[1:2Ah] - SPL Driver (Left Speaker) (00h)
TSC[1:2Bh] - SPR Driver (Right Speaker) (00h)
  7-5  Reserved. Write only zeros to these bits.
  4-3  SPx class-D driver output stage gain (0=6dB, 1=12dB, 2=18dB, 3=24dB)
  2    SPx class-D driver (0=Muted, 1=Not muted)
  1    Reserved. Write only zero to this bit.
  0    All programmed gains to SPx have been applied (0=Not yet, 1=Yes/all) (R)

TSC[1:2Ch] - HP Driver Control (00h)
  7-5  Debounce time for the headset short-circuit detection
         (0..7 = 0us, 8us, 16us, 32us, 64us, 128us, 256us)
         (when TSC[3:10h] set to 1MHz)
  4-3  DAC Performance (0=Normal, 1=Increased, 2=Reserved, 3=Further Increased)
       (increased: by increased current, further: by increased current gain)
  2    HPL output driver type (0=Headphone, 1=Lineout)
  1    HPR output driver type (0=Headphone, 1=Lineout)
  0    Reserved. Write only zero to this bit.
The clock used for the debounce has a clock period = debounce duration/8.

TSC[1:2Dh] - Reserved (xxh)
  7-0  Reserved. Do not write to these registers.

TSC[1:2Eh] - MICBIAS (00h)
  7    Device software power-down (0=Disabled, 1=PowerDown?-Enabled)
  6-4  Reserved. Write only zeros to these bits.
  3    Power up programmed MICBIAS  (0=Only if Headset inserted, 1=Always)
  2    Reserved. Write only zero to this bit.
  1-0  MICBIAS output (0=Off, 1=2V, 2=2.5V, 3=AVDD)

TSC[1:2Fh] - MIC PGA (80h)
  7    MIC PGA            (0=Controlled by bits6-0, 1=Force 0dB)
  6-0  PGA in 0.5dB units (0..119 = 0..59.5dB, 120..127=Reserved)

TSC[1:30h] - P-Terminal Delta-Sigma Mono ADC Channel Fine-Gain Input (00h)
  7-6  MIC to MIC PGA feed-forward    (0=Off, 1=10kOhm, 2=20kOhm, 3=40kOhm)
  5-4  AUX1 to MIC PGA feed-forward   (0=Off, 1=10kOhm, 2=20kOhm, 3=40kOhm)
  3-2  AUX2 to MIC PGA feed-forward   (0=Off, 1=10kOhm, 2=20kOhm, 3=40kOhm)
  1-0  Reserved. Write only zeros to these bits.
Program Bit7-6 of registers TSC[1:30h] and TSC[1:31h] with same value. Input impedance selection affects the microphone PGA gain. See the Analog Front End section for details.

TSC[1:31h] - M-Terminal ADC Input Selection (00h)
  7-6  CM to MIC PGA feed-forward     (0=Off, 1=10kOhm, 2=20kOhm, 3=40kOhm)
  5-4  AUX2 to MIC PGA feed-forward   (0=Off, 1=10kOhm, 2=20kOhm, 3=40kOhm)
  3-0  Reserved. Write only zeros to these bits.
Program Bit7-6 of registers TSC[1:30h] and TSC[1:31h] with same value. Input impedance selection affects the microphone PGA gain. See the Analog Front End section for details.

TSC[1:32h] - Input CM Settings (00h)
  7    MIC input  (0=Floating, 1=Connected to CM internally)
        (when not used for MIC PGA and analog bypass)
  6    AUX1 input (0=Floating, 1=Connected to CM internally)
        (when not used for MIC PGA and analog bypass)
  5    AUX2 input (0=Floating, 1=Connected to CM internally)
        (when not used for MIC PGA)
  4-1  Reserved. Write only zeros to these bits.
  0    All programmed gains to ADC have been applied (0=Not yet, 1=Yes/all) (R)

TSC[1:33h..FFh] - Reserved (xxh)
  7-0  Reserved. Write only the reset value to these bits.


DSi TSC[3:xxh], Touchscreen/SAR Control and TSC[FCh:xxh], Buffer

TSC[3:01h] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.

TSC[3:02h] - SAR ADC Control 1 (00h)
  7     Stop  (0=Normal mode, 1=Stop conversion and power down SAR ADC)
  6-5   SAR ADC resolution   (0=12bit, 1=8bit, 2=10bit, 3=12bit)
  4-3   SAR ADC clock divider
          0 = Div1 (use for 8bit resolution mode only) (This divider is only
                    for the conversion clock generation, not for other logic)
          1 = Div2 (use for 8bit/10bit resolution mode only)
          2 = Div4 (recommended for better performance in 8bit/10bit mode)
          3 = Div8 (recommended for better performance in 12bit mode)
          (See Figure 5-40, uh?)
  2     Filter used for on-chip data averaging (0=Mean, 1=Median) (if enabled)
  1-0   On-chip data averaging for mean/median filter
          0 = On-chip data averaging disabled
          1 = 4-data averaging (mean),  or 5-data averaging (median)
          2 = 8-data averaging (mean),  or 9-data averaging (median)
          3 = 16-data averaging (mean), or 15-data averaging (median)

TSC[3:03h] - SAR ADC Control 2 (00h)
  7     Conversions controlled,
          0 = Host-controlled conversions
          1 = Self-controlled conversions for touch screen based on pen touch
  6     Reserved. Write only zero to this bit.
  5-2   Conversion Mode
          0 = No scan
          1 = Scan X/Y         ;\Even in host-controlled mode ;\until either
          2 = Scan X/Y/Z1/Z2   ;/                             ; pen is lifted,
          3 = Scan X           ;\                             ; or a stop bit
          4 = Scan Y           ; Only in self-controlled mode ; TSC[3:02h].Bit7
          5 = Scan Z1/Z2       ;/                             ;/is sent
          6 = VBAT measurement
          7 = AUX2 measurement
          8 = AUX1 measurement
          9 = Auto scan. Sequence used is AUX1, AUX2, VBAT.
              Each of these inputs can be enabled or disabled independently
              using TSC[3:13h], and with that sequence is modified accordingly.
              Scan continues until stop bit TSC[3:02h].Bit7 is sent,
              or Bit5-2 of this register are changed.
         10 = TEMP1 measurement
         11 = Port scan: AUX1, AUX2, VBAT
         12 = TEMP2 measurement
         13-15 = Reserved. Do not write these sequences to these bits.
  1-0   Interrupt pin (GPIO1 or GPIO2 pin)
          0 = PEN-interrupt    /PENIRQ (active low)
          1 = Data-available   /DATA_AVA (active low)
          2 = PEN-interrupt    PENIRQ and Data-available DATA_AVA (active high)
          3 = Reserved

TSC[3:04h] - Precharge and Sense (00h)
  7     Pen touch detection (0=Enabled, 1=Disabled)
  6-4   Precharge time before touch detection
        (0..7 = 0.25us, 1us, 3us, 10us, 30us, 100us, 300us, 1000us)
        (when TSC[3:11h] set to 8MHz)
  3     Reserved. Write only zero to this bit.
  2-0   Sense time during touch detection
        (0..7 = 1us, 2us, 3us, 10us, 30us, 100us, 300us, 1000us)
        (when TSC[3:11h] set to 8MHz)

TSC[3:05h] - Panel Voltage Stabilization (00h)
  7-6   SAR comparator bias current (0=Normal, 1..3=Increase by 25%, 50%, 100%)
        (use Increase to support higher conversion clock)
  5     Sample duration (0=Default, 1=Doubled; for higher impedance)
  4-3   Reserved. Write only zeroes to these bits.
  2-0   Panel voltage stabilization time before conversion
        (0..7 = 0.25us, 1us, 3us, 10us, 30us, 100us, 300us, 1000us)
        (when TSC[3:11h] set to 8MHz)

TSC[3:06h] - Voltage Reference (20h)
  7     Reference for Non-touch-screen Measurement  (0=External, 1=Internal)
  6     Internal reference voltage   (0=1.25V, 1=2.5V)
  5     Internal reference powered   (0=Always, 1=Only during conversion)
  4     Reserved
  3-2   Reference Stabilization Time before Conversion
        (0=0us, 1=100us, 2=500us, 3=1ms) (when TSC[3:11h] set to 8MHz)
  1     Reserved
  0     Battery measurement input (0=VBAT<=VREF, 1=VBAT=BAT)

TSC[3:07h,08h] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.

TSC[3:09h] - Status Bits 1 (40h) (R)
  7     Pen Touch detected          (0=Not detected, 1=Detected) (R)
  6     ADC Ready                   (0=Busy, 1=Ready)            (R)
  5     New data is available       (0=None, 1=Yes)              (R)
  4     Reserved. Write only the reset value to this bit.
  3     New X data is available     (0=None, 1=Yes)              (R)
  2     New Y data is available     (0=None, 1=Yes)              (R)
  1     New Z1 data is available    (0=None, 1=Yes)              (R)
  0     New Z2 data is available    (0=None, 1=Yes)              (R)
Bit0-3 and Bit5 are not valid for the buffer mode.
Bit0-3 are cleared after reading the corresponding data.
Bit5 is cleared after completely reading ALL data.

TSC[3:0Ah] - Status Bits 2 (00h) (R)
  7     New AUX1 data is available  (0=None, 1=Yes)              (R)
  6     New AUX2 data is available  (0=None, 1=Yes)              (R)
  5     New VBAT data is available  (0=None, 1=Yes)              (R)
  4-2   Reserved. Write only zeros to these bits.
  1     New TEMP1 data is available (0=None, 1=Yes)              (R)
  0     New TEMP2 data is available (0=None, 1=Yes)              (R)
Bit0-1 and Bit5-7 are not valid for the buffer mode.
Bit0-1 and Bit5-7 are cleared after reading the corresponding data.

TSC[3:0Bh,0Ch] - Reserved (xxh)
  7-0   Reserved. Write only the reset value to these bits.

TSC[3:0Dh] - Buffer Mode (03h)
  7     Buffer Mode Enable (0=Disabled, 1=Enabled)
          (when disabled: RDPTR/WRPTR/TGPTR are set to their default values)
  6     Buffer Mode Type   (0=Countinuos-conversion, 1=Single-shot)
  5-3   Trigger level for conversion "(N+1)*8*number of converted data"
          0..7 = (8..64)*number of converted data
          uh, does "X*number of converted data" mean "after X conversions"?
  2     Reserved
  1     Buffer Full  (0=No, 1=Full; contains 64 unread converted data)   (R)
  0     Buffer Empty (0=No, 1=Empty; contains 0 unread converted data)   (R)
However, in DSi this register is unused, and DSi does instead use TSC[3:0Eh].


TSC[3:0Eh] - Reserved / Undocumented (read by DSi for Pen Down Test) (0Fh)
  7-0   Reserved. Write only the reset value to these bits.
However, in DSi this is used as so... (seems to resemble TSC[3:0Dh])...
  7     Undoc Enable   (0=Disabled, 1=Enabled)  (R/W)
  6     Undoc Whatever (0=Normal)               (R/W)
  5-3   Undoc Whatever (5=Normal)               (R/W)
  2     Undoc Unused                            (?)
  1     Undoc Pendown/DataAvailable?            (R?)
  0     Undoc Unused                            (R?)

TSC[3:0Fh] - Scan Mode Timer (40h)
  7     Programmable delay for Touch-screen measurement (0=Disable, 1=Enable)
  6-4   Programmable interval timer delay
          (0..7 = 8ms, 1ms, 2ms, 3ms, 4ms, 5ms, 6ms, 7ms)
          (when TSC[3:10h] set to 1MHz)
  3     Programmable delay for Non-touch-screen auto measurement   (1=Enable)
  2-0   Programmable interval timer delay (0..7 = 1.12min, 3.36min,
          5.59min, 7.83min, 10.01min, 12.30min, 14.54min, 16.78min)
          (uh, what is that? minutes? minimum? or what?)
          (when TSC[3:10h] set to 1MHz)
These delays are from the end of one data set of conversion to the start of another new data set of conversion.
Bit7: This interval timer mode is for all self-controlled modes. For host-controlled mode, it is valid only for (X/Y) or (X/Y/Z1/Z2) conversions.

TSC[3:10h] - Scan Mode Timer Clock (81h)
  7     Clock used for Programmable Delay Timer (0=Internal Osc/8, 1=Ext. MCLK)
  6-0   MCLK Divider to Generate 1-MHz Clock for the Programmable Delay Timer
        (1..127=Div1..127, or 0=Div128)
The timings marked "(when TSC[3:10h] set to 1MHz)" are assuming the MCLK division result to be 1MHz (1us). Other divider settings will cause those timings to change. Using Internal Osc/8 (Bit7=0) results in 1.025MHz (0.97us), which is almost same as the "1MHz" timings (internal osc isn't too accurate though).
Bit7: External clock is used only to control the delay programmed between the conversions and not used for doing the actual conversion. This is supported to get an accurate delay, because the internal oscillator frequency varies from device to device.

TSC[3:11h] - SAR ADC Clock (81h)
  7     Clock used for SAR ADC and TSC FSM (0=Internal Osc/1, 1=External MCLK)
  6-0   MCLK Divider for the SAR (min 40ns)  (1..127=Div1..127, or 0=Div128)
The timings marked "(when TSC[3:11h] set to 8MHz)" are assuming the MCLK division result to be 8MHz (125ns). Other divider settings will cause those timings to change. For the SAR unit, the division result should be max 25MHz (min 40ns). Using Internal Osc/1 (Bit7=0) results in 8.2MHz (122ns), which is almost same as the "8MHz" timings (internal osc isn't too accurate though).

TSC[3:12h] - Debounce Time for Pen-Up Detection (00h)
  7     Interface used for the buffer data reading   (0=SPI, 1=I2C)
  6     SAR/buffer data update is,
          0: held automatically (to avoid simultaneous buffer read and write
               operations) based on internal detection logic.
          1: held using software control and TSC[3:12h].Bit5.
  5     SAR/buffer data update is (only if above Bit6=1),
           0: enabled all the time
           1: stopped so that user can read the last updated data
                 without any data corruption.
  4-3   Reserved. Write only zeros to these bits.
  2-0   Pen-touch removal detection with debounce
          (0..7 = 0us, 8us, 16us, 32us, 64us, 128us, 256us, 512us)
          (when TSC[3:10h] set to 1MHz)
The clock used for the debounce has a clock period = debounce duration/8.

TSC[3:13h] - Auto AUX Measurement Selection (00h)
  7     Auto AUX1 measurement during auto non-touch screen scan (0=Off, 1=On)
  6     Auto AUX2 measurement during auto non-touch screen scan (0=Off, 1=On)
  5     Auto VBAT measurement during auto non-touch screen scan (0=Off, 1=On)
  4     Auto TEMP measurement during auto non-touch screen scan (0=Off, 1=On)
  3     TEMP Measurement (0=Use TEMP1, 1=Use TEMP2)
  2     AUX1 Usage (0=Voltage measurement, 1=Resistance measurement)
  1     AUX2 Usage (0=Voltage measurement, 1=Resistance measurement)
  0     Resistance measurement bias (0=Internal bias, 1=External bias)

TSC[3:14h] - Touch-Screen Pen Down (00h)
  7-3   Reserved
  2-0   Debounce Time for Pen-Down Detection
          (0..7 = 0us, 64us, 128us, 256us, 512us, 1024us, 2048us, 4096us)
          (when TSC[3:10h] set to 1MHz)
The clock used for the debounce has a clock period = debounce duration/8.

TSC[3:15h] - Threshold Check Flags Register (00h) (R)
  7-6   Reserved. Write only zeros to these bits.
  5     AUX1 Maximum (0=Inrange, 1=Exceeds Limit; Equal/Above MAX)
  4     AUX1 Minimum (0=Inrange, 1=Exceeds Limit; Equal/Below MIN)
  3     AUX2 Maximum (0=Inrange, 1=Exceeds Limit; Equal/Above MAX)
  2     AUX2 Minimum (0=Inrange, 1=Exceeds Limit; Equal/Below MIN)
  1     TEMP Maximum (0=Inrange, 1=Exceeds Limit; Equal/Above MAX)
  0     TEMP Minimum (0=Inrange, 1=Exceeds Limit; Equal/Below MIN)
Sticky flag bIts. These are read-only bits. They are automatically cleared once they are read and are set only if the source trigger occurs again.

TSC[3:16h,17h] - AUX1 Maximum Value Check MSB,LSB (0000h)
TSC[3:18h,19h] - AUX1 Minimum Value Check MSB,LSB (0000h)
TSC[3:1Ah,1Bh] - AUX2 Maximum Value Check MSB,LSB (0000h)
TSC[3:1Ch,1Dh] - AUX2 Minimum Value Check MSB,LSB (0000h)
TSC[3:1Eh,1Fh] - Temperature(TEMP1/TEMP2) Maximum Value Check MSB,LSB (0000h)
TSC[3:20h,21h] - Temperature(TEMP1/TEMP2) Minimum Value Check MSB,LSB (0000h)
  15-13  Reserved
  12     Threshold check (0=Disabled, 1=Enabled)
         (valid for auto/non-auto scan measurement).
  11-0   Threshold code (12bit)

TSC[3:2Ah,2Bh] - Touchscreen X-Coordinate Data MSB,LSB (0000h) (R)
TSC[3:2Ch,2Dh] - Touchscreen Y-Coordinate Data MSB,LSB (0000h) (R)
TSC[3:2Eh,2Fh] - Touchscreen Z1-Pressure Register MSB,LSB (0000h) (R)
TSC[3:30h,31h] - Touchscreen Z2-Pressure Register MSB,LSB (0000h) (R)
TSC[3:36h,37h] - AUX1 Data MSB,LSB (0000h) (R)
TSC[3:38h,39h] - AUX2 Data MSB,LSB (0000h) (R)
TSC[3:3Ah,3Bh] - VBAT Data MSB,LSB (0000h) (R)
TSC[3:42h,43h] - Temperature TEMP1 Data Register MSB,LSB (0000h) (R)
TSC[3:44h,45h] - Temperature TEMP2 Data Register MSB,LSB (0000h) (R)
  15-0   Data... but, seems to be always zero on DSi?
Going by the datasheet, these registers should contain current sample values, but they seem to be always zero on DSi.
Instead, the samples for the currently selected Conversion Mode can be read from the buffer at TSC[FCh:01h,02h], using the buffer should also ensure that MSB/LSB-pairs won't change within 16bit reads.

TSC[3:22h...29h] - Reserved (xxh)
TSC[3:32h...35h] - Reserved (xxh)
TSC[3:3Ch...41h] - Reserved (xxh)
TSC[3:46h...7Fh] - Reserved (xxh)
  7-0    Reserved. Write only the reset value to these bits.

TSC[FCh:01h,02h] - Buffer Mode Data MSB,LSB (xxxxh) (R)
  15    Ring-buffer Full  (1=All 64 entries are unread)
  14    Ring-buffer Empty (1=All 64 entries are read)
  13    Reserved          (uh?)
  12    Data ID           (0=X/Z1/BAT/AUX2, 1=Y/Z2/AUX1/TEMP)
  11-0  Converted data (12bit), read from "RDPTR" ring-buffer location
Note: One can/must read multiple words from index 01h (the index will somewhat automatically toggle between 01h and 02h in that case (or perhaps it does increment to 03h and up, but those indices mirror to 01h and 02h)).

TSC[FCh:03h..7Fh] - Reserved (xxh) (actually mirrors of TSC[FCh:01h,02h])
  7-0   Reserved. Write only the reset value to these bits.
These are somewhat mirrors of the buffer at TSC[FCh:01h,02h]. Trying to select index=03h starts reading with the 1st buffer byte (ie. it won't start at the 3rd byte).


DSi TSC[04h..05h:xxh], ADC Digital Filter Coefficient RAM

Default values shown for this page only become valid 100us following a hardware or software reset.

TSC[04h-05h:xxh] - ADC Coefficient RAM (126 x 16bit)
Coefficients are signed 16bit (-32,768..+32,767), each occupying 2 bytes (MSB,LSB).
The MSB should always be written first, immediately followed by the LSB (even if only the MSB or LSB portion of the coefficient changes, both registers should be written in this sequence).
                   ADC miniDSP   ADC FIR Filter Special
                   Coefficients  Coefficients   Coefficients
  TSC[4:00h]       Page Select   -              -
  TSC[4:01h]       Reserved      -              -
  TSC[4:02h..07h]  C1..C3        -              N0,N1,D1 for AGC LPF
                                                  (first-order IIR, used
                                                  as averager to detect level)
  TSC[4:08h..0Dh]  C4..C6        -              N0,N1,D1 for ADC-programmable
                                                  first-order IIR
  TSC[4:0Eh..17h]  C7..C11       FIR0..FIR4     N0,N1,N2,D1,D2 for ADC Biquad A
  TSC[4:18h..21h]  C12..C16      FIR5..FIR9     N0,N1,N2,D1,D2 for ADC Biquad B
  TSC[4:22h..2Bh]  C17..C21      FIR10..FIR14   N0,N1,N2,D1,D2 for ADC Biquad C
  TSC[4:2Ch..35h]  C22..C26      FIR15..FIR19   N0,N1,N2,D1,D2 for ADC Biquad D
  TSC[4:36h..3Fh]  C27..C31      FIR20..FIR24   N0,N1,N2,D1,D2 for ADC Biquad E
  TSC[4:40h..7Fh]  C32..C63      -              -
  TSC[5:00h]       Page Select   -              -
  TSC[5:01h]       Reserved      -              -
  TSC[5:02h..7Fh]  C65..C127     -              -

Multi-order FIR Filter (Finite Impulse Response)
  input[n] ---o--MUL(F0)-->ADD-----------------> output[n]
              |             ^
          input[n-1]        |                          ;\
              |             |                          ; first order FIR
              o--MUL(F1)-->ADD                         ;/
              |             ^
          input[n-2]        |                          ;\
              |             |                          ; second order FIR
              o--MUL(F2)-->ADD                         ;/
              :             ^
              :             :                          ;-further order's

First-order IIR Filter (Infinite Impulse Response)
  input[n] ---o--MUL(N0)-->ADD-------------o---> output[n]
              |             ^              |
          input[n-1]        |          output[n-1]     ;\
              |             |              |           ; first order IIR
              o--MUL(N1)-->ADD<--MUL(-D1)--o           ;/

Biquad Filter (IIR with 1st and 2nd order)
  input[n] ---o--MUL(N0)-->ADD-------------o---> output[n]
              |             ^              |
          input[n-1]        |          output[n-1]     ;\
              |             |              |           ; first order IIR
              o--MUL(N1)-->ADD<--MUL(-D1)--o           ;/
              |             ^              |
          input[n-2]        |          output[n-2]     ;\
              |             |              |           ; second order IIR
              o--MUL(N2)-->ADD<--MUL(-D2)--o           ;/



DSi TSC[08h..0Fh:xxh], DAC Digital Filter Coefficient RAM

Default values shown for this page only become valid 100us following a hardware or software reset.

TSC[08h:01h] - DAC Coefficient RAM Control (00h)
  7-4   Reserved. Write only the reset value.
  3     DAC miniDSP generated flag for toggling MSB of coefficient RAM address
        (only used in non-adaptive mode)                                (R)
  2     DAC Adaptive Filtering in DAC miniDSP (0=Disabled, 1=Enabled)   (R/W)
  1     DAC Adaptive Filter Buffer Control Flag                         (R)
          aka DAC Coefficient Buffers in adaptive filter mode
             0: miniDSP accesses Buffer A,
                  external control interface (=the user?) accesses Buffer B
             1: miniDSP accesses Buffer B,
                  external control interface (=the user?) accesses Buffer A
  0     DAC Adaptive Filter Buffer Switch Control                       (R/W)
         0: DAC coefficient buffers will not be switched at next frame boundary
         1: DAC coefficient buffers will     be switched at next frame boundary
            (only if adaptive filtering mode is enabled)
            This bit will self-clear on switching.

TSC[08h..0Bh:xxh] - DAC Coefficient RAM, DAC Buffer A (252 x 16bit)
Coefficients are signed 16bit (-32,768..+32,767), each occupying 2 bytes (MSB,LSB).
The MSB should always be written first, immediately followed by the LSB (even if only the MSB or LSB portion of the coefficient changes, both registers should be written in this sequence).
                   DAC miniDSP    Special
                  (DAC Buffer A)  DAC-programmable
                   Coefficient    Coefficient
  TSC[8:00h]       Page Select    -
  TSC[8:01h]       Control        - (see above)
  TSC[8:02h..0Bh]  C1..C5         N0,N1,N2,D1,D2 for Left Biquad A  ;N0=7FFFh
  TSC[8:0Ch..15h]  C6..C10        N0,N1,N2,D1,D2 for Left Biquad B  ;N1,N2,D1,
  TSC[8:16h..1Fh]  C11..C15       N0,N1,N2,D1,D2 for Left Biquad C  ;     D2=0
  TSC[8:20h..29h]  C16..C20       N0,N1,N2,D1,D2 for Left Biquad D
  TSC[8:2Ah..33h]  C21..C25       N0,N1,N2,D1,D2 for Left Biquad E
  TSC[8:34h..3Dh]  C26..C30       N0,N1,N2,D1,D2 for Left Biquad F
  TSC[8:3Eh..3Fh]  C31            -
  TSC[8:40h..41h]  C32            for 3D PGA for PRB_P23, PRB_P24 and PRB_P25
  TSC[8:42h..4Bh]  C33..C37       N0,N1,N2,D1,D2 for Right Biquad A
  TSC[8:4Ch..55h]  C38..C42       N0,N1,N2,D1,D2 for Right Biquad B
  TSC[8:56h..5Fh]  C43..C47       N0,N1,N2,D1,D2 for Right Biquad C
  TSC[8:60h..69h]  C48..C52       N0,N1,N2,D1,D2 for Right Biquad D
  TSC[8:6Ah..73h]  C53..C57       N0,N1,N2,D1,D2 for Right Biquad E
  TSC[8:74h..7Dh]  C58..C62       N0,N1,N2,D1,D2 for Right Biquad F
  TSC[8:7Eh..7Fh]  C63            -
  TSC[9:00h]       Page Select    -
  TSC[9:01h]       Reserved       - (do not write to this register)
  TSC[9:02h..07h]  C65..C67       N0,N1,D1 for Left first-order IIR
  TSC[9:08h..0Dh]  C68..C70       N0,N1,D1 for Right first-order IIR
  TSC[9:0Eh..13h]  C71..C73       N0,N1,D1 for DRC first-order high-pass filter
  TSC[9:14h..19h]  C74..C76       N0,N1,D1 for DRC first-order low-pass filter
  TSC[9:1Ah..7Fh]  C77..C127      -
  TSC[A:00h]       Page Select    -
  TSC[A:01h]       Reserved       - (do not write to this register)
  TSC[A:02h..7Fh]  C129..C191     -
  TSC[B:00h]       Page Select    -
  TSC[B:01h]       Reserved       - (do not write to this register)
  TSC[B:02h..7Fh]  C193..C255     -

TSC[0Ch..0Fh:xxh] - DAC Coefficient RAM, DAC Buffer B (252 x 16bit)
This is essentially same as above Buffer A. But it's unclear if Buffer B is having the same special Biquad/3DPGA/IIR/DRC functions (the official datasheet doesn't mention them, but it does specify the initial reset values same as for Buffer A, ie. with value 7FFFh for the locations that correspond to "N0" coefficients, which is suggesting that those special functions are present in Buffer B, too).
                   DAC miniDSP    Special
                  (DAC Buffer A)  DAC-programmable
                   Coefficient    Coefficient
  TSC[C:02h..0Bh]  C1..C5         Unknown  ;\
  TSC[C:0Ch..15h]  C6..C10        Unknown  ;
  TSC[C:16h..1Fh]  C11..C15       Unknown  ; maybe Left Biquad A..F
  TSC[C:20h..29h]  C16..C20       Unknown  ; as for Buffer A
  TSC[C:2Ah..33h]  C21..C25       Unknown  ;
  TSC[C:34h..3Dh]  C26..C30       Unknown  ;/
  TSC[C:3Eh..3Fh]  C31            -
  TSC[C:40h..41h]  C32            Unknown maybe 3D PGA as for Buffer A
  TSC[C:42h..4Bh]  C33..C37       Unknown  ;\
  TSC[C:4Ch..55h]  C38..C42       Unknown  ;
  TSC[C:56h..5Fh]  C43..C47       Unknown  ; maybe Right Biquad A..F
  TSC[C:60h..69h]  C48..C52       Unknown  ; as for Buffer A
  TSC[C:6Ah..73h]  C53..C57       Unknown  ;
  TSC[C:74h..7Dh]  C58..C62       Unknown  ;/
  TSC[C:7Eh..7Fh]  C63            -
  TSC[D:00h]       Page Select    -
  TSC[D:01h]       Reserved       - (do not write to this register)
  TSC[D:02h..07h]  C65..C67       Unknown  ;\
  TSC[D:08h..0Dh]  C68..C70       Unknown  ; maybe IIR and DRC
  TSC[D:0Eh..13h]  C71..C73       Unknown  ; as for Buffer A
  TSC[D:14h..19h]  C74..C76       Unknown  ;/
  TSC[D:1Ah..7Fh]  C77..C127      -
  TSC[E:00h]       Page Select    -
  TSC[E:01h]       Reserved       - (do not write to this register)
  TSC[E:02h..7Fh]  C129..C191     -
  TSC[F:00h]       Page Select    -
  TSC[F:01h]       Reserved       - (do not write to this register)
  TSC[F:02h..7Fh]  C193..C255     -


DSi TSC[20h..2Bh:xxh], TSC[40h..5Fh:xxh] ADC/DAC Instruction RAM

TSC[20h..2Bh:xxh] - ADC DSP Engine Instruction RAM (384 x 24bit)
ADC miniDSP Instructions are 20bit, each occupying 3 bytes (MSB,MID,LSB) (with dummy padding in upper 4bit of MSB).
  TSC[20h..2Bh:00h]       Page Select
  TSC[20h..2Bh:01h]       Reserved
  TSC[20h:02h...61h]      ADC Instructions 0...31
  TSC[21h:02h...61h]      ADC Instructions 32...63
  TSC[22h:02h...61h]      ADC Instructions 64...95
  TSC[23h:02h...61h]      ADC Instructions 96...127
  TSC[24h:02h...61h]      ADC Instructions 128...159
  TSC[25h:02h...61h]      ADC Instructions 160...191
  TSC[26h:02h...61h]      ADC Instructions 192...223
  TSC[27h:02h...61h]      ADC Instructions 224...255
  TSC[28h:02h...61h]      ADC Instructions 256...287
  TSC[29h:02h...61h]      ADC Instructions 288...319
  TSC[2Ah:02h...61h]      ADC Instructions 320...351
  TSC[2Bh:02h...61h]      ADC Instructions 352...383
  TSC[20h..2Bh:62h..7Fh]  Reserved

TSC[40h..5Fh:xxh] - DAC DSP Engine Instruction RAM (1024 x 24bit)
DAC miniDSP Instructions are 24bit (uh, unlike 20bit ADC ones?), each occupying 3 bytes (MSB,MID,LSB).
  TSC[40h..5Fh:00h]       Page Select
  TSC[40h..5Fh:01h]       Reserved
  TSC[40h:02h...61h]      DAC Instructions 0...31
  TSC[41h:02h...61h]      DAC Instructions 32...63
  TSC[42h:02h...61h]      DAC Instructions 64...95
  TSC[43h:02h...61h]      DAC Instructions 96...127
  TSC[44h:02h...61h]      DAC Instructions 128...159
  TSC[45h:02h...61h]      DAC Instructions 160...191
  TSC[46h:02h...61h]      DAC Instructions 192...223
  TSC[47h:02h...61h]      DAC Instructions 224...255
  TSC[48h:02h...61h]      DAC Instructions 256...287
  TSC[49h:02h...61h]      DAC Instructions 288...319
  TSC[4Ah:02h...61h]      DAC Instructions 320...351
  TSC[4Bh:02h...61h]      DAC Instructions 352...383
  TSC[4Ch:02h...61h]      DAC Instructions 384...415
  TSC[4Dh:02h...61h]      DAC Instructions 416...447
  TSC[4Eh:02h...61h]      DAC Instructions 448...479
  TSC[4Fh:02h...61h]      DAC Instructions 480...511
  TSC[50h:02h...61h]      DAC Instructions 512...543
  TSC[51h:02h...61h]      DAC Instructions 544...575
  TSC[52h:02h...61h]      DAC Instructions 576...607
  TSC[53h:02h...61h]      DAC Instructions 608...639
  TSC[54h:02h...61h]      DAC Instructions 640...671
  TSC[55h:02h...61h]      DAC Instructions 672...703
  TSC[56h:02h...61h]      DAC Instructions 704...735
  TSC[57h:02h...61h]      DAC Instructions 736...767
  TSC[58h:02h...61h]      DAC Instructions 768...799
  TSC[59h:02h...61h]      DAC Instructions 800...831
  TSC[5Ah:02h...61h]      DAC Instructions 832...863
  TSC[5Bh:02h...61h]      DAC Instructions 864...895
  TSC[5Ch:02h...61h]      DAC Instructions 896...927
  TSC[5Dh:02h...61h]      DAC Instructions 928...959
  TSC[5Eh:02h...61h]      DAC Instructions 960...991
  TSC[5Fh:02h...61h]      DAC Instructions 992...1023
  TSC[40h..5Fh:62h..7Fh]  Reserved

Unknown if the Instruction RAM is implemented, the datasheets says that the RAM is R/W, but it seems to be always zero on DSi/3DS.
The miniDSP instruction set isn't officially documented anywhere. Texas Instruments has released a tool called AIC PurePath Studio, the tool supports graphical drag-and-drop prgrammaning, and it's said to be also supporting assembly code (perhaps also including opcode specs... it isn't quite clear how to download that tool though).


DSi I2C Bus

I2C Bus
DSi I2C I/O Ports
DSi I2C Signals

Device 4Ah (BPTWL chip) (LED/Volume/Powerbutton/Reset)
DSi I2C Device 4Ah (BPTWL chip)

Device 78h/7Ah (Aptina MT9V113 Cameras)
DSi Aptina Camera Initialization
Directly addressed I2C Registers (16bit index, 16bit data):
DSi Aptina Camera Registers: SYSCTL (0000h-0051h)
DSi Aptina Camera Registers: RX_SS, FUSE, XDMA (0100h-099Fh)
DSi Aptina Camera Registers: CORE (3000h-31FFh, 38xxh)
DSi Aptina Camera Registers: SOC1 (3210h-33FDh)
DSi Aptina Camera Registers: SOC2 (3400h-3729h)
Indirectly addressed MCU Variables (via above "XDMA" commands):
DSi Aptina Camera Variables: RAM/SFR/MON (GPIO/Monitor) (MCU:0000h-20xxh)
DSi Aptina Camera Variables: SEQ (Sequencer) (MCU:21xxh)
DSi Aptina Camera Variables: AE (Auto Exposure) (MCU:22xxh)
DSi Aptina Camera Variables: AWB (Auto White Balance) (MCU:23xxh)
DSi Aptina Camera Variables: FD (Anti-Flicker) (MCU:24xxh)
DSi Aptina Camera Variables: MODE (Mode/Context) (MCU:27xxh)
DSi Aptina Camera Variables: HG (Histogram) (MCU:2Bxxh)
I2C Bus Caution: The Camera I2C access requires the "16.76MHz Camera External Clock" enabled in Port 4004004h.Bit8 on ARM9 Side. For accessing registers other than SYSCTL/CORE, one must also clear the Standby flag in SYSCTL[0018h].

Device A0h/E0h (Unknown, maybe cameras from other manufacturer)
DSi Alternate Cameras from Unknown Manufacturer

Camera Data Transfers
Camera configuration is done on ARM7 side via serial I2C bus. However, the actual Camera Data transfers are done on ARM9 side through 8bit parallel bus:
DSi Cameras

Broken Cameras (defunct device 78h/7Ah/A0h/E0h)
Consoles should contain two Aptina cameras, or two Unknown cameras. The Unlaunch installer is throwing a warning when detecting Unknown cameras, so far nobody has reported that case, so Unknown cameras seem to be very rare (if they were ever used at all). However, two people reported that warning showing FFh's in the ID bytes for most or all cameras (caused by a broken camera with only one working camera, or broken camera connector with no working cameras at all).
Bottom line is that broken cameras are more common than unknown cameras, and games with optional/extra camera features should support that situation: ie. disable the feature in case of broken camera(s) instead of becoming unplayable.

Device 90h (Whatever)
Trying to read I2C for this device just returns FFh? Maybe exists in debug version only. The firmware contains a few functions for accessing this register.
  Register  Width   Description
  02h       1       Used for DSi IRQ6 IF flags
                      uh, IF.Bit6 would be Timer3overflow ?
                      or, IF2.Bit6 would be PowerButton ?
  04h       1       Unknown (bit0 toggled)
Unknown purpose.

Device 40h (Whatever) (and New3DS QTM)
Trying to read I2C for this device just returns FFh? Maybe exists in debug version only. The firmware doesn't use this register (it does only contain the device number in the device table).
Caution: New3DS does use device number 40h for the QTM IO Expander, this device will be visible in DSi mode (and shouldn't be mistaken for whatever DSi device 40h was originally used for).

DSi I2C Devices
  Device  Delay      Description
  7Ah     0       0  Camera0(internal)  ;Aptina MT9V113 (SelfPortrait)
  78h     0       1  Camera1(external)  ;Aptina MT9V113 (External)
  A0h     0       2  Camera0 config (Ext) ;\maybe for other manufacturer?
  E0h     0       3  Camera1 config (Self);/
  4Ah     180h    4  BPTWL Chip (LED/Volume/Powerbutton/Reset)
  40h     0       5  Debug?
  90h     0       6  Debug?
Delay: required swiWaitByLoop delay

DSi Secondary I2C Devices
There are also some internal/secondary I2C busses (not connected to the ARM CPUs).
  82h   Power Managment Device                       (connected to BPTWL chip)
  50h   I2C bus potentiometer (volume D/A converter) (connected to BPTWL chip)
  30h   I2C bus unknown write-only, DSiXL omly ?     (connected to BPUTL chip)
  A0h   I2C bus EEPROM                        (connected to Atheros wifi chip)
  -     I2C voltage translator                (between ARM CPU and BPTWL chip)


DSi I2C I/O Ports

4004500h - DSi7 - I2C_DATA (R/W)
  0-7  Data (or Device, or Register)
When sending data, I2C_DATA should be written <before> setting I2C_CNT.bit7.
When reading data, I2C_DATA should be read <after> I2C_CNT.bit7 goes off.
Alongsides with the 8bit data, an additional 1bit "Ack" flag is transferred as response to the data (ie. in opposite direction of data direction), the Ack is located in I2C_CNT.Bit4, and it's usually indicating errors (or in some cases it appears to be also used to indicate that no further data is to be transferred).

4004501h - DSi7 - I2C_CNT (R/W)
  0    Stop     (0=No, 1=Stop signal, after last byte)
  1    Start    (0=No, 1=Start signal, before first byte)
  2    Error    (0=No, 1=Pause/Flush? after Error, used with/after Stop)
                (1=Transfer only selected Start/Stop signal(s), without data?)
                (Nintendo seems to use bit2+bit0 to (try to) overcome problems
                with the BPTWL chip's quirky Stop handling)
  3    Unknown/unused (0)
  4    Ack (0=High=Error/LastRead, 1=Low=Okay) ;For DataRead:W, for DataWrite:R
  5    Data Direction   (0=Write, 1=Read) (note: Ack uses opposite direction)
  6    Interrupt Enable (0=Disable, 1=Enable)
  7    Start/busy       (0=Ready, 1=Start/busy)

I2C Transfer Flowchart
The first byte (with the "Start" condition) contains the device number, which consists of a 7bit chip ID and a direction flag in bit0 (0=Write or 1=Read). The direction flag applies to all following bytes (until last byte with "Stop" condition), that rule means that "Write Index & Write Data" can be done in a single step, whilst "Write Index & Read Data" must be split into two separate steps (each with own "Start/Stop" conditions):
 For Writing:
  Write Device+0 (with Start condition)                 ;\
  Write Index byte(s)                                   ; write index + data
  Write Data byte(s) (last byte with Stop condition)    ;/
 For Reading:
  Write Device+0 (with Start condition)                 ;\1st step: write index
  Write Index byte(s)                                   ;/
  Write Device+1 (with Start condition)                 ;\2nd step: read data
  Read Data byte(s) (last byte with ACK=0 and Stop)     ;/
The index is usually a single byte (except for Aptina cameras, which do use 16bit indices transferred in two bytes; ordered MSB, LSB).
Per-byte transfer completion is indicated by the Start/busy flag, which should also indicate if the I2C chip is ready for next byte (I2C devices can hold the clock line low if they aren't ready), however, the BPTWL chip somehow doesn't support that, and it should be accessed with an extra delay:
  Invoke byte-transfer
  Do WaitByLoop (needed for the BPTWL device only)
  Wait for start/busy flag to get zero
Note: The DSi firmware is doing eight retries per I2C command (in case of receiving wrong ACK bytes), unknown if that's really required, a stable system should never need to do retries.


DSi I2C Signals

Below is some pseudo code for the I2C signal transmission. The DSi hardware is doing most of that stuff automatically. The pseudo code may be useful for understanding the purpose of the start/stop/ack flags in the control register.

       START D7  D6  D5  D4  D3  D2  D1  D0 ACK  D7  D6/ .. /D1  D0 ACK STOP
      __    ___ ___ ___ ___ ___ ___ ___ ___     ___ __/    /___ ___        ___
  SDA   |__|___|___|___|___|___|___|___|___|___|___|_/ .. /|___|___|______|
      ____   _   _   _   _   _   _   _   _   _   _  /    /   _   _   _   _____
  SCL     |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |/ .. / |_| |_| |_| |_|
                                                 /    /
       <--><------------------------------><--><--------------------><--><-->
       Start    Device/Direction Byte      Ack   Index/Data Byte(s)  Ack Stop

SDA should be changed at/after falling SCL edge (except for Start/Stop conditions, which are output during SCL=High).
The Device/Direction Byte is sent by master (the byte contains a 7bit device address in bit7-1, and a direction flag in bit0). The direction of the follwing index/data byte(s) depends on that direction flag (0=Write, 1=Read). The ACK bit responses are sent in opposite direction as the preceeding byte.
The SCL line is driven by master, however, when the master changes SCL from Low to HighZ, then the slave may keep SCL held Low to signalize that it isn't yet ready for the next bit.

i2c_write_byte(send_start,send_stop,databyte):
  if (send_start) then i2c_start_cond()                     ;-start (if so)
  for i=7 downto 0, i2c_write_bit(databyte.bit(i)), next i  ;-write 8bit
  nack = i2c_read_bit()                                     ;-read nack
  if (send_stop) then i2c_stop_cond()                       ;-stop (if so)
  return nack        ;return 0 if ack by the slave.         ;-return nack

i2c_read_byte(send_stop):
  for i=7 downto 0, databyte.bit(i)=i2c_read_bit(), next i  ;-read 8bit
  i2c_write_bit(nack)                                       ;-write nack
  if (send_stop) then                                       ;\
    i2c_write_bit(1)    ;NACK (ack=high=Last byte)          ; nack (finish)
    i2c_stop_cond()     ;STOP                               ;/
  else                                                      ;\ack (want more)
    i2c_write_bit(0)    ;ACK (ack=low=More bytes)           ;/
  return databyte                                           ;-return databyte

i2c_write_bit(bit):
  if (bit) then SDA=HighZ else SDA=Low          ;-
  I2C_delay()                                   ;-
  SCL=HighZ
  wait until SCL=High (or timeout)              ;-wait (for clock stretching)
  if (bit=1 and SDA=Low) then arbitration_lost();-errif other HW pulls SDA=low
  I2C_delay()                                   ;-
  SCL=Low                                       ;-

i2c_read_bit():
  SDA=HighZ                                     ;-let the slave drive data
  I2C_delay()                                   ;-delay (one half clk)
  SCL=HighZ
  wait until SCL=High (or timeout)              ;-wait (for clock stretching)
  bit = SDA                     ;-
  I2C_delay()                   ;-delay (one half clk)
  SCL=Low                       ;-
  return bit                    ;-

i2c_start_cond():
  if (started) then            ;if started, do a restart cond
    SDA=HighZ                   ;-set SDA to 1
    I2C_delay()
    SCL=HighZ
    wait until SCL=High (or timeout)         ;-wait (for clock stretching)
    I2C_delay()         ;Repeated start setup time, minimum 4.7us
  if (SDA=Low) then arbitration_lost()
  SDA=Low                       ;-
  I2C_delay()
  SCL=Low
  started = true

i2c_stop_cond():
  SDA=Low                               ;-
  I2C_delay()                           ;-
  SCL=HighZ                             ;-
  wait until SCL=High (or timeout)      ;-wait (for clock stretching)
  I2C_delay()   ;Stop bit setup time, minimum 4us
  if (SDA=Low) then arbitration_lost()
  I2C_delay()
  started = false

I2C ACK/NACK Notes
There are five conditions that lead to the generation of a NACK:
  1. No receiver is present on the bus with the transmitted address so there
     is no device to respond with an acknowledge.
  2. The receiver is unable to receive or transmit because it is performing
     some real-time function and is not ready to start communication with the
     master.
  3. During the transfer, the receiver gets data or commands that it does not
     understand.
  4. During the transfer, the receiver cannot receive any more data bytes.
  5. A master-receiver must signal the end of the transfer to the slave
     transmitter.
Sending the I2C Stop condition is done by sending a "corrupted" databit (instead of sending the first databit of the next byte) on the SDA output pin.
However, in receive mode, SDA would be in input direction (for receiving the first databit of next byte). So the master simply cannot output the Stop condition in that state (unless when using the ACK bit to notify the slave that the transfer will be stopped now).


DSi I2C Device 4Ah (BPTWL chip)

I2C Bus Caution: The BPTWL chip requires swiWaitByLoop(180h) after each I2C byte transfer (if the Version/Speed byte at BPTWL[00h] indicates "Fast", then the delay can be reduced to 90h instead of 180h).
And, SPI bus Powerman chip does somehow interact with I2C BPTWL chip; there must be a similar delay between Powerman writes and BPTWL writes.

BPTWL Chip (LED/Volume/Powerbutton/Reset) (Device 4Ah)
  00h     R   Version/Speed (usually 33h) (00h..20h=Slow, 21h..FFh=Fast)
  01h     R   ?  Unknown, Powerman Status 1 (00h) ;some hw/sw type/version?
  02h     R   ?  Unknown, Powerman Status 2 (50h) ;30h=AlternateCamLedHardware?
  03h-0Fh -   Reserved (5Ah-filled)
  10h     R   Power Button Status (bit0=WasWhat?, bit1=IsDown, bit3=WasDown?)
                (bit0/3 are cleared after reading)
  11h     R/W System Reset (00h=No, 01h=Force Reset, 02h=Prevent Reset?)
  12h     R/W Power Button Tapping (00h=Auto-Reset, 01h=IRQ) (bit1=WL_RXPE??)
                bit0: Enable IRQs (for Power/Vol+/- button, battery low)
                bit1: battery boundaries (and 0=disable battery low IRQs)
                bit5: initially set (while bptwl chip is booting up?)
                bit7: Linear volume button mode
  13h-1Fh -   Reserved (5Ah-filled)
  20h     R   Battery State (bit0..3=Battery Level, bit7=Charge)
          W   On 3DS in DSi mode: Write 8=Shutdown, 4=Return to 3DS mode ?
  21h     R/W Powerman Sleep?, NDS Cartridge related? (07h=normal)
  22h-2Fh -   Reserved (5Ah-filled)
  30h     R/W Wifi LED (0/2=Off, 1=On, 3=BlinkOnTraffic) and bit4=SDIO enable
  31h     R/W Camera LED (00h=Off, 01h=On, 02h=Blink)
  32h-3Fh -   Reserved (5Ah-filled)
  40h     R/W Volume Level (00h..1Fh)             ;\nonvolatile!
  41h     R/W Backlight Level (00h..04h)          ;/
  42h-4Fh -   Reserved (5Ah-filled)
  50h     R/W     Unknown Value   (DSi-XL only) (output to I2C device 30h)
  51h     R/W     Unknown Trigger (DSi-XL only) (cleared when processed)
  50h-5Fh -   Reserved (5Ah-filled) (except 50h-51h on DSi XL)
  60h     R/W Battery Calibration Mode (bit0=1=Calibrate, Stop I2C, Purple LED)
  61h     R   Battery Calibration Flag (01h=Calibrated, E0h/E8h=NotCalibrated)
  62h     R   Battery Calibration Data (xxh=BatteryBias, 50h=NotCalibrated)
  63h     R/W Force Power LED (0=Automatic, 1=Red, 2=Blue, 3=Purple)
  64h-6Fh -   Reserved (5Ah-filled)
  70h     R/W Bootflag (00h=Coldboot, 01h=Warmboot/SkipHealthSafety)
  71h     R/W ?  Unknown (00h)          ;\more general-purpose bootflags?
  72h-76h R/W ?  Unknown (00h-filled)   ;/
  77h     ?/W Firmware Updater (write 4Ah, plus HEX file with delays) (danger!)
  78h-7Fh -   Reserved (5Ah-filled)
  80h     R/W Power Button Tap delay   (10h)  ;\can affect/disable
  81h     R/W Power Button Hold delay  (64h)  ;/Power Button Tapping
  82h-FFh -   Reserved (5Ah-filled)
The R/W values can be set to 00h..FFh (except Index 40h/41h are quickly cropped to max 1Fh/04h, and Index 70h/71h are (after some time) cropped to 01h/02h).
Above should probably also include:
  Forced volume (for alerts) (ie. alternately to current "user volume")

BPTWL Emulation on 3DS
The 3DS MCU emulates the BPTWL chip for DSi mode (and the emulated registers can be also accessed in 3DS mode). The emulation supports only a few of the original BPTWL registers & bits though:
  00h     R   Version/Speed (35h on New3DS)
  10h     R   Power Button Status (only 2 bits?: bit3=WasDown?, bit6=?)
  11h     R/W Reset (01h=Reset, other=ignored) (read: always 00h)
  12h     R/W Power Button Tapping (bit0,1,7=?)
  20h     R   Battery State
  31h     R/W Camera LED (bit0,1)
  40h     R/W Volume Level
  70h     R/W Bootflag
  Other   -   Unused (FFh)

DSi Power Button
Logically, the Power Button has two functions:
  Short tap --> reset (warmboot, go to DSi menu, without health and safety)
  Hold 1 second --> power-off
Technically, the button can have three functions:
  Auto-Reset (used for NDS games)
  IRQ (supposed to be used with Manual-Reset) (used for DSi games)
  Forced Power-off (for games which fail to handle the IRQ within 5 seconds)
DSi games should handle the IRQ as follows: First, do some clean up (like finishing writes to SD/MMC storage; to avoid FAT corruption). Then, issue a Reset manually (via I2C/BPTWL registers [70h]=01h/Warmboot, [11h]=01h/Reset).
Power-Off can be implemented via SPI/Power Managment Device, however, games only need to implement Manual-Reset or Auto-Reset, but don't need to implement Power-Off (the firmware will do that automatically if the button is held down for 1 second after issuing the Reset).
Ideally, emulators should also reproduce the power button (when resetting or closing the emulator): Signalize power-button and keep the emulation running until the game responds by Reset (or until five second timeout). That will allow the game to finish writes to emulated SD/MMC storage.

DSi Autostart on Warmboot (20h-byte area) (also requires BPTWL[70h]=01h)
The DSi can be commanded to load a different title (eg. System Settings), instead of showing the Boot Menu after warmboot.
DSi Autoload on Warmboot

Older blurb...
  0x10    1       Power flags. When bit0 is set, arm7 does a system reset.
                    When bit1 or bit3 are set, arm7 does a shutdown. Bits 0-2
                    are used for DSi IRQ6 IF flags (uh, rather IF2 maybe?).
  0x20    1       Battery flags. When zero the battery is at critical level,
                    arm7 does a shutdown. Bit7 is set when the battery is
                    charging. Battery levels in the low 4-bits: battery icon
                    bars full 0xF, 3 bars 0xB, 2 bars 0x7, one solid red bar
                    0x3, and one blinking red bar 0x1. When plugging in or
                    removing recharge cord, this value increases/decreases
                    between the real battery level and 0xF, thus the battery
                    level while bit7 is set is useless.

BPTWL/BPUTL Chip Names
  DSi:      Renesas Electronics "BPTWL, KG07K"           ;reg[00h]=33h
  DSiXL:    Renesas Electronics "BP UTL-1, KG08"         ;reg[00h]=BBh or B7h
  3DS:      Renesas Electronics "UC CTR, 041KM73, KG10"  ;reg[00h]=?
  New3DSXL: Renesas Electronics "UC KTR, 423KM01, 'TK14" ;reg[00h]=35h

Inner workings
The DSi's BPTWL chip contains a 78K/0 microprocessor. The BPTWL firmware has aparently leaked in a "TWL_MCU_33-MP_95811supp.hex" file. There is also a "UTL_MCU_BA.hex" file (for DSi XL?).
78K/0 Opcode List
78K/0 Opcode Map
78K/0 Memory Map and SFRs
Programming via external serial cable is about same as on 3DS:
3DS I2C MCU - RL78 Flash Programming via UART
The 3DS' MCU emulates the BPTWL functions by using a 78K0R/ microprocessor (with similar asm syntax, but completely different opcode numbering, with more 16bit ALU opcodes, new conditional-skip opcodes, and 20bit addressing).


78K/0 Opcode List

Move Byte
  85/87/AB/AA/AE              MOV  A, [DE]/[HL]/[HL+B]/[HL+C]/[HL+nn]
  F0/F4/8E                    MOV  A, [FExx]/[FFxx]/[nnnn]
  60/--/62/63/64/65/66/67     MOV  A, X/-/C/B/E/D/L/H
  70/--/72/73/74/75/76/77     MOV  X/-/C/B/E/D/L/H, A
  A0/A1/A2/A3/A4/A5/A6/A7     MOV  X/A/C/B/E/D/L/H, nn
  95/97/BB/BA/BE              MOV  [DE]/[HL]/[HL+B]/[HL+C]/[HL+nn], A
  F2/F6/9E                    MOV  [FExx]/[FFxx]/[nnnn], A
  11/13                       MOV  [FExx]/[FFxx], nn
  30/--/32/33/34/35/36/37     XCH  A, X/-/C/B/E/D/L/H
  05/07/318B/318A/DE          XCH  A, [DE]/[HL]/[HL+B]/[HL+C]/[HL+nn]
  83/93/CE                    XCH  A, [FExx]/[FFxx]/[nnnn]

Move Word
  C2/C4/C6/10                 MOVW AX, BC/DE/HL/nnnn
  89/A9/02                    MOVW AX, [FExx]/[FFxx]/[nnnn]
  D2/D4/D6                    MOVW BC/DE/HL, AX
  12/14/16                    MOVW BC/DE/HL, nnnn
  99/B9/03                    MOVW [FExx]/[FFxx]/[nnnn], AX
  EE/FE                       MOVW [FExx]/[FFxx], nnnn
  E2/E4/E6                    XCHW AX,BC/DE/HL
  B1/B3/B5/B7/22              PUSH AX/BC/DE/HL/PSW  ;PSW=[FF1Eh] (8bit)
  B0/B2/B4/B6/23              POP  AX/BC/DE/HL/PSW  ;PSW=[FF1Eh] (8bit)

ALU Byte
  6100/6101/6102/6103/6104/6105/6106/6107  ADD  X/A/C/B/E/D/L/H, A
  6120/6121/6122/6123/6124/6125/6126/6127  ADDC X/A/C/B/E/D/L/H, A
  6110/6111/6112/6113/6114/6115/6116/6117  SUB  X/A/C/B/E/D/L/H, A
  6130/6131/6132/6133/6134/6135/6136/6137  SUBC X/A/C/B/E/D/L/H, A
  6140/6141/6142/6143/6144/6145/6146/6147  CMP  X/A/C/B/E/D/L/H, A
  6150/6151/6152/6153/6154/6155/6156/6157  AND  X/A/C/B/E/D/L/H, A
  6160/6161/6162/6163/6164/6165/6166/6167  OR   X/A/C/B/E/D/L/H, A
  6170/6171/6172/6173/6174/6175/6176/6177  XOR  X/A/C/B/E/D/L/H, A
  6108/----/610A/610B/610C/610D/610E/610F  ADD  A, X/-/C/B/E/D/L/H
  6128/----/612A/612B/612C/612D/612E/612F  ADDC A, X/-/C/B/E/D/L/H
  6118/----/611A/611B/611C/611D/611E/611F  SUB  A, X/-/C/B/E/D/L/H
  6138/----/613A/613B/613C/613D/613E/613F  SUBC A, X/-/C/B/E/D/L/H
  6148/----/614A/614B/614C/614D/614E/614F  CMP  A, X/-/C/B/E/D/L/H
  6158/----/615A/615B/615C/615D/615E/615F  AND  A, X/-/C/B/E/D/L/H
  6168/----/616A/616B/616C/616D/616E/616F  OR   A, X/-/C/B/E/D/L/H
  6178/----/617A/617B/617C/617D/617E/617F  XOR  A, X/-/C/B/E/D/L/H
  0D/0F/310B/310A/09/0E/08   ADD  A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  2D/2F/312B/312A/29/2E/28   ADDC A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  1D/1F/311B/311A/19/1E/18   SUB  A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  3D/3F/313B/313A/39/3E/38   SUBC A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  4D/4F/314B/314A/49/4E/48   CMP  A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  5D/5F/315B/315A/59/5E/58   AND  A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  6D/6F/316B/316A/69/6E/68   OR   A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  7D/7F/317B/317A/79/7E/78   XOR  A,nn/[HL]/[HL+B]/[HL+C]/[HL+nn]/[FExx]/[nnnn]
  88                         ADD  [FExx], nn
  A8                         ADDC [FExx], nn
  98                         SUB  [FExx], nn
  B8                         SUBC [FExx], nn
  C8                         CMP  [FExx], nn
  D8                         AND  [FExx], nn
  E8                         OR   [FExx], nn
  F8                         XOR  [FExx], nn
  40/41/42/43/44/45/46/47/81 INC  X/A/C/B/E/D/L/H/[FExx]
  50/51/52/53/54/55/56/57/91 DEC  X/A/C/B/E/D/L/H/[FExx]

ALU Word
  CA/DA/EA                   ADDW/SUBW/CMPW AX,nnnn
  80/82/84/86                INCW AX/BC/DE/HL
  90/92/94/96                DECW AX/BC/DE/HL

Rotate/Shift
  26                         ROL  A,1
  24                         ROR  A,1
  27                         ROLC A,1
  25                         RORC A,1
  3180                       ROL4 A,[HL] ;12bit A.lsb:[HL],4 ;native: ROL4 [HL]
  3190                       ROR4 A,[HL] ;12bit A.lsb:[HL],4 ;native: ROR4 [HL]

Jump/Call
  3198                       JMP  AX                    ;native: BR AX
  9B                         JMP  absolute addr         ;native: BR
  FA                         JMP  relative short addr   ;native: BR
  9A                         CALL absolute addr         ;native: CALL
  C1+(nn AND 3Eh)            CALL [40h..7Eh]            ;native: CALLT
  0C/1C/2C/3C/4C/5C/6C/7C    CALLF 08nn/09nn/0Ann/0Bnn/0Cnn/0Dnn/0Enn/0Fnn

Conditional Relative Jumps
  8D                         JC  aka JB  rel  ;carry/below        ;native: BC
  AD                         JZ  aka JE  rel  ;zero/equal         ;native: BZ
  9D                         JNC aka JAE rel  ;not carry/below    ;native: BNC
  BD                         JNZ aka JNE rel  ;not zero/equal     ;native: BNZ
  04/8B/8A                   DJNZ [FExx]/B/C, rel  ;decrement+jnz ;native: DBNZ

Test (and Clear) and Conditional Relative Jump
  3101/3105/3185/310D+n*10   BTCLR [FExx]/[FFxx]/[HL]/A.n, rel
  8C/3106/3186/310E+n*10     BT    [FExx]/[FFxx]/[HL]/A.n, rel
  3103/3107/3187/310F+n*10   BF    [FExx]/[FFxx]/[HL]/A.n, rel

Bit Manipulation
  7101/7109/7181/6189+n*10   MOV1 [FExx]/[FFxx]/[HL]/A.n, CY
  7104/710C/7184/618C+n*10   MOV1 CY, [FExx]/[FFxx]/[HL]/A.n
  7105/710D/7185/618D+n*10   AND1 CY, [FExx]/[FFxx]/[HL]/A.n
  7106/710E/7186/618E+n*10   OR1  CY, [FExx]/[FFxx]/[HL]/A.n
  7107/710F/7187/618F+n*10   XOR1 CY, [FExx]/[FFxx]/[HL]/A.n
  20/0A/710A/7182/618A+n*10  SET1 CY/[FExx]/[FFxx]/[HL]/A.n
  21/0B/710B/7183/618B+n*10  CLR1 CY/[FExx]/[FFxx]/[HL]/A.n
  01                         NOT1 CY

Misc
  00                         NOP
  BF/7110/7100               BRK/HALT/STOP
  AF/9F/8F                   RET/RETB/RETI
  61D0/61D8/61F0/61F8        SEL RB0/1/2/3
  3188                       MULU AX,A,X   ;unsigned AX=A*X    ;native: MULU X
  3182                       DIVUW AX,C    ;unsigned AX=AX/C, C=remainder   ;X
  6180/6190                  ADJBA/ADJBS   ;decimal BCD adjust A after Add/Sub
  7A1E/7B1E                  EI/DI         ;pseudo SET1/CLR1 PSW.7
  FA                         JR addr       ;pseudo jmp short relative addr

Note
Operand [FExx] can he in range FE20h..FF1Fh, of which FE20h..FEFFh is encoded as 20..FF, and FF00h..FF1Fh is encoded as 00..1F (the latter overlaps with operand [FFxx]) (for the overlapping addresses, [FExx] is preferred because BT/SET1/CLR1 have smaller encoding for [FExx] than [FFxx], and DJNZ/ALU support only [FExx]) (all opcodes that support [FFxx] do also support [FExx], so [FFxx] should be NEVER used for [FF00..FF1F]).


78K/0 Opcode Map

78K/0 Primary Opcode Map
      00                10                20                30
  00  NOP               MOVW AX,nnnn      SET1 CY           XCH  A,X
  01  NOT1 CY           MOV  [FExx],nn    CLR1 CY           <prefix>
  02  MOVW AX,[nnnn]    MOVW BC,nnnn      PUSH PSW ;[FF1Eh] XCH  A,C
  03  MOVW [nnnn],AX    MOV  [FFxx],nn    POP  PSW ;[FF1Eh] XCH  A,B
  04  DBNZ [FExx],rel   MOVW DE,nnnn      ROR  A,1          XCH  A,E
  05  XCH  A,[DE]       <undef>           RORC A,1          XCH  A,D
  06  <undef>           MOVW HL,nnnn      ROL  A,1          XCH  A,L
  07  XCH  A,[HL]       <undef>           ROLC A,1          XCH  A,H
  08  ADD  A,[nnnn]     SUB  A,[nnnn]     ADDC A,[nnnn]     SUBC A,[nnnn]
  09  ADD  A,[HL+nn]    SUB  A,[HL+nn]    ADDC A,[HL+nn]    SUBC A,[HL+nn]
  0A  SET1 [FExx].0     SET1 [FExx].1     SET1 [FExx].2     SET1 [FExx].3
  0B  CLR1 [FExx].0     CLR1 [FExx].1     CLR1 [FExx].2     CLR1 [FExx].3
  0C  CALLF 08nn        CALLF 09nn        CALLF 0Ann        CALLF 0Bnn
  0D  ADD  A,nn         SUB  A,nn         ADDC A,nn         SUBC A,nn
  0E  ADD  A,[FExx]     SUB  A,[FExx]     ADDC A,[FExx]     SUBC A,[FExx]
  0F  ADD  A,[HL]       SUB  A,[HL]       ADDC A,[HL]       SUBC A,[HL]

      40                50                60                70
  40  INC  X            DEC  X            MOV  A,X          MOV  X,A
  41  INC  A            DEC  A            <prefix>          <prefix>
  42  INC  C            DEC  C            MOV  A,C          MOV  C,A
  43  INC  B            DEC  B            MOV  A,B          MOV  B,A
  44  INC  E            DEC  E            MOV  A,E          MOV  E,A
  45  INC  D            DEC  D            MOV  A,D          MOV  D,A
  46  INC  L            DEC  L            MOV  A,L          MOV  L,A
  47  INC  H            DEC  H            MOV  A,H          MOV  H,A
  48  CMP  A,[nnnn]     AND  A,[nnnn]     OR   A,[nnnn]     XOR  A,[nnnn]
  49  CMP  A,[HL+nn]    AND  A,[HL+nn]    OR   A,[HL+nn]    XOR  A,[HL+nn]
  4A  SET1 [FExx].4     SET1 [FExx].5     SET1 [FExx].6     SET1 [FExx].7
  4B  CLR1 [FExx].4     CLR1 [FExx].5     CLR1 [FExx].6     CLR1 [FExx].7
  4C  CALLF 0Cnn        CALLF 0Dnn        CALLF 0Enn        CALLF 0Fnn
  4D  CMP  A,nn         AND  A,nn         OR   A,nn         XOR  A,nn
  4E  CMP  A,[FExx]     AND  A,[FExx]     OR   A,[FExx]     XOR  A,[FExx]
  4F  CMP  A,[HL]       AND  A,[HL]       OR   A,[HL]       XOR  A,[HL]

      80                90                A0                B0
  80  INCW AX           DECW AX           MOV  X,nn         POP  AX
  81  INC  [FExx]       DEC  [FExx]       MOV  A,nn         PUSH AX
  82  INCW BC           DECW BC           MOV  C,nn         POP  BC
  83  XCH  A,[FExx]     XCH  A,[FFxx]     MOV  B,nn         PUSH BC
  84  INCW DE           DECW DE           MOV  E,nn         POP  DE
  85  MOV  A,[DE]       MOV  [DE],A       MOV  D,nn         PUSH DE
  86  INCW HL           DECW HL           MOV  L,nn         POP  HL
  87  MOV  A,[HL]       MOV  [HL],A       MOV  H,nn         PUSH HL
  88  ADD  [FExx],nn    SUB  [FExx],nn    ADDC [FExx],nn    SUBC [FExx],nn
  89  MOVW AX,[FExx]    MOVW [FExx],AX    MOVW AX,[FFxx]    MOVW [FFxx],AX
  8A  DBNZ C,rel        CALL nnnn         MOV  A,[HL+C]     MOV  [HL+C],A
  8B  DBNZ B,rel        BR   nnnn         MOV  A,[HL+B]     MOV  [HL+B],A
  8C  BT   [FExx].0,rel BT   [FExx].1,rel BT   [FExx].2,rel BT   [FExx].3,rel
  8D  BC   rel          BNC  rel          BZ   rel          BNZ  rel
  8E  MOV  A,[nnnn]     MOV  [nnnn],A     MOV  A,[HL+nn]    MOV  [HL+nn],A
  8F  RETI              RETB              RET               BRK

      C0                D0                E0                F0
  C0  <undef>           <undef>           <undef>           MOV  A,[FExx]
  C1  CALLT [40]        CALLT [50]        CALLT [60]        CALLT [70]
  C2  MOVW AX,BC        MOVW BC,AX        XCHW AX,BC        MOV  [FExx],A
  C3  CALLT [42]        CALLT [52]        CALLT [62]        CALLT [72]
  C4  MOVW AX,DE        MOVW DE,AX        XCHW AX,DE        MOV  A,[FFxx]
  C5  CALLT [44]        CALLT [54]        CALLT [64]        CALLT [74]
  C6  MOVW AX,HL        MOVW HL,AX        XCHW AX,HL        MOV  [FFxx],A
  C7  CALLT [46]        CALLT [56]        CALLT [66]        CALLT [76]
  C8  CMP  [FExx],nn    AND  [FExx],nn    OR   [FExx],nn    XOR  [FExx],nn
  C9  CALLT [48]        CALLT [58]        CALLT [68]        CALLT [78]
  CA  ADDW AX,nnnn      SUBW AX,nnnn      CMPW AX,nnnn      BR   rel
  CB  CALLT [4A]        CALLT [5A]        CALLT [6A]        CALLT [7A]
  CC  BT   [FExx].4,rel BT   [FExx].5,rel BT   [FExx].6,rel BT   [FExx].7,rel
  CD  CALLT [4C]        CALLT [5C]        CALLT [6C]        CALLT [7C]
  CE  XCH  A,[nnnn]     XCH  A,[HL+nn]    MOVW [FExx],nnnn  MOVW [FFxx],nnnn
  CF  CALLT [4E]        CALLT [5E]        CALLT [6E]        CALLT [7E]

78K/0 Opcodes with Prefix 31
  3100+xxx*10  -
  3180+xxx*10  - (unless below ROL/ROR)
  3101+bbb*10  BTCLR   [FExx].n,rel    ;n=0..7
  3181+xxx*10  -
  3102+xxx*10  -
  3182+xxx*10  - (unless below DIV)
  3103+bbb*10  BF      [FExx].n,rel    ;n=0..7
  3183+xxx*10  -
  3104+xxx*10  -
  3184+xxx*10  -
  3105+bbb*10  BTCLR   [FFxx].n,rel    ;n=0..7
  3185+bbb*10  BTCLR   [HL].n,rel      ;n=0..7
  3106+bbb*10  BT      [FFxx].n,rel    ;n=0..7
  3186+bbb*10  BT      [HL].n,rel      ;n=0..7
  3107+bbb*10  BF      [FFxx].n,rel    ;n=0..7
  3187+bbb*10  BF      [HL].n,rel      ;n=0..7
  3108+xxx*10  -
  3188+xxx*10  - (unless below MUL/BR)
  3109+xxx*10  -
  3189+xxx*10  -
  310A+xxx*10  <see below ADD/SUB/ADDC/SUBC/CMP/AND/OR/XOR)
  318A+xxx*10  - (unless below XCH)
  310B+xxx*10  <see below ADD/SUB/ADDC/SUBC/CMP/AND/OR/XOR)
  318B+xxx*10  - (unless below XCH)
  310C+xxx*10  -
  318C+xxx*10  -
  310D+bbb*10  BTCLR   A.n,rel         ;n=0..7
  318D+xxx*10  -
  310E+bbb*10  BT      A.n,rel         ;n=0..7
  318E+xxx*10  -
  310F+bbb*10  BF      A.n,rel         ;n=0..7
  318F+xxx*10  -
  310A         ADD     A,[HL+C]
  310B         ADD     A,[HL+B]
  311A         SUB     A,[HL+C]
  311B         SUB     A,[HL+B]
  312A         ADDC    A,[HL+C]
  312B         ADDC    A,[HL+B]
  313A         SUBC    A,[HL+C]
  313B         SUBC    A,[HL+B]
  314A         CMP     A,[HL+C]
  314B         CMP     A,[HL+B]
  315A         AND     A,[HL+C]
  315B         AND     A,[HL+B]
  316A         OR      A,[HL+C]
  316B         OR      A,[HL+B]
  317A         XOR     A,[HL+C]
  317B         XOR     A,[HL+B]
  318A         XCH     A,[HL+C]
  318B         XCH     A,[HL+B]
  3180         ROL4    A,[HL]   ;rol 12bit A.lsb:[HL],4      ;native: ROL4 [HL]
  3190         ROR4    A,[HL]   ;ror 12bit A.lsb:[HL],4      ;native: ROR4 [HL]
  3182         DIVUW   AX,C     ;unsigned AX=AX/C, C=remainder ;native: DIVWU C
  3188         MULU    AX,A,X   ;unsigned AX=A*X               ;native: MULU X
  3198         BR      AX

78K/0 Opcodes with Prefix 61
  6100+rrr     ADD     r,A            ;r=X,A,C,B,E,D,L,H
  6108+rrr     ADD     A,r            ;r=X,-,C,B,E,D,L,H
  6110+rrr     SUB     r,A            ;r=X,A,C,B,E,D,L,H
  6118+rrr     SUB     A,r            ;r=X,-,C,B,E,D,L,H
  6120+rrr     ADDC    r,A            ;r=X,A,C,B,E,D,L,H
  6128+rrr     ADDC    A,r            ;r=X,-,C,B,E,D,L,H
  6130+rrr     SUBC    r,A            ;r=X,A,C,B,E,D,L,H
  6138+rrr     SUBC    A,r            ;r=X,-,C,B,E,D,L,H
  6140+rrr     CMP     r,A            ;r=X,A,C,B,E,D,L,H
  6148+rrr     CMP     A,r            ;r=X,-,C,B,E,D,L,H
  6150+rrr     AND     r,A            ;r=X,A,C,B,E,D,L,H
  6158+rrr     AND     A,r            ;r=X,-,C,B,E,D,L,H
  6160+rrr     OR      r,A            ;r=X,A,C,B,E,D,L,H
  6168+rrr     OR      A,r            ;r=X,-,C,B,E,D,L,H
  6170+rrr     XOR     r,A            ;r=X,A,C,B,E,D,L,H
  6178+rrr     XOR     A,r            ;r=X,-,C,B,E,D,L,H
  6180+xxx*10  - (unless below ADJ/SEL)
  6181+xxx*10  -
  6182+xxx*10  -
  6183+xxx*10  -
  6184+xxx*10  -
  6185+xxx*10  -
  6186+xxx*10  -
  6187+xxx*10  -
  6188+xxx*10  - (unless below ADJ/SEL)
  6189+bbb*10  MOV1    A.n,CY         ;n=0..7
  618A+bbb*10  SET1    A.n            ;n=0..7
  618B+bbb*10  CLR1    A.n            ;n=0..7
  618C+bbb*10  MOV1    CY,A.n         ;n=0..7
  618D+bbb*10  AND1    CY,A.n         ;n=0..7
  618E+bbb*10  OR1     CY,A.n         ;n=0..7
  618F+bbb*10  XOR1    CY,A.n         ;n=0..7
  6180         ADJBA                ;Decimal BCD adjust A after Addition
  6190         ADJBS                ;Decimal BCD adjust A after Subtraction
  61D0         SEL     RB0
  61D8         SEL     RB1
  61F0         SEL     RB2
  61F8         SEL     RB3

78K/0 Opcodes with Prefix 71
  7100+xxx*10  - (unless below STOP/HALT)
  7180+xxx*10  -
  7101+bbb*10  MOV1    [FExx].n,CY    ;n=0..7
  7181+bbb*10  MOV1    [HL].n,CY      ;n=0..7
  7102+xxx*10  -
  7182+bbb*10  SET1    [HL].n         ;n=0..7
  7103+xxx*10  -
  7183+bbb*10  CLR1    [HL].n         ;n=0..7
  7104+bbb*10  MOV1    CY,[FExx].n    ;n=0..7
  7184+bbb*10  MOV1    CY,[HL].n      ;n=0..7
  7105+bbb*10  AND1    CY,[FExx].n    ;n=0..7
  7185+bbb*10  AND1    CY,[HL].n      ;n=0..7
  7106+bbb*10  OR1     CY,[FExx].n    ;n=0..7
  7186+bbb*10  OR1     CY,[HL].n      ;n=0..7
  7107+bbb*10  XOR1    CY,[FExx].n    ;n=0..7
  7187+bbb*10  XOR1    CY,[HL].n      ;n=0..7
  7108+xxx*10  -
  7188+xxx*10  -
  7109+bbb*10  MOV1    [FFxx].n,CY    ;n=0..7
  7189+xxx*10  -
  710A+bbb*10  SET1    [FFxx].n       ;n=0..7
  718A+xxx*10  -
  710B+bbb*10  CLR1    [FFxx].n       ;n=0..7
  718B+xxx*10  -
  710C+bbb*10  MOV1    CY,[FFxx].n    ;n=0..7
  718C+xxx*10  -
  710D+bbb*10  AND1    CY,[FFxx].n    ;n=0..7
  718D+xxx*10  -
  710E+bbb*10  OR1     CY,[FFxx].n    ;n=0..7
  718E+xxx*10  -
  710F+bbb*10  XOR1    CY,[FFxx].n    ;n=0..7
  718F+xxx*10  -
  7100         STOP
  7110         HALT


78K/0 Memory Map and SFRs

78K0 References
  78K0/Kx2 User's Manual: Hardware       ;info on I/O Ports
  78K0/Kx2 Flash Memory Self Programming ;info on 8100h function
  78K0/Kx2 Flash Memory Programming      ;info on UART/SPI cable
  78K/0 Series Instructions              ;info on opcodes
  78K0/KB2 One-sheet Manual              ;quick reference poster

78K/0 Memory Map
  0000h..003Fh  FLASH ROM Exception Vectors (16bit each)
  0040h..007Fh  FLASH ROM CALLT Vectors (16bit each)
  0080h..0084h  FLASH ROM Option Byte Area (5 bytes)
  0085h..008Eh  FLASH ROM Debug Security Area (10 bytes, if any)
  008Fh..07FFh  FLASH ROM
  0800h..0FFFh  FLASH ROM (accessible via CALLF opcodes)
  1000h..1FFFh  FLASH ROM (can be swapped with 0000h..0FFFh)
  2000h..xFFFh  FLASH ROM (if any, in larger chips)
  8000h..BFFFh  FLASH ROM (if any, in larger chips) (bank-switched via BANK)
  8000h..9FFFh  System ROM area (when mapped, with function handler at 8100h)
  A000h..BFFFh  System ROM mirror (same as 8000h..9FFFh)
  C000h..       System ROM empty           (mostly FFh-filled, some FEh-bytes)
  E000h..F7FFh  Extra RAM (max 6K, if any) (mostly FFh-filled, some F0h-bytes)
  F800h..F8FFh  Undoc SFR's
  F900h..FAFFh  Zerofilled
  FB00h..FBFFh  Unknown (filled with random values) (more RAM?) (unused in DSi)
                (FB00h is ONLY mapped when ROM enabled, otherwise FFh-filled)
  FC00h..FF1Fh  RAM (officially/used area)
  FE20h..FEDFh  RAM (accessible via short "saddr" opcodes)
  FEE0h..FEE7h  Register Bank 3 (X,A,C,B,E,D,L,H aka AX,BC,DE,HL)
  FEE8h..FEEFh  Register Bank 2 (X,A,C,B,E,D,L,H aka AX,BC,DE,HL)
  FEF0h..FEF7h  Register Bank 1 (X,A,C,B,E,D,L,H aka AX,BC,DE,HL)
  FEF8h..FEFFh  Register Bank 0 (X,A,C,B,E,D,L,H aka AX,BC,DE,HL)
  FF00h..FFFFh  Special Function Registers (SFR's)
FLASH banks are 1Kbyte tall (aka erase block size?).

78K/0 Vectors
  0000h RESET input, POC, LVI, WDT
  0002h -
  0004h INTLVI
  0006h INTP0
  0008h INTP1
  000Ah INTP2
  000Ch INTP3
  000Eh INTP4
  0010h INTP5
  0012h INTSRE6
  0014h INTSR6
  0016h INTST6
  0018h INTCSI10/INTST0
  001Ah INTTMH1
  001Ch INTTMH0
  001Eh INTTM50
  0020h INTTM000
  0022h INTTM010
  0024h INTAD
  0026h INTSR0
  0028h INTWTI
  002Ah INTTM51
  002Ch INTKR
  002Eh INTWT
  0030h INTP6
  0032h INTP7
  0034h INTIIC0/NTDMU
  0036h INTCSI11
  0038h INTTM001
  003Ah INTTM011
  003Ch INTACSI
  003Eh BRK

78K/0 Option Bytes / Debug Security
  0080h db   07Eh   ;Option Byte: Watchdog Mode
  0081h db   000h   ;Option Byte: POC Mode (0=1.59V, 1=2.7V)
  0082h db   000h   ;Option Byte: Reserved (00h)
  0083h db   000h   ;Option Byte: Reserved (00h)
  0084h db   000h   ;Option Byte: On-chip Debug Control (0=Off)
       ;---
  0085h db   0CCh   ;On-chip debug security ID (0Ah bytes) ...
  0086h db   023h
  0087h db   0BAh
  0088h db   0C3h
  0089h db   07Dh
  008Ah db   094h
  008Bh db   0FEh
  008Ch db   073h
  008Dh db   0A5h
  008Eh db   0E6h

78K/0 Program Status Word (PSW) aka [FF1Eh]
  7  IE     ;Interrupt Enable
  6  Z      ;Zero Flag
  5  RBS1   ;Register Bank Select bit1
  4  AC     ;Aux Carry Flag
  3  RBS0   ;Register Bank Select bit0
  2  0
  1  ISP    ;In-Service Priority Flag
  0  CY     ;Carry Flag

78K/0 Special Function Registers (SFR's)
  Addr  Symbol R/W 1BW Reset BCDEF Special Function Register (SFR)
  FF00h P0     R/W 1B- 00h   BCDEF Port 0
  FF01h P1     R/W 1B- 00h   BCDEF Port 1
  FF02h P2     R/W 1B- 00h   BCDEF Port 2
  FF03h P3     R/W 1B- 00h   BCDEF Port 3
  FF04h P4     R/W 1B- 00h   -CDEF Port 4
  FF05h P5     R/W 1B- 00h   ---EF Port 5
  FF06h P6     R/W 1B- 00h   BCDEF Port 6
  FF07h P7     R/W 1B- 00h   -CDEF Port 7
  FF08h ADCR   R   --W 0000h BCDEF 10-bit A/D conversion result
  FF09h ADCRH  R   -B- 00h   BCDEF 8-bit A/D conversion result
  FF0Ah RXB6   R   -B- FFh   BCDEF Receive buffer 6
  FF0Bh TXB6   R/W -B- FFh   BCDEF Transmit buffer 6
  FF0Ch P12    R/W 1B- 00h   BCDEF Port 12
  FF0Dh P13    R/W 1B- 00h   -cDEF Port 13 (KC2: 48pin only)
  FF0Eh P14    R/W 1B- 00h   -cDEF Port 14 (KC2: 48pin only)
  FF0Fh SIO10  R   -B- 00h   BCDEF Serial I/O shift 10
  FF10h TM00   R   --W 0000h BCDEF 16-bit timer counter 00
  FF12h CR000  R/W --W 0000h BCDEF 16-bit timer capture/compare 000
  FF14h CR010  R/W --W 0000h BCDEF 16-bit timer capture/compare 010
  FF16h TM50   R   -B- 00h   BCDEF 8-bit timer counter 50
  FF17h CR50   R/W -B- 00h   BCDEF 8-bit timer compare 50
  FF18h CMP00  R/W -B- 00h   BCDEF 8-bit timer H compare 00
  FF19h CMP10  R/W -B- 00h   BCDEF 8-bit timer H compare 10
  FF1Ah CMP01  R/W -B- 00h   BCDEF 8-bit timer H compare 01
  FF1Bh CMP11  R/W -B- 00h   BCDEF 8-bit timer H compare 11
  FF1Ch SP     R/W --W xxxxh BCDEF CPU Stack Pointer      ;\undocumented, used
  FF1Eh PSW    R/W 1B- xxh   BCDEF CPU Program Status Word;/in pseudo opcodes
  FF1Fh TM51   R   -B- 00h   BCDEF 8-bit timer counter 51
  FF20h PM0    R/W 1B- FFh   BCDEF Port mode 0
  FF21h PM1    R/W 1B- FFh   BCDEF Port mode 1
  FF22h PM2    R/W 1B- FFh   BCDEF Port mode 2
  FF23h PM3    R/W 1B- FFh   BCDEF Port mode 3
  FF24h PM4    R/W 1B- FFh   -CDEF Port mode 4
  FF25h PM5    R/W 1B- FFh   ---EF Port mode 5
  FF26h PM6    R/W 1B- FFh   BCDEF Port mode 6
  FF27h PM7    R/W 1B- FFh   -CDEF Port mode 7
  FF28h ADM    R/W 1B- 00h   BCDEF A/D converter mode
  FF29h ADS    R/W 1B- 00h   BCDEF Analog input channel specification
  FF2Ch PM12   R/W 1B- FFh   BCDEF Port mode 12
  FF2Eh PM14   R/W 1B- FFh   -cDEF Port mode 14 (KC2: 48pin only)
  FF2Fh ADPC   R/W 1B- 00h   BCDEF A/D port configuration
  FF30h PU0    R/W 1B- 00h   BCDEF Pull-up resistor option 0
  FF31h PU1    R/W 1B- 00h   BCDEF Pull-up resistor option 1
  FF33h PU3    R/W 1B- 00h   BCDEF Pull-up resistor option 3
  FF34h PU4    R/W 1B- 00h   -CDEF Pull-up resistor option 4
  FF35h PU5    R/W 1B- 00h   ---EF Pull-up resistor option 5
  FF36h PU6    R/W 1B- 00h   ----F Pull-up resistor option 6
  FF37h PU7    R/W 1B- 00h   -CDEF Pull-up resistor option 7
  FF3Ch PU12   R/W 1B- 00h   BCDEF Pull-up resistor option 12
  FF3Eh PU14   R/W 1B- 00h   -cDEF Pull-up resistor option 14 (KC2: 48pin only)
  FF40h CKS    R/W 1B- 00h   -cDEF Clock output selection     (KC2: 48pin only)
  FF41h CR51   R/W -B- 00h   BCDEF 8-bit timer compare 51
  FF43h TMC51  R/W 1B- 00h   BCDEF 8-bit timer mode control 51
  FF48h EGP    R/W 1B- 00h   BCDEF External interrupt rising edge enable
  FF49h EGN    R/W 1B- 00h   BCDEF External interrupt falling edge enable
  FF4Ah SIO11  R   -B- 00h   ---eF Serial I/O shift 11 (KE2: 48KB only)
  FF4Ch SOTB11 R/W -B- 00h   ---eF Transmit buffer 11  (KE2: 48KB only)
  FF4Fh ISC    R/W 1B- 00h   BCDEF Input switch control
  FF50h ASIM6  R/W 1B- 01h   BCDEF Async serial interface operation mode 6
  FF53h ASIS6  R   -B- 00h   BCDEF Async serial interface reception err/stat 6
  FF55h ASIF6  R   -B- 00h   BCDEF Async serial interface transmission status 6
  FF56h CKSR6  R/W -B- 00h   BCDEF Clock selection 6
  FF57h BRGC6  R/W -B- FFh   BCDEF Baud rate generator control 6
  FF58h ASICL6 R/W 1B- 16h   BCDEF Async serial interface control 6
  FF60h SDR0   R   -BW 0000h -cdeF Remainder data 0 bit0..         ;\
  FF61h SDR0H  R   -B- 00h   -cdeF Remainder data 0 bit8..         ;
  FF62h MDA0L  R/W -BW 0000h -cdeF Multiply/divide data A0 bit0..  ; KC2-KE2:
  FF63h MDA0LH R/W -B- 00h   -cdeF Multiply/divide data A0 bit8..  ; 48KB only
  FF64h MDA0H  R/W -BW 0000h -cdeF Multiply/divide data A0 bit16.. ;
  FF65h MDA0HH R/W -B- 00h   -cdeF Multiply/divide data A0 bit24.. ;
  FF66h MDB0   R/W -BW 0000h -cdeF Multiply/divide data B0 bit0..  ;
  FF67h MDB0H  R/W -B- 00h   -cdeF Multiply/divide data B0 bit8..  ;
  FF68h DMUC0  R/W 1B- 00h   -cdeF Multiply/divide control 0       ;/
  FF69h TMHMD0 R/W 1B- 00h   BCDEF 8-bit timer H mode 0
  FF6Ah TCL50  R/W 1B- 00h   BCDEF Timer clock selection 50
  FF6Bh TMC50  R/W 1B- 00h   BCDEF 8-bit timer mode control 50
  FF6Ch TMHMD1 R/W 1B- 00h   BCDEF 8-bit timer H mode 1
  FF6Dh TMCYC1 R/W 1B- 00h   BCDEF 8-bit timer H carrier control 1
  FF6Eh KRM    R/W 1B- 00h   -CDEF Key return mode
  FF6Fh WTM    R/W 1B- 00h   -CDEF Watch timer operation mode
  FF70h ASIM0  R/W 1B- 01h   BCDEF Async serial interface operation mode 0
  FF71h BRGC0  R/W -B- 1Fh   BCDEF Baud rate generator control 0
  FF72h RXB0   R   -B- FFh   BCDEF Receive buffer 0
  FF73h ASIS0  R   -B- 00h   BCDEF Async serial interface reception err/stat 0
  FF74h TXS0   W   -B- FFh   BCDEF Transmit shift 0
  FF80h CSIM10 R/W 1B- 00h   BCDEF Serial operation mode 10
  FF81h CSIC10 R/W 1B- 00h   BCDEF Serial clock selection 10
  FF84h SOTB10 R/W -B- 00h   BCDEF Transmit buffer 10
  FF88h CSIM11 R/W 1B- 00h   ---eF Serial operation mode 11  (KE2: 48KB only)
  FF89h CSIC11 R/W 1B- 00h   ---eF Serial clock selection 11 (KE2: 48KB only)
  FF8Ch TCL51  R/W 1B- 00h   BCDEF Timer clock selection 51
  FF90h CSIMA0 R/W 1B- 00h   ----F Serial operation mode specification 0
  FF91h CSIS0  R/W 1B- 00h   ----F Serial status 0
  FF92h CSIT0  R/W 1B- 00h   ----F Serial trigger 0
  FF93h BRGCA0 R/W -B- 03h   ----F Division value selection 0
  FF94h ADTP0  R/W -B- 00h   ----F Automatic data transfer address point spec 0
  FF95h ADTI0  R/W -B- 00h   ----F Automatic data transfer interval spec 0
  FF96h SIOA0  R/W -B- 00h   ----F Serial I/O shift 0
  FF97h ADTC0  R   -B- 00h   ----F Automatic data transfer address count 0
  FF99h WDTE   R/W -B- xAh   BCDEF Watchdog timer enable (initial=1Ah/9Ah)
  FF9Fh OSCCTL R/W 1B- 00h   BCDEF Clock operation mode select
  FFA0h RCM    R/W 1B- x0h   BCDEF Internal oscillation mode
  FFA1h MCM    R/W 1B- 00h   BCDEF Main clock mode
  FFA2h MOC    R/W 1B- 80h   BCDEF Main OSC control
  FFA3h OSTC   R   1B- 00h   BCDEF Oscillation stabilization time counter stat
  FFA4h OSTS   R/W -B- 05h   BCDEF Oscillation stabilization time select
  FFA5h IIC0   R/W -B- 00h   BCDEF IIC shift 0
  FFA6h IICC0  R/W 1B- 00h   BCDEF IIC control 0
  FFA7h SVA0   R/W -B- 00h   BCDEF Slave address 0
  FFA8h IICCL0 R/W 1B- 00h   BCDEF IIC clock selection 0
  FFA9h IICX0  R/W 1B- 00h   BCDEF IIC function expansion 0
  FFAAh IICS0  R   1B- 00h   BCDEF IIC status 0
  FFABh IICF0  R/W 1B- 00h   BCDEF IIC flag 0
  FFACh RESF   R   -B- xxh   BCDEF Reset control flag
  FFB0h TM01   R   --W 0000h ---eF 16-bit timer counter 01           ;\
  FFB2h CR001  R/W --W 0000h ---eF 16-bit timer capture/compare 001  ;
  FFB4h CR011  R/W --W 0000h ---eF 16-bit timer capture/compare 011  ; KE2:
  FFB6h TMC01  R/W 1B- 00h   ---eF 16-bit timer mode control 01      ; 48KB
  FFB7h PRM01  R/W 1B- 00h   ---eF Prescaler mode 01                 ; only)
  FFB8h CRC01  R/W 1B- 00h   ---eF Capture/compare control 01        ;
  FFB9h TOC01  R/W 1B- 00h   ---eF 16-bit timer output control 01    ;/
  FFBAh TMC00  R/W 1B- 00h   BCDEF 16-bit timer mode control 00
  FFBBh PRM00  R/W 1B- 00h   BCDEF Prescaler mode 00
  FFBCh CRC00  R/W 1B- 00h   BCDEF Capture/compare control 00
  FFBDh TOC00  R/W 1B- 00h   BCDEF 16-bit timer output control 00
  FFBEh LVIM   R/W 1B- xxh   BCDEF Low-voltage detection
  FFBFh LVIS   R/W 1B- xxh   BCDEF Low-voltage detection level selection
  FFC0h PFCMD  W?  ?B? ?     ?  Undoc: Flash Protect Command (write A5h)
  FFC1h -      R/W 1B- ?     ?  Undoc: Flash ... FFC1h ... bits/pulses   FSSQ ?
  FFC2h PFS    R       ?     ?  Undoc: Flash Protect Status
  FFC4h FLPMC  R/W 1B? ?     ?  Undoc: Flash Programming Mode Ctl ;triple write
  FFC5h -      W   1?- ?     ?  Undoc: Flash ... 0FFC5h ... bits/mode   ?
  FFC6h FLAPH  W   1B- ?     ?  Undoc: Flash addr ptr upper 8bit (bit1=flag)
  FFC7h -      R/W 1?- ?     ?  Undoc: Flash ... 0FFC7h ... flag bits
  FFC8h FLAPL  W   1BW ?     ?  Undoc: Flash addr ptr lower 16bit (bit0,1=flag)
  FFCAh -      R/W ?B? ?     ?  Undoc: Flash ... 0FFCAh ...       ;triple write
  FFCBh FLWE   W   ?B- ?     ?  Undoc: Flash write data ECC error correction?
  FFCCh FLWH   W   -BW ?     ?  Undoc: Flash write data upper 16bit  ;\4-byte
  FFCEh FLWL   W   -BW ?     ?  Undoc: Flash write data lower 16bit  ;/
  FFE0h IF0L   R/W 1BW 00h   BCDEF Interrupt request flag 0L      ;\IF0
  FFE1h IF0H   R/W 1BW 00h   BCDEF Interrupt request flag 0H      ;/
  FFE2h IF1L   R/W 1BW 00h   BCDEF Interrupt request flag 1L      ;\IF1
  FFE3h IF1H   R/W 1BW 00h   BCDEF Interrupt request flag 1H      ;/
  FFE4h MK0L   R/W 1BW FFh   BCDEF Interrupt mask flag 0L         ;\MK0
  FFE5h MK0H   R/W 1BW FFh   BCDEF Interrupt mask flag 0H         ;/
  FFE6h MK1L   R/W 1BW FFh   BCDEF Interrupt mask flag 1L         ;\MK1
  FFE7h MK1H   R/W 1BW FFh   BCDEF Interrupt mask flag 1H         ;/
  FFE8h PR0L   R/W 1BW FFh   BCDEF Priority specification flag 0L ;\PR0
  FFE9h PR0H   R/W 1BW FFh   BCDEF Priority specification flag 0H ;/
  FFEAh PR1L   R/W 1BW FFh   BCDEF Priority specification flag 1L ;\PR1
  FFEBh PR1H   R/W 1BW FFh   BCDEF Priority specification flag 1H ;/
  FFF0h IMS    R/W -B- CFh   BCDEF Internal memory size switching
  FFF3h BANK   R/W -B- 00h   --def Memory bank select  (KD2-KF2: min 96KB only)
  FFF4h IXS    R/W -B- 0Ch   bcdeF Internal expansion RAM size switching
  FFF5h -      R   ?B- ?     ?  Undoc: chip_id (package type and memory size)
  FFFBh PCC    R/W 1B- 01h   BCDEF Processor clock control
And, more undoc/secret registers:
  F800h..F0h   -   --- ?     ?  Undoc: unknown values, unused by software
  F8F1h FLrE   R   -B- ?     ?  Undoc: Flash read data ECC error correction?
  F8F2h FLrH   R   -BW ?     ?  Undoc: Flash read data upper 16bit  ;\4-byte
  F8F4h FLrL   R   -BW ?     ?  Undoc: Flash read data lower 16bit  ;/total
  F8F6h ???    R/W --W ?     ?  Undoc: Flash ...0F8F6h_word     ;-16bit
  F8F8h -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8F9h ???    R/W -B- ?     ?  Undoc: Flash ...0F8F9h          ;-
  F8FAh -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8FBh -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8FCh -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8FDh -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8FEh -      -   --- ?     ?  Undoc:   ;(unused by software)
  F8FFh -      -   --- ?     ?  Undoc:   ;(unused by software)

Whereas,
  1BT   = supports Bit/Byte/Word access (1bit/8bit/16bit)
  BCDEF = supported on KB2/KC2/KD2/KE2/KF2 chip versions
For IMS/IXS: Regardless of the internal memory capacity, the initial values of the internal memory size switching register (IMS) and internal expansion RAM size switching register (IXS) of all products in the 78K0/Kx2 microcontrollers are fixed (IMS = CFH, IXS = 0CH). Therefore, set the value corresponding to each product as indicated in Tables 3-1 and 3-2.
For IMS/IXS: The ROM and RAM capacities of the products with the on-chip debug function can be debugged by setting IMS and IXS, according to the debug target products. Set IMS and IXS according to the debug target products.
For IXS on KB2-KE2: Set IXS only in products with internal expansion RAM.
The reset values of RES, LVIM and LVIS vary depending on the reset source.
The reset value of WDTE is determined by setting of option byte.
The reset value of RCM is 00h immediately after a reset release but automatically changes to 80h after oscillation accuracy stabilization of high-speed internal oscillator has been waited.


DSi Autoload on Warmboot

Overview
Launcher (and unlaunch) can be commanded to autoload a different title.
  2000000h  Autoload Parameters for newly loaded title  ;<-- optional extra
  2000300h  Autoload via numeric Title ID               ;<-- official method
  2000800h  Autoload via string "device:\path\filename" ;<-- alternate method
  2FFD800h  Title List (jump-able titles for use at 2000300h)
  BPTWL[70h].bit0  Warmboot flag                        ;<-- required flag
  BPTWL[11h].bit0  Trigger reset                        ;<-- trigger reset
Moreover, autoload can occur on warmboot & coldboot: Launcher autoloads any ROM cartridge with carthdr[01Fh].Bit2. Unlaunch defaults to autoload any file named "sdmc:\bootcode.dsi".

Examples
DSi Browser settings screen allows to autoload System Settings (via 2000300h), and automatically enter the Internet options page (via 2000000h).
Nintendo Zone, if started with Wireless Communications disabled, allows to reboot itself (via specifying it's own Title ID in 2000300h).
Homebrew frontends for unlaunch could start themselves (via bootcode.dsi) and then command unlaunch to load another title (via 2000800h or 2000300h).

2000000h - Optional Auto-load parameters (passed on to new title)
  2000000h 8    AutoParam Old Title ID (former title)    ;carthdr[230h]
  2000008h 1    AutoParam Unknown/Unused
  2000009h 1    AutoParam Flags (03h=Stuff is used?)
  200000Ah 2    AutoParam Old Maker code                 ;carthdr[010h]
  200000Ch 2    AutoParam Unknown (02ECh) ;\counter/length/indices/whatever?
  200000Eh 2    AutoParam Unknown (0000h) ;/
  2000010h 2    AutoParam CRC16 on [000h..2FFh], initial=FFFFh, [010h]=0000h
  2000012h 2    AutoParam Unknown/Unused (000Fh = want Internet Settings?)
  2000014h 2ECh AutoParam Unknown... some buffer... string maybe?
Above is the overall skeleton as intended by Nintendo, the purpose/format of the 2ECh bytes is unknown (there seems to be some relation to entries [0Ch] and [0Eh], but theoretically, each title could use that bytes as pleased).

2000300h - Nintendo Auto-load feature (via numeric Title ID)
  2000300h 4    AutoLoad ID ("TLNC")
  2000304h 1    AutoLoad Unknown/unused (usually 01h)
  2000305h 1    AutoLoad Length of data at 2000308h (01h..18h,for CRC,18h=norm)
  2000306h 2    AutoLoad CRC16 of data at 2000308h (with initial value FFFFh)
  2000308h 8    AutoLoad Old Title ID (former title) (can be 0=anonymous)
  2000310h 8    AutoLoad New Title ID (new title to be started,0=none/launcher)
  2000318h 4    AutoLoad Flags (bit0, 1-3, 4, 5,6,7) ;usually 16bit, once 32bit
  200031Ch 4    AutoLoad Unused (but part of checksummed area when CRC len=18h)
  2000320h E0h  AutoLoad Unused (but zerofilled upon erasing autoload area)
Flags (usually 13h or 17h):
  0     IsValid (somehow enables/disables HealthSafety when TitleID is wrong?)
  1-3   Boottype (01h=Cartridge, 02h=Landing, 03h=DSiware) (see below)
  4     Unknown
  5     Unknown
  6     LoadCompl (causes some error when set) (loading completed flag?)
  7     Unknown
  8-15  Unused
  16-31 Unused (usually not accessed at all, with normal 16bit reads)
Boottypes (in Flags.bit1-3):
  01h = Cartridge (with NewTitleID)    (with RSA signed header, or Whitelisted)
  02h = Landing ("nand:/tmp/jump.app") (with RSA signed DownloadPlay footer)
  03h = DSiware (with NewTitleID)      (with RSA signed header)
TitleID.LSW should match DSi cart header (or be reverse of NDS gamecode?)
TitleID.MSW should match DSi cart header (or be zero for NDS titles?)
Note: Many titles do create the above structure even when not requesting to boot a new file: with NewTitleID=0=none & flags=13h=cartridge (in that case flags should be ignored, and NewTitleID=0=none has priority).

2000800h - Unlaunch Auto-load feature (via "device:/Path/Filename.ext")
  2000800h 12   Unlaunch Auto-load ID ("AutoLoadInfo")
  200080Ch 2    Unlaunch Length for CRC16 (fixed, must be 3F0h)
  200080Eh 2    Unlaunch CRC16 (across 2000810h..2000BFFh, initial value FFFFh)
  2000810h 4    Unlaunch Flags
  2000814h 2    Unlaunch Upper screen BG color (0..7FFFh)
  2000816h 2    Unlaunch Lower screen BG color (0..7FFFh)
  2000818h 20h  Unlaunch Reserved (zero)
  2000838h 208h Unlaunch Device:/Path/Filename.ext (16bit Unicode,end by 0000h)
  2000A40h 1C0h Unlaunch Reserved (zero)
Unlaunch Flags (usually 01h):
  0    Load the title at 2000838h
  1    Use colors 2000814h (use if loaded title is KNOWN to use such colors)
  2-31 Reserved (zero)
The name can use slashes or backslashes for folders, and it can use both long or short filenames (LFN or 8.3). The total length should not exceed 260 characters including EOL (alike windows MAX_PATH, although WinNT seems to allow up to 32K characters, which isn't supported here).
  "nand:/path/name.ext",0000h   File on 1st partition of internal eMMC
  "sdmc:/path/name.ext",0000h   File on 1st partition of external SD/MMC
  "cart:",0000h      ROM cartridge (in NDS cartridge slot)
  "menu:",0000h      Force starting unlaunch filemenu
  "sett:",0000h      Force starting unlaunch options menu
  "wifi:",0000h      Force starting unlaunch wifiboot overlay
Case-sensitivity: device, path and file can use upper/lower case A-Z (not case-sensititive), however currently any other letters are case-sensitive (eg. umlaut's or accented letters) (that is, they must be uppercase for short names, or have matching case for long names).
For black colors, you should also disable backlights before issuing reset (else screen will flash white for a short moment during initial forced blank; before unlaunch gets started).

2FFD800h - Title List
Before autoloading a title, one should make sure that the title is actually installed (and which region code it is having, ie. one should use wildcards that ignore the lower 8bit of the Title ID when searching the title).
The offical way is to look up the Title List in RAM, this is faster than manually crawling the directory tree. However, there are some restrictions: The Title List contains only titles from the same Maker (as the currently loaded title), plus some special "jumpable" system titles.
  2FFD800h 1     Titles: Number of titles in below lists (max 76h)
  2FFD801h 0Fh   Titles: Zerofilled
  2FFD810h 10h   Titles: Pub Flags (1bit each) ;same maker plus public.sav
  2FFD820h 10h   Titles: Prv Flags (1bit each) ;same maker plus private.sav
  2FFD830h 10h   Titles: Jmp Flags (1bit each) ;jumpable or current-title
  2FFD840h 10h   Titles: Mkr Flags (1bit each) ;same maker
  2FFD850h 3B0h  Titles: Title IDs (8 bytes each)
Related carthdr entries are:
  [010h].bit0-15  Maker (must match current title for Mkr Flags)
  [01Dh].bir0     Jump (must be set for Jmp Flags)
  [230h].bit0-63  Title ID (must be nonzero for being listed)
  [238h].bit0-31  Public.sav size (must be nonzero for Pub Flags)
  [23Ch].bit0-31  Private.sav size (must be nonzero for Prv Flags)
The list can contain the hidden Nintendo Zone utility, and DSi ROM cartridges (both provided that Maker does match up with current title).
The jumpable titles with [01Dh].bit0 that are always in the list are:
  00030015484E42xxh  ;System Settings
  00030005484E4441h  ;DS Download Play
  00030005484E4541h  ;Pictochat
  00030004484E47xxh  ;Nintendo DSi Browser (if installed)
The list does NOT contain the Launcher itself, nor files from System Data folder (WifiFirmware, Whitelist, VersionData), nor NDS ROM cartridges, nor anything where Jmp+Mkr flags would be both zero.
If started via 2000300h, then the New Title (from 2000310h) does also receive the Old Title ID (from 2000308h) with Jmp flag being set; ie. permitting to return to the Old Title (to know which title was the old title, one should probably look at 2000000h, or at 2000308h if that's still intact in memory?).
Also, the Jmp flag is always set for the current title; ie. permitting the title to reboot itself.


DSi Aptina Camera Initialization

Aptina I2C registers are accessed via 16bit index, and one or more data bytes at auto-increasing indices (usually, all transfers are done as big-endian 2-byte (16bit) values at even indices). Additional MCU Variables are accessed indirectly via XMDA registers.

aptina_get_chip_id:
Reading a 16bit value from index 0000h returns the CHIP_VERSION_REG (always 2280h=MT9V113 for DSi/3DS/New3DS), the DSi games are actually reading that register, but they seem to ignore it's value.
If the DSi isn't fitted with Aptina cameras, then reading anything from device 78h/7Ah would most likely return FFh-bytes.

brightness / low light environments
Below configurations are okay for daylight (without much sunshine), but the picture will be almost completely black at night (in rooms with small bulbs). There are probably numerous good/bad ways to manipulate the brightness. Some random solutions are:
Leave AE_MIN_INDEX/AE_MAX_INDEX at their power-on defaults (instead of using below settings) (the power-on defaults will greatly improve the brightness, but the conversion will be also much slower). Increasing COARSE_INTEGRATION_TIME to some big value (like 0800h) does also seem to raise the brightness.

aptina_code_list_init:
Below is some minimal initialization (though it might still include some unnecessary stuff). Most important sections are leaving standby mode, matching PLL to DSi timings, selecting desired resolution(s) and YUV color format.
DSi games are usually initializing further stuff like P0..P4 Coefficients, Gamma Tables, and Color Correction Matrices - but the cameras are also working when leaving those settings at their power-on defaults.
It's recommended to initialize both cameras in parallel (eg. issue Wakeup to <both> cameras, and <then> wait for Wakeup completion; this is faster than doing it separately for each camera).
  AptWr     ,0001Ah,00003h   ;RESET_AND_MISC_CONTROL (issue reset)   ;\reset
  AptWr     ,0001Ah,00000h   ;RESET_AND_MISC_CONTROL (release reset) ;/
  AptWr     ,00018h,04028h   ;STANDBY_CONTROL (wakeup)               ;\
  AptWr     ,0001Eh,00201h   ;PAD_SLEW                               ; wakeup
  AptWr     ,00016h,042DFh   ;CLOCKS_CONTROL                         ;
  AptWaitClr,00018h,04000h   ;STANDBY_CONTROL (wait for WakeupDone)  ;
  AptWaitSet,0301Ah,00004h   ;UNDOC_CORE_301A (wait for WakeupDone)  ;/
  AptWrMcu  ,002F0h,00000h   ;UNDOC! RAM?
  AptWrMcu  ,002F2h,00210h   ;UNDOC! RAM?
  AptWrMcu  ,002F4h,0001Ah   ;UNDOC! RAM?
  AptWrMcu  ,02145h,002F4h   ;UNDOC! SEQ?
  AptWrMcu  ,0A134h,  001h   ;UNDOC! SEQ?
  AptSetMcu ,0A115h,  002h   ;SEQ_CAP_MODE (set bit1=video)
  AptWrMcu  ,02755h,00002h   ;MODE_OUTPUT_FORMAT_A (bit5=0=YUV)      ;\select
  AptWrMcu  ,02757h,00002h   ;MODE_OUTPUT_FORMAT_B                   ;/YUV mode
  AptWr     ,00014h,02145h   ;PLL_CONTROL                            ;\
  AptWr     ,00010h,00111h   ;PLL_DIVIDERS                           ; match
  AptWr     ,00012h,00000h   ;PLL_P_DIVIDERS                         ; PLL
  AptWr     ,00014h,0244Bh   ;PLL_CONTROL                            ; to DSi
  AptWr     ,00014h,0304Bh   ;PLL_CONTROL                            ; timings
  AptWaitSet,00014h,08000h   ;PLL_CONTROL (wait for PLL Lock okay)   ;
  AptClr    ,00014h,00001h   ;PLL_CONTROL (disable PLL Bypass)       ;/
  AptWrMcu  ,02703h,00100h   ;MODE_OUTPUT_WIDTH_A              ;\Size A
  AptWrMcu  ,02705h,000C0h   ;MODE_OUTPUT_HEIGHT_A             ;/ 256x192
  AptWrMcu  ,02707h,00280h   ;MODE_OUTPUT_WIDTH_B              ;\Size B
  AptWrMcu  ,02709h,001E0h   ;MODE_OUTPUT_HEIGHT_B             ;/ 640x480
  AptWrMcu  ,02715h,00001h   ;MODE_SENSOR_ROW_SPEED_A          ;\
  AptWrMcu  ,02719h,0001Ah   ;MODE_SENSOR_FINE_CORRECTION_A    ;
  AptWrMcu  ,0271Bh,0006Bh   ;MODE_SENSOR_FINE_IT_MIN_A        ; Sensor A
  AptWrMcu  ,0271Dh,0006Bh   ;MODE_SENSOR_FINE_IT_MAX_MARGIN_A ;
  AptWrMcu  ,0271Fh,002C0h   ;MODE_SENSOR_FRAME_LENGTH_A       ;
  AptWrMcu  ,02721h,0034Bh   ;MODE_SENSOR_LINE_LENGTH_PCK_A    ;/
  AptWrMcu  ,0A20Bh,  000h   ;AE_MIN_INDEX                     ;\AE min/max
  AptWrMcu  ,0A20Ch,  006h   ;AE_MAX_INDEX                     ;/
  AptWrMcu  ,0272Bh,00001h   ;MODE_SENSOR_ROW_SPEED_B          ;\
  AptWrMcu  ,0272Fh,0001Ah   ;MODE_SENSOR_FINE_CORRECTION_B    ;
  AptWrMcu  ,02731h,0006Bh   ;MODE_SENSOR_FINE_IT_MIN_B        ; Sensor B
  AptWrMcu  ,02733h,0006Bh   ;MODE_SENSOR_FINE_IT_MAX_MARGIN_B ;
  AptWrMcu  ,02735h,002C0h   ;MODE_SENSOR_FRAME_LENGTH_B       ;
  AptWrMcu  ,02737h,0034Bh   ;MODE_SENSOR_LINE_LENGTH_PCK_B    ;/
  AptSet    ,03210h,00008h   ;COLOR_PIPELINE_CONTROL (PGA pixel shading..)
  AptWrMcu  ,0A208h,  000h   ;UNDOC! RESERVED_AE_08
  AptWrMcu  ,0A24Ch,  020h   ;AE_TARGETBUFFERSPEED
  AptWrMcu  ,0A24Fh,  070h   ;AE_BASETARGET
  If Device=7Ah                                                ;\
    AptWrMcu,02717h,00024h   ;MODE_SENSOR_READ_MODE_A          ; Read Mode
    AptWrMcu,0272Dh,00024h   ;MODE_SENSOR_READ_MODE_B          ; with x-flip
  Else (xflip)                                                 ; on internal
    AptWrMcu,02717h,00025h   ;MODE_SENSOR_READ_MODE_A          ; camera
    AptWrMcu,0272Dh,00025h   ;MODE_SENSOR_READ_MODE_B          ;/
  If Device=7Ah                                                ;\
    AptWrMcu,0A202h,  022h   ;AE_WINDOW_POS                    ;
    AptWrMcu,0A203h,  0BBh   ;AE_WINDOW_SIZE                   ;
  Else (?)                                                     ;
    AptWrMcu,0A202h,  000h   ;AE_WINDOW_POS                    ;
    AptWrMcu,0A203h,  0FFh   ;AE_WINDOW_SIZE                   ;/
  AptSet    ,00016h,00020h   ;CLOCKS_CONTROL (set bit5=1, reserved)
  AptWrMcu  ,0A115h,  072h   ;SEQ_CAP_MODE (was already manipulated above)
  AptWrMcu  ,0A11Fh,  001h   ;SEQ_PREVIEW_1_AWB                ;\
  If Device=7Ah                                                ;
    AptWr   ,0326Ch,00900h   ;APERTURE_PARAMETERS              ;
    AptWrMcu,0AB22h,  001h   ;HG_LL_APCORR1                    ;
  Else (?)                                                     ;
    AptWr   ,0326Ch,01000h   ;APERTURE_PARAMETERS              ;
    AptWrMcu,0AB22h,  002h   ;HG_LL_APCORR1                    ;/
  AptWrMcu     ,0A103h,  006h   ;SEQ_CMD (06h=RefreshMode)
  AptWaitMcuClr,0A103h,  00Fh   ;SEQ_CMD (wait above to become ZERO)
  AptWrMcu     ,0A103h,  005h   ;SEQ_CMD (05h=Refresh)
  AptWaitMcuClr,0A103h,  00Fh   ;SEQ_CMD (wait above to become ZERO)
Above does set two Mode/Contexts, 256x192 and 640x480. Yet unknown how to activate the latter one.

aptina_code_list_activate:
  AptClr    ,00018h,00001h   ;STANDBY_CONTROL (bit0=0=wakeup)       ;\
  AptWaitClr,00018h,04000h   ;STANDBY_CONTROL (wait for WakeupDone) ; Wakeup
  AptWaitSet,0301Ah,00004h   ;UNDOC_CORE_301A (wait for WakeupDone) ;/
  AptWr     ,03012h,000xxh   ;COARSE_INTEGRATION_TIME (Y Time)
  AptSet    ,0001Ah,00200h   ;RESET_AND_MISC_CONTROL (Parallel On)  ;-Data on
Also, don't forget to activate the Camera LED via BPTWL chip (when using the external camera).

aptina_code_list_deactivate:
Before activating another camera: First disable the Parallel output of the old camera (for avoiding collisions on the camera's parallel databus). When not using the camera for longer time, also enter standby mode (for reducing power consumption).
  AptClr    ,0001Ah,00200h  ;RESET_AND_MISC_CONTROL (Parallel Off)  ;-Data off
  AptSet    ,00018h,00001h  ;STANDBY_CONTROL (set bit0=1=Standby)   ;\
  AptWaitSet,00018h,04000h  ;STANDBY_CONTROL (wait for StandbyDone) ; Standby
  AptWaitClr,0301Ah,00004h  ;UNDOC_CORE_301A (wait for StandbyDone) ;/

References
There aren't any MT9V113 specs released, but info for MT9D113 (a higher resolution variant) does exist: a pdf datasheet, and an xml reference for the I2C registers.
There are several source code files for MT9V113 cameras (different files from different people; for use with linux/android/whatever) including samples for adjusting stuff like contrast and sharpness. However, observe that the source code may need some adjustments: PLL register matched to DSi timings, and, use YUV 8bit parallel databus transfer for DSi.


DSi Aptina Camera Registers: SYSCTL (0000h-0051h)

SYSCTL (0000h-0051h)
  0000h   2  CHIP_VERSION_REG       Model ID (2280h=MT9V113 on DSi/3DS) (R)
  0006h  ..  RESERVED_SYSCTL_06     Reserved
  0010h   2  PLL_DIVIDERS           PLL Dividers (def=0366h)
               0-7   PLL M-Divider value (uh, actually a Multiplier?!)
               8-13  PLL N-Divider value
               14-15 Unused (0)
             Because the input clock frequency is unknown, the sensor starts
             up with the PLL disabled. The PLL takes time to power up. During
             this time, the behavior of its output clock signal is not
             guaranteed. The PLL output frequency is determined by two
             constants, M and N, and the input clock frequency.
               VCO = Fin * 2 * M / (N+1)
               PLL_output_frequency = VCO / (P1+1)
             The PLL can generate a master clock signal whose frequency is up
             to 85 MHz (input clock from 6 MHz through 54 MHz).
  0012h   2  PLL_P_DIVIDERS         PLL P Dividers (def=00F5h)
               0-3   P1 (00h..0Fh)
               4-7   Unspecified
               8-11  P3 (00h..0Fh)
               12-13 Division ratio of word clock/clockn from bit_clock (0..3)
               14    Unused (0)
               15    Unspecified
  0014h   2  PLL_CONTROL            PLL Control (def=21F9h)
               0     PLL Bypass
               1     PLL Enable
               2-3   Reserved (0..3)
               4-7   Reserved (0..0Fh)
               8     Reset_cntr
               9     Reserved
               10    Reserved
               11    Reserved
               12    Reserved
               13    Reserved
               14    Unused (0)
               15    PLL Lock (R)
  0016h   2  CLOCKS_CONTROL         Clocks Control
               0     Reserved
               1     Reserved
               2     Reserved
               3     Reserved
               4     Reserved
               5     Reserved/UNDOC/USED (manipulated by DSi)
               6     Reserved
               7     Reserved
               8     Reserved
               9     clk_clkin_en
               11-12 Reserved
               13    Reserved
               15    Reserved
  0018h   2  STANDBY_CONTROL        Standby Control and Status (def=4029h)
               0     Ship (uh?) (0=Enable various regs, 1=Standby)
               1     Reserved
               2     Stop MCU
               3     en_IRQ
               4     Reserved
               5     Reserved
               6-13  Unused (0)
               14    Standby_done (0=WakeupDone, 1=StandbyDone) (R?)
                       (takes MUCH time?)
               15    Reserved (R)
  001Ah   2  RESET_AND_MISC_CONTROL Reset and Control (def=0050h) (0-0333h)
               0     Reset SOC I2C
               1     MIPI_TX_Reset
               2     Unused (0)
               3     MIPI_TX_en       (=Serial Data?)
               4     IP_PD_en         (=Parallel Data or what?)
               5     Reserved
               6     Sensor_full_res
               7     Unused (0)
               8     OE_N_Enable
               9     Parallel_enable  (=Parallel Data?)
               10    Unused (0)
               11    Reserved
               12-15 Unused (0)
  001Ch   2  MCU_BOOT_MODE          MCU Boot Mode
               0     Reset MCU
               1     Reserved
               2     Reserved
               3     Reserved
               4-7   Reserved  (0..0Fh)
               8-15  Reserved  (0..FFh) (R)
  001Eh   2  PAD_SLEW               Pad Slew Control (def=0400h)
               0-2   Parallel Data Output Slew Rate Control (0-7)
               3     Unused (0)
               4-6   GPIO Slew Rate Control (0-7)
               7     Unused (0)
               8-10  PCLK aka PXLCLK Slew Rate Control (0-7)
               11-15 Unused (0)
  0020h  ..  RESERVED_SYSCTL_20     Reserved
  0022h   2  VDD_DIS_COUNTER        VDD_DIS_COUNTER (0..FFFFh, def=0438h)
  0024h   2  GPI_STATUS             GPI_STATUS      (0..000Fh) (R)
  0026h  ..  RESERVED_SYSCTL_26     Reserved
  0028h   2  EN_VDD_DIS_SOFT        EN_VDD_DIS_SOFT (0..0001h, def=0001h)
  0050h  ..  RESERVED_SYSCTL_50     Reserved


DSi Aptina Camera Registers: RX_SS, FUSE, XDMA (0100h-099Fh)

RX_SS (0100h-0117h)
  0100h  ..  RESERVED_RX_SS_100     Reserved
  0102h   2  TEST_PXL_RED           Test Pixel Red    ;\Default value is 1FFh
  0104h   2  TEST_PXL_G1            Test Pixel Green1 ; for Gray Flat Field
  0106h   2  TEST_PXL_G2            Test Pixel Green2 ; (0..03FFh, def=01FFh)
  0108h   2  TEST_PXL_BLUE          Test Pixel Blue   ;/
  010Ah  ..  RESERVED_RX_SS_10A-116 Reserved

FUSE_ROM (0800h-081Fh)
Reserved, unknown purpose, all zero in DSi.
  0800h  ..  RESERVED_FUSE_ROM_800-81E  Reserved

XDMA (0982h-099Fh)
Access to internal LOGICAL "driver" variables.
  0982h  ..  RESERVED_XDMA_982      Reserved
  098Ch   2  MCU_ADDRESS            MCU Address (0000h..FFFFh)
               0-7   driver_variable (0..FFh)
               8-12  driver_id       (0..1Fh) (eg. 3=AWB, 7=MODE, etc.)
               13-14 address space   (0=Physical/RAM/SFR, 1=Logical/Variables)
               15    access_8_bit    (0=16bit, 1=8bit; converted to 16bit)
  0990h 8x2  MCU_DATA_0-7           MCU Data 0..7 (8 x 16bit)
For reading, it's best to use "16bit" mode, no matter if reading an 8bit BYTE, or a 16bit MSB,LSB value. The "8bit" mode is converting bytes to 16bit values (MSB=00h, LSB=BYTE), which is a rather contraproductive idiotism; intended for I2C functions that implement only 16bit data transfers, but no 8bit transfers.
Unknown what exactly is mapped at MCU_DATA_0-7 (probably the 16 bytes at MCU_ADDRESS+0..15, probably with direct mapping / ie. without latching a copy of that memory).
MCU_ADDRESS doesn't seem to increment after reading data, however, the i2c index does increase, so one can probably read up to 16 bytes from MCU_DATA_0-7.


DSi Aptina Camera Registers: CORE (3000h-31FFh, 38xxh)

CORE (3000h-31FFh)
  3000h  ..  RESERVED_CORE_3000        Reserved (same as CHIP_VERSION_REG)
  3002h   2  Y_ADDR_START              Y1      ;\Image Position/Size ;def=0004h
  3004h   2  X_ADDR_START              X1      ; (up to including    ;def=0004h
  3006h   2  Y_ADDR_END                Y2      ; X2,Y2) (0-07FFh)    ;def=04BBh
  3008h   2  X_ADDR_END                X2      ;/                    ;def=064Bh
  300Ah   2  FRAME_LENGTH_LINES        Y Total ;\Total X/Y Size with ;def=0512h
  300Ch   2  LINE_LENGTH_PCK           X Total ;/blanking (0..FFFFh) ;def=0886h
  3010h  ..  RESERVED_CORE_3010        Reserved
  3012h   2  COARSE_INTEGRATION_TIME   Y Time  ;\Integration Time in ;def=0010h
  3014h   2  FINE_INTEGRATION_TIME     X Time  ;/lines/pix (0..FFFFh);def=00F6h
  3016h   2  ROW_SPEED                 Row Speed (def=0111h)
               0-2   Pixclk_speed (0..7)
               3     Unused (0)
               4-6   Reserved
               7     Unused (0)
               8-10  Reserved
               11-15 Unused (0)
  3018h  ..  RESERVED_CORE_3018-3019   Reserved
  301Ah      UNDOC_CORE_301A           Undocumented Status Reg (mask=D7FFh)
               0-1   Unspecified
               2     Undoc/USED (1=WakeupDone) (opposite of 0018h.bit14)
               3-4   Unspecified
               5     Whatever "demo_system, version_reg_write, value=1"
               6-8   Unspecified
               9     Mask_corrupted_frames     (alias of 3022h.bit0)
               10    Unspecified
               11    Unused (0)
               12    Unspecified
               13    Unused (0)
               14    Unspecified
               15    Grouped_parameter_hold    (alias of 3022h.bit8)
  301Ch  ..  RESERVED_CORE_301C-3020   Reserved
  3022h   2  GROUPED_PARAMETER_HOLD_MASK_CORRUPTED_FRAMES
               0     Mask_corrupted_frames  (alias of Reg 301Ah.bit9)
               1-7   Unused (0)
               8     Grouped_parameter_hold (alias of Reg 301Ah.bit15)
               9-15  Unused (0)
  3024h   2  PIXEL_ORDER                Pixel Order (mask=0300h, 0..0300h) (R)
  3026h  ..  RESERVED_CORE_3026         Reserved
  3028h   2  ANALOGUE_GAIN_CODE_GLOBAL  Analog Global   ;\
  302Ah   2  ANALOGUE_GAIN_CODE_GREENR  Analog GreenR   ; Analogue Gain Codes
  302Ch   2  ANALOGUE_GAIN_CODE_RED     Analog Red      ; with 3bit fraction
  302Eh   2  ANALOGUE_GAIN_CODE_BLUE    Analog Blue     ; (0..007Fh, def=000Bh)
  3030h   2  ANALOGUE_GAIN_CODE_GREENB  Analog GreenB   ;/
  3032h   2  DIGITAL_GAIN_GREENR        Digital GreenR  ;\Digital Gain with
  3034h   2  DIGITAL_GAIN_RED           Digital Red     ; 8bit dummy-fraction
  3036h   2  DIGITAL_GAIN_BLUE          Digital Blue    ; (bit8-10=Gain, 0..7)
  3038h   2  DIGITAL_GAIN_GREENB        Digital GreenB  ;/(mask=0700h,def=100h)
  303Ah  ..  RESERVED_CORE_303A-3C      Reserved
  3040h   2  READ_MODE                  Read Mode (0-DEFFh, def=0024h)
               0    horiz_mirror
               1    vert_flip
               2-4  y_odd_inc (0..7)
               5-7  x_odd_inc (0..7)
               8    Unused (0)
               9    low_power
               10   xy_bin_en
               11   x_bin_en
               12   bin_sum (Enable summing mode for binning)
               13   read_mode_y_sumen
               14   Reserved
               15   Reserved
  3044h  ..  RESERVED_CORE_3044-3048    Reserved
  304Ah   2  OTPM_CONTROL               One-time Programmable Memory? Control
               0    auto_wr_start              ;\
               1    auto_wr_end (finished) (R) ; automatic write sequence
               2    auto_wr_success (okay) (R) ;/
               3    unspecified
               4    auto_rd_start              ;\
               5    auto_rd_end (finished) (R) ; automatic read sequence
               6    auto_rd_success (okay) (R) ;/
               7-15 Unused (0)
  3050h  ..  RESERVED_CORE_3050-3054    Reserved
  3056h   2  GREEN1_GAIN                Gain Green1             ;\
  3058h   2  BLUE_GAIN                  Gain Blue               ; Gain Values
  305Ah   2  RED_GAIN                   Gain Red                ; (0..0FFFh,
  305Ch   2  GREEN2_GAIN                Gain Green2             ; def=022Ch)
               0-6   Initial Gain (0..7Fh, with 5bit fraction)  ;
               7-8   Analog Gain  (0..3)   (bit8+1)*(bit7+1)*(initial_gain/32)
               9-11  Digital Gain (1..7)                        ;
               12-15 Unused (0)                                 ;/
  305Eh  ..  RESERVED_CORE_305E-31DF    Reserved
  31E0h   2  UNDOC_CORE_31E0            (mask=E003h, 0..8001h, def=0001h) USED!
               Used by DSi (set to 0001h) (reportedly "PIX_DEF_ID")
  31E2h  ..  RESERVED_CORE_31E2-31F9    Reserved
  31FAh   2  UNDOC_CORE_31FA            Whatever (mask=FFFFh, def=CDEFh)
               0-4   Unspecified
               5-11  Whatever "demo_system, version_reg_read, value=3"
               12-15 Unspecified
  31FCh  ..  RESERVED_CORE_305E-31FE    Reserved


More CORE (3800h..3803h)
  3800h  ..  RESERVED_CORE_3800-3802   Reserved


DSi Aptina Camera Registers: SOC1 (3210h-33FDh)

SOC1 Registers (3210h-33FDh)
  3210h   2  COLOR_PIPELINE_CONTROL     (mask=05B8h, 0..05B0h, def=01B0h)
               3   Enable PGA pixel shading correction
                     All coefficients and other configuration settings
                     (including other fields in this register) must be set up
                     before enabling shading correction.
               4   Enable 2D aperture correction
               5   Enable color correction
               7   Enable gamma correction
               8   Decimator (1=Enable scale)
               10  Reserved
  3216h  ..  RESERVED_SOC1_3216-321A    Reserved
  321Ch   2  OFIFO_CONTROL_STATUS       Ofifo control status 1 (def=0003h)
               0-3 txfifo_bypass
                     (0=tx_fifo, 1=sensor, 2=sam observe, 3=cpipe format,
                     4=test walking ones cpipe frequency,
                     5=test walking ones sensor frequency,
                     6=RESERVED, 7=test PIXCLK, 8..F=Unspecified)
               4-6 Unused (0)
               7   sensor_bypass (0=cpipe, 1=sensor)
               8   Reserved
               9   Reserved
               10  Reserved
               11  Reserved
               12  Reserved (R)
               13  Reserved (R)
               14  Reserved (R)
               15  Reserved (R)
  321Eh   2  OFIFO_CONTROL_STATUS_2     Ofifo control status 2 (def=0010h)
               0-9   Reserved (0..3FFh)
               10    Disable PV output clock during blank (1=disable)
               11-15 Reserved (0..1Fh)
  3220h  ..  RESERVED_SOC1_3220         Reserved
  3222h   2  LOWER_X_BOUND_ZOOM_WINDOW  Lower X  ;def=?      ;\Zoom Window
  3224h   2  UPPER_X_BOUND_ZOOM_WINDOW  Upper X  ;def=063Fh  ; Boundaries
  3226h   2  LOWER_Y_BOUND_ZOOM_WINDOW  Lower Y  ;def=?      ; (0..07FFh)
  3228h   2  UPPER_Y_BOUND_ZOOM_WINDOW  Upper Y  ;def=04AFh  ;/
  322Ah   2  UNDOC_SOC1_322A            (mask=0016h, 0..0016h) USED by DSi!
  322Ch   2  WEIGHT_HORIZ_DECIMATION    Scaling Weight X ;\Scaling Weight X,Y
  322Eh   2  WEIGHT_VERTICAL_DECIMATION Scaling Weight Y ;/(0..0FFFh, def=800h)
  323Eh   2  UNDOC_SOC1_323E            (0..FFFFh, def=1A2Dh) (DSi: C22Ch)
  3240h   2  UNDOC_SOC1_3240            (0..FFFFh, def=C814h) (DSi: 6214h)
  3242h  ..  RESERVED_SOC1_3242         Reserved
  3244h   2  UNDOC_SOC1_3244            (mask=03FFh, range=0..00FFh?, def=0310)
  3254h  ..  RESERVED_SOC1_3254-326A    Reserved
  326Ch   2  APERTURE_PARAMETERS        Aperture Params (0..7FFFh, def=0A08h)
               0-7   2D aperture threshold (knee) (00h-FFh)
               8-10  2D aperture gain (0-7)
               11-13 2D aperture gain's exponent (0-7)
               14    Abs (1=force aperture gain be positive)
               15    Unused (0)
  326Eh  ..  RESERVED_SOC1_326E-3276    Reserved
  327Ah   2  BLACK_LEVEL_1ST_RED        Offset Red     ;\Offsets subtracted
  327Ch   2  BLACK_LEVEL_1ST_GREEN1     Offset Green1  ; from RGB pixels
  327Eh   2  BLACK_LEVEL_1ST_GREEN2     Offset Green2  ; (0000-01FFh/03FFh,
  3280h   2  BLACK_LEVEL_1ST_BLUE       Offset Blue    ;/def=002Ah)
  328Eh   2  THRESH_EDGE_DETECT         Demosaic Edge Threshold (def=000Ch)
  3290h   2  TEST_PATTERN               Test Pattern Enable/Width
               0-4   Unused (0)
               5     en_walk_ones_tp  Enable Test Pattern (0=disable, 1=enable)
               6     walk_ones_10     Pattern Width (0=8-bit, 1=10-bit)
               7-15  Unused (0)
  329Eh  ..  RESERVED_SOC1_329E-32A0    Reserved
  32C0h   2  COLOR_CORR_MATRIX_SCALE_14 Exponents C11..C22 (0-7FFFh, def=3923h)
  32C2h   2  COLOR_CORR_MATRIX_SCALE_11 Exponents C23..C33 (0-0FFFh, def=0724h)
  32C4h   2  COLOR_CORR_MATRIX_1_2      Elements C11=LSB, C12=MSB   (def=7DCCh)
  32C6h   2  COLOR_CORR_MATRIX_3_4      Elements C13=LSB, C21=MSB   (def=2711h)
  32C8h   2  COLOR_CORR_MATRIX_5_6      Elements C22=LSB, C23=MSB   (def=62E5h)
  32CAh   2  COLOR_CORR_MATRIX_7_8      Elements C31=LSB, C32=MSB   (def=690Dh)
  32CCh   2  COLOR_CORR_MATRIX_9        Element C33=LSB, Signs=MSB  (def=2DCDh)
  32D4h   2  DIGITAL_GAIN_1_RED         Gain for Red channel    ;\Digital Gain1
  32D6h   2  DIGITAL_GAIN_1_GREEN1      Gain for Green1 channel ; (mul 128,
  32D8h   2  DIGITAL_GAIN_1_GREEN2      Gain for Green2 channel ; 0000h..03FFh,
  32DAh   2  DIGITAL_GAIN_1_BLUE        Gain for Blue channel   ;/def=0080h)
  32F4h  ..  RESERVED_SOC1_32F4-332E    Reserved
  3330h   2  OUTPUT_FORMAT_TEST         OUTPUT_FORMAT_TEST (0..0FFFh)
               0     Disable Cr channel
               1     Disable Y channel
               2     Disable Cb channel
               3-5   Test ramp output
               6     8+2 bypass
               7     Reserved
               8     Enable Lens Correction Bypass
               9     Reserved
               10    Reserved
               11    Reserved
               12-15 Unused (0)
  3332h  ..  RESERVED_SOC1_3332-334A    Reserved
  337Ch   2  YUV_YCBCR_CONTROL          YUV_YCBCR_CONTROL (0..000Fh, def=0006h)
               0     Mult_y_uv (normalize Y in 16-235; U and V in 16-240)
               1     Coefficient control
               2     Add 128 to U and V
               3     Clip Y in 16-235; U and V in 16-240
               4-15  Unused (0)
  337Eh   2  Y_RGB_OFFSET               Y_RGB Offset
               0-7   Reserved (0..FFh)
               8-15  Y offset (0..FFh)
  33E6h  ..  RESERVED_SOC1_33E6-33EE    Reserved
  33F4h   2  KERNEL_CONFIG              Kernel Config (0..01FFh, def=0003h)
               0     Defect correction (DC) enable
               1     Reserved
               2     Reserved
               3     Noise reduction (NR) enable
               4     Reserved
               5     Reserved
               6     Reserved
               7     Reserved
               8     Reserved
  33F6h  ..  RESERVED_SOC1_33F6-33FC    Reserved


DSi Aptina Camera Registers: SOC2 (3400h-3729h)

SOC2 (3400h-3729h)
  3400h   2  MIPI_CONTROL              MIPI_Control (def=782Eh)
               0     MIPI restart enable
               1     MIPI standby
               2     Continuous MIPI clock
               3     Frame boundary sync bit (R)
               4     Wait until eof to react to standby
               5     Reserved
               6-8   MIPI channel number
               9     Unused (0) or Reserved (REV3)
               10-15 Data Type (1Eh=YUV422_8bit, 20h=RGB444, 21h=RGB555,
                       22h=RGB565, 2Ah=RAW8, 2Bh=RAW10)
  3402h   2  MIPI_STATUS               MIPI_Status (def=0011h)
               0     MIPI in standby (R)
               1-3   Unused (0)
               4     MIPI aka MIPICCP idle (R)
               5     MIPI ready to receive data (R)
               6-8   Unused (0)
               9     Reserved (R)
               10    Reserved (R)
               11    Reserved
               12    Reserved
               13-15 Unused (0)
  3404h   2  CUSTOM_SHORT_PKT          MIPI_Custom_Short_Packet (0000h-3F00h)
               0-5   Unused (0)
               6     frame_cnt_reset (sent in frame start/end short packets)
               7     frame_cnt_en (Insert frame counter value in WC field)
               8-10  custom_short_packet_data_type
               11    custom_short_packet_request
               12    custom_short_packet_frame_sync
               13    custom_short_packet_reset (R)
               14-15 Unused (0)
  3408h   2  LINE_BYTE_CNT             MIPI line byte count (def=0C80h)
  340Ch   2  CUSTOM_SHORT_PKT_WC       WC field of a custom short packet
  340Eh  ..  RESERVED_SOC2_340E-341A   Reserved
  3580h   2  AE_ZONE_X                 AE Window/Zone X (def=1300h)
               0-7:  ae_zone_x_start (00h..FFh) (div8)          ;for WINDOW
               8-15: ae_zone_x_width (00h..FFh) (div8, minus 1) ;for each ZONE
  3582h   2  AE_ZONE_Y                 AE Window/Zone Y (def=0E00h)
               0-7:  ae_zone_y_start (00h..FFh) (div8)          ;for WINDOW
               8-15: ae_zone_y_width (00h..FFh) (div8, minus 1) ;for each ZONE
  3584h   2  AE_WINDOW_SIZE_LO         LSBs ;\Size of each AE zone in pixels
  3586h   2  AE_WINDOW_SIZE_HI         MSBs ;/(0..0001FFFFh, def=000x4B00h ?)
  3588h  ..  RESERVED_SOC2_3588-35AE   Reserved
  35B0h      UNDOC_SOC2_35B0           (mask=FFFFh, 0..FFFFh, def=05FAh) USED!
  35B2h  ..  RESERVED_SOC2_35B2-3602   Reserved
  3604h  20  R_GAMMA_CURVE_KNEES_0-18  Red Gamma Curve Knees 0..18   (1B00h,..)
  3618h  20  G_GAMMA_CURVE_KNEES_0-18  Green Gamma Curve Knees 0..18 (1B00h,..)
  362Ch  20  B_GAMMA_CURVE_KNEES_0-18  Blue Gamma Curve Knees 0..18  (1B00h,..)
               Above 20-byte knees consist of ten 16bit values (Knee0 in LSB)
               Due to the 16bit-big-endian format, the byte-order is:
               Knee1,Knee0,Knee3,Knee2,...,Knee17,Knee16,UNUSED,Knee18
  3640h  ..  RESERVED_SOC2_3640        Reserved
  3642h   2  POLY_ORIGIN_R             Center Row    (max 07FFh, def=025Ch)
  3644h   2  POLY_ORIGIN_C             Center Column (max 07FFh, def=0324h)
  3646h  ..  RESERVED_SOC2_3646-364C   Reserved
  364Eh 5x2  P_GR_P0Q0-4               P0Q for Green1  ;\P0 Coefficients
  3658h 5x2  P_RD_P0Q0-4               P0Q for Red     ; (5 x float16 each)
  3662h 5x2  P_BL_P0Q0-4               P0Q for Blue    ; (0010h,... each)
  366Ch 5x2  P_GB_P0Q0-4               P0Q for Green2  ;/
  3676h 5x2  P_GR_P1Q0-4               P1Q for Green1  ;\
  3680h 5x2  P_RD_P1Q0-4               P1Q for Red     ; P1 Coefficients
  368Ah 5x2  P_BL_P1Q0-4               P1Q for Blue    ; (5 x float16 each)
  3694h 5x2  P_GB_P1Q0-4               P1Q for Green2  ;/
  369Eh 5x2  P_GR_P2Q0-4               P2Q for Green1  ;\
  36A8h 5x2  P_RD_P2Q0-4               P2Q for Red     ; P2 Coefficients
  36B2h 5x2  P_BL_P2Q0-4               P2Q for Blue    ; (5 x float16 each)
  36BCh 5x2  P_GB_P2Q0-4               P2Q for Green2  ;/
  36C6h 5x2  P_GR_P3Q0-4               P3Q for Green1  ;\
  36D0h 5x2  P_RD_P3Q0-4               P3Q for Red     ; P3 Coefficients
  36DAh 5x2  P_BL_P3Q0-4               P3Q for Blue    ; (5 x float16 each)
  36E4h 5x2  P_GB_P3Q0-4               P3Q for Green2  ;/
  36EEh 5x2  P_GR_P4Q0-4               P4Q for Green1  ;\
  36F8h 5x2  P_RD_P4Q0-4               P4Q for Red     ; P4 Coefficients
  3702h 5x2  P_BL_P4Q0-4               P4Q for Blue    ; (5 x float16 each)
  370Ch 5x2  P_GB_P4Q0-4               P4Q for Green2  ;/
  3716h  ..  RESERVED_SOC2_3716-3278   Reserved


DSi Aptina Camera Variables: RAM/SFR/MON (GPIO/Monitor) (MCU:0000h-20xxh)

Internal RAM (MCU:0000h..0xxxh)
Internal RAM is reserved for whatever internal purposes (probably including for storing the 'logical variables' at MCU:2xxxh at some physical memory locations at MCU:0xxxh). However, some of those undocumented reserved RAM cells are manipulated by DSi games:
  02F0h   2  UNDOC_RAM_02F0   (set to 0000h by DSi games)
  02F2h   2  UNDOC_RAM_02F2   (set to 0210h by DSi games)
  02F4h   2  UNDOC_RAM_02F4   (set to 001Ah by DSi games)
Exact RAM Size is unknown (around 2Kbyte or so)? Some Aptina chips do also contain some sort of User RAM (at 0800h or so) for unknown purpose (just general purpose storage maybe). Unknown if the DSi chips are having any such User RAM.

Special Function Registers SFR (MCU:1040h..10FEh)
  1040h  ..  RESERVED_SFR_1040-1050    Reserved
  1060h  ..  RESERVED_SFR_1060-1066    Reserved (REV3)
  1070h   2  GPIO_DATA                 GPIO Data  (0..1E00h)
               0-8   Unused (0)
               9-12  gpio_3_0_data
               13-15 Unused (0)
  1072h   2  RESERVED_SFR_1072         Reserved
  1074h   2  GPIO_OUTPUT_SET           GPIO Set   (0..0C00h/1E00h?) (W)
               0-8   Unused (0)
               9-12  gpio_3_0_output_toggle (uh, toggle or set?)
               13-15 Unused (0)
  1076h   2  GPIO_OUTPUT_CLEAR         GPIO Clear (0..0C00h/1E00h?) (W)
               0-8   Unused (0)
               9-12  gpio_3_0_output_clear
               13-15 Unused (0)
  1078h   2  GPIO_DIR                  GPIO Direction (0..1E00h, def=1E00h)
               0-8   Unused (0)
               9     gpio_0_dir (0=Output, 1=Input) ;(LSB0 of 10bit Output)
               10    gpio_1_dir (0=Output, 1=Input) ;(LSB1 of 10bit Output)
               11    gpio_2_dir (0=Output, 1=Input) ;(Flash/Shutter Pulse)
               12    gpio_3_dir (0=Output, 1=Input) ;(OE_BAR for Databus)
               13-15 Unused (0)
  107Ah  ..  RESERVED_SFR_107A-10FD    Reserved

Monitor Variables MON (MCU:2000h..2025h)
  2000h   5  RESERVED_MON_00-04        Reserved
  2005h   1  MON_CMD                   Monitor Command (0..FFh)
  2006h   2  MON_ARG1                  Monitor First Argument (0..FFFFh)
  2008h  ..  RESERVED_MON_08-22        Reserved
  2024h   2  MON_PATCH_ID_0            Monitor First Patch (0..FFFFh) (REV1)
               0-7   mon_patch_0_version (00h-0Fh)
                       The version number of the first patch (R)
               8-15  mon_patch_0_number  (00h-0Fh)
                       Identifies which patch the first patch is (R)
  2024h   1  MON_PATCH_ID_0            (mask=FFh) (R) ;\unlike above  (REV3)
  2025h   1  MON_PATCH_ID_1            (0..FF)        ;/REV1 specs    (REV3)
  2026h   1  MON_PATCH_ID_2            (0..FF)                        (REV3)
  2027h   1  RESERVED_MON_27           Reserved                       (REV3)


DSi Aptina Camera Variables: SEQ (Sequencer) (MCU:21xxh)

Sequencer Variables SEQ (MCU:2100h..215Ah)
  2100h  ..  RESERVED_SEQ_00           Reserved
  2102h   1  SEQ_MODE                  SEQ Mode (enables "drivers") (def=0Fh)
               0    Enable AE   (ID=2)
               1    Enable FD   (ID=4)
               2    Enable AWB  (ID=3)
               3    Enable HG   (ID=11)
               4-7  Unspecified
  2103h   1  SEQ_CMD                   SEQ Cmd   (0..FFh, def=01h)
               0-7  Cmd   (0=Run, 1=Preview, 2=Capture, 3=Standby,
                          4=Lock, 5=Refresh, 6=Refresh Mode)
  2104h   1  SEQ_STATE                 SEQ State (0..FFh)
               0-7  State (0=Run, 1=ToPreview, 2=Enter, 3=Preview
                           4=Leave, 5=ToCapture, 6=Enter, 7=Capture,
                           8=Leave, 9=Standby)
  2105h  ..  RESERVED_SEQ_05           Reserved
  2106h   1  SEQ_FLASHTYPE             Type of flash to be used
               0-6 Flash Type (0=None, 1=LED, 2=Xenon, 3=XenonBurst)
               7   Set flash to LOCK mode (0=Normal, 1=LOCK mode)
  2107h  ..  RESERVED_SEQ_07-08        Reserved
  2109h   1  SEQ_AE_FASTBUFF           AE Fast Buff  (0..FFh, def=10h)
  210Ah   1  SEQ_AE_FASTSTEP           AE Fast Step  (0..FFh, def=02h)
  210Bh   1  SEQ_AWB_CONTBUFF          AWB Cont Buff (0..FFh, def=08h)
  210Ch   1  SEQ_AWB_CONTSTEP          AWB Cont Step (0..FFh, def=02h)
  210Dh  ..  RESERVED_SEQ_0D-10        Reserved
  2111h   1  SEQ_OPTIONS               SEQ Options (0..FFh, def=08h)
               0  Reserved
               1  Reserved
               2  Reserved
               3  seq_crop_win_ae, Use crop window for AE statistics
               4  seq_crop_win_awb, Use crop window for AWB statistics
               7  Reserved
  2112h  ..  RESERVED_SEQ_12           Reserved
  2113h   2  SEQ_FLASH_TH              SEQ Flash TH (0..FFFFh)
  2115h   1  SEQ_CAP_MODE              Capture mode (in Capture state only)
               0  Xenon Flash (Still Only)
               1  Video
               2  Turn Flash off before last frame in capture state
               4  Video AE on
               5  Video AWB on
               6  Video HG on
  2116h   1  SEQ_CAP_NUMFRAMES         Num still frames captured (0..FFh,def=3)
  2117h   1  SEQ_PREVIEW_0_AE          Preview 0 AE (PREVIEW ENTER)     ;\
               0-3  AE (0=Off, 1=Fast, 2=Manual, 3=Continuous, 4=MDR)   ;
               4-7  Unspecified (0..5) (0..0Fh for PREVIEW_2/3)         ; Pre-
  2118h   1  SEQ_PREVIEW_0_FD          Preview 0 FD (PREVIEW ENTER)     ; view
               0-7  FD (0=Off, 1=Continuous, 2=Manual)                  ; 0
  2119h   1  SEQ_PREVIEW_0_AWB         Preview 0 AWB (PREVIEW ENTER)    ;
               0-7  AWB (0=Off, 1=On)                                   ; PRE-
  211Ah   1  SEQ_PREVIEW_0_HG          Preview 0 HG (PREVIEW ENTER)     ; VIEW
               0-7  HG (0=Off, 1=Fast, 2=Manual, 3=Continuous)          ; ENTER
  211Bh   1  SEQ_PREVIEW_0_FLASH       Flash Config (0..FFh)            ;
               0-6 Flash (0=Off,1=On,2=Locked,3=AutoEvaluate,7=UserDef) ;
               7   Reserved                                             ;
  211Ch   1  SEQ_PREVIEW_0_SKIPFRAME   Skipframe State Config (def=40h) ;
               0-3 Unspecified                                          ;
               4   Unspecified (except PREVIEW_2: Reserved)             ;
               5   Skip_led_on                                          ;
               6   Skip_state (0=No skip state, 1=Skip state)           ;
               7   Turn_off_fen                                         ;/
  211Dh   1  SEQ_PREVIEW_1_AE            ;\                             def=01h
  211Eh   1  SEQ_PREVIEW_1_FD            ; Preview 1 (PREVIEW)          def=01h
  211Fh   1  SEQ_PREVIEW_1_AWB           ; (same as Preview 0, but      def=01h
  2120h   1  SEQ_PREVIEW_1_HG            ; without AE=MDR,              def=01h
  2121h   1  SEQ_PREVIEW_1_FLASH         ; without HG=Manual/Continous)
  2122h   1  SEQ_PREVIEW_1_SKIPFRAME     ;/                             def=N/A
  2123h   1  SEQ_PREVIEW_2_AE            ;\
  2124h   1  SEQ_PREVIEW_2_FD            ; Preview 2 (PREVIEW LEAVE)
  2125h   1  SEQ_PREVIEW_2_AWB           ; (same as Preview 0, but
  2126h   1  SEQ_PREVIEW_2_HG            ; without HG=Manual/Continous)
  2127h   1  SEQ_PREVIEW_2_FLASH         ;
  2128h   1  SEQ_PREVIEW_2_SKIPFRAME     ;/
  2129h   1  SEQ_PREVIEW_3_AE            ;\
  212Ah   1  SEQ_PREVIEW_3_FD            ; Preview 3 (CAPTURE ENTER)
  212Bh   1  SEQ_PREVIEW_3_AWB           ; (same as Preview 0)
  212Ch   1  SEQ_PREVIEW_3_HG            ;
  212Dh   1  SEQ_PREVIEW_3_FLASH         ;
  212Eh   1  SEQ_PREVIEW_3_SKIPFRAME     ;/
  212Fh  ..  RESERVED_SEQ_2F-33        Reserved
  2134h   1  UNDOC_SEQ_34              (0..FFh)
  2135h  ..  RESERVED_SEQ_35-44        Reserved
  2145h   2  UNDOC_SEQ_45              (0..FFFFh)
  2147h  ..  RESERVED_SEQ_47-59        Reserved


DSi Aptina Camera Variables: AE (Auto Exposure) (MCU:22xxh)

Auto Exposure Variables AE (MCU:2200h-2261h)
  2200h  ..  RESERVED_AE_00            Reserved
  2202h   1  AE_WINDOW_POS             AE Window Position Y0 and X0
               0-3  X0 (in units of 1/16th of frame width)  (0..0Fh)
               4-7  Y0 (in units of 1/16th of frame height) (0..0Fh)
  2203h   1  AE_WINDOW_SIZE            AE Window Height and Width (def=FFh)
               0-3  Width  (units of 1/16th of frame width, minus 1)  (0..0Fh)
               4-7  Height (units of 1/16th of frame height, minus 1) (0..0Fh)
  2204h  ..  RESERVED_AE_04            Reserved
  2206h   1  AE_TARGET                 AE Target Brightness (0..FFh, def=32h)
  2207h   1  AE_GATE                   AE Sensitivity       (0..FFh, def=04h)
  2208h  ..  UNDOC_AE_08               (0..FFh, def=02h)
  2209h  ..  RESERVED_AE_09-0A         Reserved
  220Bh   1  AE_MIN_INDEX              Min                      (0-FFh)
  220Ch   1  AE_MAX_INDEX              Max allowed zone number  (0-FFh,def=18h)
  220Dh   1  AE_MIN_VIRTGAIN           Min allowed virtual gain (0-FFh,def=10h)
  220Eh   1  AE_MAX_VIRTGAIN           Max allowed virtual gain (0-FFh,def=80h)
  220Fh  ..  RESERVED_AE_0F-11         Reserved
  2212h   2  AE_MAX_DGAIN_AE1          Max digital gain pre-LC  (def=8000h)
  2214h  ..  RESERVED_AE_14-16         Reserved
  2217h   1  AE_STATUS                 AE Status
               0   AE_at_limit (1=AE reached limit)
               1   R9_changed  (1=Need to skip frame)
               2   Ready       (0=AE not ready, 1=AE ready)
               3-7 Unused (0)
  2218h   1  AE_CURRENT_Y              Last measured luma   (0-FFh,def=4Bh) (R)
  2219h   2  AE_R12                    Curr shutter delay       (def=0279h) (R)
  221Bh   1  AE_INDEX                  Curr zone integration time (def=04h) (R)
  221Ch   1  AE_VIRTGAIN               Curr virtual gain    (0-FFh,def=10h) (R)
  221Dh  ..  RESERVED_AE_1D-1E         Reserved
  221Fh   2  AE_DGAIN_AE1              Current digital gain pre-LC (def=0080h)
  2221h  ..  RESERVED_AE_21            Reserved
  2222h   2  AE_R9                     Current R9:0 value (0-FFFFh, def=0010h)
  2224h  ..  RESERVED_AE_24-2C         Reserved
  222Dh   2  AE_R9_STEP                Integration time per zone   (def=009Dh)
  222Fh  ..  RESERVED_AE_2F-49         Reserved
  224Ah   1  AE_TARGETMIN              Min value for target  (0..FFh, def=32h)
  224Bh   1  AE_TARGETMAX              Max value for target  (0..FFh, def=96h)
  224Ch   1  AE_TARGETBUFFERSPEED      Target Buffer Speed   (0..FFh, def=0Ch)
  224Dh  ..  RESERVED_AE_4D            Reserved
  224Fh   1  AE_BASETARGET             Target Base           (0..FFh, def=36h)
  2250h  ..  RESERVED_AE_50-61         Reserved
  2262h  ..  RESERVED_AE_62-64         Reserved (REV3)


DSi Aptina Camera Variables: AWB (Auto White Balance) (MCU:23xxh)

Auto White Balance Variables AWB (MCU:2300h..236Eh)
  2300h  ..  RESERVED_AWB_00           Reserved
  2302h   1  AWB_WINDOW_POS            AWB Window Position Y0 and X0
               0-3  X0 (in units of 1/16th of frame width)  (0..0Fh)
               4-7  Y0 (in units of 1/16th of frame height) (0..0Fh)
  2303h   1  AWB_WINDOW_SIZE           AWB Window Size (def=EFh)
               0-3  Width  (units of 1/16th of frame width, minus 1)  (0..0Fh)
               4-7  Height (units of 1/16th of frame height, minus 1) (0..0Fh)
  2304h  ..  RESERVED_AWB_04           Reserved
  2306h 3x2  AWB_CCM_L_0-2             Left CCM K11,K12,K13 (0180h,FF00h,0080h)
  230Ch 3x2  AWB_CCM_L_3-5             Left CCM K21,K22,K23 (FF66h,0180h,FFEEh)
  2312h 3x2  AWB_CCM_L_6-8             Left CCM K31,K32,K33 (FFCDh,FECDh,019Ah)
  2318h   2  AWB_CCM_L_9               Left CCM Red/Green gain  (0020h)
  231Ah   2  AWB_CCM_L_10              Left CCM Blue/Green gain (0033h)
  231Ch 3x2  AWB_CCM_RL_0-2            DeltaCCM D11,D12,D13 (0100h,FF9Ah,xxxxh)
  2322h 3x2  AWB_CCM_RL_3-5            DeltaCCM D21,D22,D23 (004Dh,FFCDh,FFB8h)
  2328h 3x2  AWB_CCM_RL_6-8            DeltaCCM D31,D32,D33 (004Dh,0080h,FF66h)
  232Eh   2  AWB_CCM_RL_9              DeltaCCM Red/Green gain  (0008h)
  2330h   2  AWB_CCM_RL_10             DeltaCCM Blue/Green gain (FFF7h)
  2332h 3x2  AWB_CCM_0-2               Curr CCM C11,C12,C13 (01BAh,FF5Bh,FFF1h)
  2338h 3x2  AWB_CCM_3-5               Curr CCM C21,C22,C23 (FFC7h,01B9h,FF87h)
  233Eh 3x2  AWB_CCM_6-8               Curr CCM C31,C32,C33 (FFF9h,FF32h,01DCh)
  2344h   2  AWB_CCM_9                 Curr CCM Red/Green gain  (003Ch)
  2346h   2  AWB_CCM_10                Curr CCM Blue/Green gain (002Bh)
  2348h   1  AWB_GAIN_BUFFER_SPEED     Gain Speed (1-20h, def=08h, 20h=fastest)
  2349h   1  AWB_JUMP_DIVISOR          Jump Divisor (1-FFh, def=02h, 1=fastest)
  234Ah   1  AWB_GAIN_MIN              Min AWB Red     (def=59h) ;\Digital Gain
  234Bh   1  AWB_GAIN_MAX              Max allowed Red (def=B6h) ; Min/max
  234Ch   1  AWB_GAINMIN_B             Min AWB         (def=59h) ; (0..FFh)
  234Dh   1  AWB_GAINMAX_B             Max allowed     (def=A6h) ;/
  234Eh   1  AWB_GAIN_R                Current R digital gain    ;\Current Gain
  234Fh   1  AWB_GAIN_G                Current G digital gain    ; (0..FFh,
  2350h   1  AWB_GAIN_B                Current B digital gain    ;/def=80h)
  2351h   1  AWB_CCM_POSITION_MIN      Min/Left  (def=?)   ;\(range 0..FFh,
  2352h   1  AWB_CCM_POSITION_MAX      Max/Right (def=7Fh) ; 00h=incandescent,
  2353h   1  AWB_CCM_POSITION          Position  (def=40h) ;/7Fh=daylight)
  2354h   1  AWB_SATURATION            Saturation (0..FFh, def=80h, 80h=100%)
  2355h   1  AWB_MODE                  Misc control for AWB (0..FFh)
               0  Steady         (1=AWB is done)
               1  Limits Reached (1=AWB limit is reached)
               2  Reserved
               3  Reserved
               4  Reserved
               5  Force_unit_dgains
               6  NormCCM_off
  2356h   2  AWB_GAINR_BUF             Time-buffered R gain (0..FFFFh)
  2358h   2  AWB_GAINB_BUF             Time-buffered B gain (0..FFFFh)
  235Ah  ..  RESERVED_AWB_5A-5C        Reserved
  235Dh   1  AWB_STEADY_BGAIN_OUT_MIN  (0-FF, def=78h)
  235Eh   1  AWB_STEADY_BGAIN_OUT_MAX  (0-FF, def=86h)
  235Fh   1  AWB_STEADY_BGAIN_IN_MIN   (0-FF, def=7Eh)
  2360h   1  AWB_STEADY_BGAIN_IN_MAX   (0-FF, def=82h)
  2361h   2  UNDOC_AWB_61              (0..FFFFh, def=0040h)
  2363h   1  AWB_TG_MIN0               True Gray minimum (0..FFh, def=D2h)
  2364h   1  AWB_TG_MAX0               True Gray maximum (0..FFh, def=F6h)
  2365h   1  AWB_X0                    (0-FFh, def=10h)
  2366h   1  AWB_KR_L                  (0-FFh, def=80h)
  2367h   1  AWB_KG_L                  (0-FFh, def=80h)
  2368h   1  AWB_KB_L                  (0-FFh, def=80h)
  2369h   1  AWB_KR_R                  (0-FFh, def=80h)
  236Ah   1  AWB_KG_R                  (0-FFh, def=80h)
  236Bh   1  AWB_KB_R                  (0-FFh, def=80h)
  236Ch  ..  RESERVED_AWB_6C-6E        Reserved


DSi Aptina Camera Variables: FD (Anti-Flicker) (MCU:24xxh)

Anti-Flicker Variables FD (MCU:2400h..247Bh)
  2400h  ..  RESERVED_FD_00            Reserved
  2402h   1  FD_WINDOW_POSH            Window Pos H (0..FFh, def=1Dh)
               0-3  Width (in units of 1/16th of frame width, minus 1) (0..0Fh)
               4-7  X0 (=position/origin or so?) (0..0Fh)
  2403h   1  FD_WINDOW_HEIGHT          FlickerMeasurementWindowHeight (def=04h)
               0-5  Flicker measurement window height in rows (0..3Fh)
               6-7  Unspecified
  2404h   1  FD_MODE                   Flicked Detection switches/indicators
               0-3  Reserved      (0..0Fh) (R)
               4    Debug_mode    (0=Disable, 1=Enable single period mode)
               5    Curr Flicker State (0=60Hz, 1=50Hz) (R)
               6    Curr Settings (0=60Hz, 1=50Hz)
               7    Manual Mode   (0=Disable, 1=Enable)
  2405h  ..  RESERVED_FD_05-07         Reserved
  2408h   1  FD_SEARCH_F1_50           Search F1 50Hz  (0..FFh, def=33h)
  2409h   1  FD_SEARCH_F2_50           Search F2 50Hz  (0..FFh, def=35h)
  240Ah   1  FD_SEARCH_F1_60           Search F1 60Hz  (0..FFh, def=29h)
  240Bh   1  FD_SEARCH_F2_60           Search F2 60Hz  (0..FFh, def=2Bh)
  240Ch   1  UNDOC_FD_0C               (0..FFh)
  240Dh   1  FD_STAT_MIN               Stat Min (0..FFh, def=03h)
  240Eh   1  FD_STAT_MAX               Stat Max (0..FFh, def=05h)
  240Fh  ..  RESERVED_FD_0F            Reserved
  2410h   1  FD_MIN_AMPLITUDE          Ignore Signals below Min (0..FFh, def=5)
  2411h   2  FD_R9_STEP_F60_A          60HzA (def=0D4h) ;\Minimal Shutter Width
  2413h   2  FD_R9_STEP_F50_A          50HzA (def=103h) ; Steps for 60Hz/50H AC
  2415h   2  FD_R9_STEP_F60_B          60HzB (def=09Dh) ; in Context A/B
  2417h   2  FD_R9_STEP_F50_B          50HzB (def=0B8h) ;/(0..FFFFh)
  2419h  ..  RESERVED_FD_19-7B         Reserved


DSi Aptina Camera Variables: MODE (Mode/Context) (MCU:27xxh)

Mode Variables MODE (MCU:2700h..2768h)
  2700h  ..  RESERVED_MODE_00-02              Reserved
  2703h   2  MODE_OUTPUT_WIDTH_A        (CX)  (0..FFFFh, def=0320h)  ;\Size A
  2705h   2  MODE_OUTPUT_HEIGHT_A       (CY)  (0..FFFFh, def=0258h)  ;/
  2707h   2  MODE_OUTPUT_WIDTH_B              (0..FFFFh, def=0640h)  ;\Size B
  2709h   2  MODE_OUTPUT_HEIGHT_B             (0..FFFFh, def=04B0h)  ;/
  270Bh   1  MODE_A_MIPI_VC                   (0..07h) (REV3)        ;-Mipi A
  270Ch   1  MODE_B_MIPI_VC                   (0..07h) (REV3)        ;-Mipi B
  270Dh   2  MODE_SENSOR_ROW_START_A    (Y1)  (0..FFFFh)             ;\
  270Fh   2  MODE_SENSOR_COL_START_A    (X1)  (0..FFFFh)             ;
  2711h   2  MODE_SENSOR_ROW_END_A      (Y2)  (0..FFFFh, def=040Dh)  ;
  2713h   2  MODE_SENSOR_COL_END_A      (X2)  (0..FFFFh, def=050Dh)  ; Sensor
  2715h   2  MODE_SENSOR_ROW_SPEED_A          (0..0777h, def=0112h)  ; A
               0-2:  pixclk_speed (0..7)                             ;
                       1ADC: Pclk = 2 mclks * bits[0:2]              ;
                       2ADC: bits[0:2]                               ;
               4-6:  Reserved (0..7)                                 ;
               8-10: Reserved (0..7)                                 ;
  2717h   2  MODE_SENSOR_READ_MODE_A          (0..FFFFh, def=046Ch)  ;
               0:   horiz_mirror                                     ;
               1:   vert_flip                                        ;
               2-4: y_odd_inc (0..7)                                 ;
               5-7: x_odd_inc (0..7)                                 ;
               9:   low_power                                        ;
               10:  xy_bin_en                                        ;
               11:  x_bin_en                                         ;
  2719h   2  MODE_SENSOR_FINE_CORRECTION_A    (0..FFFFh, def=007Bh)  ;
  271Bh   2  MODE_SENSOR_FINE_IT_MIN_A        (0..FFFFh, def=0408h)  ;
  271Dh   2  MODE_SENSOR_FINE_IT_MAX_MARGIN_A (0..FFFFh, def=00ABh)  ;
  271Fh   2  MODE_SENSOR_FRAME_LENGTH_A       (0..FFFFh, def=0293h)  ;
  2721h   2  MODE_SENSOR_LINE_LENGTH_PCK_A    (0..FFFFh, def=07D0h)  ;/
  2723h   2  MODE_SENSOR_ROW_START_B          (0..FFFFh, def=0004h)  ;\
  2725h   2  MODE_SENSOR_COL_START_B          (0..FFFFh, def=0004h)  ; Sensor
  2727h   2  MODE_SENSOR_ROW_END_B            (0..FFFFh, def=040Bh)  ; B
  2729h   2  MODE_SENSOR_COL_END_B            (0..FFFFh, def=050Bh)  ;
  272Bh   2  MODE_SENSOR_ROW_SPEED_B          (0..0777h, def=0111h)  ; (same
  272Dh   2  MODE_SENSOR_READ_MODE_B          (0..FFFFh, def=0024h)  ; as
  272Fh   2  MODE_SENSOR_FINE_CORRECTION_B    (0..FFFFh, def=00A4h)  ; Sensor
  2731h   2  MODE_SENSOR_FINE_IT_MIN_B        (0..FFFFh, def=0408h)  ; A, see
  2733h   2  MODE_SENSOR_FINE_IT_MAX_MARGIN_B (0..FFFFh, def=00A4h)  ; there)
  2735h   2  MODE_SENSOR_FRAME_LENGTH_B       (0..FFFFh, def=04EDh)  ;
  2737h   2  MODE_SENSOR_LINE_LENGTH_PCK_B    (0..FFFFh, def=0D06h)  ;/
  2739h   2  MODE_CROP_X0_A                   (0..FFFFh)             ;\
  273Bh   2  MODE_CROP_X1_A                   (0..FFFFh, def=031Fh)  ; Crop A
  273Dh   2  MODE_CROP_Y0_A                   (0..FFFFh)             ;
  273Fh   2  MODE_CROP_Y1_A                   (0..FFFFh, def=0257h)  ;/
  2741h  ..  RESERVED_MODE_41-45              Reserved
  2747h   2  MODE_CROP_X0_B                   (0..FFFFh)             ;\
  2749h   2  MODE_CROP_X1_B                   (0..FFFFh, def=063Fh)  ; Crop B
  274Bh   2  MODE_CROP_Y0_B                   (0..FFFFh)             ;
  274Dh   2  MODE_CROP_Y1_B                   (0..FFFFh, def=04AFh)  ;/
  274Fh  ..  RESERVED_MODE_4F-53              Reserved
  2755h   2  MODE_OUTPUT_FORMAT_A             Format A (0..FFFFh     ;\
  2757h   2  MODE_OUTPUT_FORMAT_B             Format B (0..FFFFh     ;
               0     swap_channels (swap Cb/Cr in YUV and R/B in RGB);
               1     swap_chrominance_luma                           ; Format
               2     bayer_out (Progressive Bayer)                   ; A/B
               3     monochrome (0..1)                               ;
               4     Reserved                                        ;
               5     output_mode (0=YUV, 1=RGB)                      ;
               6-7   RGB Format (0=565, 1=555, 2=444xh, 3:x444h)     ;
               8     Processed Bayer (0..1)                          ;
               9     Invert out_clk (0..1) (REV3)                    ;
               10-15 Unspecified                                     ;/
  2759h   2  MODE_SPEC_EFFECTS_A              Effects A  (def=6440h) ;\
  275Bh   2  MODE_SPEC_EFFECTS_B              Effects B  (def=6440h) ;
               0-2  Selection (1=Mono, 2=Sepia, 3=Negative,          ; Effects
                      4=Solarization, 5=Solarization w/ UV)          ; A/B
               3-5  Dither_bitwidth                                  ;
               6    Dither_luma                                      ;
               8-15 Solarization Threshold (0..7 for diff effects)   ;/
  275Dh   1  MODE_Y_RGB_OFFSET_A              Offset A (00h..FFh)    ;\Offset
  275Eh   1  MODE_Y_RGB_OFFSET_B              Offset B (00h..FFh)    ;/A/B
  275Fh   2  MODE_COMMON_MODE_SETTINGS_BRIGHT_COLOR_KILL             ;\
               Shadow register for 35A4h in SOC2                     ;
               0-2   Color kill saturation point (0..7)              ; Kill
               3-5   Bright color kill gain      (0..7)              ; Bright
               6-8   Bright color kill threshold (0..7)              ;
               9     Signal_ctrl (1=use luma as min/max value)       ;
               10    en_kl       (1=enable bright color kill)        ;
               11-15 Unspecified                                     ;/
  2761h   2  MODE_COMMON_MODE_SETTINGS_DARK_COLOR_KILL               ;\
               Shadow register for 35A2h in SOC2                     ;
               0-2   Dark color kill gain      (0..7)                ; Kill
               3-5   Dark color kill threshold (0..7)                ; Dark
               6     Signal_ctrl (1=use luma as min/max value)       ;
               7     en_dark_kl  (1=enable dark color kill)          ;
               8-15  Unspecified                                     ;/
  2763h   2  MODE_COMMON_MODE_SETTINGS_FX_SEPIA_SETTINGS             ;\
               0-7   Sepia constants for Cr (00h..FFh)               ; Sepia
               8-15  Sepia constants for Cb (00h..FFh)               ;/
  2765h   1  MODE_COMMON_MODE_SETTINGS_FILTER_MODE                   ;\
               Shadow register for 326Eh in SOC1                     ;
               0-2   UV Filter mode (0..7)                           ; Filter
               3-4   Y Filter mode  (0..3)                           ;
               5     Enable_y_filter (enable y permanently)          ;
               6     Threshold_switch, switch for adaptive Y filter threshold
               7     Off_switch, B/W filter enable switch            ;/
  2766h   1  MODE_COMMON_MODE_SETTINGS_TEST_MODE   Test (00h..FFh)
               0-?  Test Pattern (0=None?, 1=Flat, 2=Ramp, 3=ColorBars,
                    4=VertStripes, 5=Noise, 6=HoriStripes)
               Output test pattern (instead camera image)
               requires "Refresh Command" sent to Sequencer
  2767h  ..  RESERVED_MODE_67-68                   Reserved


DSi Aptina Camera Variables: HG (Histogram) (MCU:2Bxxh)

Histogram Variables HG (MCU:2B00h..2B61h)
  2B00h  ..  RESERVED_HG_00-03         Reserved
  2B04h   1  HG_MAX_DLEVEL             DarkLevel Limit (0..FFh, def=40h)
  2B05h  ..  RESERVED_HG_05            Reserved
  2B06h   1  HG_PERCENT                Percent?        (0..FFh, def=03h)
  2B07h  ..  RESERVED_HG_07            Reserved
  2B08h   1  HG_DLEVEL                 DarkLevel       (0..FFh, def=10h)
  2B09h  ..  RESERVED_HG_09-16         Reserved
  2B17h   1  HG_AVERAGELUMA            Average Luma      (0..FFh)
  2B18h  ..  RESERVED_HG_18-1A         Reserved
  2B1Bh   2  HG_BRIGHTNESSMETRIC       Brightness Metric (0..FFFFh)
  2B1Dh  ..  RESERVED_HG_1D            Reserved
  2B1Fh   1  HG_LLMODE                 Low Light mode controls (def=C4h)
               0-3  Brightness Metric Prescaler (01h..0Fh)
               4-5  Unused (0)
               6    HG_2d_corr_vs_clusterdc
               7    Clusterdc_vs_gains
  2B20h   1  HG_LL_SAT1                LL_SAT1            (0..FFh, def=43h)
  2B21h   1  UNDOC_HG_21               Whatever           (0..FFh, def=10h)
  2B22h   1  HG_LL_APCORR1             LL_APCORR1         (0..FFh, def=03h)
  2B23h   1  UNDOC_HG_23               Whatever           (0..FFh, def=04h)
  2B24h   1  HG_LL_SAT2                LL_SAT2            (0..FFh, def=0Ch)
  2B25h   1  HG_LL_INTERPTHRESH2       LL_INTERPTHRESH2   (0..FFh, def=23h)
  2B26h   1  HG_LL_APCORR2             LL_APCORR2         (0..FFh)
  2B27h   1  HG_LL_APTHRESH2           LL_APTHRESH2       (0..FFh, def=04h)
  2B28h   2  HG_LL_BRIGHTNESSSTART     LL_BRIGHTNESSSTART (0..FFFFh, def=0A8Ch)
  2B2Ah   2  HG_LL_BRIGHTNESSSTOP      LL_BRIGHTNESSSTOP  (0..FFFFh, def=34BCh)
  2B2Ch   1  HG_NR_START_R             NR_START_R         (0..FFh, def=06h)
  2B2Dh   1  HG_NR_START_G             NR_START_G         (0..FFh, def=0Eh)
  2B2Eh   1  HG_NR_START_B             NR_START_B         (0..FFh, def=06h)
  2B2Fh   1  HG_NR_START_OL            NR_START_OL        (0..FFh, def=06h)
  2B30h   1  HG_NR_STOP_R              NR_STOP_R          (0..FFh, def=1Eh)
  2B31h   1  HG_NR_STOP_G              NR_STOP_G          (0..FFh, def=1Eh)
  2B32h   1  HG_NR_STOP_B              NR_STOP_B          (0..FFh, def=1Eh)
  2B33h   1  HG_NR_STOP_OL             NR_STOP_OL         (0..FFh, def=1Eh)
  2B34h   1  HG_NR_GAINSTART           NR_GAINSTART       (0..FFh, def=08h)
  2B35h   1  HG_NR_GAINSTOP            NR_GAINSTOP        (0..FFh, def=80h)
  2B36h   1  HG_CLUSTERDC_TH           CLUSTERDC_TH       (0..FFh, def=1Eh)
  2B37h   1  HG_GAMMA_MORPH_CTRL       Gamma Morphing Control (0..FFh, def=3)
               0-1 Enable Gamma Morph (0=Disable, 1=Use Table A, 2=Use Table B,
                   3=AutoMorph between Table A and B based on BrightnessMetric)
               2-7 Unspecified
  2B38h   2  HG_GAMMASTARTMORPH        Gamma Start Morph (0..FFFFh, def=0A8Ch)
  2B3Ah   2  HG_GAMMASTOPMORPH         Gamma Stop Morph  (0..FFFFh, def=34BCh)
  2B3Ch  19  HG_GAMMA_TABLE_A_0-18     Gamma Table A for normal light condition
              Default=xx,1B,2E,4C,78,98,B0,E8,CF,D9,E1,E8,EE,F2,F6,F9,FB,FD,FF
  2B4Fh  19  HG_GAMMA_TABLE_B_0-18     Gamma Table B for low light condition
              Default=xx,0F,1A,2E,50,6A,80,91,A1,AF,BB,C6,D0,D9,E2,EA,F1,F9,FF
              Above 2 tables have normal byte-order (Entry0,Entry1,...,Entry18)
  2B62h   2  HG_FTB_START_BM           (0..FFFFh, def=7FBCh) (REV3)
  2B64h   2  HG_FTB_STOP_BM            (0..FFFFh, def=82DCh) (REV3)
  2B66h   2  HG_CLUSTER_DC_BM          (0..FFFFh, def=4A38h) (REV3)


DSi Alternate Cameras from Unknown Manufacturer

Device A0h/E0h appear to be cameras from an alternate manufacturer. DSi games are supporting these devices, but as by now, there aren't any DSi consoles known to be actually fitted with these cameras.
The camera type & manufacturer are still unknown. Below initialization data is containing some characterstic info that should allow to identify them. For example, register 03h appears to be bank-switching the other registers.

unknown_cam_get_chip_id:
Reading an 8bit value from index 00h (in any bank?) seems to return some Chip ID, at least the DSi is reading that register before initialization (despite of reading it, the DSi does appear to ignore that value though).
Note: On a DSi with Aptina cameras, trying to read anything from I2C devices A0h/E0h does just return FFh-bytes.

Formatting Note
Below tables consist of "Index,Length,Data[Length]" entries.

unknown_cam_type_code_list_init:
  003h, 1,001h               ;<-- bank maybe?
  009h, 3,0E2h,002h,002h
  004h, 1,010h
  004h, 1,0A0h
  004h, 2,090h,04Ch
  00Dh, 1,0FFh
  016h, 1,053h
  018h, 3,002h,001h,00Fh
  020h, 1,000h
  023h, 2,000h,000h
  034h, 8,000h,003h,000h,003h,001h,002h,000h,0C2h
  03Dh, 4,050h,050h,000h,067h
  042h, 1,01Ch
  04Ah, 2,043h,0F8h
  04Eh, 7,028h,0FCh,000h,024h,014h,008h,008h
  056h,13,000h,018h,028h,034h,044h,056h,06Eh,080h,0A4h,0C2h,0D6h,0E8h,0F4h
  065h,12,00Fh,038h,008h,000h,01Fh,01Fh,01Fh,01Fh,01Fh,01Fh,01Fh,01Fh
  07Ah,17,039h,03Bh,03Ah,036h,03Ch,03Ch,03Ah,03Ch,03Ch,03Ch,03Ah,03Ch,038h
          03Ah,031h,03Ah,082h
  08Dh,22,08Ah,090h,096h,09Ch,0A4h,0AAh,0B0h,0B6h,0BCh,0C4h,0CAh,0D0h,0D6h
          0DCh,0E4h,0EAh,0F0h,0F2h,0F4h,0F6h,0F8h,0FAh
  0A9h, 1,02Bh
  0ABh, 3,02Eh,000h,050h
  0AFh, 1,070h
  0B2h, 4,03Ch,068h,049h,070h
  0B7h,21,032h,000h,00Eh,0F8h,00Ch,07Ah,040h,000h,000h,010h,044h,064h,052h
          012h,001h,0D7h,004h,002h,024h,002h,024h
  0D4h, 5,004h,004h,008h,00Ah,010h
  016h, 1,0F7h
  0DEh, 2,002h,024h
  016h, 1,053h
  0E1h, 1,034h
  0FFh, 1,00Fh
  003h, 1,002h               ;<-- bank maybe?
  005h, 2,06Dh,004h
  011h, 4,004h,048h,004h,048h
  016h, 2,00Ch,0D8h
  019h, 2,00Ch,0D8h
  01Eh, 6,002h,024h,070h,000h,001h,06Eh
  026h, 7,008h,00Fh,00Fh,006h,0FFh,0FFh,003h
  02Eh,19,07Eh,088h,074h,07Eh,008h,010h,080h,008h,084h,078h,001h,003h,00Ah
          025h,060h,0B0h,006h,000h,000h
  042h, 7,080h,010h,010h,010h,040h,080h,0FFh
  04Ah,30,000h,000h,001h,0E5h,001h,0E0h,000h,070h,002h,0F0h,000h,02Eh,001h
          0F3h,000h,005h,000h,000h,001h,000h,000h,0C0h,000h,026h,000h,01Ch
          000h,0B3h,000h,086h
  069h,36,000h,000h,006h,014h,014h,01Fh,000h,000h,000h,000h,000h,01Fh,000h
          000h,010h,010h,010h,01Fh,000h,000h,004h,004h,004h,01Fh,000h,000h
          000h,000h,000h,01Fh,000h,000h,010h,010h,010h,01Fh
  095h, 1,084h
  097h,18,002h,000h,0FFh,0FFh,000h,0FFh,0FFh,000h,000h,0FFh,0FFh,000h,0FFh
          0FFh,000h,0F8h,014h,010h
  0AAh,13,044h,098h,08Ch,09Ch,048h,08Ch,08Ah,09Ch,046h,02Ah,080h,008h,026h
  0B8h, 8,02Ah,084h,000h,026h,02Ah,080h,008h,020h
  0C1h,10,038h,020h,01Fh,01Dh,034h,020h,01Fh,01Dh,045h,05Dh
  0CCh, 2,020h,020h
  0D0h, 3,080h,000h,0FFh
  003h, 1,000h               ;<-- bank maybe?
  013h, 2,000h,04Ch
  01Dh, 2,000h,04Ch
  015h, 2,001h,05Fh
  055h, 2,001h,05Eh
  031h, 6,006h,068h,00Ch,005h,004h,047h
  047h, 2,000h,003h
  04Ah, 3,0A0h,000h,003h
  04Fh, 2,000h,003h
  059h, 2,000h,001h
  05Fh, 2,000h,001h
  066h, 1,09Eh
  06Eh, 2,07Fh,003h
  075h, 1,050h
  07Ah, 2,000h,001h
  07Eh, 1,020h
  082h, 1,038h
  084h,14,003h,040h,003h,040h,000h,000h,040h,003h,0FFh,002h,008h,020h,018h,006h
  093h,11,020h,040h,040h,01Fh,002h,000h,000h,000h,000h,000h,000h
  003h, 1,001h               ;<-- bank maybe?
  00Fh, 1,0C9h                    ;or, for Device E0h: 00Fh, 1,0C8h
  052h, 3,004h,008h,008h          ;or, for Device E0h: N/A
  003h, 1,002h               ;<-- bank maybe?
  026h, 1,008h                    ;or, for Device E0h: 026h, 1,000h
  0CCh, 2,0C0h,0C0h               ;or, for Device E0h: N/A
  0B4h, 1,000h                    ;or, for Device E0h: N/A
  0B6h, 1,026h                    ;or, for Device E0h: N/A
  0B9h, 3,000h,008h,026h          ;or, for Device E0h: N/A
  0BDh, 1,000h                    ;or, for Device E0h: N/A
  026h, 1,008h                    ;or, for Device E0h: N/A
  003h, 1,001h               ;<-- bank maybe?
  02Dh, 1,0FFh
  004h, 1,020h

unknown_cam_type_code_list_activate:
  003h, 1,002h               ;<-- bank maybe?
  0A7h, 1,014h
  003h, 1,001h               ;<-- bank maybe?
  004h, 1,0A0h
  004h, 1,090h
  02Dh, 1,000h
  004h, 1,098h

Random Note
This info is probably not really helpful, but the DSi firmware contains code for setting Register C1h..C9h (within unknown bank) to one of the following twelve settings.
  C1h, 8,038h,030h,01Fh,01Fh,02Ch,030h,01Fh,01Fh
  C1h, 8,038h,030h,01Fh,01Fh,038h,030h,01Fh,01Fh
  C1h, 8,02Ch,030h,01Fh,01Fh,02Ch,030h,01Fh,01Fh
  C1h, 8,02Ch,030h,01Fh,01Fh,02Ch,030h,01Fh,01Fh
  C1h, 8,02Ch,030h,01Fh,01Fh,02Ch,030h,01Fh,01Fh
  C1h, 8,02Ch,030h,01Fh,01Fh,02Ch,030h,01Fh,01Fh
  C1h, 8,030h,028h,018h,018h,034h,028h,008h,018h
  C1h, 8,030h,028h,018h,018h,030h,028h,008h,018h
  C1h, 8,028h,028h,018h,018h,028h,028h,008h,018h
  C1h, 8,028h,028h,018h,018h,028h,028h,008h,018h
  C1h, 8,028h,028h,018h,018h,028h,028h,008h,018h
  C1h, 8,028h,028h,018h,018h,028h,028h,008h,018h


DSi Cameras

Camera registers
Cameras are controlled and initialized via I2C bus (on ARM7 side).
DSi I2C Bus
The actual camera data transfers are done with below registers (on ARM9 side).

4004200h - DSi9 - CAM_MCNT - Camera Module Control
  0     Unknown                                                      (R or R/W)
  1     Unknown (1=Enable?)                                          (R or R/W)
  2-4   Unknown                                                      (R or R/W)
  5     Unknown (1=Enable?) (0=CamI2C fails?)                        (R or R/W)
  6     Unknown                                                      (R or R/W)
  7     Unknown (gets set automatically?)                                  (R?)
  8-15  Unknown/Unused (00h)                                               (0?)
Written values are 0000h and 0022h.
Camera I2C access works only when bit5=1 (otherwise camera i2c reads just return FFh; maybe bit5=0 issues a reset to the camera devices or so?)
"Used for resetting cameras. Once cameras are reset by poking this register, all three 0x0400420X camera registers are set to zero." Uh, is that really true, and which "three" registers are that?

4004202h - DSi9 - CAM_CNT - Camera Control
  0-3   Number of DMA scanlines minus 1 (usually 3=Four Scanlines)   (R or R/W)
  4     Data overrun/underrun error                                         (R)
  5     Clear bit4, and flush CAM_DAT till next Camera Vblank?              (W)
  6-7   Unknown/Unused (0)                                                 (0?)
  8-9    ? Set to 2 during init, 0 on cameras shutdown                    (R/W)
  10     ? Set to 1 during init, 0 on cameras shutdown                    (R/W)
  11    IRQ Enable      (0=Disable, 1=Enable)                             (R/W)
  12    Unknown/Unused (0)                                                 (0?)
  13    Color Format    (0=Direct/YUV422, 1=Convert YUV-to-RGB555)   (R or R/W)
  14    Trimming Enable (0=Normal/FullPicture, 1=Crop via SOFS/EOFS) (R or R/W)
  15    Transfer Enable (0=Disable/AllowConfig, 1=Enable/Transfer)        (R/W)

4004204h - DSi9 - CAM_DAT - Camera Data (R)
Transfers two camera pixels at once (from left-to-right, starting with upper scanline).
Pixel Format (in "YUV422" mode):
  0-7   First Pixel Luminance (Y)   (unsigned, 00h..FFh, FFh=white)
  8-15  Both Pixels Blue (Cb aka U) (unsigned, 00h..FFh, 80h=gray)
  16-23 Second Pixel Luminance (Y)  (unsigned, 00h..FFh, FFh=white)
  24-31 Both Pixels Red (Cr aka V)  (unsigned, 00h..FFh, 80h=gray)
Pixel Format (in YUV-to-RGB555 mode) (matches 2D Engine Bitmap format):
  0-4   First Pixel Red Intensity    (0..31)
  5-9   First Pixel Green Intensity  (0..31)
  10-14 First Pixel Blue Intensity   (0..31)
  15    First Pixel Alpha (always 1=NonTransparent)
  16-20 Second Pixel Red Intensity   (0..31)
  21-25 Second Pixel Green Intensity (0..31)
  26-30 Second Pixel Blue Intensity  (0..31)
  31    Second Pixel Alpha (always 1=NonTransparent)
The Aptina camera's MODE_OUTPUT_FORMAT registers and MIPI_CONTROL register can be configured to output stuff like YUV, RGB555, RGB444, BGR565, RAW8, etc. However, DSi games seem to be always using YUV mode at camera side (and the above RGB555 data is produced by activating YUV-to-RGB conversion in CAM_CNT.bit13 at console side).
YUV mode gives better quality with 8bit resolution (whilst RGB555 mode is having only 5bit, and, as it's converted from YUV, it's certainly having color information being shared for each two-pixel groups, too).
CAM_DAT should be usually read via NDMA (see below). Manually reading CAM_DAT for one block (eg. 256x4 pixels) does work, but it's unknown how to retrieve further blocks via manual reading (except, one further block arrives after around 40000h clock cycles, but that's much too slow, and it's only one extra block).

Formulas for converting YUV to RGB
  R = Y+(Cr-80h)*1.402
  G = Y-(Cr-80h)*0.714)-(Cb-80h)*0.344
  B = Y+(Cb-80h)*1.772
Clip results to MinMax(00h,FFh), and apply final divide by 8 for RGB555.

4004210h - DSi9 - CAM_SOFS Camera Trimming Starting Position Setting (32bit)
4004214h - DSi9 - CAM_EOFS Camera Trimming Ending Position Setting (32bit)
  0      Unused (0)                                                         (0)
  1-9    X-Offset  (0..1FFh)   in words (ie. 2-pixel units)?         (R or R/W)
  10-15  Unused (0)                                                         (0)
  16-24  Y-Offset  (0..1FFh)   in scanlines?                         (R or R/W)
  25-31  Unused (0)                                                         (0)
Crops the incoming camera picture before passing it to CAM_DAT, used only if enabled in CAM_CNT.14.

Write-Protected Camera Bits (R or R/W)
The "(R or R/W)" bits are getting Read-Only when camera transmission is enabled, ie. they can be changed only when CAM_CNT.Bit15=0.

Internal Camera Reflections from LCD Backlights
The LCD backlights can cause nasty reflections on the internal camera (particulary when wearing glasses). There isn't much that could be done during preview, but when taking photos, it might be recommended to output a black/dark picture on the LCDs during the capture.

Internal Camera Mirroring
The Internal Camera is conventionally having x-flip enabled (in Aptina MODE_SENSOR_READ_MODE registers), so the internal camera will behave as a mirror (which may appear more familar to most users in preview mode). The firmware's "Nintendo DSi Camera" utility is even saving jpg's in mirrored form instead of saving true authentic photos.

Camera Detection
There are four possible I2C camera devices, although usually only two of them should be installed. The firmware detects the cameras by reading their Chip ID registers (but without actually insisting on any specific ID values, instead, it's merely checking the ACK error flag in the I2C register - if all four devices are returning ACK=okay, then it's actually initializing all four cameras; though unknown if the GUI is actually supporting that many cameras).

Camera Init
  [4004004h]=[4004004h] OR 0004h             ;SCFG_CLK, CamInterfaceClock = ON
  [4004200h]=0000h, delay(1Eh)               ;CAM_MCNT, Camera Module Control
  [4004004h]=[4004004h] OR 0100h, delay(1Eh) ;SCFG_CLK, CamExternal Clock = ON
  [4004200h]=0022h, delay(2008h)             ;CAM_MCNT, Camera Module Control
  [4004004h]=[4004004h] AND NOT 0100h        ;SCFG_CLK, CamExternal Clock = OFF
  [4004202h]=[4004202h] AND NOT 8000h        ;CAM_CNT, allow changing params
  [4004202h]=[4004202h] OR 0020h             ;CAM_CNT, flush data fifo
  [4004202h]=([4004202h] AND NOT 0300h) OR 0200h
  [4004202h]=[4004202h] OR 0400h
  [4004202h]=[4004202h] OR 0800h             ;CAM_CNT, irq enable
  [4004004h]=[4004004h] OR 0100h, delay(14h) ;SCFG_CLK, CamExternal Clock = ON
  issue "aptina_code_list_init" via I2C bus on ARM7 side
  [4004004h]=[4004004h] AND NOT 0100h        ;SCFG_CLK, CamExternal Clock = OFF
  [4004004h]=[4004004h] OR 0100h, delay(14h) ;SCFG_CLK, CamExternal Clock = ON
  issue "aptina_code_list_activate" via I2C bus on ARM7 side
  [4004202h]=[4004202h] OR 2000h             ;CAM_CNT, enable YUV-to-RGB555
  [4004202h]=([4004202h] AND NOT 000Fh) OR 0003h
  [4004202h]=[4004202h] OR 0020h             ;CAM_CNT, flush data fifo
  [4004202h]=[4004202h] OR 8000h             ;CAM_CNT, start transfer
  [4004120h]=04004204h                       ;NDMA1SAD, source CAM_DTA
  [4004124h]=0xxxxxxxh                       ;NDMA1DAD, dest RAM/VRAM
  [4004128h]=00006000h                       ;NDMA1TCNT, len for 256x192 total
  [400412Ch]=00000200h                       ;NDMA1WCNT, len for 256x4 blocks
  [4004130h]=00000002h                       ;NDMA1BCNT, timing interval or so
  [4004138h]=8B044000h                       ;NDMA1CNT, start camera DMA

Specifications
The Nintendo DSi contains two cameras. The cameras can be used in the Nintendo DSi Camera application or DSi games that are compatible.
  640*480 VGA (0.3 Megapixel)
  No zoom and no flash.
Photos saved in JPG format (saved in DCIM/ folder on the SD/SDHC or in the internal memory).

Camera Applications
  Nintendo DSi Camera
  System Menu (can take photos, and can display JPG's with "Star" sticker)
  Flipnote (doesn't directly support camera hardware, but can import JPG's)
Camera Games
  Asphalt 4 : Elite Racing (DSiWare)
  Brain Challenge (DSiWare)
  Classic Word Games
  Cooking Coach
  Pop SuperStar : Road To Celebrity (DSiWare)
  Real Football 2009 (DSiWare)
  WarioWare : Snapped! (DSiWare)
  iCarly
  Pokemon Black,White (2010,JP)
  Castle of Magic (DSiWare)
  Photo Dojo (DSiWare)
  System Flaw (mis-uses camera as gyro sensor)


DSi SD/MMC Protocol and I/O Ports

I/O Ports
DSi SD/MMC I/O Ports: Command/Param/Response/Data
DSi SD/MMC I/O Ports: Interrupt/Status
DSi SD/MMC I/O Ports: Control Registers
DSi SD/MMC I/O Ports: Unknown/Unused Registers
DSi SD/MMC I/O Ports: Misc

SD/MMC Protocol
DSi SD/MMC Protocol: Command/Response/Register Summary
DSi SD/MMC Protocol: General Commands
DSi SD/MMC Protocol: Block Read/Write Commands
DSi SD/MMC Protocol: Special Extra Commands
DSi SD/MMC Protocol: CSR Register (32bit Card Status Register)
DSi SD/MMC Protocol: SSR Register (512bit SD Status Register)
DSi SD/MMC Protocol: OCR Register (32bit Operation Conditions Register)
DSi SD/MMC Protocol: CID Register (128bit Card Identification)
DSi SD/MMC Protocol: CSD Register (128bit Card-Specific Data)
DSi SD/MMC Protocol: EXT_CSD Register (4096bit Extended CSD Register) (MMC)
DSi SD/MMC Protocol: RCA Register (16bit Relative Card Address)
DSi SD/MMC Protocol: DSR Register (16bit Driver Stage Register) (Optional)
DSi SD/MMC Protocol: SCR Register (64bit SD Card Configuration Register)
DSi SD/MMC Protocol: PWD Register (128bit Password plus 8bit Password len)
DSi SD/MMC Protocol: State
DSi SD/MMC Protocol: Signals

SDIO Protocol
DSi SDIO Special SDIO Commands
DSi SDIO Memory and I/O Maps
DSi SDIO Common Control Registers (CCCR)
DSi SDIO Function Basic Registers (FBR)
DSi SDIO Card Information Structures (CIS)
The DSi is using SDIO for the new DSi Wifi interface,
DSi Atheros Wifi SDIO Interface
DSi Atheros Wifi Internal Hardware

Pinouts
AUX DSi SD/MMC Pin-Outs


DSi SD/MMC I/O Ports: Command/Param/Response/Data

4004800h/4004A00h - SD_CMD - Command and Response/Data Type (R/W)
  15    undoc   Unknown/undoc  (read/write-able)
  14    undoc   Security Cmd?  (0=Normal, 1=Whatever/Security?) (sdio?)
  13    undoc   Data Length    (0=Single Block, 1=Multiple Blocks)
  12    undoc   Data Direction (0=Write, 1=Read)
  11    NTDT    Data Transfer  (0=No data, 1=With data)
  10-8  REP2-0  Response Type  (0=Auto, 1..2=Unknown/Reserved, 3=None, 4=48bit,
                                5=48bit+Busy, 6=136bit, 7=48bitOcrWithoutCRC7)
  7-6   CMD1-0  Command Type   (0=CMD, 1=ACMD, 2..3=unknown, maybe GEN WR/RD?)
  5-0   CIX     Command Index  (0..3Fh, command index)
Setting Command Type to "ACMD" does NOT automatically send the APP_CMD prefix prior to the command number.
For Multiple Blocks, the hardware supports automatically sending STOP_TRANSMISSION after the last block.
DSi software is usually setting Response Type to "Auto", which is causing the hardware to use the correct response/data type for standard SD/MMC commands (bit11-13 are ignored/should be zero when using "Auto"; and maybe same for bit14-15?).
One exception is that the DSi firmware isn't using "Auto" for SDIO commands (maybe the hardware isn't aware of them; or it's unable to distinguish between read/write direction of CMD53, which would require examining the command's PARAM bits).
There are some differences between some SD and MMC commands, unknown if/how "Auto" is working in that cases; unknown if there's a SD-or-MMC mode select bit for that purpose in some configuration register (note: The DSi firmware uses manual config instead of Auto for CMD8, which differs for SD vs MMC).
Invalid values can cause ILA error (particulary on setting NTDT for CMD12, or for CMD's Response=None). ILA error will also occur if an old CMD is still busy.

4004804h/4004A04h - SD_CMD_PARAM0-1 - Argument (32bit, 2 halfwords) (R/W)
  31-0  Parameter value for CMD
The parameter value should be written <before> sending the command via SD_CMD/SDIO_CMD.

400480Ch/4004A0Ch - SD_RESPONSE0-7 - Response (128bit, 8 halfwords) (R)
After sending a command, wait for the CMDRESPEND bit (IRQ_STATUS.bit0) to get set, then read the RESPONSE (if the command does have any response).
For normal 32bit responses:
  31-0      Response
  127-32    Older Responses
For CID/CSD responses:
  119-0     120bit Response
  127-120   Zero (always?)
The above stuff is left-shifted when receiving new response bits (hence moving older responses to MSBs).

DATA16 vs DATA32
Data can be transferred in 16bit or 32bit units (as selected in DATA_CTL.bit1 and DATA32_IRQ.bit1). There are separate data, block len, and block count registers for 16bit and 32bit mode. 16bit mode uses two FIFOs (each with 200h-byte capactity). 32bit adds another FIFO (also with 200h-byte capacity):
                  .----------.                                  CPU
               o--| FIFO16_A |--o             o---------------- 4004830h
  serial          '----------'   \                              16bit
  SD/MMC  ---o                    o---------o
  bus         \   .----------.               \    .--------.    CPU/NDMA
               o--| FIFO16_B |--o             o---| FIFO32 |--- 400490Ch
                  '----------'                    '--------'    32bit
The 32bit mode is some odd patchwork, apparently Nintendo/Toshiba considered it easier to add an extra 32bit FIFO (rather than to figure out how to add native 32bit access to Toshiba's original 16bit chip design).
The DSi firmware does use both 32bit and 16bit mode once and then; 32bit mode can be faster, and it's required for NDMA transfers (which don't support 16bit).

40048D8h/4004AD8h - SD_DATA_CTL
  15-13  Always zero
  12     Unknown (usually 1)                                             (R?)
  11-6   Always zero
  5      Unknown (read/write-able) (usually 0)                           (R/W)
  4      Unknown (usually 1)                                             (R?)
  3-2    Always zero
  1      Select 16bit/32bit Data Mode (0=DATA16, 1=DATA32, see 4004900h) (R/W)
  0      Always zero
DATA32 mode requires setting both 40048D8h.bit1 and 4004900h.bit1. For DATA16 mode, both bits should be zero (though DATA16 seems to be also working the same way when only either of the bits is zero).

400480Ah/4004A0Ah - SD_DATA16_BLK_COUNT - NumBlocks for 16/32 bit Modes (R/W)
4004908h/4004B08h - SD_DATA32_BLK_COUNT - NumBlocks for 32 bit Mode (R/W)
  15-0   Number of Data Blocks for multiple read/write commands (0..FFFFh)
SD_DATA16_BLK_COUNT needs to be initialized in both 16bit and 32bit mode, the written value is copied to a internal register, which gets decremented after each block, and (when enabled in STOP_INTERNAL_ACTION.bit8) the hardware will automatically send STOP_TRANSMISSION (CMD12) after the last block (otherwise the hardware would keep transferring blocks infinitely).
For Data32 mode, DATA32_BLK_COUNT should be set to the same value (it doesn't really affect the transfer though, the register is intended only for watching the transfer progress: DATA32_BLK_COUNT is decremented after each block (when FIFO32 gets empty); except when it would become zero, in that case it stays stuck at 0001h).

4004826h/4004A26h - SD_DATA16_BLK_LEN - FIFO16 Size for 16/32 bit Modes (R/W)
4004904h/4004B04h - SD_DATA32_BLK_LEN - FIFO32 Size for 32 bit Mode (R/W)
  15-10  Always zero
  9-0    Data Block Length in bytes (for DATA16: clipped to max 0200h by hw)
SD_DATA16_BLK_LEN needs to be initialized in both 16bit and 32bit mode. For 32bit mode, SD_DATA32_BLK_LEN should be also set to the same value (otherwise odd effects might occur when forwarding FIFO16 to/from FIFO32).
The block length should be usually 0200h (for 512-byte SD/MMC memory blocks). Other values may be needed for SDIO functions, or when accessing SSR/SCR/PWD registers via data transfers.
DATA32_BLK_LEN can be set to max=3FFh (unlike DATA16_BLK_LEN which is clipped to max=200h by hardware), though settings bigger than 200h won't work in practice (since the FIFOs are only 200h bytes in size).

4004830h/4004A30h - SD_DATA16_FIFO - Data FIFO for 16bit Mode (R/W)
400490Ch/4004B0Ch - SD_DATA32_FIFO - Data FIFO for 32bit Mode (R/W)
For Data16:
  15-0   Data (Read/Write one block (usually 100h halfwords) upon RXRDY/TXRQ)
For Data32:
  31-0   Data (Read/Write one block (usually 80h words) upon RX32RDY/TX32RQ)
See the RXRDY/TXRQ and RX32RDY/TX32RQ interrupt flags for details.
The first Data32 block may be written even before sending the command (the DSi firmware is actually doing that, although, performance-wise, it would make sense only when writing multiple clusters, ie. sending the first block of the next cluster while the previous write is still in progress).
Observe that RX32RDY/TX32RQ are actually FIFO full/empty flags (getting triggered any time when FIFO is full/empty, so you must know for yourself if you want to transfer data in that situations; eg. FIFO empty will trigger even after having written all data blocks, or when not intending to write any data at all).


DSi SD/MMC I/O Ports: Interrupt/Status

All SD/MMC IRQs are triggering IF2.8, CardIRQ does ADDITIONALLY trigger IF2.9
All SDIO IRQs are triggering IF2.10, CardIRQ does ADDITIONALLY trigger IF2.11?

400481Ch/4004A1Ch - SD_IRQ_STATUS0-1 - Interrupt Status (R/ack)
4004820h/4004A20h - SD_IRQ_MASK0-1 - Interrupt Mask (R/W)
The IRQ_STATUS registers contain acknowledge-able IRQ Flags (those bits that that are maskable in IRQ_MASK register), as well as static read-only status bits without IRQ function (eg. WRPROTECT).
IRQ Flags/Write (0=Acknowledge, 1=No change)
IRQ Flags/Read (0=No IRQ, 1=IRQ)
IRQ Mask (0=Enable, 1=Disable) (8B7F031Dh when all IRQs disabled)
  Bit Stat  Mask  Function
  0   SREP  MREP  CMDRESPEND    (response end) (or R1b: busy end)
  1   0     0     Unknown/unused (always 0)
  2   SRWA  MRWA  DATAEND       (set after (last) data block end)
  3   SCOT  MCOT  CARD_REMOVE (0=No event, 1=Is/was newly ejected)      ;\
  4   SCIN  MCIN  CARD_INSERT (0=No event, 1=Is/was newly inserted)     ; SD
  5   undoc 0     SIGSTATE    (0=Ejected, 1=Inserted) (SDIO: always 1)  ; Slot
  6   0     0     Unknown/unused (always 0)                             ; Sw's
  7   undoc 0     WRPROTECT   (0=Locked/Ejected, 1=Unlocked/HalfEjected);/
  8   undoc undoc CARD_REMOVE_A (0=No event, 1=High-to-Low occurred)    ;\SD
  9   undoc undoc CARD_INSERT_A (0=No event, 1=Low-to-High occurred)    ; Slot
  10  undoc 0     SIGSTATE_A    (usually 1=High) ;also as so for SDIO   ;/Data3
  11  0     0     Unknown/unused (always 0)
  12  0     0     Unknown/unused (always 0)
  13  0     0     Unknown/unused (always 0)
  14  0     0     Unknown/unused (always 0)
  15  0     0     Unknown/unused (always 0)
  16  SCIX  MCIX  CMD_IDX_ERR   Bad CMD-index in response      (RCMDE,SCMDE)
  17  SCRC  MCRC  CRCFAIL       CRC response error (WCRCE,RCRCE,SCRCE,CCRCE)
  18  SEND  MEND  STOPBIT_ERR   End bit error      (WEBER,REBER,SEBER,CEBER)
  19  SDTO  MDTO  DATATIMEOUT   Data Timeout                (NRCS,NWCS,KBSY)
  20  SFOF  MFOF  RXOVERFLOW    HOST tried write full
  21  SFUF  MFUF  TXUNDERRUN    HOST tried read empty
  22  SCTO  MCTO  CMDTIMEOUT    Response start-bit timeout         (NRS,NSR)
  23  undoc 0     DATA0_PIN (0=Low, 1=High) (of selected port: eMMC or SD Slot)
  24  SBRE  MBRE  RXRDY         (fifo not empty) (request data read)
  25  SBWE  MBWE  TXRQ          (datafifoempty?) (request data write)
  26  0     0     Unknown/unused (always 0)
  27  undoc undoc Unknown/undoc  (bit27 is mask-able in IRQ_MASK)
  28  0     0     Unknown/unused (always 0)
  29  undoc 0     CMD_READY? (inverse of BUSY?) (unlike toshiba ILFSL/IFSMSK)
  30  undoc 0     CMD_BUSY   (CMD_BUSY=0 shortly before CMD_READY=1?)
  31  ILA   IMSK  Illegal Command Access (old CMD still busy, or wrong NTDT)
Normally, IRQs should be acknowledged by writing "FLAGS=NOT X", whilst the firmware is using an unstable "FLAGS=FLAGS AND NOT X" read-modify-write function (accidentally acknowledging any IRQs that have newly occurred during that operation).

4004836h/4004A36h - SD_CARD_IRQ_STAT (R/ack)
4004838h/4004A38h - SD_CARD_IRQ_MASK (R/W)
IRQ Flags/Write (0=Acknowledge, 1=No change)
IRQ Flags/Read (0=No IRQ, 1=IRQ)
IRQ Mask (0=Enable, 1=Disable) (C007h when all IRQs disabled)
  Bit  Stat  Mask   Function
  15   undoc undoc  SomeIRQ (triggered SOMETIMES on forced CMDTIMEOUT?)
  14   undoc undoc  SomeIRQ (triggered near DATAEND?)
  13-3 0     0      Always zero
  2    undoc undoc  SomeIRQ (triggered on forced TXUNDERRUN?)
  1    undoc undoc  SomeIRQ (triggered about once per datablock?)
  0    CINT0 CIMSK0 CardIRQ (triggered by /IRQ aka Data1 pin; for SDIO devices)
All stat bits (except bit1) are triggered only if enabled in SD_CARD_IRQ_CTL.
Bit0 is actually used (for SDIO hardware), the other bits aren't used by existing software (they don't seem to be useful; purpose might be error testing, or forcing commands to abort).

4004834h/4004A34h - SD_CARD_IRQ_CTL (R/W)
CardIRQ Enable works only when also writing SD_CARD_PORT_SELECT.bit10=0 and only with valid SD_CARD_CLK_CTL setting.
  15-10  Always zero
  9      Enable setting SD_CARD_IRQ_STAT.bit14 and cause nothing special? (R/W)
  8      Enable setting SD_CARD_IRQ_STAT.bit15 and cause CMDTIMEOUT?      (R/W)
  7-3    Always zero
  2      Enable setting SD_CARD_IRQ_STAT.bit2 and cause TXUNDERRUN?       (R/W)
  1      Always zero
  0      Enable setting SD_CARD_IRQ_STAT.bit0 (CardIRQ upon Data1=LOW)    (R/W)
Bit9 is autocleared at time when bit9 causes setting SD_CARD_IRQ_STAT.bit14.
Bit2 is autocleared shortly before bit8 causes CMDTIMEOUT.
SD_CARD_IRQ_STAT.bit15 is set only when setting bit8 AND bit2 DURING cmd/xfer.

40048F8h/40048FAh - SD_EXT_IRQ_STAT0-1 - Interrupt Status (R/ack)
40048FCh/40048FEh - SD_EXT_IRQ_MASK0-1 - Interrupt Mask (R/W)
The 3DS bootroom is using bit0-2 for eMMC insert/eject detection. DSi software isn't doing such stuff (though the registers seem to exist in DSi hardware, too). Either way, eMMC cannot be ejected on neither DSi nor 3DS, so the feature is kinda useless.
  Bit   Stat  Mask  Function
  0     SCOT  MCOT  CARD_REMOVE (0=No event, 1=Is/was newly ejected)     ;\eMMC
  1     SCIN  MCIN  CARD_INSERT (0=No event, 1=Is/was newly inserted)    ; Slot
  2     undoc 1     SIGSTATE    (MMC: Always 1=Inserted) (SDIO: always 0);/Sw
  3     0     RW    Unknown (stat always 0, but mask is R/W)   ;\maybe another
  4     0     RW    Unknown (stat always 0, but mask is R/W)   ; unimplemented
  5     0     1     Unknown (stat always 0, and mask always 1) ;/device?
  6     0     RW    Unknown (stat always 0, but mask is R/W)   ;\maybe yet one
  7     0     RW    Unknown (stat always 0, but mask is R/W)   ; more?
  8-15  0     0     Unknown/unused (always 0)                  ;/
  16    ??    RW    Unknown (stat can be 0/1)               (R/W? or rather R?)
  17    ??    RW    Unknown (stat can be 0/1)               (R/W? or rather R?)
  18    ??    1     Unknown (1=normal, 0=data/read from card to fifo busy?) (R)
  19    0     RW    Unknown (stat always 0, but mask is R/W)
  20    0     RW    Unknown (stat always 0, but mask is R/W)
  21    0     1     Unknown (stat always 0, and mask always 1)
  22    0     RW    Unknown (stat always 0, but mask is R/W)
  23    0     RW    Unknown (stat always 0, but mask is R/W)
  24-31 0     0     Unknown/unused (always 0)
Some of the unknown bits might be CD/Data3 or IRQ/Data1 pins for Device 1, in similar way as for Device 0 (maybe that is in bit16-18, which are observed to become nonzero in certain situations).
EXT_IRQ_STAT can be 00000000h..00070004h for MMC, or always 00000000h for SDIO (as there's only one device on SDIO bus). EXT_IRQ_MASK is R/W (can be 00240024h..00FF00FFh) for both SD/MMC and SDIO.

4004900h/4004B00h - SD_DATA32_IRQ
  15-13  Always zero
  12     TX32RQ IRQ Enable   (0=Disable, 1=Enable)                       (R/W)
  11     RX32RDY IRQ Enable  (0=Disable, 1=Enable)                       (R/W)
  10     Clear FIFO32        (0=No change, 1=Force FIFO32 Empty)         (W)
  9      TX32RQ IRQ Flag     (0=IRQ, 1=No) (0=FIFO32 Empty)              (R)
  8      RX32RDY IRQ Flag    (0=No, 1=IRQ) (1=FIFO32 Full)               (R)
  7-2    Always zero
  1      Select 16bit/32bit Data Mode (0=DATA16, 1=DATA32, see 40048D8h) (R/W)
  0      Always zero
Bit8,9 are extra IRQ flags, the flags get set ONLY in DATA32 mode (not in DATA16 mode).
Bit8,9 are somewhat edge-triggered (setting the IF2 bit only on NoIRQ-to-IRQ transitions; whilst Disable-to-Enable transitions don't trigger IF2).
Bit8,9 don't need to be acknowledged, they are automatically switched to "No IRQ" by hardware (when reading/writing DATA32_FIFO, ie. when the FIFO is no longer empty/full).

400482Ch/4004A2Ch - SD_ERROR_DETAIL_STATUS0-1 - Error Detail Status (R)
This register contains extra info about the error bits in SD_IRQ_STATUS. The error bits (except bit13/always set) are automatically cleared when sending a new command by writing to SD_CMD.
  31-23 0      Always zero
  22    KBSY   Timeout for CRC status busy                          ;\STAT.19
  21    NWCS   Timeout for CRC status   (can occur for Data Write)  ; (SDTO)
  20    NRCS   Timeout for Data start-bit, or for Post Data Busy    ;/
  19-18 0      Always zero
  17    NRS    Response Timeout for auto-issued CMD12               ;\STAT.22
  16    NCR    Response Timeout for non-auto-issued CMD's           ;/(SCTO)
  15-14 0      Always zero
  13    undoc  Unknown/undoc (always 1)                             ;-Always 1
  12    0      Always zero
  11    WCRCE  CRC error for Write CRC status for a write command   ;\
  10    RCRCE  CRC error for Read Data                              ; STAT.17
  9     SCRCE  CRC error for a Response for auto-issued CMD12       ; (SCRC)
  8     CCRCE  CRC error for a Response for non-auto-issued CMD's   ;/
  5     WEBER  End bit error for Write CRC status                   ;\
  4     REBER  End bit error for Read Data                          ; STAT.18
  3     SEBER  End bit error for Response for auto-issued CMD12     ; (SEND)
  2     CEBER  End bit error for Response for non-auto-issued CMD's ;/
  1?    SCMDE  Bad CMD-index in Response of auto-issued CMD12       ;\STAT.16
  0     RCMDE  Bad CMD-index in Response of non-auto-issued CMD's   ;/(SCIX)
Note: CMD12 is STOP_TRANSMISSION (automatically sent after BLK_COUNT blocks).
The four "auto-issued CMD12" bits exist for SD registers only (not for SDIO, going by old toshiba datasheets; which may be wrong).
SCMDE is probably in bit1 (though, official specs say bit0, which would be same as RCMDE).
Some error bits can be intentionally provoked: Bit8=1 when programming the controller to expect GET_STATUS to return a 136bit response. Bit16=1 when sending GET_CID in "tran" state. Bit20=1 when sending GET_STATUS configured to expect a data/read reply. Bit21=1 when sending GET_STATUS configured to expect a data/write block (and with actually sending a data block to it).

40048F6h/4004AF6h - SD_WRPROTECT_2 (RESERVED4) (R)
  15-1   Always zero
  0      WRPROTECT_2 for onboard eMMC (usually/always 0=Unlocked)           (R)
Bit0 is write-protect flag for onboard eMMC (equivalent to the SD/MMC slot's write-protect switch in 400481Ch.bit7, but in inverted form: 0=Unlocked for eMMC, instead of 0=Locked for SD/MMC). The firmware does check bit0 (and, if set, hangs shortly before starting games), unknown if the TWL CPU and DSi mainboard do actually have any solder pads for it.

IRQ Edge-Triggering
One nasty "feature" for both IRQ_STATUS and DATA32_IRQ is that the interrupts are edge-triggered (IF2.bit8 gets set only on No-IRQ-to-IRQ transitions) (IF2 can be acknowledged even if IRQ(s) are still requested, which would mean that those IRQ(s) would get lost). Workaround would be:
 - first acknowledge IF2.bit8 (must be done before next step)
 - then check for pending IRQs in IRQ_STATUS and DATA32_IRQ, and process
   all of them
Ie. if you would process only a single IRQ, then any other IRQs would get lost.
For IRQ_STATUS, one could also force unprocessed IRQs to re-trigger IF2 by temporarily disabling IRQ_MASK bits (disable-to-enable for pending IRQs is also edge-triggering IF2). That trick works for IRQ_STATUS only, not for DATA32_IRQ.


DSi SD/MMC I/O Ports: Control Registers

4004802h/4004A02h - SD_CARD_PORT_SELECT
  15-11 Always zero
  10    Unknown (should be set on write) (reads as zero) (1=CardIRQ off!) (W)
  9-8   Unknown (Always 2 for SD/4004802h, always 1 for SDIO/4004A02h)    (R)
  7-4   Always zero
  3-1   Unknown (read/write-able)                                         (R/W)
  0     Port Select (0=SD Card Slot, 1=Onboard eMMC) (for SDIO: Unknown)  (R/W)
Known written values are 0400h and 0401h for SD/MMC. The register is left uninitialized for SDIO.

4004828h/4004A28h - SD_CARD_OPTION - Card Option Setup
  15   undoc Bus Width (0=4bit, 1=1bit)                                   (R/W)
  14   undoc Unknown (usually set)                                        (R?)
  13-9 0     Always zero
  8    undoc Unknown (firmware tries to toggle this after CLK change?)    (W?)
  7-4  RTO   Data start/busy timeout (2000h SHL 0..14, or 15=100h SDCLK's)(R/W)
  0-3  TO?   SIGSTATE detect delay   (400h SHL 0..14, or 15=100h HCLK's)  (R/W)
See Timeout Notes below for details.

4004824h/4004A24h - SD_CARD_CLK_CTL Card Clock Control
  15-11 Always zero          ;unlike Toshiba: no HCLK divider-disable in bit15)
  10    Unknown (0=Normal, 1=Unknown, doesn't affect SDCLK output?)       (R/W)
  9     SDCLK Auto pause (0=Normal, 1=Freeze SDCLK output when inactive)  (R/W)
  8     SDCLK Pin Enable (0=Force SDCLK=LOW, 1=Output SDCLK=HCLK/n)       (R/W)
  7-0   HCLK Div (0,1,2,4,8,16,32,64,128 = Div2,4,8,16,32,64,128,256,512) (R/W)
The DSi uses HCLK=33.513982 MHz, the SDCLK pin can range from HCLK/512=65kHz to HCLK/2=16.757MHz, max transfer rate would be thus 8MByte/s in 4bit mode.
Max CLK speed:
Observe that card detection/initialization should be done at lower CLK rate than during normal operation.
For SD/MMC initialization: The DSi firmware starts with HCLK/128=262kHz (max allowed would be 400kHz for MMC). This is actually required: The DSi's onboard Samsung KMAPF0000M-S998 eMMC chip won't respond to ALL_GET_CID when trying to use 16MHz CLK). Higher CLK can be used once when detecting max speed (see TRAN_SPEED in CSD register; when extracting bits from CSD: mind the different 120bit-without-CRC vs 128bit-with-CRC notations).
For SDIO/Wifi initialization: The DSi firmware starts with HCLK/256=131kHz, and switches to HCLK/2=16.757MHz after reading SDIO Bus Speed register (Function0:00013h).
After init, one can use the detected speeds (see above), it should be also safe to assume that HCLK/2=16.757MHz is always supported after initialization (all SD devices should support at least 25MHz, and all(?) MMC devices at least 26MHz, and all DSi SDIO/Wifi boards should be fast enough either).
Notes:
The SDCLK pins are permanently pulsed, even for devices deselected via SD_CARD_PORT_SELECT.0, and even if no CMD or DATA is being transferred. However, the DSi firmware is usually stopping SDCLK via Bit8=0 when not accessing SD/MMC (doing so may reduce noise and power consumption).
Setting bit9, or to trying to set more than one bit in bit7-0 will freeze the SDCLK output (in this case SDCLK may get stuck HIGH or LOW, unlike Bit8=0 which forces LOW).
Odd Effect: Setting bit10-8 to ALL ones, combined with an invalid HDIV (eg. writing 0703h) does disable CardIRQ on Data1 pin.

4004808h/4004A08h - SD_STOP_INTERNAL_ACTION
  15-9   Always zero
  8      Auto-Stop (1=Automatically send CMD12 after BLK_COUNT blocks)  (R/W)
  7-1    Always zero
  0      Unknown (firmware often clears this bit, but never sets it?)   (R/W)
Existing code does set bit8 (prior to changing SD_DATA16_BLK_COUNT).
Existing code does clear bit0 (alongsides with IRQ enable/acknowledge or so).
Note: Bit8 MUST be also set for SDIO with multiple blocks (although SDIO doesn't literally have CMD12).

40048E0h/4004AE0h - SD_SOFT_RESET - Software Reset
  15-3 Always zero
  2    Unknown (always 1)                                            (R?)
  1    Unknown (always 1) (though firmware tries to toggle this bit) (R?)
  0    SRST Soft Reset (0=Reset, 1=Release)                          (R/W)
Software should apply reset after sensing card insertion/removal, and (thereafter) release reset in case of card insertion. Software reset does acknowledge all IRQs (except that from SDIO /IRQ pin?), and does probably also reinitialize some other registers.
Clearing bit0 does force following settings (while and as long as Bit0=0):
  SD_STOP_INTERNAL_ACTION   = 0000h
  SD_RESPONSE0-7            = zerofilled
  SD_IRQ_STATUS0-1          = all IRQ flags acknowledged
  SD_ERROR_DETAIL_STATUS0-1 = all bits cleared (except bit13/always set)
  SD_CARD_CLK_CTL           = bit 8 and 10 cleared
  SD_CARD_OPTION            = 40EEh
  SD_CARD_IRQ_STAT          = 0000h
  Internal FIFO16 address is reset to first halfword of FIFO_A
  Reading FIFO16 returns 0000h (but old content reappears when releasing reset)
All other registers seem to be left unaffected (including the extra IRQ flags in 4004900h); though there may be some further hidden effects (like aborting transfers or resetting internal registers).
Note: The DSi firmware does issue reset by toggling both bit0 and bit1, although bit1 does seem to be read-only (always 1), and trying to clear that bit doesn't seem to have any effect at all.

Timeout Notes
Timeouts are counted in SDCLK units (the CLK-Pin rate selected in SD_CARD_CLK_CTL register). For Response-Timeouts, the timeout is fixed: Around 290h SDCLK's (preceeded by 30h SDCLK's for sending the command). For Data-Timeouts, the timeout can be selected in SD_CARD_OPTION.bit4-7, which is apparently what toshiba tried to describe as "RTO" bits. Values 0..14 select timeout "2000h SHL 0..14 SDCLK's" and value 15 selects "100h SDCLK's" (that, oddly, resulting in Data-timeout getting triggered before Response-timeout, which is rather nonsense since it's opposite of the actual transfer order).
For data/read, the timeout starts counting after transferring Command+Response. For data/write it starts after transferring Command+Response+DataBlock. The maximum duration for data timeouts (with RTO=14) would be around 8 seconds (at SDCLK=HCLK/2), or up to about 30 minutes (at HCLK/512).
One odd effect is that Response-Timeouts can occur (after 290h SDCLKs, and recursing the selected SDCLK=HCLK/n rate) even if SDCLK is stopped via SD_CARD_CLK_CTL.Bit8 (ie. the selected clock is kept running internally, and only the CLK-Pin output is forced LOW when Bit8=0).

CFG9_SDMMC_CTL and SD_CARD_OPTION
On DSi, SD/MMC Slot power supply is always on (it takes about 3ms to reach the 3.3V after power on; if the console booted up and loaded data from eMMC, one can be sure that the SD/MMC Slot is properly powered up).
On 3DS, SD/MMC Slot power supply can be enabled/disabled, the bootrom does leave it disabled, so, before accessing SD/MMC Slot or before testing the card insert flag, FIRM software must enable it (set CFG9_SDMMC_CTL bit0=0 and usually bit9=1, it takes about 4.2ms to reach 3.3V, SD cards may take 1ms to boot up, for those 4.2ms+1ms delays, best set the SIGSTATE detect delay in SD_CARD_OPTION.bit0-3 to 09h, ie. circa 8ms).


DSi SD/MMC I/O Ports: Unknown/Unused Registers

Below registers don't seem to be used by existing software...

40048F2h/4004AF2h - Can be 0003h
  15-2   Always zero
  1-0    Unknown (0..3)                                                   (R/W)

40048F4h/4004AF4h - Can be 0770h
  15-11  Always zero
  10-8   Unknown (0..7)                                                   (R/W)
  7      Always zero
  6-4    Unknown (0..7)                                                   (R/W)
  3-0    Always zero

Unused Registers with Fixed value (all bits read-only, or write-only)
  400482Ah/4004A2Ah 2    Fixed always zero?
  4004832h/4004A32h 2    Fixed always zero?   ;(TC6371AF:BUF1 Data MSBs?)
  400483Ah/4004A3Ah 2    Fixed always zero?   ;(SDCTL_SDIO_HOST_INFORMATION)
  400483Ch/4004A3Ch 2    Fixed always zero?   ;(SDCTL_ERROR_CONTROL)
  400483Eh/4004A3Eh 2    Fixed always zero?   ;(TC6387XB: LED_CONTROL)
  4004840h/4004A40h 2    Fixed always 003Fh?
  4004842h/4004A42h 2    Fixed always 002Ah?
  4004844h/4004A44h 6Eh  Fixed always zerofilled?
  40048B2h/4004AB2h 2    Fixed always FFFFh?
  40048B4h/4004AB4h 6    Fixed always zerofilled?
  40048BAh/4004ABAh 2    Fixed always 0200h?
  40048BCh/4004ABCh 1Ch  Fixed always zerofilled?
  40048DAh/4004ADAh 6    Fixed always zerofilled?
  40048E2h/4004AE2h 2    Fixed always 0009h?  ;(RESERVED2/9, TC6371AF:CORE_REV)
  40048E4h/4004AE4h 2    Fixed always zero?
  40048E6h/4004AE6h 2    Fixed always zero?   ;(RESERVED3, TC6371AF:BUF_ADR)
  40048E8h/4004AE8h 2    Fixed always zero?   ;(TC6371AF:Resp_Header)
  40048EAh/4004AEAh 6    Fixed always zerofilled?
  40048F0h/4004AF0h 2    Fixed always zero?   ;(RESERVED10)
  4004902h/4004B02h 2    Fixed always zero?
  4004906h/4004B06h 2    Fixed always zero?
  400490Ah/4004B0Ah 2    Fixed always zero?
  4004910h/4004B10h F0h  Fixed always zerofilled?


DSi SD/MMC I/O Ports: Misc

Toshiba Chips
The DSi SDIO/MMC port addresses and status bits appear to be identical to those on Toshiba SD/MMC/SDIO controller chips.
One small difference is that the DSi can set SD_IRQ_MASK.Bit27 (which wasn't used on (older) Toshiba chips). The Toshiba chips seem to include additional "CNF" configuration registers (which seem to be missing on DSi).
  Chip             Year   Pages Features
  Toshiba TC6371AF 2000-2002 58 SD/MMC/Smart/PCI (old/basic specs, no SDIO)
  Toshiba TC6380AF 2001-2002 90 SD/MMC/SDIO/SmartMedia
  Toshiba TC6387XB 2001-2002 62 SD/MMC/SDIO/SDLED
  Toshiba TC6391XB 2002     202 SD/MMC/SDIO/SmartMedia/USB/LCD/etc.
  Toshiba TC6393XB ?  ;\unknown features, no datasheet exists (the chips
  Toshiba T7L66XB  ?  ;/are mentioned in tmio_mmc.h and tmio_mmc.c source)
Related source code:
  https://github.com/torvalds/linux/tree/master/drivers/mmc/host/
  (see files toshsd.* and tmio_mmc.*)
  (that just as historic references, meanwhile there's better source code
  around, written specifically for DSi and 3DS hardware)
The TC6380AF/TC6387XB/TC6391XB datasheets are more or less identical on the SD/MMC/SDIO section, TC6387XB is probably the best reference because it doesn't contain offtopic extras like SmartMedia, USB, LCD, etc. The datasheets contain I/O Maps with port addresses, but no description tables for the bits in those ports (though some bits are mentioned here and there in the text, scattered across many different pages, and other bits are left completely undocumented).


DSi SD/MMC Protocol: Command/Response/Register Summary

Basic Commands (class 0)
  CMD0     sd/mmc spi GO_IDLE_STATE (CMD0 with arg=stuff) (type=bc)
  CMD0     mmc        GO_PRE_IDLE_STATE (CMD0 with arg=F0F0F0F0h) (type=bc)
  CMD0     mmc        BOOT_INITIATION (CMD0 with arg=FFFFFFFAh, type=N/A)
  CMD1     sd/mmc spi SEND_OP_COND (On SD Cards: SPI only)
  CMD2     sd/mmc     ALL_GET_CID (type=bcr)
  CMD3     sd         GET_RELATIVE_ADDR (type=bcr)
  CMD3     mmc        SET_RELATIVE_ADDR (type=ac)
  CMD4     sd/mmc     SET_DSR (type=bc)
  CMD5     sd     spi Reserved for I/O cards (see "SDIO Card Specification")
  CMD5     mmc    ?   SLEEP_AWAKE (type=ac) (MMC only, IO_SEND_OP_COND on SDIO)
  CMD7     sd/mmc     SELECT_DESELECT_CARD (type=ac) ;actually: (type=bcr)
  CMD8     sd     spi SET_IF_COND (type=bcr)
  CMD8     mmc    spi GET_EXT_CSD (type=adtc)
  CMD9     sd/mmc spi GET_CSD (type=ac) (SPI: type=adtc)
  CMD10    sd/mmc spi GET_CID (type=ac) (SPI: type=adtc)
  CMD11    sd         VOLTAGE_SWITCH (type=ac)
  CMD12    sd/mmc spi STOP_TRANSMISSION (type=ac)
  CMD13    sd/mmc spi GET_STATUS (type=ac) (sends 16bit status in SPI Mode)
  CMD14    mmc        BUSTEST_R (type=adtc) (MMC only, Reserved on SD)
  CMD19    mmc        BUSTEST_W (type=adtc) (MMC only, SET_TUNING_BLOCK on SD)
  CMD15    sd/mmc     GO_INACTIVE_STATE (type=ac)

Block-Oriented Read Commands (class 2)
  CMD16    sd/mmc spi SET_BLOCKLEN (type=ac)
  CMD17    sd/mmc spi READ_SINGLE_BLOCK (type=adtc)
  CMD18    sd/mmc spi READ_MULTIPLE_BLOCK (type=adtc)
  CMD19    sd         SET_TUNING_BLOCK (type=adtc)
  CMD20    sd         SPEED_CLASS_CONTROL (type=ac)
  CMD22    sd         Reserved
  CMD23    sd/mmc-spi SET_BLOCK_COUNT (type=ac) (SPI supported ONLY on MMC?)

Block-Oriented Write Commands (class 4)
  CMD16    sd/mmc spi SET_BLOCKLEN (type=ac)
  CMD20    sd         SPEED_CLASS_CONTROL (type=ac)
  CMD23    sd/mmc-spi SET_BLOCK_COUNT (type=ac) (SPI supported ONLY on MMC?)
  CMD24    sd/mmc spi WRITE_BLOCK (type=adtc)
  CMD25    sd/mmc spi WRITE_MULTIPLE_BLOCK (type=adtc)
  CMD26    sd/mmc     Reserved For Manufacturer (MMC: PROGRAM_CID)
  CMD27    sd/mmc spi PROGRAM_CSD (type=adtc)

Block-Oriented Write-Protection Commands (class 6)
  CMD28    sd/mmc spi SET_WRITE_PROT (type=ac)
  CMD29    sd/mmc spi CLR_WRITE_PROT (type=ac)
  CMD30    sd/mmc spi GET_WRITE_PROT (type=adtc)
  CMD31    -          SD: Reserved
  CMD31    mmc        MMC: SEND_WRITE_PROT_TYPE (type=adtc)

Erase Commands (class 5)
  CMD32    sd     spi ERASE_WR_BLK_START (type=ac)
  CMD33    sd     spi ERASE_WR_BLK_END (type=ac)
  CMD32-34 mmc    spi Reserved for compatibility with older MMC cards (uh?)
  CMD35    mmc    spi ERASE_GROUP_START (type=ac)
  CMD36    mmc    spi ERASE_GROUP_END (type=ac)
  CMD37    mmc    spi Reserved for compatibility with older MMC cards (uh?)
  CMD38    sd/mmc spi ERASE (type=ac)
  CMD39    -          Reserved
  CMD41    -          Reserved

Lock Card (class 7)
  CMD16    sd/mmc spi SET_BLOCKLEN (type=ac)
  CMD40    sd         Defined by DPS Spec (Data Protection System) (type=adtc)
  CMD42    sd/mmc spi LOCK_UNLOCK (type=adtc)
  CMD43-47 -          Reserved
  CMD51    -          Reserved

Application-Specific Commands (class 8)
  CMD39-40 mmc        MMCA Optional Command, currently not supported
  CMD55-56 mmc        MMCA Optional Command, currently not supported
  CMD55    sd     spi APP_CMD (type=ac)    ;\also defined for MMC,
  CMD56    sd     spi GEN_CMD (type=adtc)  ;/but ONLY in SPI mode !!??
  CMD60-63 sd/mmc spi Reserved for manufacturer

I/O Mode Commands (class 9) (Refer to "SDIO Card Specification")
  CMD5     sdio   spi SDIO: IO_SEND_OP_COND
  CMD52    sdio   spi SDIO: IO_RW_DIRECT
  CMD53    sdio   spi SDIO: IO_RW_EXTENDED
  CMD54    -          SDIO: Reserved
  CMD39    mmcio      MMCIO: FAST_IO (type=ac)
  CMD40    mmcio      MMCIO: GO_IRQ_STATE (type=bcr)

Switch Function Commands (class 10) (version 1.10+)
  CMD6     mmc    spi SWITCH      (type=ac)   ;related to EXT_CSD register
  CMD6     sd     spi SWITCH_FUNC (type=adtc)
  CMD34-37 sd+spi     Reserved for Command Systems from CMD6  ;\SPI
  CMD50,57 sd+spi     Reserved for Command Systems from CMD6  ;/
  CMD34-35 sd         Reserved                                ;\
  CMD36-37 sd         Undoc (description field is held blank) ; Non-SPI
  CMD50,57 sd         Undoc (description field is held blank) ;/

Function Extension Commands (class 11)
  CMD21    sd         Reserved for DPS Specification (Data Protection System)
  CMD48    sd         READ_EXTR_SINGLE (type=adtc)
  CMD49    sd         WRITE_EXTR_SINGLE (type=adtc)
  CMD58    sd         READ_EXTR_MULTI (type=adtc)   ;SPI: READ_OCR
  CMD59    sd         WRITE_EXTR_MULTI (type=adtc)  ;SPI: CRC_ON_OFF

MMC Data Streaming Commands (class 1/class 3)
  CMD11    mmc        READ_DAT_UNTIL_STOP (class 1) (type=adtc)
  CMD20    mmc        WRITE_DAT_UNTIL_STOP (class 3) (type=adtc)

Below CMD58-59 SPI-only (in Non-SPI mode: MMC=Reserved, SD=EXTR_MULTI)
  CMD58    sd/mmc+spi READ_OCR     ;SPI-only ;SD Mode: READ_EXTR_MULTI
  CMD59    sd/mmc+spi CRC_ON_OFF   ;SPI-only ;SD Mode: WRITE_EXTR_MULTI
Above two commands are supported in SPI mode only, and are supported for both SD and MMC (though newer MMC docs are no longer mentioning them since JEDEC dropped SPI support).

Application Specific Commands (prefixed by CMD55 aka APP_CMD)
  ACMD6     sd        SET_BUS_WIDTH (type=ac)
  ACMD13    sd    spi SD_STATUS (type=adtc) (get 512bit SSR)
  ACMD22    sd    spi GET_NUM_WR_BLOCKS (type=adtc)
  ACMD23    sd    spi SET_WR_BLK_ERASE_COUNT (type=ac)
  ACMD41    sd    spi SD_SEND_OP_COND (type=bcr)  ;SPI: reduced functionality
  ACMD42    sd    spi SET_CLR_CARD_DETECT (type=ac)
  ACMD51    sd    spi GET_SCR (type=adtc)
  ACMD1-5   -         Reserved
  ACMD7-12  -         Reserved
  ACMD14-16 sd        Reserved for DPS Specification (Data Protection System)
  ACMD17    -         Reserved
  ACMD18    sd    spi Reserved for SD security applications
  ACMD19-21 -         Reserved
  ACMD24    -         Reserved
  ACMD25    sd    spi Reserved for SD security applications
  ACMD26    sd    spi Reserved for SD security applications
  ACMD27    -         Shall not use this command
  ACMD28    sd        Reserved for DPS Specification (Data Protection System)
  ACMD29    -         Reserved
  ACMD30-35 sd        Reserved for Security Specification
  ACMD36-37 -         Reserved
  ACMD38    sd    spi Reserved for SD security applications
  ACMD39-40 -         Reserved
  ACMD43-49 sd    spi Reserved for SD security applications
  ACMD52-54 sd        Reserved for Security Specification
  ACMD55    -         Not exist (equivalent to CMD55)
  ACMD56-59 sd        Reserved for Security Specification
  ACMD0     -         Unknown/Unused/Undocumented
  ACMD50    -         Unknown/Unused/Undocumented
  ACMD60-63 -         Unknown/Unused/Undocumented

Card Registers
  CSR       32bit  sd/mmc spi Card Status: command error & state information
  OCR       32bit  sd/mmc spi Operation Conditions Register
  CID      128bit  sd/mmc spi Card Identification
  CSD      128bit  sd/mmc spi Card-Specific Data (CSD Version 1.0 and 2.0)
  RCA       16bit  sd/mmc     Relative Card Address (not used in SPI mode)
  DSR       16bit  sd/mmc spi Driver Stage Register (optional)
  SSR      512bit  sd     spi SD Card Status Register: Extended status field
  SCR       64bit  sd     spi SD Card Configuration Register
  EXT_CSD 4096bit  mmc    spi MMC Extended CSD Register (status & config)
  PWD      128bit  sd/mmc spi Password (Card Lock) (max 16 bytes)
  PWD_LEN    8bit  sd/mmc spi Password Length (0..16 max) (0=no password)

SD Mode Response Types
  N/A    0bit  CMD0, CMD4, CMD15   No response
  R1    48bit  Normal CMDs/ACMDs   32bit CSR Card Status
  R1b   48bit  Busy CMDs/ACMDs     32bit CSR Card Status (and DATA=busy)
  R2   136bit  CMD9                120bit CSD Card-Specific Data
  R2   136bit  CMD2, CMD10         120bit CID Card Identification
  R3    48bit  ACMD41, MMC:CMD1    32bit OCR Register (without crc7)
  R4        -  -                   Reserved for SDIO
  R5        -  -                   Reserved for SDIO
  R6    48bit  CMD3                16bit RCA and cut-down 16bit CSR
  R7    48bit  CMD8                32bit Card interface condition

SPI Mode Response Types
  R1     8bit  Normal CMDs/ACMDs   8bit CSR Card Status
  R1b    8bit  Busy CMDs/ACMDs     8bit CSR Card Status (and DATA=busy)
  R2    16bit  CMD13, ACMD13       16bit CSR Card Status
  R3    40bit  CMD58               8bit CSR and 32bit OCR
  R4        -  -                   Reserved for SDIO
  R5        -  -                   Reserved for SDIO
  R6        -  -                   Reserved
  R7    40bit  CMD8                8bit CSR and 32bit Card interface condition
  ERROR  8bit  Only first 8bit sent upon Illegal Command or Command CRC Error

Commands with Data Transfers (additionally to command/response) (type=adtc)
  CMD17,18 R   sd/mmc spi READ_SINGLE_BLOCK, READ_MULTIPLE_BLOCK
  CMD24,25 W   sd/mmc spi WRITE_BLOCK, WRITE_MULTIPLE_BLOCK
  CMD8     R   mmc    spi GET_EXT_CSD (4096bit)
  CMD9     R   sd/mmc spi GET_CSD (128bit)  ;\in SPI Mode only (Non-SPI mode
  CMD10    R   sd/mmc spi GET_CID (128bit)  ;/sends that info as CMD response)
  ACMD13   R   sd     spi SD_STATUS (512bit SSR register)
  ACMD22   R   sd     spi GET_NUM_WR_BLOCKS (32bit counter)
  ACMD51   R   sd     spi GET_SCR (64bit SCR register)
  CMD14,19 R/W mmc        BUSTEST_R, BUSTEST_W
  CMD19    W?  sd         SET_TUNING_BLOCK (512bit tuning pattern)
  CMD27    W   sd/mmc spi PROGRAM_CSD (128bit CSD register)
  CMD30    R   sd/mmc spi GET_WRITE_PROT (32bit write-protect flags)
  CMD31    R   mmc        GET_WRITE_PROT_TYPE (32x2bit write-protect types)
  CMD42    W   sd/mmc spi LOCK_UNLOCK (password header/data)
  CMD6     ??  sd     spi SWITCH_FUNC
  CMD40    ?   sd         Defined by DPS Spec (Data Protection System)
  CMD48,49 R/W sd         READ_EXTR_SINGLE, WRITE_EXTR_SINGLE
  CMD58,59 R/W sd         READ_EXTR_MULTI, WRITE_EXTR_MULTI
  CMD56    R/W sd     spi GEN_CMD
  CMD11    R   mmc        READ_DAT_UNTIL_STOP (class 1) (type=adtc)
  CMD20    W   mmc        WRITE_DAT_UNTIL_STOP (class 3) (type=adtc)
 xR1b      R   sd/mmc spi Busy signal for commands with "R1b" response

Misnamed Commands
Official command names include various SEND_xxx commands, which are misleading because they don't indicate if they "send" information <to> or <from> the card (or both). Better naming would be GET_xxx, SET_xxx, or GET_SET_xxx.
  Official Name         Renamed
  ALL_SEND_CID          ALL_GET_CID
  SEND_CID              GET_CID
  SEND_CSD              GET_CSD
  SEND_STATUS           GET_STATUS
  SEND_RELATIVE_ADDR    GET_RELATIVE_ADDR
  SEND_SCR              GET_SCR
  SEND_EXT_CSD          GET_EXT_CSD
  SEND_WRITE_PROT       GET_WRITE_PROT
  SEND_WRITE_PROT_TYPE  GET_WRITE_PROT_TYPE
  SEND_NUM_WR_BLOCKS    GET_NUM_WR_BLOCKS
  SEND_IF_COND          SET_IF_COND             ;-to card
  SEND_TUNING_BLOCK     SET_TUNING_BLOCK        ;-to card
  SEND_OP_COND          ...
  SD_SEND_OP_COND       ...
Other misnamed commands include SET_BLOCKLEN occassionally spelled SET_BLOCK_LEN in SD specs. SELECT_DESELECT_CARD is officially spelled SELECT/DESELECT_CARD.

Difference of SD Commands Definition in UHS-II
SD-TRAN driver of host should manage the difference of SD commands functions. Not supported commands should not issue to UHS-II card. CMD13 shall not be issued during data transfer. Normally, data transfer should be stopped by setting TLEN instead of using CMD12.
CMD23 and CMD55 functions are included in UHS-II packet functions.
 CMD0   Terminate SD transaction and reset SD-TRAN state.
 CMD3   Returns Device ID in the response instead of RCA
 CMD4   Illegal
 CMD6   Function Group 1 and 3 are not used.
 CMD7   Device ID is set to the argument instead of RCA
 CMD13  Device operation is up to implementation during data transfer (eg. CTS)
 CMD11  Illegal
 CMD12  Normally, TLEN (data length) in UHS-II packet is used to stop data
        transfer.
 CMD12  Should be used to abort an operation when illegal situation occurs.
 CMD15  Illegal
 CMD19  Illegal
 CMD23  Not Affected. TLEN in UHS-II packet is used to specify data length.
 CMD55  Not Affected. ACMD is set by APP field in UHS-II packet.
 ACMD6  Illegal
 ACMD42 Illegal
Not Affected means that the command is not executed in any card state, and response is returned (response type is up to implementation).
Illegal means that card returns response with NACK=1.
As SDHC/SDXC Cards do not support CMD28, 29 and 30, these commands are also illegal in UHS-II mode.

Note
All future reserved commands shall have a codeword length of 48 bits, as well as their responses (if there are any).


DSi SD/MMC Protocol: General Commands

CMD0 - SD/MMC - SPI - GO_IDLE_STATE (type=bc)
Parameter bits:
  31-0  stuff bits
SD Mode Response: N/A
SPI Mode Response: R1
Resets all cards to idle state, it's usually sent to (re-)invoke card detection and initialization. The command does also seem to reset many further registers (for example, TRAN_SPEED is said to be reset to 25MHz, and, although not officially specified, the DSi's eMMC chip appears to get forced back to 1bit data bus mode).
Observe that card detection/initialization should be done at lower CLK rate than usually (MMC specifies max 400kHz - this is actually required - the DSi's onboard Samsung KMAPF0000M-S998 eMMC chip won't respond to ALL_GET_CID when trying to use 16MHz CLK), higher CLK can be used once when detecting max speed (TRAN_SPEED in CSD register).
The command is also used to enter SPI mode (in SPI mode, the /CS pin is held low, while in 1bit/4bit mode that pin would be DAT3=floating/high), SPI commands can be sent without CRCs, however, at time when entering SPI mode, memory cards may still insist on checksums, CMD0 should be thus always sent with CRC7.

CMD8 - SD (SD v2.00 and up) - SPI - SET_IF_COND (type=bcr)
Parameter bits:
  31-12 reserved bits
  11-8  supply voltage (VHS)
  7-0   check pattern
SD Mode Response: R7:
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-20   Reserved (zero filled)           (20bit)      ;\2nd..4th byte
  19-16   Voltage accepted (see below)     (4bit)       ;/
  23-8    Echo-back of check pattern       (8bit)       ;-5th byte
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/
SPI Mode Response: R7:
  39-32  R1 (8bit Card Status, same as in normal SPI command responses)
  31-28  Command version (???)         (4bit)
  27-12  Reserved (0)                  (16bit)
  11-8   Voltage Accepted (see below)  (4bit)
  7-0    Echo-back of check pattern    (8bit)
Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage.
Voltage Accepted values:
  0001b  = 2.7-3.6V
  0010b  = Reserved for Low Voltage Range
  0100b  = Reserved
  1000b  = Reserved
  Others = Not Defined
The card supported voltage information of 3.3V range power pin is sent by the response of CMD8. Bits 19-16 indicate the voltage range that the card supports. The card that accepted the supplied voltage returns R7 response. In the response, the card echoes back both the voltage range and check pattern set in the argument.

CMD11 - SD - VOLTAGE_SWITCH (type=ac)
Parameter bits:
  31-0  reserved bits (0)
Response: R1
Switch to 1.8V bus signaling level.

CMD12 - SD/MMC - SPI - STOP_TRANSMISSION (type=ac)
Parameter bits:
  31-0  stuff bits
Response: R1b
Additional Data Transfer (from card): Busy signal for "R1b" response
Forces the card to stop transmission (SPI: in Multiple Block Read Operation).
Note: Toshiba SD/MMC controllers are sending STOP_TRANSMISSION automatically.

CMD15 - SD/MMC - GO_INACTIVE_STATE (type=ac)
Parameter bits:
  31-16 RCA
  15-0  reserved bits (0)
Response: N/A
Sends an addressed card into the Inactive State. This command is used when the host explicitly wants to deactivate a card once and forever (and won't even react to GO_IDLE_STATE) until next power-up (aka until ejecting/reinserting the card).

CMD59 - SD/MMC - SPI-ONLY (not Non-SPI Mode) - CRC_ON_OFF
Supported in SPI Mode only (in Non-SPI mode, CMD59 would be: MMC=Reserved, SD=WRITE_EXTR_MULTI)!
Parameter bits:
  31-1  stuff bits
  0     CRC option (0=off, 1=on)
SPI Mode Response: R1
Default on power up is unknown. Also unknown if this does completely prevent transmission of both CRC7 and CRC-CCITT values (especially in case of CID/CSD registers that have the CRC7 "inside" of the "128bit" register). Also unknown if CID/CSD are having "double" checksums (CRC7 plus CRC-CCITT) when transferring them as DATA packet (instead of as normal command/response).

ACMD6 - SD - SET_BUS_WIDTH (type=ac)
  31-2  stuff bits
  1-0   Bus width for Data transfers (0=1bit, 2=4bit, 1/3=reserved).
Response: R1
The supported widths can be found in SCR register. The current width is stored in SSR register. Default width is 1bit on power up.
Note: MMC uses a different mechanism to change the bus-width (via EXT_CSD).

ACMD42 - SD - SPI - SET_CLR_CARD_DETECT (type=ac)
  31-1  stuff bits
  0     set_cd (0=Disconnect, 1=Connect)
Response: R1
Connect/Disconnect the 50 KOhm pull-up resistor on CD/DAT3 pin of the card.
The pull-up might be intended for card detection (other than by using the slot's card detect switch), and/or for sensing SPI mode (which would drag that pin to LOW level when asserting /CS chip select).
During operation, disabling the pull-up might improve 4bit mode data transfers (unless for card controllers which do rely on the card pull-up to be present). The TC6387XB datasheet recommends external 100K pull-ups on DAT0-2, and only 47K on DAT3 (not quite sure why, unless Toshiba believed the parallel 50K+47K pull-ups to sum up to 100K, rather than to 25K).

CMD55 - SD/MMC (MMC: only in SPI-mode?) - SPI - APP_CMD (type=ac)
  31-16  RCA (SPI Mode: stuff bits)
  15-0   stuff bits
Response: R1
Used as prefix for application specific commands, ie. the next command will be treated as "ACMDnn" rather than as normal "CMDnn".
As the name says, this was originally intended for "application specific" extensions, however, in the SD Card protocol, it's also used for some ACMD's that are part of the SD protocol.

CMD56 - SD/MMC (MMC: only in SPI-mode?) - SPI - GEN_CMD (type=adtc)
  31-1  stuff bits
  0     RD/WR Direction (0=Write to Card, 1=Read from Card)
Response: R1
Additional Data Transfer (to/from card, depending on above R/W bit):
  General purpose data
  For SDSC, block length is set via SET_BLOCKLEN command.
  For SDHC/SDXC, block length is fixed to 512 bytes.
Used to transfer a data block to/from the card for general purpose/application specific commands.

CMD14 - MMC - BUSTEST_R (type=adtc) (MMC only, Reserved on SD)
CMD19 - MMC - BUSTEST_W (type=adtc) (MMC only, SET_TUNING_BLOCK on SD)
  31-0  stuff bits
Response: R1
Additional Data Transfer (to/from card):
  test pattern (2bit per DATA line? eg. 8bit pattern in 4bit-mode?)
MMC only. And, that, in Non-SPI mode only.
BUSTEST_W: Host sends the "bus TEST Data pattern" to card.
BUSTEST_R: Host reads the "REVERSED bus TESTING data pattern" from card.
The reversing is said to change a 2bit value of "01" into "10", unknown if that means that the bit-order is reversed, or that the bits are inverted.


DSi SD/MMC Protocol: Block Read/Write Commands

CMD16 - SD/MMC - SPI - SET_BLOCKLEN (type=ac)
  31-0  Block length (for Block Read, Block Write, Lock, and GEN_CMD)
Response: R1
In the case of SDSC Card, this command sets the block length (in bytes) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Set length is valid for memory access commands only if partial block read operation are allowed in CSD.
In the case of SDHC/SDXC Cards, block length set by CMD16 command does not affect memory read and write commands. Always 512 Bytes fixed block length is used. This command is effective for LOCK_UNLOCK command.
In both cases, if block length is set larger than 512 Bytes, the card sets the BLOCK_LEN_ERROR bit.
In DDR50 mode, block length must be even (because data is sampled on both clock edges).

CMD20 - SD (optional, see SCR.Bit32) - SPEED_CLASS_CONTROL (type=ac)
  31-28  Speed Class Control (for Block Read, and Block Write commands)
  27-0   Reserved (0)
Response: R1b
Additional Data Transfer (from card): Busy signal for "R1b" response
Speed Class control command. Refer to Section 4.13.2.8.

CMD23 - SD/MMC - SPI (but only on MMC) - SET_BLOCK_COUNT (type=ac)
Supported by SD and MMC Cards. However, in SPI-mode it's supported only for MMC? And, for SD it's optional (see SCR.Bit33).
  31-0  Block Count (MMC: only lower 16bit used, upper 16bit=reserved)
Response: R1
Specify block count for CMD18 and CMD25.

 ________________________ Block-Oriented READ Commands ________________________

CMD17 - SD/MMC - SPI - READ_SINGLE_BLOCK (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Additional Data Transfer (from card):
  data
In the case of SDSC Card, this command reads a block of the size selected by the SET_BLOCKLEN command. The data transferred shall not cross a physical block boundary unless READ_BLK_MISALIGN is set in the CSD.
In case of SDHC and SDXC Cards, block length is fixed 512 Bytes regardless of the SET_BLOCKLEN command.

CMD18 - SD/MMC - SPI - READ_MULTIPLE_BLOCK (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Additional Data Transfer (from card):
  data
Continuously transfers data blocks from card to host until interrupted by a STOP_TRANSMISSION command.
Block length is specified the same as READ_SINGLE_BLOCK command.

CMD19 - SD - SET_TUNING_BLOCK (type=adtc) (SD only, BUSTEST_W on MMC)
  31-0  reserved bits (0)
Response: R1
Additional Data Transfer (to card):
  64 bytes (512bit) tuning pattern is sent for SDR50 and SDR104.

 _______________________ Block-Oriented WRITE Commands _______________________

CMD24 - SD/MMC - SPI - WRITE_BLOCK (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Additional Data Transfer (to card):
  data
In case of SDSC Card, block length is set by the SET_BLOCKLEN command. The data transferred shall not cross a physical block boundary unless WRITE_BLK_MISALIGN is set in the CSD. In the case that write partial blocks is not supported, then the block length=default block length (given in CSD).
In case of SDHC and SDXC Cards, block length is fixed 512 Bytes regardless of the SET_BLOCKLEN command.

CMD25 - SD/MMC - SPI - WRITE_MULTIPLE_BLOCK (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Additional Data Transfer (to card):
  data
Continuously writes blocks of data until a STOP_TRANSMISSION follows.
Block length is specified the same as WRITE_BLOCK command.

ACMD22 - SD - SPI - GET_NUM_WR_BLOCKS (type=adtc)
  31-0  stuff bits
Response: R1
Additional Data Transfer (from card):
  31-0  Number of the written (without errors) write blocks (32bit)
Responds with 32bit+CRC data block.
If WRITE_BL_PARTIAL='0', the unit of ACMD22 is always 512 byte.
If WRITE_BL_PARTIAL='1', the unit of ACMD22 is a block length which was used when the write command was executed.

ACMD23 - SD - SPI - SET_WR_BLK_ERASE_COUNT (type=ac)
  31-23  stuff bits
  22-0   Number of blocks
Response: R1
Set the number of write blocks to be pre-erased before writing (to be used for faster Multiple Block WR command). "1"=default (one wr block).
Command STOP_TRAN (CMD12) shall be used to stop the transmission in Write Multiple Block whether or not the pre-erase (ACMD23) feature is used.

 _____________________ Byte-Streaming READ/WRITE Commands _____________________

CMD11 - MMC - READ_DAT_UNTIL_STOP (class 1) (type=adtc)
CMD20 - MMC - WRITE_DAT_UNTIL_STOP (class 3) (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Additional Data Transfer (to/from card):
  data
Similar to read/write multiple blocks, but transferring the data as an endless byte stream (instead of splitting it into separate blocks). Transfer is terminated by sending STOP_TRANSMISSION.


DSi SD/MMC Protocol: Special Extra Commands

 _________________________ Write PROTECTION Commands _________________________

CMD28 - SDSC/MMC (not SDHC/SDXC) - SPI - SET_WRITE_PROT (type=ac)
CMD29 - SDSC/MMC (not SDHC/SDXC) - SPI - CLR_WRITE_PROT (type=ac)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: Unsupported)
Response: R1b
Additional Data Transfer (from card): Busy signal for "R1b" response
Write protection support is indicated in CSD(WP_GRP_ENABLE), and additionally "class 6" should be flagged in CSD(CCC). The group size is indicated in CSD(WP_GRP_SIZE), observe that that field is 5bit/7bit wide for SD/MMC accordingly.

CMD30 - SDSC/MMC (not SDHC/SDXC) - SPI - GET_WRITE_PROT (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: Unsupported)
Response: R1
Additional Data Transfer (from card):
  31-0  Flags (1=write-protected) (bit0=addressed group, bit1..31=next groups)
If the card provides write protection features, this command asks the card to send the status of the write protection bits: 32 write protection bits (representing 32 write protect groups starting at the specified address) followed by 16 CRC bits are transferred in a payload format via the DATA line. The last (least significant) bit of the protection bits corresponds to the first addressed group. If the addresses of the last groups are outside the valid range, then the corresponding write protection bits shall be set to 0.

CMD31 - MMC - GET_WRITE_PROT_TYPE (type=adtc)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: Unsupported)
Response: R1
Additional Data Transfer (from card):
  63-0  Flags (1=write-protected) (bit0-1=addressed group, bit2..63=next)
Returns thirty-two 2bit values (0=not protected, 1=temporary write protection, 2=power-on write protection, 3=permanent write protection).

Further Write-Protection Mechanisms
The whole card can be write-protected via PERM_WRITE_PROTECT and TMP_WRITE_PROTECT bits in CSD register (supported for MMC and SDSC/SDHC/SDXC).
SD Cards (and SD Card adaptors for miniSD and microSD cards) are additionally having a mechanical "LOCK" write protection tab (MMC cards don't have that feature).
The PWD feature provides Read/Write-protection (when not knowing the password).

 _______________________________ Erase Commands _______________________________

CMD32 - SD - SPI - ERASE_WR_BLK_START (type=ac)
CMD33 - SD - SPI - ERASE_WR_BLK_END (type=ac)
  31-0  data address (SDSC: in 1-byte units, SDHC/SDXC: in 512-byte units)
Response: R1
Sets the address of the first/last write block of the continuous range to be erased.

CMD35 - MMC - SPI - ERASE_GROUP_START (type=ac)
CMD36 - MMC - SPI - ERASE_GROUP_END (type=ac)
  31-0  data address (MMC: in WHAT units?)
Response: R1
MMC only. Unknown, maybe similar to above SD commands?

CMD32-34,37 - SPI - MMC - Reserved for compatibility with older MMC cards
MMC only. Unknown, maybe also Erase related?

CMD38 - SD/MMC - SPI - ERASE (type=ac)
  31-0  stuff bits
Response: R1b
Additional Data Transfer (from card): Busy signal for "R1b" response
Erases all previously selected write blocks.

Further Erase Commands
Sectors are automatically erased on-the-fly when writing data blocks, so manually using above erase commands isn't really necessary; it may be useful for shreddering private data though, and it might also speed up subsequent writes since the writes can omit the on-the-fly erasing step.
The SET_WR_BLK_ERASE_COUNT (ACMD23) can be used to notify the card that it may pre-erase multiple sectors upon write commands (eg. to speed-up cluster writes that are spanning across multiple sectors).
The password lock feature includes a Forced Erase function, which will reset the password, and ERASE THE WHOLE CARD, this may be useful if the user has forgot the password, but will destroy data (possibly including the pre-formatted filesystem headers; which would be bad, because that headers should contain cluster sizes somewhat matched to the physical sector sizes).

 ________________________________ I/O Commands ________________________________

CMD5 - SD - SPI - Reserved for I/O cards
CMD52-54 - SD - SPI - Commands for SDIO
  CMD5  SDIO: IO_SEND_OP_COND
  CMD52 SDIO: IO_RW_DIRECT
  CMD53 SDIO: IO_RW_EXTENDED
Refer to the "SDIO Card Specification". SDIO is an extension to the SD protocol that allows to access non-memory-card hardware (such like cameras or network adaptors).

 __________________________ Switch Function Commands __________________________

CMD6 - SD (SD v1.10 and up) - SPI - SWITCH_FUNC (type=adtc)
  31     Mode (0=Check function, 1=Switch function)
  30-24  reserved (All '0')
  23-20  function group 6: Reserved (0h or Fh)
  19-16  function group 5: Reserved (0h or Fh)
  15-12  function group 4: Power Limit     ;SPI Mode: Reserved (0h or Fh)
  11-8   function group 3: Drive Strength  ;SPI Mode: Reserved (0h or Fh)
  7-4    function group 2: Command System
  3-0    function group 1: Access Mode
Response: R1
Additional Data Transfer (to/from whatever):
  unknown
Checks switch-able function (mode 0) and switch card function (mode 1). See Chapter 4.3.10.

CMD34-35 - SD - Reserved
Reserved for each command system set by switch function command (CMD6).
Detailed definition is referred to each command system specification.
Maybe related to above "function group 5..6"?

CMD36,37 - SD - Undoc (description field is held blank)
CMD50,57 - SD - Undoc (description field is held blank)
Undoc. Maybe related to above "function group 1..4"?

SPI: CMD34-37 - SD - SPI - Reserved for Command Systems from CMD6
SPI: CMD50,57 - SD - SPI - Reserved for Command Systems from CMD6
Described as so for SPI Mode. Maybe related to above "function group 1..6"?

 ________________________ Function Extension Commands ________________________

CMD21 - SD - Reserved for DPS Specification (Data Protection System)
Reserved.

CMD48 - SD (optional, see SCR.Bit34) - READ_EXTR_SINGLE (type=adtc)
  31     MIO (0=Memory, 1=I/O)
  30-27  FNO
  26     Reserved (0)
  25-9   ADDR
  8-0    LEN
Response: R1
Additional Data Transfer (from card):
  whatever
Single block read type. Refer to Section 5.7.2.1.

CMD49 - SD (optional, see SCR.Bit34) - WRITE_EXTR_SINGLE (type=adtc)
  31     MIO (0=Memory, 1=I/O)
  30-27  FNO
  26     MW
  25-9   ADDR
  8-0    LEN/MASK
Response: R1
Additional Data Transfer (to card):
  whatever
Single block write type. Refer to Section 5.7.2.2.

CMD58 - SD (optional, see SCR.Bit35) - READ_EXTR_MULTI (type=adtc)
  31     MIO (0=Memory, 1=I/O)
  30-27  FNO
  26     BUS (0=512B, 1=32KB)
  25-9   ADDR
  8-0    BUC
Response: R1
Additional Data Transfer (from card):
  whatever
Multi-block read type. Refer to Section 5.7.2.4.

CMD59 - SD (optional, see SCR.Bit35) - WRITE_EXTR_MULTI (type=adtc)
  31     MIO (0=Memory, 1=I/O)
  30-27  FNO
  26     BUS (0=512B, 1=32KB)
  25-9   ADDR
  8-0    BUC
Response: R1
Additional Data Transfer (to card):
  whatever
Multi-block write type. Refer to Section 5.7.2.5.

Note: CCC bit 11 is set to 1 when any command of class 11 is supported. Supporting of these commands is indicated in SCR register.


DSi SD/MMC Protocol: CSR Register (32bit Card Status Register)

CMD13 - SD/MMC - SPI - GET_STATUS (type=ac)
Parameter bits:
  31-16 RCA (SPI Mode: stuff bits)
  15-0  stuff bits
SD Mode Response: R1 (32bit Card Status):
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-8    CSR Card Status Register (32bit) (see below)  ;-2nd..5th byte
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/
SPI Mode Response: R2 (16bit Card Status):
  15-0    CSR Card Status Register (16bit) (see below)  ;-1st..2nd byte
Addressed card sends its status register.

CMDxx/ACMDxx - Other Commands
Most other commands are also returning the Card Status in their responses:
SD Mode Response: R1 (32bit Card Status)
SPI Mode Response: R1 (8bit Card Status; most SPI commands return only 8bit)
SPI Mode Response: R2 (16bit Card Status; SPI commands CMD13/ACMD return 16bit)

CMDxx/ACMDxx - Other Commands with R1b Response
R1b is identical to R1, with an optional busy signal transmitted on the DATA line (R1b occurs for CMD7, CMD12, CMD20, CMD28, CMD29, CMD38) (and for MMC: also for CMD5, CMD6). The card may become busy after receiving these commands based on its state prior to the command reception. The Host shall check for busy at the response.
In SD Mode, the busy signal is sent on DAT0 line (DAT1-3 aren't used, even if the card is in 4bit mode). The busy signal does consist of BITs? (not bytes?), and has a "start bit"?, followed by what-value-when-busy? and what-final-value-when-ready?
In SPI Mode, the busy signal is sent as BYTEs (00h=Busy, xxh=Nonzero=Ready).

CSR Card Status Register (full 32bit, as returned in SD Mode Response: R1)
  Bit  Typ Clr Identifier         Meaning
  31   ERX  C  OUT_OF_RANGE       (1=Command's argument was out of range)
  30   ERX  C  ADDRESS_ERROR      (1=Misaligned address/block len mismatch)
  29   ERX  C  BLOCK_LEN_ERROR    (1=Wrong block length, bytelen mismatch)
  28   ER   C  ERASE_SEQ_ERROR    (1=Error in erase command sequence)
  27   ERX  C  ERASE_PARAM        (1=Wrong erease selection of write-blocks)
  26   ERX  C  WP_VIOLATION       (1=Write failed due to write-protection)
  25   SX   A  CARD_IS_LOCKED     (1=Card is locked by the host)
  24   ERX  C  LOCK_UNLOCK_FAILED (1=Lock/unlock sequence or password error)
  23   ER   B  COM_CRC_ERROR      (1=CRC check of previous command failed)
  22   ER   B  ILLEGAL_COMMAND    (1=Command not legal for the card state)
  21   ERX  C  CARD_ECC_FAILED    (1=Internal error correction failed)
  20   ERX  C  CC_ERROR           (1=Internal card controller error)
  19   ERX  C  ERROR              (1=General error, or Unknown error)
  18   -    -  Reserved (eMMC: UNDERRUN)
  17   -    -  Reserved (eMMC: OVERRUN) (eSD: DEFERRED_RESPONSE)
  16   ERX  C  CSD_OVERWRITE      (1=read-only CSD section doesn't match card
                                  content, or attempted to reverse the
                                  Copy/WP bits)
  15   ERX  C  WP_ERASE_SKIP      (1=partial erase error due to write-protect)
  14   SX   A  CARD_ECC_DISABLED  (1=Internal error correction wasn't used)
  13   SR   C  ERASE_RESET        (1=Erase sequence was aborted)
  12-9 SX   B  CURRENT_STATE      (00h..0Fh=state, see below)
  8    SX   A  READY_FOR_DATA     (1=Ready/buffer is empty)
  7    EX   C  SWITCH_ERROR       (1=SWITCH command refused, MMC only)
  6    -    -  Reserved/Unspecified (description is left blank)
  5    SR   C  APP_CMD            (1=Card will expect ACMD)
  4    -    -  Reserved for SD I/O Card
  3    ER   C  AKE_SEQ_ERROR      (1=Authentication Sequence Error)
  2    -    -  Reserved for application specific commands
  1-0  -    -  Reserved for manufacturer test mode
Values for CURRENT_STATE (bit12-9):
  These bits indicate the OLD state of card when receiving the command,
  (ie. if the command does change the state, then the NEW state won't be
  seen until the NEXT command returns the new updated status bits)
  00h     = idle
  01h     = ready
  02h     = ident
  03h     = stby
  04h     = tran    ;<-- normal state (when waiting for read/write commands)
  05h     = data    ;data read  (CMD8,CMD11,CMD17,CMD18,CMD30,CMD56/R)
  06h     = rcv     ;data write (CMD20?,CMD24,CMD25,CMD26,CMD27,CMD42,CMD56/W)
  07h     = prg     ;erase/wprot (CMD6,CMD28,CMD29,CMD38)
  08h     = dis
  09h     = btst    ;bus test write (CMD19, MMC only)
  0Ah     = slp     ;sleep (CMD5, MMC only)
  0Bh-0Eh = reserved
  0Fh     = reserved for I/O mode (SDIO-only devices, without SD-memory)
  N/A     = ina     ;inactive (CMD15) (card is killed, and can't send status)
  N/A     = irq     ;interrupt mode (CMD40, MMC only)
  N/A     = pre     ;pre-idle (MMC only)
Type aka Typ column (in above table):
  E: Error bit.
  S: Status bit.
  R: Flag may get set within response of current command.
  X: Flag may get set within response of NEXT command (with R1 response)
Clear Condition aka Clr column (in above table):
  A: According to the card current state.
  B: Always related to the previous command. Reception of a valid command
     will clear it (with a delay of one command).
  C: Clear by read.

SPI Responses (8bit "R1" Responses, and 16bit "R2" Responses)
 FIRST BYTE of all SPI Responses:
  7  always 0                          ;\
  6  parameter error                   ; These 8bit are returned in ALL normal
  5  address error                     ; SPI commands (with 8bit "R1" response)
  4  erase sequence error              ; and,
  3  com crc error                     ; the same 8bits are also returned
  2  illegal command                   ; as FIRST BYTE in SPI commands with
  1  erase reset                       ; longer responses
  0  in idle state                     ;/
 SECOND BYTE of SPI "R2" Response:
  7  out of range, or csd overwrite           ;\
  6  erase param                              ;
  5  wp violation                             ; These extra 8bits are returned
  4  card ecc failed                          ; as SECOND BYTE in SPI commands
  3  CC error                                 ; with 16bit "R2" status response
  2  error                                    ; (ie. in CMD13 and ACMD13)
  1  wp erase skip, or lock/unlock cmd failed ;
  0  Card is locked                           ;/

Card Status Field/Command - Cross Reference
For each command responded by R1 response, following table defines the affected bits in the status field. An 'x' means the error/status bit may be set in the response to the respective command.
  Bits     31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12-9 8 5
  CMD3                             x  x        x                    x
  CMD6     x                 x     x  x  x  x  x                    x
  CMD7                 x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD11                      x     x  x        x                    x
  CMD12    x  x           x  x     x  x  x  x  x              x     x
  CMD13    x  x        x  x  x  x  x  x  x  x  x        x  x  x     x    x
  CMD16          x     x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD17    x  x        x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD18    x  x        x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD19    x  x        x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD20    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD23    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD24    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD25    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD26                x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD27                x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD28    x           x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD29    x           x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD30    x           x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD32    x        x  x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD33    x        x  x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD38             x  x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD42                x  x  x  x  x  x  x  x  x        x  x  x  x  x
  CMD48    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD49    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD55                x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  CMD56                x  x  x  x  x  x  x  x  x        x  x  x  x  x    x  x
  CMD58    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  CMD59    x  x  x     x  x  x  x  x  x  x  x  x        x  x  x  x  x    x
  ACMD6    x           x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  ACMD13               x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  ACMD22               x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  ACMD23               x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  ACMD42               x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
  ACMD51               x  x  x  x  x  x  x  x  x        x  x  x  x  x       x
Note: The response to CMD3 is R6 that includes only bits 23, 22, 19 and 12:9 out of the Card Status.


DSi SD/MMC Protocol: SSR Register (512bit SD Status Register)

ACMD13 - SD - SPI - SD_STATUS (type=adtc)
  31-0   stuff bits
SD Mode Response: R1 (32bit Card Status)
SPI Mode Response: R2 (16bit Card Status) (same as for CMD13, see there)
Additional Data Transfer (from card):
  511-0  SSR Register (512bit)
Send the SD Status. The status fields are given in Table 4-43.

SD Status (transferred on DATA line after ACMD13)
The size of the SD Status is one data block of 512 bit. The content of this register is transmitted to the Host over the DAT bus along with a 16-bit CRC.
ACMD13 can be sent to a card only in 'tran_state' (card is selected).
  Bits   Type Clr Identifier
  511-510  SR A   DAT_BUS_WIDTH (0..3, see below)
  509      SR A   SECURED_MODE  (0=Normal, 1=Secured) (Part 3 Security Specs)
  508-502  -  -   Reserved for Security Functions     (Part 3 Security Specs)
  501-496  -  -   Reserved
  495-480  SR A   SD_CARD_TYPE  (0..FFFFh, see below)
  479-448  SR A   SIZE_OF_PROTECTED_AREA   Size of protected area (see below)
  447-440  SR A   SPEED_CLASS      Speed Class of the card (see below)
  439-432  SR A   PERFORMANCE_MOVE Performance of move indicated by 1 MB/s step
  431-428  SR A   AU_SIZE          Size of AU (see below)
  427-424  -  -   Reserved
  423-408  SR A   ERASE_SIZE       Number of AUs to be erased at a time
  407-402  SR A   ERASE_TIMEOUT    Timeout value for erasing areas
                                   specified by UNIT_OF_ERASE_AU (see below)
  401-400  SR A   ERASE_OFFSET     Fixed offset value added to erase time
  399-396  SR A   UHS_SPEED_GRADE  Speed Grade for UHS mode  (see below)
  395-392  SR A   UHS_AU_SIZE      Size of AU  for UHS mode  (see below)
  391-312  -  -   Reserved
  311-0    -  -   Reserved for manufacturer

Values for DAT_BUS_WIDTH (as set via SET_BUS_WIDTH command):
  00h = 1 bit width (default)
  01h = reserved
  02h = 4 bit width
  03h = reserved

Values for SD_CARD_TYPE
  0000h = Regular SD RD/WR Card
  0001h = SD ROM Card
  0002h = OTP
  0004h,0008h,0010h,0020h,0040h,0080h = Reserved for future variations
  01xxh..FFxxh = Reserved for Cards that don't comply to Physical Layer Specs

Values for SIZE_OF_PROTECTED_AREA
Setting this field differs between SDSC and SDHC/SDXC.
In case of SDSC Card, the capacity of protected area is calculated as follows:
  Protected Area = SIZE_OF_PROTECTED_AREA_* MULT * BLOCK_LEN.
  SIZE_OF_PROTECTED_AREA is specified by the unit in MULT*BLOCK_LEN.
In case of SDHC and SDXC Cards, the capacity of protected area is calculated as follows:
  Protected Area = SIZE_OF_PROTECTED_AREA
  SIZE_OF_PROTECTED_AREA is specified by the unit in byte.

Values for SPEED_CLASS
This 8-bit field indicates the Speed Class. Classes lower than indicated by this field are also effective.
  00h      Speed Class 0
  01h      Speed Class 2
  02h      Speed Class 4
  03h      Speed Class 6
  04h      Speed Class 10
  05h-FFh  Reserved for future/faster classes
Application Note:
If a Class value indicated in SD Status (including reserved value) is larger than that of host supported, the host should read as any Class can be used with the card.
For example, Class 10 is indicated, host should consider Class 2 to 6 is also effective.

Values for PERFORMANCE_MOVE
This 8-bit field indicates Pm and the value can be set by 1 [MB/sec] step.
If the card does not move used RUs, Pm should be considered as infinity.
Setting to FFh means infinity.
Pm is defined for Class 2 to 6 in Default Speed Mode. When host uses Class 10, Pm indicated in SD Status shall be ignored and treated as 0.
  00h    Sequential Write
  01h    1 [MB/sec]
  02h    2 [MB/sec]
  ...    ...
  FEh    254 [MB/sec]
  FFh    Infinity

Values for AU_SIZE
This 4-bit field indicates AU Size and the value can be selected from 16 KB.
  00h    Not Defined
  01h    16 KB
  02h    32 KB
  03h    64 KB
  04h    128 KB
  05h    256 KB
  06h    512 KB
  07h    1 MB
  08h    2 MB
  09h    4 MB
  0Ah    8 MB
  0Bh    12 MB (!)
  0Ch    16 MB
  0Dh    24 MB (!)
  0Eh    32 MB
  0Fh    64 MB
Maximum AU size (depending on card capacity):
  Card Capacity     up to 64MB  up to 256MB  up to 512MB  up to 32GB  up to 2TB
  Maximum AU Size   512 KB      1 MB         2 MB         4 MB1       64MB
The card can set any AU size (up to above maximum AU size values).
The card should set smaller AU size as much as possible.
Application Notes:
The host should determine host buffer size based on total busy time of 4MB and the card supported class. The host can treat multiple AUs combined as one unit.

Values for ERASE_SIZE
This 16-bit field indicates NERASE. When NERASE numbers of AUs are erased, the timeout value is specified by ERASE_TIMEOUT (Refer to ERASE_TIMEOUT).
The host should determine proper number of AUs to be erased in one operation so that the host can indicate progress of erase operation.
  0000h    Erase Time-out Calculation is not supported.
  0001h    1 AU
  0002h    2 AU
  0003h    3 AU
  ...      ...
  FFFFh    65535 AU

Values for ERASE_TIMEOUT
This 6-bit field indicates the TERASE and the value indicates erase timeout from offset when multiple AUs are erased as specified by ERASE_SIZE. The range of ERASE_TIMEOUT can be defined as up to 63 seconds and the card manufacturer can choose any combination of ERASE_SIZE and ERASE_TIMEOUT depending on the implementation. Once ERASE_TIMEOUT is determined, it determines the ERASE_SIZE. The host can determine timeout for any number of AU erase by the Equation (6). Refer to 4.14 for the concept of calculating erase timeout. If ERASE_SIZE field is set to 0, this field shall be set to 0.
  00h      Erase Time-out Calculation is not supported.
  01h      1 [sec]
  02h      2 [sec]
  03h      3 [sec]
  ...      ...
  3Fh      63 [sec]

Values for ERASE_OFFSET
This 2-bit field indicates the TOFFSET and one of four values can be selected. The erase offset adjusts the line by moving in parallel on the upper side. Refer to Figure 4-57 and Equation (6) in 4.14. This field is meaningless if ERASE_SIZE and ERASE_TIMEOUT fields are set to 0.
  00h      0 [sec]
  01h      1 [sec]
  02h      2 [sec]
  03h      3 [sec]

Values for UHS_SPEED_GRADE
This 4-bit field indicates the UHS mode Speed Grade. Reserved values are for future speed grades larger than the highest defined value. Host shall treat reserved values (undefined) as highest grade defined.
  00h      Less than 10MB/sec
  01h      10MB/sec and above
  02h-0Fh  Reserved

Values for UHS_AU_SIZE
This 4-bit field indicates AU Size for UHS-I and UHS-II cards. Card should set smaller value as much as possible. Host shall refer to UHS_AU_SIZE instead of AU_SIZE when the card is operating in UHS-I or UHS-II bus speed modes.
  00h      Not Defined
  01h-06h  Not Used
  07h      1 MB
  08h      2 MB
  09h      4 MB
  0Ah      8 MB
  0Bh      12 MB (!)
  0Ch      16 MB
  0Dh      24 MB (!)
  0Eh      32 MB
  0Fh      64 MB


DSi SD/MMC Protocol: OCR Register (32bit Operation Conditions Register)

CMD1 (MMC) and ACMD41 (SD) are intended to exchange OCR information. That is, the OCR parameter bits should indicate the host conditions (eg. for DSi: 40100000h, ie. bit20=3.3V supply, and bit30=HCS support for High Capacity carts with more than 2GBytes). The OCR response may then return something like 007f8000h when busy, and 807f8000h when ready (bit20 indicating the voltage being actually supported, bit30 indicating if it's High Capacity card, and bit31 indicating if the card is ready & switched from "idle" to "ready" state).
Cards do usually send at least one response with bit31=0 (busy), one should repeat sending CMD1/ACMD51 until bit31=1 (ready).
Note: All card(s) on the bus will respond to CMD1/ACMD51: with the response bits ANDed together (thus returning nonsense in bit30=HCS when actually sharing the same bus for multiple cards).
Note: The card switches to "ina" state if the voltage in param bits isn't supported.

CMD1 - SD/MMC (For SD Cards: SPI-only) - SPI - SEND_OP_COND
Parameter For MMC Cards (supported in SPI and Non-SPI mode):
  31-0  OCR without busy (ie. without the power-up busy flag in bit31)
Parameter For SD Cards (supported in SPI mode only, not in Non-SPI mode):
  31    Reserved (0)                            ;\special case (applies
  30    HCS (Host Capacity Support information) ; to SD-cards in SPI-mode
  29-0  Reserved (0)                            ;/only)
SD Response: R1
MMC Response: R3 (same/similar as SD Mode's ACMD41 response, see below)
Sends host capacity support information and activates the card's initialization process. HCS is effective when card receives SET_IF_COND command.

ACMD41 - SD - SPI - SD_SEND_OP_COND (type=bcr)
  31     reserved bit
  30     HCS(OCR[30]) (Host Capacity Support information)
  29     reserved for eSD                 ;\
  28     XPC Max Power Consumption (watts); SPI Mode: Reserved
  27-25  reserved bits                    ; (ie. only bit30 is used for SPI)
  24     S18R                             ; (ie. ACMD41 is SAME as SPI CMD1 ?)
  23-0   VDD Voltage Window(OCR[23-0])    ;/
SD Mode Response: R3:
  47     Start Bit (0)                                 ;\
  46     Transmission To Host (0)                      ; 1st byte
  45-40  Reserved (111111) (instead of Command value)  ;/
  39-8   OCR (32bit)                                   ;-2nd..5th byte
  7-1    Reserved (111111) (instead of CRC7)           ;\6th byte
  0      End Bit (1)                                   ;/
SPI Mode Response: R1 (without extra Data transfer? use READ_OCR instead?)
Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. HCS is effective when card receives SET_IF_COND command (uh, but IF_COND should be set BEFORE setting OP_COND?).
Sends request to switch to 1.8V signaling (S18R).
Reserved bit shall be set to '0'. CCS bit is assigned to OCR[30].
XPC controls the maximum power in the default speed mode of SDXC card.
  XPC=0: 0.36W (100mA at 3.6V on VDD1) (max) but speed class is not supported.
  XPC=1: 0.54W (150mA at 3.6V on VDD1) (max) and speed class is supported.

CMD58 - SD/MMC - SPI-ONLY (not Non-SPI Mode) - READ_OCR
Supported on SD Cards in SPI Mode only (in Non-SPI mode, CMD58 would be: MMC=Reserved, SD=READ_EXTR_MULTI)!
Parameter bits:
  31-0  stuff bits
SPI Mode Response: R3:
  39-32  R1 (8bit Card Status, same as in normal SPI command responses)
  31-0   OCR (32bit)

OCR register
The 32-bit operation conditions register stores the VDD voltage profile of the non UHS-II card and VDD1 voltage profile of the UHS-II card. Additionally, this register includes status information bits. One status bit is set if the card power up procedure has been finished. This register includes another status bit indicating the card capacity status after set power up status bit. The OCR register shall be implemented by the cards.
The 32-bit operation conditions register stores the VDD voltage profile of the card.
Bit 7 of OCR is newly defined for Dual Voltage Card and set to 0 in default. If a Dual Voltage Card does not receive CMD8, OCR bit 7 in the response indicates 0, and the Dual Voltage Card which received CMD8, sets this bit to 1.
  31     Card power up status bit (0=Busy, 1=Ready)
  30     Card Capacity Status (CCS) (valid only if above Bit31 indicates Ready)
          CCS=0   SDSC Card      (addressed in 1-byte units)   ;MMC max 2GB
          CCS=1   SDHC/SDXC card (addressed in 512-byte units) ;MMC > 2GB
  29     UHS-II Card Status
  28-25  Reserved
  24     Switching to 1.8V Accepted (S18A) (Only UHS-I card supports this bit)
  23     3.5-3.6                        ;\
  22     3.4-3.5                        ;
  21     3.3-3.4                        ;
  20     3.2-3.3 ;<-- this used by DSi  ;
  19     3.1-3.2                        ; VDD Voltage Window
  18     3.0-3.1                        ;
  17     2.9-3.0                        ;
  16     2.8-2.9                        ;
  15     2.7-2.8                        ;
  14-8   Reserved (MMC: 2.0V .. 2.6V)   ;  ;<-- uh, probably in opposite order?
  7      Reserved for Low Voltage Range ;
  6-4    Reserved                       ;
  3-0    Reserved                       ;/
The supported voltage range is coded as shown in Table 5-1. A voltage range is not supported if the corresponding bit value is set to LOW. As long as the card is busy, the corresponding bit (31) is set to LOW.
VDD Voltage Window of OCR indicates VDD1 voltage range in case of UHS-II Card.
UHS-II Card Status bit is added in Bit 29 to indicate whether the card supports UHS-II Interface. Non UHS-II Card sets Bit 29 to 0 and UHS-II Card sets Bit 29 to 1. This bit is not affected by whether VDD2 is supplied or not.


DSi SD/MMC Protocol: CID Register (128bit Card Identification)

CMD2 - SD/MMC - ALL_GET_CID (type=bcr)
CMD2 is/was intended for multiple MMC cards on the same SD/MMC bus, the connected card(s) should compare the CMD2 response bits seen on the bus, and the card with the smallest CID number is switched to "ident" state (and any other cards stay in "ready" state until sending further CMD2's).
CMD2 is still required for both SD and MMC during initialization, although actually sharing the same bus for multiple cards is rather uncommon/depracted (and might envolve various problems: Like conflicting OCR responses, conflicting pull-ups on DAT3 pin, signal noise/spikes on insertion/removal of a second card while accessing another card, problems with (shared) Write Protect and Card Detect switches, and so on).
Parameter bits:
  31-0  stuff bits
SD Mode Response: R2 (same 136bit response as for CMD10, see there)
Asks any card to send the CID numbers on the CMD line (any card that is connected to the host will respond - until it sees a "0" bit from another card while itself outputting a "1" bit).
Observe that CMD2 (and other card detection/initialization commands) should be done at lower CLK rate than usually (MMC specifies max 400kHz - this is actually required - the DSi's onboard Samsung KMAPF0000M-S998 eMMC chip won't respond to ALL_GET_CID when trying to use 16MHz CLK), higher CLK can be used once when detecting max speed (TRAN_SPEED in CSD register).

CMD10 - SD/MMC - SPI - GET_CID (type=ac)
This command should be used for actually READING the CID (as opposed to ALL_GET_CID which is primarily intended for the connected card(s) to COMPARE their CIDs with each other).
Parameter bits:
  31-16 RCA (SPI Mode: stuff bits)
  15-0  stuff bits
SD Mode Response: R2:
  135     Start Bit (0)                                 ;\
  134     Transmission To Host (0)                      ; 1st byte
  133-128 Reserved (111111) (instead of Command value)  ;/
  127-8   CID (120bit) (15 bytes)     ;\aka 128bit      ;-2nd..16th byte
  7-1     CRC7                        ; when including  ;\17th byte
  0       End Bit (1)                 ;/CRC7+EndBit     ;/
SPI Mode Response: R1, plus DATA line,
SPI Mode Additional Data Transfer (from card):
  127-0   CID (128bit) ... or 120bit ?
Addressed card sends its card identification (CID).

CID register
The Card IDentification (CID) register is 128 bits wide. It contains the card identification information used during the card identification phase. Every individual Read/Write (RW) card shall have a unique identification number.
For SD Cards (short product name, but bigger date field, 2000..2255?):
  Bit     Siz  Field  Name
  127-120   8  MID    Manufacturer ID    (binary) ;\assigned by SD-3C, LLC
  119-104  16  OID    OEM/Application ID (ASCII)  ;/
  103-64   40  PNM    Product name       (ASCII)
  63-56     8  PRV    Product revision   (BCD, 00h-99h) (eg 62h = rev 6.2)
  55-24    32  PSN    Product serial number (32bit)
  23-20     4  -      Reserved (zero)
  19-8     12  MDT    Manufacturing date (yymh) (m=1..12, yy=0..255?; +2000)
  7-1       7  CRC    CRC7 checksum
  0         1  1      Stop bit (always 1)
For MMC Cards (smaller date field, range 1997..2012 only):
  Bit     Siz  Field  Name
  127-120   8  MID    Manufacturer ID    (binary)   ;\assigned by MMCA
  119-104  16  OID    OEM/Application ID (binary)   ;/  ... or ...
  127-120   8  MID    Manufacturer ID    (binary)   ;\assigned by MMCA/JEDEC
  119-114   6  -      Reserved (0)                  ;
  113-112   2  CBX    Device (0=Card, 1=BGA, 2=POP) ;
  119-104   8  OID    OEM/Application ID (binary)   ;/
  103-56   48  PNM    Product name       (ASCII)
  55-48     8  PRV    Product revision   (BCD, 00h-99h) (eg 62h = rev 6.2)
  47-16    32  PSN    Product serial number (32bit)
  15-8      8  MDT    Manufacturing date (myh) (m=1..12, y=0..15; +1997)
  7-1       7  CRC    CRC7 checksum
  0         1  1      Stop bit (always 1)

Known CID's for DSi eMMC chips (excluding CRC in LSB, padded 00 in MSB)
  MY ss ss ss ss 03 4D 30 30 46 50 41 00 00 15 00  ;DSi Samsung KMAPF0000M-S998
  MY ss ss ss ss 32 57 37 31 36 35 4D 00 01 15 00  ;DSi Samsung KLM5617EFW-B301
  MY ss ss ss ss 30 36 35 32 43 4D 4D 4E 01 FE 00  ;DSi ST NAND02GAH0LZC5 rev30
  MY ss ss ss ss 31 36 35 32 43 4D 4D 4E 01 FE 00  ;DSi ST NAND02GAH0LZC5 rev31
  MY ss ss ss ss 03 47 31 30 43 4D 4D 00 01 11 00  ;3DS whatever chiptype?
  MY ss ss ss ss 07 43 59 31 47 34 4D 00 01 15 00  ;3DS Samsung KLM4G1YE0C-B301

See also:
DSi Console IDs


DSi SD/MMC Protocol: CSD Register (128bit Card-Specific Data)

CMD9 - SD/MMC - SPI - GET_CSD (type=ac)
Parameter bits:
  31-16 RCA (SPI Mode: stuff bits)
  15-0  stuff bits
SD Mode Response: R2:
  135     Start Bit (0)                                 ;\
  134     Transmission To Host (0)                      ; 1st byte
  133-128 Reserved (111111) (instead of Command value)  ;/
  127-8   CSD (120bit) (15 bytes)     ;\aka 128bit      ;-2nd..16th byte
  7-1     CRC7                        ; when including  ;\17th byte
  0       End Bit (1)                 ;/CRC7+EndBit     ;/
SPI Mode Response: R1, plus DATA line,
SPI Mode Additional Data Transfer (from card):
  127-0   CID (128bit) ... or 120bit ?
Addressed card sends its card-specific data (CSD).

CMD27 - SD/MMC - SPI - PROGRAM_CSD (type=adtc)
  31-0  stuff bits
Response: R1
Additional Data Transfer (to card):
  128-0  CSD register (whole 128bit) (read-only bits must be unchanged)
Programming of the programmable bits of the CSD, ie. the "R/W" bits, the "R" bits must be kept unchanged (read via CMD9, and write-back same values via CMD27).
The writable once "R/W(1)" bits can be changed only from 0-to-1, or vice-versa, they can be really written only ONCE, by the manufacturer?
Most of the "R/W(1)" bits are probably set by the manufacturer at time when pre-formatting the card, so they aren't actually user-writeable.

CSD Register
The types of the entries in the table below are coded as follows: R=readable, W(1)=writable once, W=multiple writable.
  Bit    Siz Type   Name                             Field             Value
  127-126 2  R      CSD structure version            CSD_STRUCTURE     00b
  125-122 4  R      MMC: System spec version         SPEC_VERS         ..
  125-122 4  R      SD: reserved                     -                 0000b
  121-120 2  R      reserved                         -                 00b
  119-112 8  R      data read access-time-1          TAAC              xxh
  111-104 8  R      data read access-time-2          NSAC              xxh
  103-96  8  R      max data transfer rate           TRAN_SPEED   32h or 5Ah
  95-84  12  R      card command classes             CCC          01x110110101b
  83-80   4  R      max read data block len          READ_BL_LEN          xh
  79      1  R      partial blocks for read allowed  READ_BL_PARTIAL      1b
  78      1  R      write block misalignment         WRITE_BLK_MISALIGN   xb
  77      1  R      read block misalignment          READ_BLK_MISALIGN    xb
  76      1  R      DSR implemented                  DSR_IMP              xb
  75-74   2  R      reserved                              -               00b
  73-70   4  R      SDHC/SDXC: reserved                   -               0000b
  69-48  22  R      SDHC/SDXC: device size                C_SIZE          ...
  47      1  R      SDHC/SDXC: reserved                   -               0
  73-62  12  R      MMC/SDSC: device size                 C_SIZE          xxxh
  61-59   3  R      MMC/SDSC: max read current @VDD min   VDD_R_CURR_MIN  xxxb
  58-56   3  R      MMC/SDSC: max read current @VDD max   VDD_R_CURR_MAX  xxxb
  55-53   3  R      MMC/SDSC: max write current @VDD min  VDD_W_CURR_MIN  xxxb
  52-50   3  R      MMC/SDSC: max write current @VDD max  VDD_W_CURR_MAX  xxxb
  49-47   3  R      MMC/SDSC: device size multiplier      C_SIZE_MULT     xxxb
  46-42   5  R      MMC: Erase Group Size             ERASE_GRP_SIZE   ..
  41-37   5  R      MMC: Erase Group Multiplier       ERASE_GRP_MULT   ..
  36-32   5  R      MMC: Write Protect Grp Size       WP_GRP_SIZE      ..
  46      1  R      SD: erase single block enable     ERASE_BLK_EN     xb
  45-39   7  R      SD: erase sector size             SECTOR_SIZE      xxxxxxxb
  38-32   7  R      SD: write protect group size      WP_GRP_SIZE      xxxxxxxb
  31      1  R      write protect group enable        WP_GRP_ENABLE    xb
  30-29   2  R      MMC: Manufacturer default ECC     DEFAULT_ECC      ..
  30-29   2  R      SD: reserved (do not use)         -                00b
  28-26   3  R      write speed factor                R2W_FACTOR       xxxb
  25-22   4  R      max write data block len          WRITE_BL_LEN     xxxxb
  21      1  R      partial blocks for write allowed  WRITE_BL_PARTIAL xb
  20-17   4  R      reserved                          -                0000b
  16      1  R      SD: reserved                      -                0
  16      1  R      MMC: Content Protection Applicat. CONTENT_PROP_APP ..
  15      1  R/W(1) File format group                 FILE_FORMAT_GRP  xb
  15      1  R      SDHC/SDXC: reserved               (FILE_FORMAT_GRP)0
  14      1  R/W(1) copy flag                         COPY             xb
  13      1  R/W(1) permanent write protection     PERM_WRITE_PROTECT  xb
  12      1  R/W    temporary write protection     TMP_WRITE_PROTECT   xb
  11-10   2  R/W(1) File format                    FILE_FORMAT         xxb
  11-10   2  R      SDHC/SDXC: reserved            (FILE_FORMAT)       00b
  9-8     2  R/W    MMC: ECC Code                  ECC                 ..
  9-8     2  R/W    SDSC: reserved, R/W            -                   00b
  9-8     2  R      SDHC/SDXC: reserved, R         -                   00b
  7-1     7  R/W    CRC                            CRC                 xxxxxxxb
  0       1  -      not used, always '1'           -                   1b

Known CSD's for DSi eMMC chips (excluding CRC in LSB, padded 00 in MSB)
  8  16 24 32 40 48 56 64 72 80 88 96 104112120pad ;<--bit numbers
  40 40 96 E9 7F DB F6 DF 01 59 0F 2A 01 26 90 00  ;DSi Samsung KMAPF0000M-S998
  40 40 8E FF 03 DB F6 DF 01 59 0F 32 01 27 90 00  ;DSi Samsung KLM5617EFW-B301
  00 40 8A E0 BF FF 7F F5 80 59 0F 32 01 2F 90 00  ;DSi ST NAND02GAH0LZC5 rev30
  00 40 8A E0 BF FF 7F F5 80 59 0F 32 01 2F 90 00  ;DSi ST NAND02GAH0LZC5 rev31
  ?                                            00  ;3DS whatever chiptype?
  40 40 8A E7 FF DB F6 6B 02 5A 0F 32 01 27 D0 00  ;3DS Samsung KLM4G1YE0C-B301
That is, differences are:
  bit     name            KMAPF0000M  KLM5617EFW NAND02GAH0LZC5 KLM4G1YE0C
  126-127 CSD_STRUCTURE   2=v1.2      2=v1.2     2=v1.2         3=SeeEXT_CSD
  112-119 TAAC            26h=1.5ms   27h=15ms   2Fh=20ms       27h=15ms
  96-103  TRAN_SPEED      2Ah=20MHz   32h=25MHz  32h=25MHz      32h=25MHz
  80-83   READ_BL_LEN     9=512       9=512      9=512          0Ah=1024
  79      READ_BL_PARTIAL 0=No(?)     0=No(?)    1=Yes          0=No(?)
  62-73   C_SIZE          77Fh=240MB  77Fh=240MB 3D5h=245.5MB   9AFh=1240MB
  59-61   VDD_R_CURR_MIN  6=60mA      6=60mA     7=100mA        6=60mA
  56-58   VDD_R_CURR_MAX  6=80mA      6=80mA     7=200mA        6=80mA
  53-55   VDD_W_CURR_MIN  6=60mA      6=60mA     7=100mA        6=60mA
  50-52   VDD_W_CURR_MAX  6=80mA      6=80mA     7=200mA        6=80mA
  47-49   C_SIZE_MULT     6=256       6=256      7=512          7=512
  42-46   ERASE_GRP_SIZE  1Fh=32x32   00h=1x32   1Fh=32x32      1Fh=32x32
  32-36   WP_GRP_SIZE     09h=10      1Fh=32     00h=1          07h=8
  26-28   R2W_FACTOR      05h=32x     03h=8x     02h=4x         02h=4x
  14      COPY            1=Copy      1=Copy     0=Original     1=Copy
Not sure if that values are really correct, or if the manufacturer has screwed up some bits. TAAC being 10x slower in newer chips looks weird, 20MHz would be for 1bit MCC (whilst 4bit MMCplus/MMCmobile should support 26MHz), erase group 32x32x512 bytes would somewhat require 512Kbyte clusters, write protect group size 10 decimal looks a bit odd (though it could be true), and, well, faster writing in newer chips looks plausible.

CSD_STRUCTURE (upper 2bit of CSD register)
Field structures of the CSD register are different depend on the Physical Layer Specification Version and Card Capacity.
The CSD_STRUCTURE field in the CSD register indicates its structure version.
For MMC:
  00h      CSD version No. 1.0    MMC Version 1.0 - 1.2
  01h      CSD version No. 1.1    MMC Version 1.4 - 2.2
  02h      CSD version No. 1.2    MMC Version 3.1 - 3.2 - 3.31 - 4.0 - 4.1- 4.2
  03h      Version is coded in the CSD_STRUCTURE byte in the EXT_CSD register
For SD:
  00h      CSD Version 1.0   SDSC (Standard Capacity)
  01h      CSD Version 2.0   SDHC/SDXC (High Capacity and Extended Capacity)
  02h-03h  Reserved
SDHC/SDXC applies major changes to CSD register (C_SIZE is expanded, and many other fields are removed or set to dummy values), for details see:
DSi SD/MMC Protocol: CSD Register (128bit Card-Specific Data) Version 2.0

SPEC_VERS (MMC only)
  00h       MMC System Specification Version 1.0 - 1.2
  01h       MMC System Specification Version 1.4
  02h       MMC System Specification Version 2.0 - 2.2
  03h       MMC System Specification Version 3.1 - 3.2 - 3.31
  04h       MMC System Specification Version 4.0 - 4.1 - 4.2
  05h-0Fh   Reserved

TAAC
Defines the asynchronous part of the data access time.
  7    Reserved
  6-3  Time value
         0=reserved, 1=1.0, 2=1.2, 3=1.3, 4=1.5, 5=2.0, 6=2.5, 7=3.0,
         8=3.5, 9=4.0, A=4.5, B=5.0, C=5.5, D=6.0, E=7.0, F=8.0
  2-0  Time unit
         0=1ns, 1=10ns, 2=100ns, 3=1us, 4=10us, 5=100us, 6=1ms, 7=10ms

NSAC
Defines the worst case for the clock-dependent factor of the data access time. The unit for NSAC is 100 clock cycles. Therefore, the maximal value for the clock-dependent part of the data access time is 25500 clock cycles.
The total access time NAC is the sum of TAAC and NSAC. It should be computed by the host for the actual clock rate. The read access time should be interpreted as a typical delay for the first data bit of a data block or stream.

TRAN_SPEED
The following table defines the maximum data transfer rate PER ONE data line:
  7    Reserved
  6-3  Time value
         0=reserved, 1=1.0, 2=1.2, 3=1.3, 4=1.5, 5=2.0, 6=2.5, 7=3.0,
         8=3.5, 9=4.0, A=4.5, B=5.0, C=5.5, D=6.0, E=7.0, F=8.0
  2-0  Transfer rate unit
         0=100kbit/s, 1=1Mbit/s, 2=10Mbit/s, 3=100Mbit/s, 4..7=reserved
         MMC: same as above, but specified in <Hz> instead of <bits/s>
Note that for current SD Memory Cards, this field shall be always 32h which is equal to 25 MHz - the mandatory maximum operating frequency of SD Memory Card.
In High-Speed mode, this field shall be always 5Ah which is equal to 50 MHz, and when the timing mode returns to the default by CMD6 or CMD0 command, its value will be 32h.

CCC (Card Command Class)
The SD Memory Card command set is divided into subsets (command classes). A value of 1 in a CCC bit means that the corresponding command class is supported. For command class definitions, refer to Table 4-21.
  11   Supports Command Class 11 - Function Extension Commands (SD)
  10   Supports Command Class 10 - Switch Function Commands (SD)
  9    Supports Command Class 9 - I/O Mode Commands (SDIO/MMCIO)
  8    Supports Command Class 8 - Application-Specific Commands
  7    Supports Command Class 7 - Password Lock Commands
  6    Supports Command Class 6 - Block-Oriented Write Protection Commands
  5    Supports Command Class 5 - Erase Commands
  4    Supports Command Class 4 - Block-Oriented Write Commands
  3    Supports Command Class 3 - WRITE_DAT_UNTIL_STOP (MMC)
  2    Supports Command Class 2 - Block-Oriented Read Commands
  1    Supports Command Class 1 - READ_DAT_UNTIL_STOP (MMC)
  0    Supports Command Class 0 - Basic Commands
Same for MMC (though on MMC the classes may have different meaning?)

READ_BL_LEN
The maximum read data block length is computed as 2^READ_BL_LEN. The maximum block length might therefore be in the range 512...2048 bytes (Refer to 4.3.3 for details). Note that in an SD Memory Card the WRITE_BL_LEN is always equal to READ_BL_LEN.
  3-0  Setting
Values:
  00h..08h  Reserved
  09h       Block length 512 Bytes (2^9)
  0Ah       Block length 1024 Bytes (2^10)
  0Bh       Block length 2048 Bytes (2^11)
  0Ch..0Fh  Reserved
MMC allows any values from 2^0 to 2^14, and uses 0Fh for Extension (see TBD field in EXT_CSD) (uh, but "TBD" isn't yet defined in KMCEN0000M datasheet, maybe TBD means to-be-defined?).

READ_BL_PARTIAL (always = 1 in SDSC Memory Card)
Partial Block Read is always allowed in an SDSC Memory Card. It means that smaller blocks can be used as well. The minimum block size will be one byte.

WRITE_BLK_MISALIGN
Defines if the data block to be written by one command can be spread over more than one physical block of the memory device. The size of the memory block is defined in WRITE_BL_LEN.
  WRITE_BLK_MISALIGN=0   crossing physical block boundaries is invalid
  WRITE_BLK_MISALIGN=1   crossing physical block boundaries is allowed

READ_BLK_MISALIGN
Defines if the data block to be read by one command can be spread over more than one physical block of the memory device. The size of the memory block is defined in READ_BL_LEN.
  READ_BLK_MISALIGN=0    crossing physical block boundaries is invalid
  READ_BLK_MISALIGN=1    crossing physical block boundaries is allowed

DSR_IMP
Defines if the configurable driver stage is integrated on the card. If set, a driver stage register (DSR) shall be implemented (also see Chapter 5.5).
  DSR_IMP=0    no DSR implemented
  DSR_IMP=1    DSR implemented

C_SIZE (for max 2GB)
This parameter is used to compute the user's data card capacity (not include the security protected area). The memory capacity of the card is computed from the entries C_SIZE, C_SIZE_MULT and READ_BL_LEN as follows:
  memory capacity = BLOCKNR * BLOCK_LEN
Whereas,
  BLOCKNR = (C_SIZE+1) * MULT
  MULT = 2^(C_SIZE_MULT+2)    ;(C_SIZE_MULT < 8)
  BLOCK_LEN = 2^READ_BL_LEN   ;(READ_BL_LEN < 12)
To indicate 2 GByte card, BLOCK_LEN shall be 1024 bytes.
Therefore, the maximal capacity that can be coded is 4096*512*1024 = 2 G bytes.
Example: A 32 Mbyte card with BLOCK_LEN = 512 can be coded by C_SIZE_MULT = 3 and C_SIZE = 2000.
The Maximum Data Area size of SDSC Standard Capacity Card is 4,153,344 sectors (2028MB).

C_SIZE (for MMC above 2GB)
The 12bit C_SIZE field should be set 0FFFh. Use "SEC_COUNT" in EXT_CSD to specify actual size.

VDD_R_CURR_MIN, VDD_W_CURR_MIN
Maximum values for read and write currents at the MINIMAL power supply VDD:
  2-0   0=0.5mA, 1=1mA, 2=5mA, 3=10mA, 4=25mA, 5=35mA, 6=60mA, 7=100mA

VDD_R_CURR_MAX, VDD_W_CURR_MAX
Maximum values for read and write currents at the MAXIMAL power supply VDD:
  2-0   0=1mA, 1=5mA, 2=10mA, 3=25mA, 4=35mA, 5=45mA, 6=80mA, 7=200mA

C_SIZE_MULT
This parameter is used for coding a factor MULT for computing the total device size (see 'C_SIZE'). Defined as "MULT = 2^(C_SIZE_MULT+2)".
  2-0   Device Size Factor (0..7 = Factor 4,8,16,32,64,128,256,512)

SD: ERASE_BLK_EN
The ERASE_BLK_EN defines the granularity of the unit size of the data to be erased. The erase operation can erase either one or multiple units of 512 bytes or one or multiple units (or sectors) of SECTOR_SIZE (see definition below).
If ERASE_BLK_EN=0, the host can erase one or multiple units of SECTOR_SIZE. The erase will start from the beginning of the sector that contains the start address to the end of the sector that contains the end address. For example, if SECTOR_SIZE=31 and the host sets the Erase Start Address to 5 and the Erase End Address to 40, the physical blocks from 0 to 63 will be erased as shown in Figure 5-1.
  Figure 5-1: ERASE_BLK_EN = 0 Example
  Physical Block (per CSD)
  0          1          2          3          4          5          6
  0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789
       <----- Host Erase Address Range ------->
  <---------- Erase Area ---------------------------------------------->
  <---------- Erase Unit Size ------><------- Erase Unit Size --------->
If ERASE_BLK_EN=1 the host can erase one or multiple units of 512 bytes. All blocks that contain data from start address to end address are erased. For example, if the host sets the Erase Start Address to 5 and the Erase End Address to 40, the physical blocks from 5 to 40 will be erased as shown in Figure 5-2.
  Figure 5-2: ERASE_BLK_EN = 1 Example
  Physical Block (per CSD)
  0          1          2          3          4          5          6
  0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789
       <----- Host Erase Address Range ------->
       <----- Erase Area --------------------->

SD: SECTOR_SIZE
The size of an erasable sector. The content of this register is a 7-bit binary coded value, defining the number of write blocks (see WRITE_BL_LEN). The actual size is computed by increasing this number by one. A value of zero means one write block, 127 means 128 write blocks.

MMC: ERASE_GRP_SIZE
The contents of this register is a 5 bit binary coded value, used to calculate the size of the erasable unit of the moviNAND. The size of the erase unit (also referred to as erase group) is determined by the ERASE_GRP_SIZE and the ERASE_GRP_MULT entries of the CSD, using the following equation:
  size of erasable unit = (ERASE_GRP_SIZE + 1) * (ERASE_GRP_MULT + 1)
This size is given as minimum number of write blocks that can be erased in a single erase command.

MMC: ERASE_GRP_MULT
A 5 bit binary coded value used for calculating the size of the erasable unit of the moviNAND. See ERASE_GRP_SIZE section for detailed description.

MMC: DEFAULT_ECC
Set by the moviNAND manufacturer. It defines the ECC code which is recommended for use. The field definition is the same as for the ECC field described later.

MMC: CONTENT_PROT_APP
This field in the CSD indicates whether the content protection application is supported. MultiMediaCards which implement the content protection application will have this bit set to '1'.

MMC: ECC
Defines the ECC code that was used for storing data on the moviNAND. This field is used by the host (or application) to decode the user data. The following table defines the field format:
  ECC      ECC type         Maximum number of correctable bits per block
  00h      None (default)   Mone
  01h      BCH (542,512)    3
  02h-03h  Reserved         -

MMC: WP_GRP_SIZE (5bit)
The size of a write protected group. The contents of this register is a 5 bit binary coded value, defining the number of erase groups which can be write protected.
The actual size is computed by increasing this number by one. A value of zero means 1 erase group, 31 means 32 erase groups. (Refer to the chapter 4.11.1 on page 48)

SD: WP_GRP_SIZE (7bit)
The size of a write protected group. The content of this register is a 7-bit binary coded value, defining the number of erase sectors (see SECTOR_SIZE). The actual size is computed by increasing this number by one. A value of zero means one erase sector, 127 means 128 erase sectors.

WP_GRP_ENABLE
A value of 0 means no group write protection possible.

R2W_FACTOR
Defines the typical block program time as a multiple of the read access time.
  2-0   Multiples of read access time (0..5=Mul 1,2,4,8,16,32, 6..7=Reserved)
For example, value 5 means that writing is 32 times slower than reading.

WRITE_BL_LEN
The maximum write data block length is computed as 2^WRITE_BL_LEN. The maximum block length might therefore be in the range from 512 to 2048 bytes. Write Block Length of 512 bytes is always supported.
Note that in the SD Memory Card, the WRITE_BL_LEN is always equal to READ_BL_LEN.
  3-0    Block Length
Values:
  00h..08h  Reserved
  09h       512 bytes (2^9)
  0Ah       1024 Bytes (2^10)
  0Bh       2048 Bytes (2^11)
  0Ch..0Fh  Reserved
MMC: See READ_BL_LEN

WRITE_BL_PARTIAL
Defines whether partial block sizes can be used in block write commands.
WRITE_BL_PARTIAL=0 means that only the WRITE_BL_LEN block size and its partial derivatives, in resolution of units of 512 bytes, can be used for block oriented data write.
WRITE_BL_PARTIAL=1 means that smaller blocks can be used as well. The minimum block size is one byte.

COPY
Defines whether the contents is original (=0) or has been copied (=1). Setting this bit to 1 indicates that the card content is a copy. The COPY bit is a one time programmable bit except ROM card.

PERM_WRITE_PROTECT
TMP_WRITE_PROTECT
Permanently/temporarily write-protects the entire card (by disabling all write and erase commands). The default values are 0, ie. not write protected.

FILE_FORMAT
FILE_FORMAT_GRP
Indicates the file format on the card. These fields are read-only for ROM. The following formats are defined:
  FILE_FORMAT_GRP  FILE_FORMAT  Type
  0                0            Hard disk-like file system with partition table
  0                1            DOS FAT (floppy-like) with boot sector only
                                  (no partition table)
  0                2            Universal File Format
  0                3            Others/Unknown
  1                0, 1, 2, 3   Reserved
A more detailed description is given in the Filesystem Specification.


DSi SD/MMC Protocol: CSD Register (128bit Card-Specific Data) Version 2.0

CSD Register (CSD Version 2.0) (SDHC/SDXC)
The field name in parenthesis is set to fixed value and indicates that the host is not necessary to refer these fields. The fixed values enables host, which refers to these fields, to keep compatibility to CSD Version 1.0.
The Cell Type field is coded as follows: R=readable, W(1)=writable once, W=multiple writable.
  Bit   Siz Type   Name                        Field          Value
  127-126 2 R      CSD structure               CSD_STRUCTURE  01b
  125-120 6 R      reserved                    -              000000b
  119-112 8 R      data read access-time-1     (TAAC)         0Eh
  111-104 8 R      data read access-time-2     (NSAC)         00h
  103-96  8 R      max data transfer rate      (TRAN_SPEED)   32h,5Ah,0Bh,2Bh
  95-84  12 R      card command classes        CCC            x1x110110101b
  83-80   4 R      max read data block length       (READ_BL_LEN)        9
  79      1 R      partial blocks for read allowed  (READ_BL_PARTIAL)    0
  78      1 R      write block misalignment         (WRITE_BLK_MISALIGN) 0
  77      1 R      read block misalignment          (READ_BLK_MISALIGN)  0
  76      1 R      DSR implemented                  DSR_IMP              x
  75-70   6 R      reserved                         -                   000000b
  69-48  22 R      device size                      C_SIZE              xxxxxxh
  47      1 R      reserved                         -                    0
  46      1 R      erase single block enable        (ERASE_BLK_EN)       1
  45-39   7 R      erase sector size                (SECTOR_SIZE)        7Fh
  38-32   7 R      write protect group size         (WP_GRP_SIZE)        00h
  31      1 R      write protect group enable       (WP_GRP_ENABLE)      0
  30-29   2 R      reserved                         -                    00b
  28-26   3 R      write speed factor               (R2W_FACTOR)         010b
  25-22   4 R      max write data block length      (WRITE_BL_LEN)       9
  21      1 R      partial blocks for write allowed (WRITE_BL_PARTIAL)   0
  20-16   5 R      reserved                         -                    00000b
  15      1 R      File format group                (FILE_FORMAT_GRP)    0
  14      1 R/W(1) copy flag                        COPY                 x
  13      1 R/W(1) permanent write protection       PERM_WRITE_PROTECT   x
  12      1 R/W    temporary write protection       TMP_WRITE_PROTECT    x
  11-10   2 R      File format                      (FILE_FORMAT)        00b
  9-8     2 R      reserved                         -                    00b
  7-1     7 R/W    CRC                              CRC                  xxh
  0       1 -      not used, always '1'             -                    1

C_SIZE
This field is expanded to 22 bits and can indicate up to 2 TBytes (that is the same as the maximum memory space specified by a 32-bit block address.)
This parameter is used to calculate the user data area capacity in the SD memory card (not include the protected area). The user data area capacity is calculated from C_SIZE as follows:
  memory capacity = (C_SIZE+1) * 512KByte
The Minimum user area size of SDHC Card is 4,211,712 sectors (2GB + 8.5MB).
The Minimum value of C_SIZE for SDHC in CSD Version 2.0 is 001010h (4112).
The Maximum user area size of SDHC Card is (32GB - 80MB).
The Maximum value of C_SIZE for SDHC in CSD Version 2.0 is 00FF5Fh (65375).
The Minimum user area size of SDXC Card is 67,108,864 sectors (32GB).
The Minimum value of C_SIZE for SDXC in CSD Version 2.0 is 00FFFFh (65535).

TRAN_SPEED
TRAN_SPEED is variable depends on bus speed mode of SD Interface.
When CMD0 is received, this field is reset to 32h.
On SDSC (but not SDHC/SDXC), CMD6 does the same reset stuff?
  32h   SDSC/SDHC/SDXC in Default Speed mode (25MHz)
  5Ah   SDSC/SDHC/SDXC in High Speed mode    (50MHz)
  0Bh   SDHC/SDXC in SDR50 or DDR50 mode     (100Mbit/sec)
  2Bh   SDHC/SDXC in SDR104 mode             (200Mbit/sec)
UHS-II mode is not related to this field.

CCC, DSR_IMP, COPY, PERM_WRITE_PROTECT, TMP_WRITE_PROTECT
Definition of these fields is same as in CSD Version 1.0.

TAAC, NSAC, R2W_FACTOR
In SDHC/SDXC, these fields should be fixed to TAAC=0Eh (1 ms), NSAC=00h, and R2W_FACTOR=02h (mul4).
The host should not use TAAC, NSAC, and R2W_FACTOR to calculate timeout and should uses fixed timeout values for read and write operations (See 4.6.2).

READ_BL_LEN, WRITE_BL_LEN
These two fields are fixed to 9h (which indicates 512 Bytes).

READ_BL_PARTIAL, WRITE_BL_PARTIAL, READ_BLK_MISALIGN, WRITE_BLK_MISALIGN
These four fields are fixed to 0 (partial block read and physical page crossing prohibited for block read/write).

SECTOR_SIZE
This field is fixed to 7Fh, which indicates 64 KBytes. This value is not related to erase operation. SDHC and SDXC Cards indicate memory boundary by AU size and this field should not be used.

ERASE_BLK_EN
This field is fixed to 1, which means the host can erase one or multiple units of 512 bytes.

WP_GRP_SIZE, WP_GRP_ENABLE
These field are fixed to WP_GRP_SIZE=00h, and WP_GRP_ENABLE=0.
SDHC and SDXC Cards do not support write protected groups.

FILE_FORMAT_GRP
FILE_FORMAT
These fields are set to 0. Host should not use these fields.


DSi SD/MMC Protocol: EXT_CSD Register (4096bit Extended CSD Register) (MMC)

CMD8 - MMC - SPI - GET_EXT_CSD (type=adtc)
  31-0  stuff bits
Response: R1
Additional Data Transfer (from card):
  4095-0  EXT_CSD Register (4096bit)
MMC only.

CMD6 - MMC - SPI - SWITCH (type=ac)
  31-26  6bit  Reserved (0)
  25-24  2bit  Access
                 00h  Change Command Set (EXT_CSD[191] = parameter bit2-0)
                 01h  Set bits (EXT_CSD[index] = EXT_CSD[index] OR value)
                 02h  Clr bits (EXT_CSD[index] = EXT_CSD[index] AND NOT value)
                 03h  Write    (EXT_CSD[index] = value)
  23-16  8bit  Index (0..191)   ;\used only if "Access=1..3"
  15-8   8bit  Value (0..255)   ;/
  7-3    5bit  Reserved (0)
  2-0    3bit  Cmd Set (0..7)   ;-used only if "Access=0"
Response: R1b
Additional Data Transfer (from card): Busy signal for "R1b" response
MMC only.

Extended CSD Register (MMC only)
The Extended CSD register defines the card properties and selected modes. It is 512 bytes (4096 bits) long.
The most significant 320 bytes are the Properties segment, which defines the card capabilities and cannot be modified by the host. The lower 192 bytes are the Modes segment, which defines the configuration the card is working in. These modes can be changed by the host by means of the SWITCH command.
  Properties Segment
  Byte    Siz  Type  Name                                  Field
  511-505   7  -     Reserved(1)                           -
  504       1  R     Supported Command Sets                S_CMD_SET
  503-216 288  -     Reserved(1)                           -
  215-212   4  R     moviNAND only: Sector Count           SEC_COUNT
  211       1  -     Reserved                              -
  210       1  R     Min Write Performance for 8bit @52MHz MIN_PERF_W_8_52
  209       1  R     Min Read Performance for 8bit @52MHz  MIN_PERF_R_8_52
  208       1  R     Min Write Perf. for 8/4bit @26/52MHz  MIN_PERF_W_8_26_4_52
  207       1  R     Min Read Perf. for 8/4bit @26/52MHz   MIN_PERF_R_8_26_4_52
  206       1  R     Min Write Performance for 4bit @26MHz MIN_PERF_W_4_26
  205       1  R     Min Read Performance for 4bit @26MHz  MIN_PERF_R_4_26
  204       1  -     Reserved(1)                           -
  203       1  R     Power Class for 26MHz @ 3.6V          PWR_CL_26_360
  202       1  R     Power Class for 52MHz @ 3.6V          PWR_CL_52_360
  201       1  R     Power Class for 26MHz @ 1.95V         PWR_CL_26_195
  200       1  R     Power Class for 52MHz @ 1.95V         PWR_CL_52_195
  199-197   3  -     Reserved(1)                           -
  196       1  R     Card Type                             CARD_TYPE
  195       1  -     Reserved(1)                           -
  194       1  R     CSD Structure Version                 CSD_STRUCTURE
  193       1  -     Reserved(1)                           -
  192 C0h   1  R     Extended CSD Revision                 EXT_CSD_REV
  Modes Segment
  191 BFh   1  R/W   Command Set                           CMD_SET
  190 BEh   1  -     Reserved(1)                           -
  189 BDh   1  RO    Command Set Revision                  CMD_SET_REV
  188 BCh   1  -     Reserved(1)                           -
  187 BBh   1  R/W   Power Class                           POWER_CLASS
  186 BAh   1  -     Reserved(1)                           -
  185 B9h   1  R/W   High Speed Interface Timing           HS_TIMING
  184 B8h   1  -     Reserved(1)                           -
  183 B7h   1  WO    Bus Width Mode                        BUS_WIDTH
  182 B6h      ?     ?
  181 B5h   1  -     Reserved                              -
  180 B4h   1  RO    moviNAND only: Erased Memory Content  ERASED_MEM_CONT
  180-0   181  -     Reserved(a)                           -
(a) Reserved(a) bits should read as '0'.
(1) Reserved(1) bits should be probably ZERO, too.
The above table is transferred "most significant first", which does probably mean that it starts with BYTE 0, not with byte 511. ALTHOUGH, the 4-byte SEC_COUNT appears to be LITTLE-ENDIAN?
Note: JEDEC Standard No. 84-A44 contains MANY additional fields in EXT_CSD.

S_CMD_SET
This field defines which command sets are supported by the card.
  Bit   Command Set
  7-5   Reserved
  4     moviNAND only: ATA on MMC
  3     moviNAND only: SecureMCC 2.0
  2     Content Protection SecureMMC
  1     SecureMMC
  0     Standard MMC

SEC_COUNT (moviNAND and newer JEDEC specs only)
The device density is calculated from the register by multiplying the value of the register (sector count) by 512B/sector. The maximum density possible to be indicated is thus 2 Tera bytes (minus 512 bytes) (4,294,967,295 x 512B). The least significant byte (LSB) of the sector count value is the byte [212].

MIN_PERF_a_b_ff
These fields defines the overall minimum performance value for the read and write access with different bus width and max clock frequency modes. The value in the register is coded as follows. Other than defined values are illegal.
  Value Performance
  0x00  For Cards not reaching the 2.4MB/s minimum value
  0x08  Class A: 2.4MB/s and is the lowest allowed value for MMCplus and
         MMCmobile(16x150kB/s)
  0x0A  Class B: 3.0MB/s and is the next allowed value (20x150kB/s)
  0x0F  Class C: 4.5MB/s and is the next allowed value (30x150kB/s)
  0x14  Class D: 6.0MB/s and is the next allowed value (40x150kB/s)
  0x1E  Class E: 9.0MB/s and is the next allowed value (60x150kB/s)
         This is also the highest class which any MMCplus or MMCmobile card
         is needed to support in low bus category operation mode (26MHz with
         4bit data bus).
         A MMCplus or MMCmobile card supporting any higher class than this
         have to support this class also (in low category bus operation mode).
  0x28  Class F: Equals 12.0MB/s and is the next allowed value (80x150kB/s)
  0x32  Class G: Equals 15.0MB/s and is the next allowed value (100x150kB/s)
  0x3C  Class H: Equals 18.0MB/s and is the next allowed value (120x150kB/s)
  0x46  Class J: Equals 21.0MB/s and is the next allowed value (140x150kB/s)
         This is also the highest class which any MMCplus or MMCmobile card
         is needed to support in mid bus category operation mode (26MHz with
         8bit data bus or 52MHz with 4bit data bus).
         A MMCplus or MMCmobile card supporting any higher class than this
         have to support this Class (in mid category bus operation mode) and
         Class E also (in low category bus operation mode).
  0x50  Class K: Equals 24.0MB/s and is the next allowed value (160x150kB/s)
  0x64  Class M: Equals 30.0MB/s and is the next allowed value (200x150kB/s)
  0x78  Class O: Equals 36.0MB/s and is the next allowed value (240x150kB/s)
  0x8C  Class R: Equals 42.0MB/s and is the next allowed value (280x150kB/s)
  0xA0  Class T: Equals 48.0MB/s and is the last defined value (320x150kB/s)

PWR_CL_ff_vvv
These fields define the supported power classes by the card. By default, the card has to operate at maximum frequency using 1 bit bus configuration, within the default max current consumption, as stated in the table below. If 4 bit/8 bits bus configurations, require increased current consumption, it has to be stated in these registers.
By reading these registers the host can determine the power consumption of the card in different bus modes. Bits [7:4] code the current consumption for the 8 bit bus configuration. Bits [3:0] code the current consumption for the 4 bit bus configuration.
The PWR_52_vvv registers are not defined for 26MHz MultiMediaCards.
  Voltage Value Max RMS Current   Max Peak Current   Remarks
  3.6V    0     100 mA            200 mA             Default current
          1     120 mA            220 mA             consumption for
          2     150 mA            250 mA             high voltage cards
          3     180 mA            280 mA
          4     200 mA            300 mA
          5     220 mA            320 mA
          6     250 mA            350 mA
          7     300 mA            400 mA
          8     350 mA            450 mA
          9     400 mA            500 mA
          10    450 mA            550 mA
          11-15 Reserved for future use
  1.95V   0     65 mA             130 mA             Default current
          1     70 mA             140 mA             consumption for
          2     80 mA             160 mA             Dual voltage cards
          3     90 mA             180 mA             (if any, not moviNAND)
          4     100 mA            200 mA
          5     120 mA            220 mA
          6     140 mA            240 mA
          7     160 mA            260 mA
          8     180 mA            280 mA
          9     200 mA            300 mA
          10    250 mA            350 mA
          6-15  Reserved for future use
The measurement for max RMS current is done as average RMS current consumption over a period of 100ms.
Max peak current is defined as absolute max value not to be exceeded at all.
The conditions under which the power classes are defined are:
  - Maximum bus frequency
  - Maximum operating voltage
  - Worst case functional operation
  - Worst case environmental parameters (temperature,...)
These registers define the maximum power consumption for any protocol operation in data transfer mode, Ready state and Identification state.

CARD_TYPE
This field defines the type of the card. The only currently valid values for this field are 0x01 and 0x03.
  Bit Card Type
  7-2 Reserved
  1   High Speed MultiMediaCard @ 52MHz
  0   High Speed MultiMediaCard @ 26MHz

CSD_STRUCTURE
This field is a continuation of the CSD_STRUCTURE field in the CSD register.
  CSD_STRUCTURE CSD structure version   Valid for System Specification Version
  0             CSD version No. 1.0     Version 1.0 - 1.2
  1             CSD version No. 1.1     Version 1.4 - 2.2
  2             CSD version No. 1.2     Version 3.1-3.2-3.31-4.0-4.1-4.2
  3             Reserved for future use
  4-255         Reserved for future use

EXT_CSD_REV
Defines the fixed parameters. related to the EXT_CSD, according to its revision.
  EXT_CSD_REV   Extended CSD Revision
  0             Revision 1.0
  1             Revision 1.1
  2             Revision 1.2 (moviNAND)
  3-255         Reserved

CMD_SET
Contains the binary code of the command set that is currently active in the card. It is set to '0' (Standard MMC) after power up and can be changed by a SWITCH command.

CMD_SET_REV
Contains a binary number reflecting the revision of the currently active command set. For Standard MMC command set it is:
  Code    MMC Revisions
  0       v4.0
  1-255   Reserved
This field, though in the Modes segment of the EXT_CSD, is read only.

POWER_CLASS
This field contains the 4 bit value of the selected power class for the card. The power classes are defined in Table. The host should be responsible of properly writing this field with the maximum power class it allows the card to use. The card uses this information to, internally, manage the power budget and deliver an optimized performance.
This field is 0 after power-on or software reset.
  Bits    Description
  7-4     Reserved
  3-0     Card power class code (See Table 5-29)

HS_TIMING
This field is 0 after power-on, or software reset, thus selecting the backwards compatibility interface timing for the card. If the host writes 1 to this field, the card changes its timing to high speed interface timing (refer to Chapter 5.4.8).

BUS_WIDTH
It is set to '0' (1 bit data bus) after power up and can be changed by a SWITCH command.
  Value   Bus Mode
  0       1 bit data bus (MMC, with old 7pin connector)
  1       4 bit data bus (MMCplus, with SD-card-compatible 9pin connector)
  2       8 bit data bus (MMCplus, with special 13pin connector)
  3-255   Reserved
For detecting cards with 4bit/8bit data bus support: Switch the SD/MMC controller to 4bit/8bit modes, and use BUSTEST_W and BUSTEST_R to test if the card sends a proper response, see https://www.mikrocontroller.net/attachment/101561/AN_MMCA050419.pdf
Note: The SD/MMC controller in the DSi supports 1bit/4bit modes only (no 8bit mode). For the DSi's onboard eMMC it's safe to assume 4bit being supported, however, external MMC cards do require detecting 4bit support.

ERASED_MEM_CONT (moviNAND) (but, RESERVED in newer JEDEC specs!)
This Field defines the content of an explicitly erased memory range.
  Value   Erased Memory content
  00h     Erased memory range shall be '0'
  01h     Erased memory range shall be '1'
  02h-FFh Reserved
Looks like a mis-definition, since value 00h should have been kept reserved for cards that do not specify whether they set erased bits to 0 or 1.


DSi SD/MMC Protocol: RCA Register (16bit Relative Card Address)

The RCA was intended for connecting multiple cards to the same host, possibly even sharing the same signal wires for multiple cards. The multi-card feature isn't used to often though.
Most hosts are having only a single card slot. And, hosts that <do> support multiple cards may use separate busses and even separate controllers for each card (eg. Nintendo DSi is doing so for onboard NAND and external SD slot).
However, even single-card systems will need to obtain a "dummy" RCA, and use that RCA value for selecting the card.
The only exception is SPI mode: SPI isn't using RCA, and doesn't support RCA commands at all - instead, in SPI mode, the cards are selected via /CS signal (which may include multiple /CS signals for multiple cards).

CMD3 - SD - GET_RELATIVE_ADDR (type=bcr)
Parameter bits:
  31-0  stuff bits
Response: R6:
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-24   New published RCA of the card   ;-16bit       ;-2nd..3th byte
  23-22   CSR Card Status, bit 23-22      ;\            ;\
  21      CSR Card Status, bit 19         ; 16bit       ; 4nd..5th byte
  20-8    CSR Card Status, bit 12-0       ;/            ;/
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/
Ask the card to publish a new relative address (RCA).
Dunno how this is intended to work with multiple cards. The goal should be to assign <different> RCAs to each card. The command should be probably repeatedly used until all cards respond with different RCAs. This would require the cards to contain some sort of analog random generator - or maybe to use the CID register as random seed (the CID seems to contain unique serial numbers per card)?

CMD3 - MMC - SET_RELATIVE_ADDR (type=ac)
Parameter bits:
  31-16 RCA
  15-0  stuff bits
Response: R1
Assigns an RCA value TO the card (ie. the opposite of CMD3 on SD Cards).
Dunno how this is intended to work with multiple cards. The goal should be to assign <different> RCAs to each card. But actually, the command appears to assign the <same> RCA to all cards?

CMD7 - SD/MMC - SELECT_DESELECT_CARD (type=ac) ;actually: (type=bcr)
Parameter bits:
  31-16 RCA
  15-0  stuff bits
Response: R1b (only from the selected card)
Additional Data Transfer (from card): Busy signal for "R1b" response
Command toggles a card between the stand-by and transfer states or between the programming and disconnect states. In both cases, the card is selected by its own relative address and gets deselected by any other address; address 0 deselects all.
In the case that the RCA equals 0, then the host may do one of the following:
- Use other RCA number to perform card de-selection.
- Re-send CMD3 to change its RCA number to other than 0 and then use CMD7 with RCA=0 for card deselection.

CMD5 - MMC - SLEEP_AWAKE (type=ac)
Parameter bits:
  31-16 RCA
  15    Sleep/Awake flag (0=Awake/stby, 1=Sleep/slp)
  14-0  stuff bits
Response: R1b

RCA register
The writable 16-bit relative card address register carries the card address that is published by the card during the card identification. This address is used for the addressed host-card communication after the card identification procedure. The default value of the RCA register is 0000h. The value 0000h is reserved to set all cards into the Stand-by State with CMD7.
In UHS-II mode, Node ID is used as RCA. Refer to SD-TRAN Section of UHS-II Addendum for more details.

Note
Commands GET_CSD, GET_CID, APP_CMD, GO_INACTIVE_STATE, and GET_STATUS allow/require to specify RCA in parameter field.
Other commands are either processed by all cards (broadcast commands), or processed only be cards that have been previously selected via CMD7 (most normal commands).

Broadcast Commands
  CMD0     sd/mmc spi GO_IDLE_STATE (type=bc)
  CMD2     sd/mmc     ALL_GET_CID (type=bcr)
  CMD3     sd         GET_RELATIVE_ADDR (type=bcr)
  CMD4     sd/mmc     SET_DSR (type=bc)
  CMD7     sd/mmc     SELECT_DESELECT_CARD (type=ac) ;actually: (type=bcr)
  CMD8     sd     spi SET_IF_COND (type=bcr)
  ACMD41   sd     spi SD_SEND_OP_COND (type=bcr)  ;SPI: reduced functionality
Some broadcast commands are sending responses.
SD specs are suggesting to use separate CMD lines for each card (so the host would broadcast the same command on all CMD lines, and would receive separate responses in parallel from each CMD line).
MMC cards are said to support open-collector CMD lines (so responses from separate cards would be logically ORed, though, dunno what that would be good for).


DSi SD/MMC Protocol: DSR Register (16bit Driver Stage Register) (Optional)

CMD4 - SD/MMC - SET_DSR (type=bc)
Parameter bits:
  31-16 DSR
  15-0  stuff bits
Response: N/A
Programs the DSR of all cards.

DSR register (Optional)
The 16-bit driver stage register is described in detail in Chapter 0 (uh, where?). It can be optionally used to improve the bus performance for extended operating conditions (depending on parameters like bus length, transfer rate or number of cards). The CSD register carries the information about the DSR register usage. The default value of the DSR register is 0404h.


DSi SD/MMC Protocol: SCR Register (64bit SD Card Configuration Register)

ACMD51 - SD - SPI - GET_SCR (type=adtc)
  31-0  stuff bits
Response: R1
Additional Data Transfer (from card):
  63-0  SCR Register (8bytes, aka 64bit)

SD Configuration Register (SCR)
In addition to the CSD register, there is another configuration register named SD CARD Configuration Register (SCR). SCR provides information on the SD Memory Card's special features that were configured into the given card. The size of SCR register is 64 bits. This register shall be set in the factory by the SD Memory Card manufacturer.
  Bit  Siz  Typ Description                      Field                 ;common
  63-60  4  R   SCR Structure                    SCR_STRUCTURE         ;\00h or
  59-56  4  R   SD Memory Card - Spec. Version   SD_SPEC               ;/01h
  55     1  R   data_status_after erases         DATA_STAT_AFTER_ERASE ;\
  54-52  3  R   CPRM Security Support            SD_SECURITY           ; A5h
  51-48  4  R   DAT Bus widths supported         SD_BUS_WIDTHS         ;/
  47     1  R   Spec. Version 3.00 or higher     SD_SPEC3              ;\
  46-43  4  R   Extended Security Support        EX_SECURITY           ; 0000h
  42     1  R   Spec. Version 4.00 or higher     SD_SPEC4              ;
  41-36  6  R   Reserved                         -                     ;
  35-32  4  R   Command Support bits             CMD_SUPPORT           ;/
  31-0  32  R   reserved for manufacturer usage  -                     ;-var

SCR Register Structure Version
  SCR_STRUCTURE  SCR Structure Version  SD Physical Layer Specification Version
  00h            SCR version 1.0        Version 1.01-4.00
  01h..0Fh       reserved
Note: SD_SPEC is used to indicate SCR Structure Version instead of this field.

SD_SPEC, SD_SPEC3, SD_SPEC4
The Physical Layer Specification Version is indicated in combination with SD_SPEC, SD_SPEC3 and SD_SPEC4 as described Table 5-19.
  SD_SPEC  SD_SPEC3  SD_SPEC4   Physical Layer Specification Version Number
  0        0         0          Version 1.0 and 1.01
  1        0         0          Version 1.10
  2        0         0          Version 2.00
  2        1         0          Version 3.0X
  2        1         1          Version 4.XX
         Others                 Reserved
(1) Version 2.00 hosts do not recognize SD_SPEC3 and SD_SPEC4.
(2) Version 3.00 hosts do not recognize SD_SPEC4.
Hosts recognize Physical Layer Specification Version shall also recognize including future version. Next version will be defined in SD_SPEC field.

The card manufacturer determines SD_SPEC value by conditions indicated below. All conditions shall be satisfied for each version. The other combination of conditions is not allowed.

Essential conditions to indicate Version 1.01 Card (SD_SPEC=0, SD_SPEC3=0 and SD_SPEC4=0):
  (1) The card does not support CMD6
  (2) The card does not support CMD8
  (3) User area capacity shall be up to 2GB
Essential conditions to indicate Version 1.10 Card (SD_SPEC=1, SD_SPEC3=0 and SD_SPEC4=0):
  (1) The card shall support CMD6
  (2) The card does not support CMD8
  (3) User area capacity shall be up to 2GB
Essential conditions to indicate Version 2.00 Card (SD_SPEC=2, SD_SPEC3=0 and SD_SPEC4=0):
  (1) The card shall support CMD6
  (2) The card shall support CMD8
  (3) The card shall support CMD42
  (4) User area capacity shall be up to 2GB (SDSC) or 32GB (SDHC)
  (5) Speed Class shall be supported (SDHC)
Essential conditions to indicate Version 3.00 Card (SD_SPEC=2, SD_SPEC3=1 and SD_SPEC4=0):
  (1) The card shall support CMD6
  (2) The card shall support CMD8
  (3) The card shall support CMD42
  (4) User area capacity shall be up to 2GB (SDSC) or 32GB (SDHC)
    User area capacity shall be more than or equal to 32GB and up to 2TB (SDXC)
  (5) Speed Class shall be supported (SDHC or SDXC)
Optional conditions to indicate Version 3.00 Card:
  A card supports any of following functions shall satisfy essential
  conditions of Version 3.00 Card
  (1) Speed Class supported under the conditions defined in Version 3.00
  (2) UHS-I supported card
  (3) CMD23 supported card
Essential conditions to indicate Version 4.XX Card (SD_SPEC=2, SD_SPEC3=1 and SD_SPEC4=1):
  (1) Same as the essential conditions of Version 3.00 device
  (2) Support any of additional functions defined by Version 4.XX:
      Followings functions (a) to (c) are defined by Version 4.00.
        (a) Support of CMD48 and CMD49
        (b) Support of UHS-II mode
        (c) Support of DPS (Data Protection System)
      Followings functions (d) to (f) are defined by Version 4.10.
        (d) Support of CMD58 and CMD59
        (e) Support of Power Management Functions
        (f) Support of Speed Grade 1 for UHS-II mode
The requirements of supporting commands mentioned above are for the optional commands, the support of which depends on versions (SD_SPEC, SD_SPEC3 and SD_SPEC4). Refer to Table 4-21 (and Notes below the table) about the mandatory and optional commands in the card.

DATA_STAT_AFTER_ERASE
Defines the data status after erase, whether it is 0 or 1 (the status is card vendor dependent).

SD_SECURITY
This field indicates CPRM Security Specification Version for each capacity card. The definition of Protected Area is different in each capacity card.
  00h           No Security
  01h           Not Used
  02h           SDSC Card (CPRM Security Version 1.01)
  03h           SDHC Card (CPRM Security Version 2.00)
  04h           SDXC Card (CPRM Security Version 3.xx)
  05h-07h       Reserved
The basic rule of setting this field:
  SDSC Card sets this field to 2 (Version 1.01).
  SDHC Card sets this field to 3 (Version 2.00).
  SDXC Card sets this field to 4 (Version 3.xx).
Note that it is mandatory for a regular writable SD Memory Card to support Security Protocol. For ROM (Read Only) and OTP (One Time Programmable) types of the SD Memory Card, the security feature is optional.

SD_BUS_WIDTHS
Describes all the DAT bus widths that are supported by this card.
  Bit 3          Reserved
  Bit 2          4 bit (DAT0-3)
  Bit 1          Reserved
  Bit 0          1 bit (DAT0)
Since the SD Memory Card shall support at least the two bus modes 1-bit or 4-bit width, then any SD Card shall set at least bits 0 and 2 (SD_BUS_WIDTH="0101").

EX_SECURITY
This field indicates Extended Security which is defined by the Part A4 Data Protection System Specification Version 1.00 or will be defined by a later version of the Part 3 Security Specification Version 3.00.
  00h          Extended Security is not supported.
  01h..0Fh     Extended Security is supported. SCR[44-43] is defined by the
                 Part A4 Data Protection System Specification. SCR[46-45] is
                 reserved for future extension.

CMD_SUPPORT
Support bit of new commands are defined to Bit 33-32 (uh, 35-32?) of SCR.
  Bit Supported Command               Command  CCC  Remark
  35  Extension Register Multi-Block  CMD58/59 11   Optional.
  34  Extension Register Single Block CMD48/49 11   Optional.
  33  Set Block Count                 CMD23    2,4  Mandatory for UHS104 card
  32  Speed Class Control             CMD20    2,4  Mandatory for SDXC card
If CMD58/59 is supported, then CMD48/49 shall be also supported.


DSi SD/MMC Protocol: PWD Register (128bit Password plus 8bit Password len)

CMD40 - SD - Defined by DPS Spec (Data Protection System) (type=adtc)
  Defined by DPS Spec.
Response: R1
Additional Data Transfer (to/from whatever):
  unknown
Single block read type. Intended to read whatever "public" data, which is available even if the card is locked.

CMD42 - SD/MMC (SD v2.00 and up) - SPI - LOCK_UNLOCK (type=adtc)
  31-0  Reserved bits (0)
Response: R1 (MMC: R1b?)
MMC?: Additional Data Transfer (from card): Busy signal for "R1b" response
Additional Data Transfer (to card):
  Note: Before using this command, the size of the following data block (ie.
        "1st..Nth/Extra" byte) must be set via SET_BLOCKLEN command (CMD16).
  1st byte: Flags
    Bit7-4 Reserved (0)
    Bit3   ERASE       Force Erase (1=Erase WHOLE CARD and clear password)
    Bit1   LOCK_UNLOCK Lock card (0=Unlock, 1=Lock) (default on power up: Lock)
    Bit1   CLR_PWD     Clears password  (0=no, 1=yes)
    Bit0   SET_PWD     Set new password (0=no, 1=yes)
  2nd byte: PWDS_LEN   Length of the Password(s) in bytes ("3rd..Nth" byte)
  3rd..Nth byte: Password (old password, if SET_PWD: followed by new password)
  Extra byte: Alignment padding (only in DDR50 mode, if above is odd num bytes)
Used to set/clear the password (=to change the password), or to lock/unlock the card (=to log out/log in). If the password exists, then the default state on power-up is Locked (user is logged out).
In locked state, the card will accept only "Basic Commands" (class 0), plus CMD16,40,42, plus ACMD41,42. Observe that this will prevent some initialization commands (for example, switching to 4bit bus via SET_BUS_WIDTH (ACMD6) isn't possible on locked cards).
The password is stored in a 128bit PWD register, so password can be max 16 bytes long. The PWDS_LEN value can be max 32 bytes (when sending old+new password). The length of the current/old password is stored in an 8bit PWD_LEN register (though due to the above limit, that "8bit" value can be in range 0..16 only; PWD_LEN=0 means that there is no password, which is somewhat equivalent to what happens when setting the CLR_PWD bit?).
PWD Notes:
Related CSR status bits are: CARD_IS_LOCKED and LOCK_UNLOCK_FAILED. Presence of the locking feature is indicated by the CCC "class 7" bit in CSD register.
Many SD cards are internally containing separate controller and memory chips, so it might be quite easy to bypass the locking by desoldering one of those chips.


DSi SD/MMC Protocol: State

SD/MMC State
The "state" is an important SD/MMC feature to deal with - most commands can be send only in certain states:
For normal operation, the card should be in "tran" state (and it may then temporarily switch to "data/rcv/prg" states during read/write/erase commands).
For initialization, the card should be first forced to "idle" state, and the init commands should then go through "ready/ident/stby" states, until finally reaching "tran" state.
Less important states are "dis/ina", and, on MMC only, "btst/slp/irq" and "pre-idle".
Both SD and MMC specs are leaving state undocumented for SPI mode (meaning that SPI specific commands like CMD58/CMD59 are supported only in "unknown" state).

SD Card State Transition Table
  Command       old state --> idle readyidentstby tran data rcv  prg  dis  ina
  DONE  Operation Complete    ---- ---- ---- ---- ---- tran ---- tran stby ----
  class 0
  CMD0  GO_IDLE_STATE         ok   idle idle idle idle idle idle idle idle ----
  CMD2  ALL_SEND_CID          ---- ident---- ---- ---- ---- ---- ---- ---- ----
  CMD3  SEND_RELATIVE_ADDR    ---- ---- stby ok   ---- ---- ---- ---- ---- ----
  CMD4  SET_DSR               ---- ---- ---- ok   ---- ---- ---- ---- ---- ----
  CMD7  SELECT_DESELECT_CARD
        card is addressed     ---- ---- ---- tran ---- ---- ---- ---- prg  ----
        card is not addr.     ---- ---- ---- ok   stby stby ---- dis  ---- ----
  CMD8  SEND_IF_COND          ok   ---- ---- ---- ---- ---- ---- ---- ---- ----
  CMD9  SEND_CSD              ---- ---- ---- ok   ---- ---- ---- ---- ---- ----
  CMD10 SEND_CID              ---- ---- ---- ok   ---- ---- ---- ---- ---- ----
  CMD11 VOLTAGE_SWITCH        ---- ok   ---- ---- ---- ---- ---- ---- ---- ----
  CMD12 STOP_TRANSMISSION     ---- ---- ---- ---- ---- tran prg  ---- ---- ----
  CMD13 SEND_STATUS           ---- ---- ---- ok   ok   ok   ok   ok   ok   ----
  CMD15 GO_INACTIVE_STATE     ---- ---- ---- ina  ina  ina  ina  ina  ina  ----
  class 2
  CMD16 SET_BLOCKLEN          ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  CMD17 READ_SINGLE_BLOCK     ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD18 READ_MULTIPLE_BLOCK   ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD19 SEND_TUNING_BLOCK     ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD20 SPEED_CLASS_CONTROL   ---- ---- ---- ---- prg  ---- ---- ---- ---- ----
  CMD23                       ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  class 4
  CMD16 SET_BLOCKLEN       (2)---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  CMD20 SPEED_CLASS_CONTROL(2)---- ---- ---- ---- prg  ---- ---- ---- ---- ----
  CMD23 SET_BLOCK_COUNT       ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  CMD24 WRITE_BLOCK           ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  CMD25 WRITE_MULTIPLE_BLOCK  ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  CMD27 PROGRAM_CSD           ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  class 6
  CMD28 SET_WRITE_PROT        ---- ---- ---- ---- prg  ---- ---- ---- ---- ----
  CMD29 CLR_WRITE_PROT        ---- ---- ---- ---- prg  ---- ---- ---- ---- ----
  CMD30 SEND_WRITE_PROT       ---- ---- ---- ---- data ---- ---- ---- ---- ----
  class 5
  CMD32 ERASE_WR_BLK_START    ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  CMD33 ERASE_WR_BLK_END      ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  CMD38 ERASE                 ---- ---- ---- ---- prg  ---- ---- ---- ---- ----
  class 7
  CMD40 Read Block (DPS Spec) ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD42 LOCK_UNLOCK           ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  class 8
  CMD55 APP_CMD               ok   ---- ---- ok   ok   ok   ok   ok   ok   ----
  CMD56 GEN_CMD, RD/WR=0      ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
        GEN_CMD, RD/WR=1      ---- ---- ---- ---- data ---- ---- ---- ---- ----
  ACMD6  SET_BUS_WIDTH        ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  ACMD13 SD_STATUS            ---- ---- ---- ---- data ---- ---- ---- ---- ----
  ACMD22 SEND_NUM_WR_BLOCKS   ---- ---- ---- ---- data ---- ---- ---- ---- ----
  ACMD23 SET_WR_BLK_ERASE_CO. ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  ACMD41 SD_SEND_OP_COND
       OCR check is OK
       and card is not busy   ready---- ---- ---- ---- ---- ---- ---- ---- ----
       OCR check is OK
       and card is busy(2)    ok   ---- ---- ---- ---- ---- ---- ---- ---- ----
       OCR check fails
       query mode             ina  ---- ---- ---- ---- ---- ---- ---- ---- ----
  ACMD42 SET_CLR_CARD_DETECT  ---- ---- ---- ---- ok   ---- ---- ---- ---- ----
  ACMD51 SEND_SCR             ---- ---- ---- ---- data ---- ---- ---- ---- ----
  class 9
  class 10 (1)
  CMD6  SWITCH_FUNC           ---- ---- ---- ---- data ---- ---- ---- ---- ----
  class 11
  CMD48 READ_EXTR_SINGLE      ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD49 WRITE_EXTR_SINGLE     ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  CMD58 READ_EXTR_MULTI       ---- ---- ---- ---- data ---- ---- ---- ---- ----
  CMD59 WRITE_EXTR_MULTI      ---- ---- ---- ---- rcv  ---- ---- ---- ---- ----
  ACMD14-16               Refer to DPS Specification (class 8)
  ACMD28                  Refer to DPS Specification (class 8)
  ACMD18,25,26,38,
  43,44,45,46,47,48,49    Refer to the "Part3 Security Specification" for
                          information about the SD Security Features (class 8)
  CMD52-CMD54             Refer to the "SDIO Card Specification" (class 9)
  CMD21                   Refer to DPS Specification (class 11)
  CMD34-37,50,57          Refer to each command system specification (class 10)
  CMD41,CMD43-47          reserved (class 11)
  CMD60...CMD63           reserved for manufacturer (class 11)
  SPI Mode
  CMD1 SEND_OP_COND       SPI-only
  CMD58 READ_OCR          SPI-only
  CMD59 CRC_ON_OFF        SPI-only
Note (1): Class 10 commands were defined in Version 1.10.
Note (2): Card returns busy in case of following:
  - Card executes internal initialization process
  - When HCS in the argument is set to 0 to SDHC or SDXC Card.
The state transitions of the SD Memory Card application-specific commands are given under Class 8, above.
  ----  command is treated as illegal command
  ok    command is accepted, and card stays in SAME state
  xxx   command is accepted, and card switches to "xxx" state

MMC Card State Transition Table (JEDEC)
  Command     old state --> idl rdy idt stb trn dta tst rcv prg dis ina slp irq
  Class Independent
  ERR  CRC error            --- --- --- --- --- --- --- --- --- --- --- --- stb
  ERR  command not supported--- --- --- --- --- --- --- --- --- --- --- --- stb
  Class 0
  CMD0  (arg=00000000h)     ok  idl idl idl idl idl idl idl idl idl --- idl stb
        GO_IDLE_STATE
  CMD0  (arg=F0F0F0F0h)     pre pre pre pre pre pre pre pre pre pre --- pre stb
        GO_PRE_IDLE_STATE
  CMD0  (arg=FFFFFFFAh)     initiate alternative boot operation
        BOOT_INITIATION
  CMD1  SEND_OP_COND
        card VDD range ok   rdy --- --- --- --- --- --- --- --- --- --- --- stb
        card is busy        ok  --- --- --- --- --- --- --- --- --- --- --- stb
        card VDD range bad  ina --- --- --- --- --- --- --- --- --- --- --- stb
  CMD2  ALL_SEND_CID
         card wins bus      --- idt --- --- --- --- --- --- --- --- --- --- stb
         card loses bus     --- ok  --- --- --- --- --- --- --- --- --- --- stb
  CMD3  SET_RELATIVE_ADDR   --- --- stb --- --- --- --- --- --- --- --- --- stb
  CMD4  SET_DSR             --- --- --- ok  --- --- --- --- --- --- --- --- stb
  CMD5  SLEEP_AWAKE         --- --- --- slp -?- -?- -?- -?- -?- -?- -?- stb stb
  CMD6  SWITCH              --- --- --- --- prg --- --- --- --- --- --- --- stb
  CMD7  SELECT_DESELECT_CARD
        card is addressed   --- --- --- trn --- --- --- --- --- prg --- --- stb
        card is not addr.   --- --- --- --- stb stb --- --- dis --- --- --- stb
  CMD8  SEND_EXT_CSD        --- --- --- --- dta --- --- --- --- --- --- --- stb
  CMD9  SEND_CSD            --- --- --- ok  --- --- --- --- --- --- --- --- stb
  CMD10 SEND_CID            --- --- --- ok  --- --- --- --- --- --- --- --- stb
  CMD12 STOP_TRANSMISSION   --- --- --- --- --- trn --- prg --- --- --- --- stb
  CMD13 SEND_STATUS         --- --- --- ok  ok  ok  ok  ok  ok  ok  --- --- stb
  CMD14 BUSTEST_R           --- --- --- --- --- --- trn --- --- --- --- --- stb
  CMD15 GO_INACTIVE_STATE   --- --- --- ina ina ina ina ina ina ina --- --- stb
  CMD19 BUSTEST_W           --- --- --- --- tst --- --- --- --- --- --- --- stb
  Class 1
  CMD11 READ_DAT_UNTIL_STOP --- --- --- --- dta --- --- --- --- --- --- --- stb
  Class 2
  CMD16 SET_BLOCKLEN        --- --- --- --- ok  --- --- --- --- --- --- --- stb
  CMD17 READ_SINGLE_BLOCK   --- --- --- --- dta --- --- --- --- --- --- --- stb
  CMD18 READ_MULTIPLE_BLOCK --- --- --- --- dta --- --- --- --- --- --- --- stb
  CMD23 SET_BLOCK_COUNT     --- --- --- --- ok  --- --- --- --- --- --- --- stb
  Class 3
  CMD20 WRITE_DAT_UNTIL_STOP--- --- --- --- rcv --- --- --- --- --- --- --- stb
  Class 4
  CMD16 SET_BLOCKLEN        see class 2
  CMD23 SET_BLOCK_COUNT     see class 2
  CMD24 WRITE_BLOCK         --- --- --- --- rcv --- --- --- rcv1--- --- --- stb
  CMD25 WRITE_MULTIPLE_BL.  --- --- --- --- rcv --- --- --- rcv2--- --- --- stb
  CMD26 PROGRAM_CID         --- --- --- --- rcv --- --- --- --- --- --- --- stb
  CMD27 PROGRAM_CSD         --- --- --- --- rcv --- --- --- --- --- --- --- stb
  Class 6
  CMD28 SET_WRITE_PROT      --- --- --- --- prg --- --- --- --- --- --- --- stb
  CMD29 CLR_WRITE_PROT      --- --- --- --- prg --- --- --- --- --- --- --- stb
  CMD30 SEND_WRITE_PROT     --- --- --- --- dta --- --- --- --- --- --- --- stb
  CMD31 SEND_WRITE_PROT_TYPE--- --- --- --- dta --- --- --- --- --- --- --- stb
  Class 5
  CMD35 ERASE_GROUP_START   --- --- --- --- ok  --- --- --- --- --- --- --- stb
  CMD36 ERASE_GROUP_END     --- --- --- --- ok  --- --- --- --- --- --- --- stb
  CMD38 ERASE               --- --- --- --- prg --- --- --- --- --- --- --- stb
  Class 7
  CMD16 SET_BLOCKLEN        see class 2
  CMD42 LOCK_UNLOCK         --- --- --- --- rcv --- --- --- --- --- --- --- stb
  Class 8
  CMD55 APP_CMD             --- --- --- ok  ok  ok  ok  ok  ok  ok  --- --- ok
  CMD56 GEN_CMD, RD/WR=0    --- --- --- --- rcv --- --- --- --- --- --- --- stb
        GEN_CMD, RD/WR=1    --- --- --- --- dta --- --- --- --- --- --- --- stb
  Class 9
  CMD39 FAST_IO             --- --- --- ok  --- --- --- --- --- --- --- --- stb
  CMD40 GO_IRQ_STATE        --- --- --- irq --- --- --- --- --- --- --- --- stb
  Class 10-11
  CMD41, CMD43..CMD54       Reserved
  CMD57..CMD59              Reserved
  CMD60..CMD63              Reserved for Manufacturer
  SPI Mode
  CMD58 READ_OCR            SPI-only
  CMD59 CRC_ON_OFF          SPI-only
NOTE 1. Due to legacy considerations, a card may treat CMD24/25 during a prg state_while busy is active_as a legal or an illegal command. A card that treats CMD24/25 during a prg-state_while busy is active_as an illegal command will not change its state to the rcv state. A host should not send CMD24/25 while the card is in prg state and busy is active.
NOTE 2. Due to legacy considerations, a card may treat CMD24/25 during a prg state_while busy is active_as a legal or an illegal command. A card that treats CMD24/25 during a prg state_while busy is active_as an illegal command will not change its state to the rcv state. A host should not send CMD24/25 while the card is in prg state and busy is active.
NOTE 3. As there is no way to obtain state information in boot mode, boot-mode states are not shown in this table.
  pre  Pre-idle
  idl  idle
  rdy  ready
  idt  ident
  stb  stby
  trn  tran
  dta  data
  tst  btst


DSi SD/MMC Protocol: Signals

XXX...

SD Mode 1-bit data transfer mode
          __ start bit                             __ checksum bits (CRC-CCITT)
         |                                        |
         |  <------------data bits------------->  |   __ stop bit
         |                                        |  |
  DAT0   0  1st 2nd 3rd 4th 5th 6th 7th ... last crc 1

SD Mode 4-bit data transfer mode
          __ start bit         __ checksum bits (CRC-CCITT)
         |                    |
         |  <--data bits-->   |   __ stop bit
         |                    |  |
  DAT3   0  1st 5th ... ...  crc 1
  DAT2   0  2nd 6th ... ...  crc 1
  DAT1   0  3rd 7th ... ...  crc 1
  DAT0   0  4th 8th ... last crc 1


DSi SDIO Special SDIO Commands

CMD52 - SDIO: IO_RW_DIRECT
Read/write single byte. Mostly used for detection/configuration via SDIO Function 0 commands.
  31     R/W Flag               (0=Read, 1=Write)
  30-28  Function Number (3bit)
  27     Read-after-write (RAW) Flag (if Bit31=1=Write, and Bit27=1)
  26     Stuff (unspecified, should be probably 0, but is 1 on DSi)
  25-9   Register Address (17bit)
  8      Stuff (unspecified, should be probably 0, but is 1 on DSi)
  7-0    Write Data (8bit), or Stuff bits (for read)
SD Mode Response: R5:
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-24   Stuff Bits                                    ;-2nd..3rd byte
  23-16   Response Flags                                ;-4th byte
           7   COM_CRC_ERROR
           6   ILLEGAL_COMMAND
           5-4 IO_CURRENT STATE (0=dis, 1=cmd, 2=trn(cmd53), 3=rfu)
           3   ERROR
           2   RFU (reserved for future use)
           1   INVALID_FUNCTION_NUMBER
           0   OUT_OF_RANGE
  15-8    Read or Write Data (8bit)                     ;-5th byte
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/
SPI Mode Response: R5:
  8bit  modified R1 response
           7  start bit (0)
           6  parameter error       (0=okay, 1=error)
           5  RFU (0)
           4  function number error (0=okay, 1=error)
           3  COM CRC error         (0=okay, 1=error)
           2  illegal command       (0=okay, 1=error)
           1  RFU (0)
           0  in idle state         (0=no, 1=idle)
  8bit  Read or Write Data

CMD53 - SDIO: IO_RW_EXTENDED
Mostly used for actual command/data transfers via SDIO Function 1 commands.
  31     R/W Flag               (0=Read, 1=Write)
  30-28  Function Number (3bit) (0=CIA)
  27     Block Mode             (0=Bytes, 1=Blocks/optional)
  26     OP Code                (0=Fixed Address, 1=Incrementing Address)
  25-9   Register Address (17bit)
  8-0    Byte/Block Count (9bit) (1..511) (0=512 Bytes, or 0=Infinite Blocks)
Response: R5: Same as for CMD52 (with 8bit data = 00h)
Data Transfer:
  For Byte Mode: Similar to CMD17/CMD24 (single block)
  For Block Mode: Similar to CMD18/CMD25 (multiple block)
  For Block Mode: CMD52:STOP_TRANSMISSION only needed if using "InfiniteBlocks"

CMD5 - SPI - SDIO: IO_SEND_OP_COND
Similar to SD Memory Card's ACMD41.
  31-25  stuff bits (0)
  24     Switching to 1.8V Request (S18R)
  23     I/O OCR VDD Voltage Window 3.5V-3.6V
  22     I/O OCR VDD Voltage Window 3.4V-3.5V
  21     I/O OCR VDD Voltage Window 3.3V-3.4V
  20     I/O OCR VDD Voltage Window 3.2V-3.3V
  19     I/O OCR VDD Voltage Window 3.1V-3.2V
  18     I/O OCR VDD Voltage Window 3.0V-3.1V
  17     I/O OCR VDD Voltage Window 2.9V-3.0V
  16     I/O OCR VDD Voltage Window 2.8V-2.9V
  15     I/O OCR VDD Voltage Window 2.7V-2.8V
  14     I/O OCR VDD Voltage Window 2.6V-2.7V
  13     I/O OCR VDD Voltage Window 2.5V-2.6V
  12     I/O OCR VDD Voltage Window 2.4V-2.5V
  11     I/O OCR VDD Voltage Window 2.3V-2.4V
  10     I/O OCR VDD Voltage Window 2.2V-2.3V
  9      I/O OCR VDD Voltage Window 2.1V-2.2V
  8      I/O OCR VDD Voltage Window 2.0V-2.1V
  7-4    I/O OCR VDD Voltage Window Reserved
  3-0    I/O OCR VDD Voltage Window Reserved
SD Mode Response: R4:
  47     Start Bit (0)                                 ;\
  46     Transmission To Host (0)                      ; 1st byte
  45-40  Reserved (111111) (instead of Command value)  ;/
  39     Card is ready to operate after init           ;\
  38-36  Number of I/O Functions                       ;
  35     Memory Present                                ; 2nd byte
  34-33  Stuff bits (0)                                ;
  32     Switching to 1.8V Accepted (S18R) (not SPI)   ;/
  31-8   I/O OCR (24bit)                               ;-3rd..5th byte
  7-1    Reserved (111111) (instead of CRC7)           ;\6th byte
  0      End Bit (1)                                   ;/
SPI Mode Response: R4:
  8bit   modified R1 Response
           7  start bit (0)
           6  parameter error       (0=okay, 1=error)
           5  RFU (0)
           4  function number error (0=okay, 1=error)
           3  COM CRC error         (0=okay, 1=error)
           2  illegal command       (0=okay, 1=error)
           1  RFU (0)
           0  in idle state         (0=no, 1=idle)
  32bit  same as SD Response bit39-8 (but without S18R bit)

DSi SDIO Wifi Init
Related required registers/bits are:
 - SCFG_EXT7.bit19 needed for SDIO controller (else 4004Axxh-4004Bxxh disabled)
 - SCFG_CLK7 seems to be NOT needed for SDIO clock enable (unlike SDMMC)
 - SCFG_WL.bit0 seems to be wifi-related (but effect is unknown)
 - GPIO_WIFI.bit8 needed for AR6013G chips (else SDIO Function 1 fails)
 - BPTWL[30h] needed for LED and SDIO (else SDIO fails badly)
 - RTC.FOUT pin as configured by firmware (else WMI commands/events fail)
DSi init sequence is trying to send one CMD52 command first; if that fails, then the DSi is sending several CMD5's, followed by CMD3+CMD7.

SDIO State
  Command                 ini  stb  cmd  trn  ina
  CMD3  SET_RELATIVE_ADDR stb  ok   ---  ---  ---
  CMD5  IO_SEND_OP_COND   ok   ---  ---  ---  ---
         ocr bad          ina  ---  ---  ---  ---
  CMD7  SELECT_CARD       ---  cmd  ok   ---  ---
        DESELECT_CARD     ---  ok   stb  ---  ---
  CMD15 GO_INACTIVE_STATE ina  ina  ina  ---  ---
  CMD52 IO_RW_DIRECT      ---  ---  ok   (cmd)---
  CMD53 IO_RW_EXTENDED    ---  ---  trn  ---  ---
Note: In CMD52, state "dis" can mean state "ini","stb","ina" (though, theoretically CMD52 cannot be used in that states, so one should never see the "dis" state at all).

More SD commands that are (occassionally) used for SDIO
  CMD0  GO_IDLE_STATE     for entering SPI mode only (but does NOT reset SDIO)
  CMD8  SEND_IF_COND      optional for SDHC/SDXC
  CMD11 VOLTAGE_SWITCH    optional for UHS-I
  CMD19 SEND_TUNING_BLOCK optional for UHS-I
  CMD59 CRC_ON_OFF        spi-only
Moreover a combo card (a SDIO device with built-in SD memory card) may implement various SD commands; these commands will affect only the SD memory card side, not the SDIO device).
SDIO doesn't have CID or CSD registers, nor commands for STOP_TRANSMISSION, SET_BUSWIDTH, or SET_BLOCKLEN (but CMD52 can do equivalent stuff via SDIO Function 0 registers).

 ____________________________ I/O Commands for MMC____________________________

CMD39 - MMCIO: FAST_IO (type=ac)
  31-16  RCA
  15     Register Write Flag
  14-8   Register Address
  7-0    Register Data
MMC Response: R4:
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-24   RCA                                           ;-2nd..3rd byte
  23      Status (0=Bad, 1=Successful)                  ;\4th byte
  22-16   Register Address                              ;/
  15-8    Read Register Contents                        ;-5th byte
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/

CMD40 - MMCIO: GO_IRQ_STATE (type=bcr)
  31-0   Stuff Bits
MMC Response: R5:
  47      Start Bit (0)                                 ;\
  46      Transmission To Host (0)                      ; 1st byte
  45-40   Command (the 6bit CMD being responded to)     ;/
  39-24   RCA                                           ;-2nd..3rd byte
  23-8    Not defined (may be used for IRQ data)        ;-4th..5th byte
  7-1     CRC7                                          ;\6th byte
  0       End Bit (1)                                   ;/


DSi SDIO Memory and I/O Maps

Function 0 - Common I/O Area (CIA)
  0:00000h..000FFh  Card Common Control Registers (CCCR)
  0:00100h..001FFh  Function Basic Registers (FBR) for Function 1
  0:00200h..002FFh  Function Basic Registers (FBR) for Function 2
  0:00300h..003FFh  Function Basic Registers (FBR) for Function 3
  0:00400h..004FFh  Function Basic Registers (FBR) for Function 4
  0:00500h..005FFh  Function Basic Registers (FBR) for Function 5
  0:00600h..006FFh  Function Basic Registers (FBR) for Function 6
  0:00700h..007FFh  Function Basic Registers (FBR) for Function 7
  0:00800h..00FFFh  Reserved for Future
  0:01000h..17FFFh  Card Information Structures (Common CIS and Func 1-7 CIS)
  0:18000h..1FFFFh  Reserved for Future

Function 1..7 - Function specific Register Space
  n:00000h..1FFFFh  Registers (seven 128K spaces, one for each function)

Code Storage Area (CSA) (optional, R or R/W)
  CSA:00000h..FFFFFh  16Mbyte FAT12/FAT16 (accessed indirectly via "Window")

Card Common Control Registers (CCCR)
  0:00000h 2   CCCR: Revision (R)
  0:00002h 2   CCCR: I/O Function Enable/Ready (R/W)
  0:00004h 2   CCCR: Interrupt Enable/Pending (R/W)
  0:00006h 1   CCCR: I/O Abort (W)
  0:00007h 1   CCCR: Bus Interface Control (R/W)
  0:00008h 1   CCCR: Card Capability
  0:00009h 3   CCCR: Common CIS Pointer, Lo/Mid/Hi
  0:0000Ch 1   CCCR: Bus Suspend
  0:0000Dh 1   CCCR: Function Select (R/W)
  0:0000Eh 2   CCCR: Exec/Ready Flags (R)
  0:00010h 2   CCCR: CMD53 Block Size for Function 0, Lo/Hi (R/W)
  0:00012h 1   CCCR: Power Control
  0:00013h 2   CCCR: Bus Speed Select
  0:00015h 1   CCCR: Driver Strength
  0:00016h 1   CCCR: Interrupt Extension
  0:00017h D9h CCCR: Reserved for Future
  0:000F0h 10h CCCR: Reserved for Vendors

Function Basic Registers (FBR) for Function n (n=1..7)
  0:00n00h 1    FBR(n): Misc
  0:00n01h 1    FBR(n): Extended standard SDIO Function interface code
  0:00n02h 1    FBR(n): Misc
  0:00n02h 7    FBR(n): Reserved for Future
  0:00n09h 3    FBR(n): Pointer to Card Information Structure (CIS), Lo/Mid/Hi
  0:00n0Ch 3    FBR(n): Code Storage Area (CSA) Address, Lo/Mid/Hi
  0:00n0Fh 1    FBR(n): Code Storage Area (CSA) Data "Window"
  0:00n10h 2    FBR(n): CMD53 Block Size for Function n, Lo/Hi
  0:00n12h EEh  FBR(n): Reserved for Future


DSi SDIO Common Control Registers (CCCR)

0:00000h - CCCR: Revision (R)
  0-3   CCCR/FBR Format Version      (0=v1.00, 1=v1.10, 2=v2.00, 3=v3.00) (R)
  4-7   SDIO Spec Version   (0=v1.00, 1=v1.10, 2=v1.20, 3=v2.00, 4=v3.00) (R)
  8-11  SD Physical Layer Spec       (0=v1.01, 1=v1.10, 2=v2.00, 3=v3.0x) (R)
  12-15 Reserved for Future                                               (-)

0:00002h - CCCR: I/O Function Enable/Ready (R/W)
  0     Reserved for Future                                               (-)
  1-7   SDIO Function 1..7 Enable Flags             (0=Disable, 1=Enable) (R/W)
  8     Reserved for Future                                               (-)
  9-15  SDIO Function 1..7 Ready Flags         (0=Disabled/Busy, 1=Ready) (R)

0:00004h - CCCR: Interrupt Enable/Pending (R/W)
  0     SDIO Interrupt Master Enable                (0=Disable, 1=Enable) (R/W)
  1-7   SDIO Function 1..7 Interrupt Enable         (0=Disable, 1=Enable) (R/W)
  8     Reserved for Future                                               (-)
  9-15  SDIO Function 1..7 Interrupt Pending                (0=No, 1=IRQ) (R)

0:00006h - CCCR: I/O Abort (W)
  0-2   SDIO Function Number to be Aborted  (0=None?, 1..7=Function 1..7) (W)
            XXXsee pg 35
  3     Reset SDIO Card                               (0=Normal, 1=Reset) (W)
  4-7   Reserved for Future                                               (-)

0:00007h - CCCR: Bus Interface Control (R/W)
  0-1   Bus Width       (0=1bit, 1=Reserved, 2=4bit, 3=EmbeddedSDIO/8bit) (R/W)
  2     Support 8bit Bus Flag             (0=No, 1=Yes/EmbeddedSDIO only) (R)
  3-4   Reserved for Future                                               (-)
  5     Enable Continous SPI Interrupt              (0=Disable, 1=Enable) (R/W)
  6     Support Continous SPI Interrupt                     (0=No, 1=Yes) (R)
  7     Card Detect Disable     (0=Enable Pull-up on DAT3 pin, 1=Disable) (R/W)

0:00008h - CCCR: Card Capability
  0     Support Direct Command (CMD52) during Data Transfer (0=No, 1=Yes) (R)
  1     Support Multi-Block transfer (CMD53.block mode)     (0=No, 1=Yes) (R)
  2     Support Read Wait Control (RWC via DAT2 pin)        (0=No, 1=Yes) (R)
  3     Support Bus Control Suspend/Resume                  (0=No, 1=Yes) (R)
  4     Support Block Gap Interrupt during Multi-Block      (0=No, 1=Yes) (R)
  5     Enable Block Gap Interrupt during Multi-Block    (0=No, 1=Enable) (R/W)
  6     Low Speed Card                        (0=Full-Speed, 1=Low-Speed) (R)
  7     Support 4bit Mode for Low-Speed Card                (0=No, 1=Yes) (R)

0:00009h - CCCR: Common CIS Pointer, Lo
0:0000Ah - CCCR: Common CIS Pointer, Mid
0:0000Bh - CCCR: Common CIS Pointer, Hi
  0-16  Pointer to Card Common Card Information Structure (Common CIS)    (R)
  17-23 Unspecified (probably reserved)                                   (-)

0:0000Ch - CCCR: Bus Suspend
  0     Bus Status              XXX see pg 37                             (R)
  1     Bus Release Request     XXX see pg 38                             (R)
  2-7   Reserved for Future                                               (-)

0:0000Dh - CCCR: Function Select (R/W)
  0-3   Select Function (0=CIA, 1..7=Function 1..7, 8=Memory Card)        (R/W)
  4-6   Reserved for Future                                               (-)
  7     Data Flag (more data after resuming) (0=No, 1=Yes)                (R)

0:0000Eh - CCCR: Exec/Ready Flags (R)
  0     Command Execution Flag for Memory (=SD/Combo? or CSA?)            (R)
  1-7   Command Execution Flags for Function 1..7       (0=Busy, 1=Ready) (R)
  8     Read/Write Ready Flag for Memory (=SD/Combo? or CSA?)             (R)
  9-15  Read/Write Ready Flags for Function 1..7        (0=Busy, 1=Ready) (R)

0:00010h - CCCR: CMD53 Block Size for Function 0, Lo (R/W)
0:00011h - CCCR: CMD53 Block Size for Function 0, Hi (R/W)
  0-15  CMD53 Block size for Function(0)          (0001h..0800h) (0=None) (R/W)

0:00012h - CCCR: Power Control
  0     Support Master Power Control                        (0=No, 1=Yes) (R)
  1     Enable Master Power Control    (0=No/max 720mW, 1=Yes/allow more) (R/W)
  2-7   Reserved for Future                                               (-)

0:00013h,00014h - CCCR: Bus Speed Select
  0     Support High-Speed Mode (SDR25 or higher)           (0=No, 1=Yes) (R)
  1-3   Bus Speed Select   (0=SDR12, 1=SDR25, 2=SDR50, 3=SDR104, 4=DDR50) (R/W)
  4-7   Reserved for Future                                               (-)
  8     Support UHS-I SDR50  (usable in 1.8V mode only)     (0=No, 1=Yes) (R)
  9     Support UHS-I SDR104 (usable in 1.8V mode only)     (0=No, 1=Yes) (R)
  10    Support UHS-I DDR50  (usable in 1.8V mode only)     (0=No, 1=Yes) (R)
  11-15 Reserved for Future

0:00015h - CCCR: Driver Strength
  0     Support Driver Type A ;\see Physical Layer Specs    (0=No, 1=Yes) (R)
  1     Support Driver Type C ; version 3.0x for details    (0=No, 1=Yes) (R)
  2     Support Driver Type D ;/                            (0=No, 1=Yes) (R)
  3     Reserved for Future                                               (-)
  5-4   Driver Type Select    (0=Default/B, 1=Type A, 2=Type C, 3=Type D) (R/W)
  7-6   Reserved for Future                                               (-)

0:00016h - CCCR: Interrupt Extension
  0     Support Asynchronous Interrupt in 4bit mode         (0=No, 1=Yes) (R)
  1     Enable Asynchronous Interrupt in 4bit mode       (0=No, 1=Enable) (R/W)
  7-2   Reserved for Future                                               (-)


DSi SDIO Function Basic Registers (FBR)

0:00n00h - FBR(n): Interface Type
  0-3   Standard SDIO Function Interface Code                             (R)
  4-5   Reserved for Future                                               (-)
  6     Code Storage Area (CSA) Supported                   (0=No, 1=Yes) (R)
  7     Code Storage Area (CSA) Enable   (0=Block reads/writes, 1=Enable) (R/W)
  8-15  Extended standard SDIO Function interface code  (when bit0-3=0Fh) (R)
The interface type is merged of bit0-3 and bit8-15:
  0h:00h = No SDIO standard interface (eg. Atheros Wifi in DSi)
  1h:00h = SDIO Standard UART
  2h:00h = SDIO Bluetooth Type-A standard interface
  3h:00h = SDIO Bluetooth Type-B standard interface
  4h:00h = SDIO GPS standard interface
  5h:00h = SDIO Camera standard interface
  6h:00h = SDIO PHS standard interface
  7h:00h = SDIO WLAN interface
  8h:00h = Embedded SDIO-ATA standard interface
  9h:00h = SDIO Bluetooth Type-A Alternate MAC PHY (AMP) standard interface
  Ah:00h = Reserved for Future
  Bh:00h = Reserved for Future
  Ch:00h = Reserved for Future
  Dh:00h = Reserved for Future
  Eh:00h = Reserved for Future
  Fh:00h..FFh = Reserved for Future

0:00n02h - FBR(n): Power
  0     Support Power Selection                             (0=No, 1=Yes) (R)
  1     Enable Power Selection        (0=Normal Current, 1=Lower Current) (R/W)
  2-3   Reserved for Future                                               (-)
  4-7   Power State                                                       (R/W)

0:00n09h-00n0Bh - FBR(n): Pointer to Card Information Structure (CIS)
  0-16  Pointer to Function(n)'s Card Information Structure (Function CIS)(R)
  17-23 Unspecified (probably reserved)                                   (-)
Should point to "End-of-Chain Tuple" for unsupported functions?

0:00n0Ch-00n0Eh - FBR(n): Code Storage Area (CSA) Address (R/W)
  0-23  Pointer to CSA memory (incremented after CSA data read/write)     (R/W)

0:00n0Fh - FBR(n): Code Storage Area (CSA) Data "Window" (R or R/W)
  0-7   Data (to/from auto-incrementing CSA Address) (R for ROM, R/W otherwise)

0:00n10h-00n11h - FBR(n): CMD53 Block Size (R/W)
  0-15  CMD53 Block size for Function(n)          (0001h..0800h) (0=None) (R/W)


DSi SDIO Card Information Structures (CIS)

The CIS used by SDIO is based directly upon the metaformat specification used by PCMCIA and Compact Flash. For details on the metaformat, refer to:
  PC Card Standard, Volume 4, Metaformat Specification
Published by: PCMCIA (Personal Computer Memory Card International Association)

Basic Format
  00h           CISTPL_code
  01h           Offset to next tuple (n) (aka size of body)
  02h+(0..n-1)  Body (n bytes)

Summary
  00h = CISTPL_NULL          Null Tuple
  10h = CISTPL_CHECKSUM      Checksum Control
  15h = CISTPL_VERS_1        Level 1 Version/Product Information
  16h = CISTPL_ALTSTR        Alternate Language String
  20h = CISTPL_MANFID        Manufacturer ID
  21h = CISTPL_FUNCID        Function ID
  22h = CISTPL_FUNCE         Function Extensions
  80h-8Fh = Vendor specific  Vendor specific
  91h = CISTPL_SDIO_STD      Info for Standard SDIO Functions
  92h = CISTPL_SDIO_EXT      Reserved for future SDIO stuff
  FFh = CISTPL_END           End-of-chain

Tuple 00h - Null Tuple (meaningless, unknown purpose)
  00h Tuple ID   (00h)
  01h Tuple Size (00h)
Unspecified in SDIO reference... but maybe defined in PCMIA specs?)

Tuple 10h - Checksum Control
  00h Tuple ID   (10h)
  01h Tuple Size (?)
  ... Unknown
Unspecified in SDIO reference... but maybe defined in PCMIA specs?)

Tuple 15h - Level 1 Version/Product Information
  00h Tuple ID   (15h)
  01h Tuple Size (?)
  ... Unknown
Unspecified in SDIO reference... but maybe defined in PCMIA specs?)


Tuple 20h - Manufacturer ID
  00h      Tuple ID   (20h)
  01h      Tuple Size (at least 4)
  02h-03h  Manufacturer ID (assigned by JEIDA or PCMCIA)
  04h-05h  Part Number/Revision (manufacturer specific)

Tuple 21h - Function ID
  00h      Tuple ID   (21h)
  01h      Tuple Size (2)
  02h      Card Function Code (0Ch for SDIO)
  03h      System initialization bit mask (Not used, 00h)

Tuple 22h - Function Extension
  00h      Tuple ID   (22h)
  01h      Tuple Size (..)
  02h      Type of extended data
  03h..xxh Function information

Tuple 22h - Function Extension, Type 00h, for Function 0
  00h      Tuple ID   (22h)
  01h      Tuple Size (04h+2*N)
  02h      Type of extended data (00h=Type 00h)
  03h-04h  Max Block Size for Function 0 (0001h or higher)
  05h      Max Transfer Speed for Function 0-7 (specified as Value*Unit bits/s)
           bit0-2: Unit  (0=0.1M, 1=1M, 2=10M, 3=100M, 4..7=Reserved)
           bit3-6: Value (0=Reserved, 1=1, 2=1.2, 3=1.3, 4=1.5, 5=2, 6=2.5,
                   7=3, 8=3.5, 9=4, 10=4.5, 11=5, 12=5.5, 13=6, 14=7, 15=8)
           bit7:   Reserved
  06h...   N two-byte pairs (TC,CP) for 1..N   ;(N=([01h]-4)/2)

Tuple 22h - Function Extension, Type 01h, for Function 1-7
  00h      Tuple ID   (22h)
  01h      Tuple Size (2Ah)
  02h      Type of extended data (01h=Type 01h)
  03h      Function Info (bit0=WakeUpSupport, bit1..7=Reserved)
  04h      Standard SDIO Function version (2x4bit maj.min, or 00h=Nonstandard)
  05h-08h  Card Product Serial Number PSN (32bit) (unique value, or 0=None)
  09h-0Ch  CSA Size in bytes available for this Function (32bit)
  0Dh      CSA Property (bit0=WriteProtected/ReadOnly, bit1=NoReformatting)
  0Eh-0Fh  Max Block Size for this Function (0001h or higher)
  10h-13h  Operation Condition OCR (same as in ACMD41 for SD Memory devices)
  14h-16h  3x8bit Operation Power (Min/Average/Max) (0..254mA, or 255=more)
  17h-19h  3x8bit Standby Power   (Min/Average/Max) (0..254mA, or 255=more)
  1Ah-1Dh  2x16bit Bandwidth      (Min/Optimal) (1..65535 KB/sec, or 0=None)
  1Eh-1Fh  Timeout for Enable-till-Ready in 10ms units (max 655.35 seconds)
  20h-23h  2x16bit Operation 3.3V         (Average/Max) (1..65535mA, or 0=?)
  24h-25h  2x16bit High-Current-Mode 3.3V (Average/Max) (1..65535mA, or 0=?)
  28h-2Bh  2x16bit Low-Current-Mode 3.3V  (Average/Max) (1..65535mA, or 0=?)

Tuple 22h - Function Extension, Type 02h, for Function 1-7 (Power State)
  00h      Tuple ID   (22h)
  01h      Tuple Size (02h+N*2) (N=1..15, for up to 15 power states)
  02h      Type of extended data (02h=Type 02h)
  03h      Fixed value (00h)
  04h..xxh Nx16bit Max consumption in Power State 1..N (0..65535mW)

Tuple 91h - SDIO_STD - Info about Standard SDIO Functions
  00h      Tuple ID   (91h)
  01h      Tuple Size (02h..FFh)
  02h      SDIO STD ID (the 4+8bit Interface Type in FBR, squeezed into 8bits?)
  03h      SDIO STD Type           ;\depends on Interface Type
  04h...   SDIO STD Data (if any)  ;/

Tuple 92h - SDIO_EXT
  00h      Tuple ID   (92h)
  01h      Tuple Size (?)
  02h...   Reserved (if any)

Tuple FFh - END
  00h      Tuple ID   (FFh)
Indicates the end of tuple's list. Unlike all other tuple's, this is only a single FFh-byte (without "Tuple Size" entry).

01 CISTPL_DEVICE
14 CISTPL_NO_LINK
1A CISTPL_CONFIG
1B CISTPL_CFTABLE_ENTRY


DSi SD/MMC Filesystem

DSi Partition Table and FAT Filesystems
DSi SD/MMC Partition Table (aka Master Boot Record aka MBR)
DSi SD/MMC Filesystem (FAT)
System Tools and DSiware games are having regular "ROM Cartridge" headers, with NitroROM filesystem defined in that headers (ie. the ".app" files are internally containing a 2nd filesystem inside of the FAT filesystem; eventually there can be also NARC files as 3rd filesystem inside of the NitroROM filesystem).
DSi Cartridge Header
DS Cartridge NitroROM and NitroARC File Systems
Savedata for DSiWare games is usually stored in "public.sav" or "private.sav" files. That .sav files are usually containing a FAT12 with its own VBR, FAT, and Directories (so they use some virtual FAT12 inside of the real FAT16).

DSi Filesystem Overview
DSi SD/MMC Internal NAND Layout
DSi SD/MMC Bootloader
DSi SD/MMC Device List
DSi SD/MMC Complete List of SD/MMC Files/Folders
DSi SD/MMC Summary of SD/MMC Files/Folders
DSi SD/MMC Images
DSi Autoload on Warmboot

DSi Files
DSi SD/MMC DSiware Files on Internal eMMC Storage
DSi SD/MMC DSiware Files on External SD Card (.bin aka Tad Files)
DSi SD/MMC DSiware Files from Nintendo's Server
DSi SD/MMC DSiware Tickets and Title metadata
DSi SD/MMC Firmware dev.kp and cert.sys Certificate Files
DSi SD/MMC Firmware Certificate/Keys (DER)
DSi SD/MMC Firmware Font File
DSi SD/MMC Firmware Log Files
DSi SD/MMC Firmware Misc Files
DSi SD/MMC Firmware Wifi Firmware
DSi SD/MMC Firmware System Settings Data Files
DSi SD/MMC Firmware Version Data File
DSi SD/MMC Firmware Nintendo DS Cart Whitelist File
DSi SD/MMC Camera Files - Overview
DSi SD/MMC Camera Files - JPEG's
DSi SD/MMC Camera Files - pit.bin
DSi SD/MMC Flipnote Files
DS File Formats


DSi SD/MMC Partition Table (aka Master Boot Record aka MBR)

DSi eMMC Partition table
The decrypted DSi MBR contains (for 240MB chips; 3rd part differs for 245.5MB):
  0000  00 00 00 00 00 00 00 00 .. .. .. .. 00 00        ;bootcode (zero)
  01BE  00 03 18 04 06 0F E0 3B 77 08 00 00 89 6F 06 00  ;1st partition (main)
  01CE  00 02 CE 3C 06 0F E0 BE 4D 78 06 00 B3 05 01 00  ;2nd partition (photo)
  01DE  00 02 DE BF 01 0F E0 BF 5D 7E 07 00 A3 01 00 00  ;3rd partition (extra)
  01EE  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ;4th partition (none)
  01FE  55 AA                                            ;mbr id (55h,AAh)
Above values are following the classical standard MBR format:
  000h      446  bootcode (zerofilled on DSi)                   ;-bootcode
  1BEh+n*10h  1  status (00h)                                   ;\
  1BFh+n*10h  3  chsFirst                                       ; four
  1C2h+n*10h  1  type (00h=unused, 01h=FAT12, 06h=FAT16B)       ; partitions
  1C3h+n*10h  3  chsLast                                        ; (n=0..3)
  1C6h+n*10h  4  lbaFirst  ;\logical block addresses/sizes      ;
  1CAh+n*10h  4  lbaSize   ;/counted in 200h-byte sectors       ;/
  1FEh        2  mbrsig (55h,AAh)                               ;-MBR ID
The CHS and LBA values are essentially containing the same information (CHS being an older standard, and LBA being invented in 1996). The 24bit CHS values are encoded as:
  0-7    Head Bit0-7     (00h..FEh) (or less common, 00h..FFh)
  8-13   Sector Bit0-5   (01h..3Fh)
  14-15  Cylinder Bit8-9
  16-23  Cylinder Bit0-7 (000h..3FFh, with above bit8-7)
To convert CHS to LBA, one must know the number of (logical) heads and sectors per cylinder (that info isn't stored in the MBR). The DSi's eMMC uses 32 sectors, 16 heads, 1024 cylinders:
  LBA = (Cylinder*32*16) + (Head*32) + (Sector-1)
Anyways, it's better/easier to use the LBA values directly, and ignore the CHS values.

3DS eMMC Partition table
The 3DS does have a DSi compatible MBR (with main & photo partitions, as shown above). The additional 3DS partitions are accessed via a separate "NCSD" header (with 3DS specific encryption keys, which aren't available in DSi mode).

SD/MMC Card Partition table
SD/MMC Cards are shipped with pre-formatted filesystem, so they should stick to some standarized MBR variant, with only a single partition used, possibly with additional date/id fields(?).
Note that SD/MMC Cards may or may not use partition tables (see CSD Register, FILE_FORMAT entry).

Formatting and Reformatting
SD/MMC cards are usually pre-formatted with empty filesystems. Reformatting should be avoided, or should be done only with tools that are aware of some memory card specific requirements:
The cluster size should not be less than the physical sector size (otherwise, when writing smaller clusters, sectors may get erased multiple times, which would result in slower writing and reduced lifetime).
Many devices do support only the standard FAT filesystems (for example, cameras or mp3-players may be unable to access memory cards with NTFS filesystem).

More info
For more info on MBR variants (and on the Partition Type value at 1C2h+n*10h), see:
  http://en.wikipedia.org/wiki/Master_Boot_Record
  http://en.wikipedia.org/wiki/Partition_type <-- rather meaningless


DSi SD/MMC Filesystem (FAT)

Volume Boot Record (VBR) (FAT12/FAT16) (DOS 4.0 EBPB)
  000h 3   80x86 jump opcode       (DSi: E9h,00h,00h)
  003h 8   ascii disk name         (DSi: "TWL     ")
  00Bh 2   bytes / sector          (DSi: 0200h)
  00Dh 1   sectors / cluster       (DSi: 20h)
  00Eh 2   sectors / boot-record   (DSi: 0001h)
  010h 1   number of FAT-copys     (DSi: 02h)
  011h 2   entrys / root-directory (DSi: 0200h)
  013h 2   sectors / disk          (DSi: 0000h)
  015h 1   ID                      (DSi: F8h=HDD)
  016h 2   sectors / FAT           (DSi: A:0034h, B:0009h)
  018h 2   sectors / track         (DSi: 0020h)
  01Ah 2   heads / disk            (DSi: 0010h)
  01Ch 2   number of reserved sectors    (DSi: None such entry!)
  01Ch 4   LBA First "hidden"      (DSi: A:00000877h, B:0006784Dh)
  020h 4   LBA Size (total sectors)(DSi: A:00066F89h, B:000105B3h)
  024h 1   Drive Number            (DSi: A:00h, B:01h)
  025h 1   Flags (reserved)        (DSi: 00h)
  026h 1   EBPB Version            (DSi: 29h) (that is, DOS 4.0 EBPB)
  027h 4   Volume Serial Number    (DSi: 12345678h)
  02Bh 11  Volume Label            (DSi: "           ")
  036h 8   Filesystem Type         (DSi: 00h-filled)
  03Eh 448 Bootcode                (DSi: 00h-filled)
  1FEh 2   Signature               (DSi: 55h,AAh)
SDHC carts use FAT32, which differs in entries 011h, 016h and 024h-059h:
  011h 2   Must be 0 (number of root entries, is variable-length FAT chain)
  016h 2   Must be 0 (sectors per fat, instead use 32bit value at 024h)
  024h 4   sectors / FAT  (new 32bit value instead of old entry 016h)
  028h 2   ExtFlags (related to "active" FAT copy)
  02Ah 2   Version of FAT32 filesystem (minor, major) (should be 0.0)
  02Ch 4   Cluster number of first Root directory cluster (usually/often 2)
  030h 2   Sector number of FSINFO in reserved area (usually 0001h)
  032h 2   Sector number of VBR backup copy in reserved area (usually 0006h)
  034h 12  Reserved for future   ;Should be zerofilled
  040h 1   Drive Number                                               ;\
  041h 1   Flags (reserved)                                           ; as old
  042h 1   EBPB Version          ;Must be 29h (that is, DOS 4.0 EBPB) ; entries
  043h 4   Volume Serial Number                                       ; at 024h
  047h 11  Volume Label                                               ;
  052h 8   Filesystem Type       ;Must be "FAT32   "                  ;/
Moreover, FAT32 has the "FSINFO" at sector number VBR[30h]:
  000h 4   Value 41615252h (aka "RRaA")
  004h 480 Reserved (should be 0)
  1E4h 4   Value 61417272h (aka "rrAa")
  1E8h 4   Hint on number of free clusters   (or FFFFFFFFh=unknown)
  1ECh 4   Hint on first free cluster number (or FFFFFFFFh=unknown)
  1F0h 12  Reserved (should be 0)
  1FCh 4   Value AA550000h
For more info see http://en.wikipedia.org/wiki/BIOS_Parameter_Block and fatgen103.pdf (official specs from microsoft).

File Allocation Table - FAT and FAT copy(s)
The following sectors are occupied by the File Allocation Table (FAT), which contains 12bit, 16bit, or 32bit entries (for FAT12/16/32) for each cluster:
  (x000)(0)000      unused, free
  (x000)(0)001      ???
  (x000)(0)002...   pointer to next cluster in chain (0)002..(F)FEF
  (xFFF)(F)FF0-6    reserved (no part of chain, not free)
  (xFFF)(F)FF7      defect cluster, don't use
  (xFFF)(F)FF8-F    last cluster of chain
The "x" in MSB of FAT32 entries is reserved (ie. FAT32 is restricted to 28bit cluster numbers).
Number and size of FATs can be calculated by the information in the boot sector.
Note on The first two FAT entries:
"The first cluster of the data area is cluster #2. That leaves the first two entries of the FAT unused. In the first byte of the first entry a copy of the media descriptor is stored. The remaining bits of this entry are 1. In the second entry the end-of-file marker is stored. The high order two bits of the second entry are sometimes, in the case of FAT16 and FAT32, used for dirty volume management: high order bit 1: last shutdown was clean; next highest bit 1: during the previous mount no disk I/O errors were detected.
(Historically this description has things backwards: DOS 1.0 did not have a BIOS Parameter Block, and the distinction between single-sided and double-sided 5.25" 360K floppies was indicated by the first byte in the FAT. DOS 2.0 introduced the BPB with media descriptor byte.)"

Root directory
The following sectors are the Root directory, again, size depends on the info in bootsector (on FAT32 is it's a normal cluster chain with variable size). Each entry consists of 32 bytes:
  00-07  8    Filename (first byte: 00=free entry, 2E=dir, E5=deleted entry)
  08-0A  3    Filename extension
  0B     1    Fileattribute
                bit0 read only
                bit1 hidden
                bit2 system
                bit3 volume label
                bit4 subdirectory
                bit5 archive-flag
                bit6 reserved
                bit7 reserved
  0C-0D  2    Reserved, or stuff
  0E-0F  2    Reserved, or Creation Timestamp
  10-11  2    Reserved, or Creation Datestamp
  12-13  2    Reserved, or Last Access Datestamp
  14-15  2    Reserved, or MSBs of Cluster (for FAT32)
  16-17  2    Last Modify Timestamp: HHHHHMMM, MMMSSSSS
  18-19  2    Last Modify Datestamp: YYYYYYYM, MMMDDDDD
  1A-1B  2    Pointer to first Cluster of file
  1C-1F  4    Filesize in bytes (always 0 for directories)
The 'cluster' entry points to the first used cluster of the file. The FAT entry for that cluster points to the next used cluster (if any), the FAT entry for that cluster points to the next cluster, and so on.

Long File Names (LFNs)
Long File Names (LFNs) are occupying multiple continous directory entries, consisting of a normal short filename entry, preceeded by one or more LFN prefix entries (with Attribute=0Fh). Each LFN prefix can hold 13 characters, the total length should not exceed 255 characters. The name should be terminated by 0000h, and any remaining unused characters should be padded by FFFFh. The LFN prefix entries are using the following format:
  00h  1  Sequence Number (bit6: last logical, first physical LFN entry,
          bit5: 0, bit4-0: number 01h..14h (1Fh)) (or E5h=deleted entry)
  01h  10 Long Filename characters (five UCS-2 characters)
  0Bh  1  Attributes (always 0Fh for LFN prefix)
  0Ch  1  Type (always 00h)
  0Dh  1  Short Filename Checksum
          sum=00h, for i=0 to 10, sum = (sum ROR 1) + shortname_char[i], next i
  0Eh  12 Long Filename characters (six UCS-2 characters)
  1Ah  2  First cluster (always 0000h)
  1Ch  4  Long Filename characters (two UCS-2 characters)
For example, "File with very long filename.ext" would be formatted as so:
  Entry 1: LFN Prefix (43h) "me.ext", 0000h, 6xFFFFh
  Entry 2: LFN Prefix (02h) "y long filena"
  Entry 3: LFN Prefix (01h) "File with ver"
  Entry 4: Normal 8.3 short filename entry "FILEWI~1.EXT"
http://en.wikipedia.org/wiki/Design_of_the_FAT_file_system#VFAT_long_file_names

Reserved Sectors (if any)
Usually the number of reserved sectors is zero. If it is non-zero, then the following sector(s) are reserved (and could be used by the boot procedure for whatever purposes).

Data Clusters 0002..nnnn
Finally all following sectors are data clusters. The first cluster is called cluster number (000)(0)002, followed by number (000)(0)003, (000)(0)004, and so on.

http://en.wikipedia.org/wiki/Design_of_the_FAT_file_system


DSi SD/MMC Internal NAND Layout

The DSi uses a 256MB Samsung eMMC moviNAND(?) flash chip, which is a NAND flash chip with a built-in controller that implements a MMC (SDIO?) interface. In many ways, it's like an SD card (or actually: MMC card) in BGA packaging, and some people have successfully read it with modified(why/how?) SD(/MMC?) card readers (is there any standard software that can be used for doing that?). The last 16MB is used for wear-leveling purposes (such as replacing bad blocks), while the first 240MB is used for storing actual data.

Addressing is done in terms of 512-bytes sectors. All wear-levelling and bad-block-mapping is handled transparently inside the chip by the controller. Most sectors are encrypted with a per-console key.

Overall eMMC Layout
  Offset     Size     Description
  00000000h  200h     PC-style MBR, encrypted with a per-console key
  00000200h  200h     Stage 2 Boot Info Block 1 (used)
  00000400h  200h     Stage 2 Boot Info Block 2 (unused, same as above)
  00000600h  200h     Stage 2 Boot Info Block 3 (unused, nonsense NAND offsets)
  00000800h  26600h   Stage 2 ARM9 Bootcode (encrypted with universal key)
  00026E00h  27600h   Stage 2 ARM7 Bootcode (encrypted with universal key)
  0004E400h  400h     Stage 2 Footer -- unknown format, but first 10 bytes
                        are (unencrypted) build number of Stage 2 bootloader
  0004E800h  B1000h   Unused (all 00h)
  000FF800h  200h     Unused (all 00h) (or No$gba Footer with CID & Console ID)
  000FFA00h  400h     Diagnostic area. (often contains build date of
                        device in plaintext) Blank in never-before-booted
                        DSi. Might be written to during firmware updates.
  000FFE00h  200h     Unused (all FFh)
  00100000h  EE00h    Unused (all 00h)
  0010EE00h  CDF1200h 1st partition (205.9Mbyte) (main, encrypted, FAT16)
  0CF00000h  9A00h    Unused (all 00h)
  0CF09A00h  20B6600h 2nd partition (32.7Mbyte)  (photo, encrypted, FAT12)
 For 240.0MB chips (Samsung KMAPF0000M-S998 or KLM5617EFW-B301):
  0EFC0000h  BA00h    Unused (all 00h)
  0EFCBA00h  34600h   3rd partition (0.2Mbyte)   (extra, unformatted)
  0F000000h  -        End of 240MByte Address Space
 For 245.5MB chips (ST NAND02GAH0LZC5, both rev30 and rev31):
  0EFC0000h  B600h    Unused (all 00h?) (smaller unused area as in 240MB chip)
  0EFCB600h  5B4A00h  3rd partition (5.7Mbyte)   (extra, unformatted)
  0F580000h  -        End of 245.5MByte Address Space

Stage 2 Boot Info Blocks 1, 2, 3 (unencrypted, aside from the RSA block)
  000h 20h Zerofilled
  020h 4   ARM9 Bootcode NAND Offset         (800h)      (Info Block 3: 80400h)
  024h 4   ARM9 Bootcode Size actual         (26410h)
  028h 4   ARM9 Bootcode RAM Address / Entry (37B8000h)
  02Ch 4   ARM9 Bootcode Size rounded-up     (26600h)
  030h 4   ARM7 Bootcode NAND Offset         (26E00h)    (Info Block 3: A6A00h)
  034h 4   ARM7 Bootcode Size actual         (27588h)
  038h 4   ARM7 Bootcode RAM Address / Entry (37B8000h)
  03Ch 4   ARM7 Bootcode Size rounded-up     (27600h)
  040h BFh Zerofilled
  0FFh 1   ARM Loadmode Flags               (0Ch)
  100h 80h RSA Block (B3,FF,EC,E5,..)       (Boot Info Block 3: 5B,E1,7A,9F,..)
  180h 14h Global MBK1..MBK5 Slot Settings
  194h 0Ch Local MBK6..MBK8 Settings, WRAM Areas for ARM9
  1A0h 0Ch Local MBK6..MBK8 Settings, WRAM Areas for ARM7
  1ACh 4   Global MBK9 Setting, WRAM Slot Write Protect (FF000000h)
  1B0h 50h Zerofilled
The ARM Loadmode Flags are (usually 0Ch):
  0    ARM9 Loadmode    (0=Normal to memory, 1=Special via bit3)
  1    ARM7 Loadmode    (0=Normal to memory, 1=Special via bit3)
  2    Unused, set      (usually 1)
  3    Special Loadmode (0=LZSS to memory, 1=Transfer via IPC FIFO)
  4-7  Unused, cleared  (usually 0)
BUG: If bit3 is set, then parts of bootrom behaves as if both bit0 & bit1 are also set. Hmmm, but bit3 is actually set, so it's default behaviour...?
The above RSA Block contains 74h bytes of information (plus 0Bh bytes padding):
  Pre  0Bh  Leading RSA Padding (01,FF,FF,FF,FF,FF,FF,FF,FF,FF,00)
  00h  10h  AES_Engine Key Y for ARM9/ARM7 Bootcode (EC,07,00,00,...)
  10h  14h  SHA1 on WifiFlash[00h..27h] and eMMCBootInfo[00h..FFh,180h..1FFh]
            3DS: reportedly NAND/MBR[00h..27h] instead of WifiFlash[00h..27h]??
  24h  14h  SHA1 on decrypted ARM9 Bootcode, with the actual binary size
  38h  14h  SHA1 on decrypted ARM7 Bootcode, with the actual binary size
  4Ch  14h  Zerofilled
  60h  14h  SHA1 on above 60h-byte area at [00h..5Fh] (63,D2,FC,6E,...)

eMMC Encryption for Boot Sectors (AES-CTR, with fixed key; from RSA block)
The ARM9/ARM7 bootcode is encrypted via AES-CTR:
  RSA_KEY  = F1,F5,1A,FF,...         ;-from 3DS TWL_FIRM (for RSA Block)
  IV[0..3] = +size                   ;\
  IV[4..7] = -size                   ; size rounded up to 200h boundary, ie.
  IV[8..B] = -size-1                 ; from Boot Info Block entries [02Ch,03Ch]
  IV[C..F] = 00000000h               ;/
  KEY_X[0..F] = "Nintendo DS",...    ;-same as Key X for "Tad Files"
  KEY_Y[0..F] = EC,07,00,00,...      ;-from RSA Block (see above)
The RSA_KEY key is stored in some non-dumpable area of the DSi BIOS, making it impossible to obtain that key without chip decapping. However, Nintendo has included the same RSA_KEY in the "TWL_FIRM" firmware update for 3DS.

eMMC Encryption for MBR/Partitions (AES-CTR, with console-specific key)
The MBR and both partitions are encrypted via AES-CTR:
  IV[0..F]:    SHA1(CID)+Address/10h                    ;-eMMC Chip ID
  KEY_X[0..3]: [4004D00h]                               ;\
  KEY_X[4..7]: [4004D00h] XOR 24EE6906h                 ; CPU/Console ID, for
  KEY_X[8..B]: [4004D04h] XOR E65B601Dh                 ; DSi partitions on DSi
  KEY_X[C..F]: [4004D04h]                               ;/
  KEY_X[0..3]: [4004D00h]                               ;\CPU/Console ID, for
  KEY_X[4..B]: "NINTENDO"                               ; DSi partitions on 3DS
  KEY_X[C..F]: [4004D04h]                               ;/
  KEY_Y[0..F]: 0AB9DC76h,BD4DC4D3h,202DDD1Dh,E1A00005h  ;-Constant
The CID value (eMMC Chip ID) should be in same format as stored in RAM at 2FFD7BCh: little-endian 120bit (without crc7), padded to 128bit (with MSB=00h), ie. it should look like this (dd/ss being date/serial numbers):
  CID = [2FFD7BCh] = dd,ss,ss,ss,ss,03,4D,30,30,46,50,41,00,00,15,00
  SHA1(CID) = SWI_27h(SHA1value,2FFD7BCh,10h)
The resulting SHA1value is 14h-bytes, the first 10h-bytes are used as IV value, whereas the DSi doesn't adjust the endianness (it does just use the SWI's "big-endian" SHA1value as "little-endian" AES/IV value).
The CTR gets incremented after each 10h bytes (ie. to access a random address: "IV=SHA1value+(address/10h)".
For more info on obtaining the CID and Port [4004D00h] values, see:
DSi Console IDs
See also:
DSi SD/MMC Images

Related Decryption Tools
  "NUS Downloader" allows to download and decrypt system updates
  "DSi SRL Extract" allows to decrypt DSiware files (when copied to SD card)
  "TWLTool" decrypt/encrypt eMMC images (firmware downgrading, dsiware-hax)
  "TWLbf" and "bfCL" bruteforce Console ID or CID (or both) from eMMC images


DSi SD/MMC Bootloader

Stages
  Stage 1: Load Stage 2 from NAND Boot Sectors (via code in BIOS ROM)
  Stage 2: Load Stage 3 from NAND Filesystem
  Stage 3: Contains GUI and allows to boot Cartridges or NAND files

Stage 1
The first stage of the DSi's bootloader lives in ROM, presumably on the CPU die. It loads further encrypted (and probably signed) stages from NAND flash, starting with a (partially unencrypted) offset table in the sector at 0x200.
Not much is known about this bootloader yet, but it presumably knows how to:
  Initialize the encryption hardware
  Read the contents of NVRAM
  Initialize both LCDs
  Read blocks (but not files) from the NAND flash
  Perform some variety of integrity check on all data it reads(signature,CRC,?)
  Display basic hexadecimal error codes
  Possibly factory-programming the NAND flash?
  Might also do basic power-on self test of peripherals
When the Stage 1 bootloader (in ROM) fails, it displays a 32-bit hexadecimal number on the top screen, known Stage 1 error codes are:
  Error Code Description
  0000FE00   Error communicating NAND chip (It's missing, CLK shorted, etc.)
  0000FEFC   Integrity error in first block of Stage 2 (address at 220h)
  0000FEFD   Integrity error in second block of Stage 2 (address at 230h)
  0000FEFE   Boot sector integrity error (Sector 200h not valid), or error
               in NVRAM contents.

Stage 2
Unlike the stage1 bootloader, which must be small enough to fit in ROM (probably several kilobytes), the stage2 bootloader has about a megabyte of NAND flash reserved for it. The stage2 bootloader understands partitions and filesystems, and it is capable of loading the DSi menu. It also must understand the encryption used on filesystem blocks in the NAND, and it must understand how to load and validate title metadata.
The Stage 2 loader was not modified by the System Menu 1.4 update. This is still earlier in the boot process than the "Health and Safety" warning.
The first stage bootloader reads sector 0x200 in order to find a table of offsets to the Stage 2 bootloader:
  00000220  00 08 00 00 10 64 02 00  00 80 7b 03 00 66 02 00 |.....d....{..f..|
  00000230  00 6e 02 00 88 75 02 00  00 80 7b 03 00 76 02 00 |.n...u....{..v..|
  00000240  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00 |................|
This appears to be describing two chunks of the stage2 loader, one 0x26410 bytes in length at address 0x800, and one 0x27588 bytes at address 0x26e00.
Note that this sector (and two similar ones at 0x400 and 0x600) appear to be the only unencrypted blocks on the NAND flash.
It is unclear why there are two pieces which are nearly but not quite the same size. Passive traces of the boot sequence confirm that the 0x26e00 chunk is slightly larger, and it's loaded first. The 0x800 chunk is read immediately after the 0x26e00 chunk.
Whereas the filesystem data in NAND is encrypted using a unique key for every DSi, the stage2 bootloader is identical on every DSi tested so far. This probably means that it is encrypted using a fixed key included in stage1.

After Stage 2 is loaded:
  1. The NAND flash is partially re-initialized
  2. Sector 0 is read from the NAND. Appears to be (encrypted) DOS-style MBR.
  3. The MBR signature and the type of the first partition are verified.
  4. Filesystem metadata is read from sectors starting around 0x100000. The
       metadata appears to be in FAT format with long filenames.
  5. Multiple files are loaded from the filesystem. The exact read addresses
       will vary depending on your DSi's firmware version and the state of
       its filesystem when you performed the last firmware update. On a brand
       new DSi, it appears that the DSi Menu itself is loaded from 0xb20000
       after two small metadata files are read from 0xb1c000 and 0x7a0000.

All Stage 2 errors show before the health and safety screen. It appears that Stage 2 errors from a cold power-on always cause the DSi to hang at a black screen, whereas Stage 2 errors after reset (pressing but not holding the power button) will give an error message screen. Known Stage 2 errors:
  Text                    Description
  "Error: 1-2435-8325"    Invalid signature or partition type in MBR,
                            invalid starting LBA.
  "Error: 2-2435-8325"    Error reading fat/sectors from eMMC
  "Error: 3-2435-8325"    DSi Menu integrity checks failed

Boot Sectors in DSi Debug version
Debug version bootsectors are almost same as in retail version: There's an extra RSA key inserted at ARM9:37CEADCh, and lots of B/BL/BLX/LDR addresses have changed due to the inserted bytes, but, apart from that changes, only 5 opcodes are really different, ARM9:37C07A0h, ARM9:37C0864h, ARM7:37B9110h, ARM7:37B9200h do trigger errors when SCFG_DEBUG bit0-1 are zero (opposite of retail version), and ARM9:37B8BA4h uses the extra RSA key at 37CEADCh for Debug Launcher (instead of the retail key at 1FFC400h).


DSi SD/MMC Device List

The Device List is automatically copied to ARM7 RAM address defined in cartheader[1D4h] by firmware. The 400h-byte list is mainly used for DSiware/firmware titles (DSi ROM titles will usually just receive an empty zerofilled 400h-byte list; unless maybe if they are flagged to use SD/MMC hardware in cartheader?). There appears to be no range check for the cartheader[1D4h] entry (setting it to zero causes the list to be 'written' to ARM7 ROM area).

Device List, 400h-bytes, loaded to ARM7/RAM address from cartheader[1D4h]
  000h 54h*11 Device List (max 11 entries)
  39Ch 24h    Zerofilled
  3C0h 40h    Name 'nand:/title/000300tt/4ggggggg/content/000000vv.app' + 00h's
Format of the 54h-byte device list entries:
  00h  1    Drive Letter ("A".."I")
  01h  1    Flags (see below)
  02h  1    Access Rights (bit1=Write, bit2=Read)
  03h  1    Zero
  04h  10h  Device Name (eg. "nand" or "dataPub") (zeropadded)
  14h  40h  Path        (eg. "/" or "nand:/shared1") (zeropadded)
Bits in Flags byte:
  0    Physical Drive (0=External SD/MMC Slot, 1=Internal eMMC)
  1-2  Zero (maybe MSBs of Drive)
  3-4  Device Type (0=Physical, 1=Virtual/File, 2=Virtual/Folder, 3=Reserved)
  5    Partition (0=1st, 1=2nd)
  6    Zero (maybe MSB of Partition)
  7    Encrypt? (set for eMMC physical devices; not for virtual, not for SD)
The DSi has 9 default devices ("A"-"I"):
  Letter/Flags     Name       Path                   ;Notes
  'A',81h,06h,00h  'nand'     '/'                    ;eMMC Cart Partition 1
  'B',A1h,06h,00h  'nand2'    '/'                    ;eMMC Cart Partition 2
  'C',11h,04h,00h  'content'  'nand:/title/000300tt/4ggggggg/content'
  'D',11h,04h,00h  'shared1'  'nand:/shared1'        ;TWLCFGn.dat
  'E',11h,06h,00h  'shared2'  'nand:/shared2'        ;Sound and wrap.bin
  'F',31h,06h,00h  'photo'    'nand2:/photo'         ;Camera photos/frames
  'G',09h,06h,00h  'dataPrv'  'nand:/title/000300tt/4ggggggg/data/private.sav'
  'H',09h,06h,00h  'dataPub'  'nand:/title/000300tt/4ggggggg/data/public.sav'
  'I',00h,06h,00h  'sdmc'     '/'                    ;SD Cart Partition 1
Depending on the cartheader, usually only 5-8 of that 9 devices are copied to the device list in RAM, and Access Rights for some devices can be crippled in the RAM list entries.
Caution: The list may not contain forward references (eg. one can redirect "dataPub" to "sdmc:/flipnote.pub", but that works only if "sdmc" was already defined in one of the previous entries).
A and B: These physical eMMC partitions are always included in the list (because they are needed as parent entries for Virtual devices), however, their Access Rights are usually set to 00h (unless Title ID indicates a system file; with cartheader[234h].bit4=1).
C and E: These virtual devices are passed ONLY to System Menu (Launcher)... hmmm, or actually, the Launcher doesn't receive ANY device list at all?
G and H: Present only if Title ID indicates DSiware/firmware; with cartheader[234h].bit2=1 (ie. not ROM carts), and only if public/private.sav sizes are nonzero in carthdr[238h/23Ch].
A-H: removed from list if carthdr[1B4h].4=0 (no eMMC access).
I: removed from list if carthdr[1B4h].3=0 (no SD card access).
Some games may adjust the Device List AFTER booting. For example, Flipnote changes the "photo" (F) Access Rights to 04h, and appends an extra device at the end of the list, using a spare drive letter (C):
  'C',09h,06h,00h  'share'    'nand:/shared2/0000'   ;Sound file
Other device names that have been spotted here or there:
  'verdata'   for Version Data NARC file
  'rom'       for executable's NitroROM filesystem
  'otherPub'
  'otherPrv'
Apart from Virtual Devices, there are also some Virtual Filename Placeholders:
  'nand:/<tmpjump>'     --> 'nand:/tmp/jump.app'
  'nand:/<sharedFont>'  --> 'nand:/sys/TWLFontTable.dat'
  'nand:/<verdata>'     --> 'nand:/title/0003000f/484e4c%02x/content/%08x.app'
  'nand:/<banner>'      --> ..... '/data/banner.sav'
  ':<srl>'              --> .....

public & private savedata
If the file is in a folder named "CONTENT", then savedata is stored in a separata "DATA" folder (this is as how Nintendo is doing it officially):
  "nand:/../CONTENT/title.tmd"
  "nand:/../CONTENT/00000002.app"
  "nand:/../DATA/public.sav"
  "nand:/../DATA/private.sav"
If the file is anywhere else (not in a CONTENT folder), then savedata should be stored in the same folder & same name, with extension changed to .pub or .prv (this homebrew convention allows to use more descriptive non-numeric filenames, and doesn't require "title.tmd"):
  "sdmc:/../My Folder Name/Filpnote Studio (EUR.AUS).dsi"
  "sdmc:/../My Folder Name/Filpnote Studio (EUR.AUS).pub"
  "sdmc:/../My Folder Name/Filpnote Studio (EUR.AUS).prv"
As seen above, names can exceed the 8.3 character shortfilename limit (and can use 16bit unicode), however, using such long filenames can quickly exceed the 64 character limit of the DSi's Device List (or it's 8bit character space), as a workaround, unlaunch is converting the above names to 8.3 character format before storing them in the Device List:
  "sdmc:/../MYFOLD~1/FLIPN~12.DSI"
  "sdmc:/../MYFOLD~1/FLIPN~10.PUB"
  "sdmc:/../MYFOLD~1/FLIPNO~2.PRV"
With those short 8-character folder names, one can have up to five folders nested (or only three folders with extension alike "MYFOLD~1.EXT", or more than five folders if folder/filename are shorter than 8 characters).
As shown in the above examples, the longname ("Filpnote Studio (EUR.AUS)") is same for all three files, but the ~NN suffix may vary for shortnames.


DSi SD/MMC Complete List of SD/MMC Files/Folders

DSi eMMC Partition 1 (FAT16)
  SYS          <DIR>    sys
  LOG          <DIR>     log
  PRODUCT  LOG 0000023D   product.log
  SYSMENU  LOG 00004000   sysmenu.log
  SHOP     LOG 00000020   shop.log
  HWINFO_S DAT 00004000  HWINFO_S.dat
  HWINFO_N DAT 00004000  HWINFO_N.dat
  CERT     SYS 00000F40  cert.sys
  HWID     SGN 00000100  HWID.sgn
  TWLFON~1 DAT 000D2C40  TWLFontTable.dat
  DEV      KP  000001BE  dev.kp
  TITLE        <DIR>    title
  00030017     <DIR>     00030017 (aka System Menu)
  484E4150     <DIR>      484e4150 (aka Launcher)
  DATA         <DIR>       data
  PRIVATE  SAV 00004000     private.sav
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000002 APP 0019E400     00000002.app
  00030015     <DIR>     00030015 (aka System Base Tools)
  484E4250     <DIR>      484e4250 (aka System Settings)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000002 APP 00285C00     00000002.app
  484E4650     <DIR>      484e4650 (aka Nintendo DSi Shop)
  DATA         <DIR>       data
  PRIVATE  SAV 00004000     private.sav
  EC       CFG 00000134     ec.cfg
  CONTENT      <DIR>       content
  00000004 APP 00526400     00000004.app
  TITLE    TMD 00000208     title.tmd
  0003000F     <DIR>     0003000f (aka System Data)
  484E4341     <DIR>      484e4341 (aka Wifi Firmware)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000002 APP 00017E60     00000002.app
  484E4841     <DIR>      484e4841 (aka Nintendo DS Cart Whitelist)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000001 APP 0004B1D0     00000001.app
  484E4C50     <DIR>      484e4c50 (aka Version Data)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  00000004 APP 00001B50     00000004.app
  TITLE    TMD 00000208     title.tmd
  00030005     <DIR>     00030005 (aka System Fun Tools)
  484E4441     <DIR>      484e4441 (aka DS Download Play)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000001 APP 00069BC0     00000001.app
  484E4541     <DIR>      484e4541 (aka Pictochat)
  DATA         <DIR>       data
  CONTENT      <DIR>       content
  00000000 APP 00074FC0     00000000.app
  TITLE    TMD 00000208     title.tmd
  484E4950     <DIR>      484e4950 (aka Nintendo DSi Camera)
  DATA         <DIR>       data
  PRIVATE  SAV 00080000     private.sav
  CONTENT      <DIR>       content
  TITLE    TMD 00000208     title.tmd
  00000002 APP 00443C00     00000002.app
  484E4A50     <DIR>      484e4a50 (aka Nintendo Zone)
  DATA         <DIR>       data
  PRIVATE  SAV 00100000     private.sav
  CONTENT      <DIR>       content
  00000003 APP 0014D000     00000003.app
  TITLE    TMD 00000208     title.tmd
  484E4B50     <DIR>      484e4b50 (aka Nintendo DSi Sound)
  DATA         <DIR>       data
  PRIVATE  SAV 00080000     private.sav
  CONTENT      <DIR>       content
  00000002 APP 00451000     00000002.app
  TITLE    TMD 00000208     title.tmd
  00030004     <DIR>     00030004 (aka DSiware)
  484E4750     <DIR>      484e4750 (aka Nintendo DSi Browser)
  DATA         <DIR>       data
  PRIVATE  SAV 00200000     private.sav
  CONTENT      <DIR>       content
  00000001 APP 008F1C00     00000001.app
  TITLE    TMD 00000208     title.tmd
  4B475556     <DIR>      4b475556 (aka Flipnote Studio)
  DATA         <DIR>       data
  PUBLIC   SAV 007F0000     public.sav
  CONTENT      <DIR>       content
  00000000 APP 00348400     00000000.app
  TITLE    TMD 00000208     title.tmd
  TICKET       <DIR>    ticket
  00030017     <DIR>     00030017 (aka System Menu)
  484E4150 TIK 000002C4   484e4150.tik (aka Launcher)
  00030015     <DIR>     00030015 (aka System Base Tools)
  484E4250 TIK 000002C4   484e4250.tik (aka System Settings)
  484E4650 TIK 000002C4   484e4650.tik (aka Nintendo DSi Shop)
  0003000F     <DIR>     0003000f (aka System Data)
  484E4341 TIK 000002C4   484e4341.tik (aka Wifi Firmware)
  484E4841 TIK 000002C4   484e4841.tik (aka Nintendo DS Cart Whitelist)
  484E4C50 TIK 000002C4   484e4c50.tik (aka Version Data)
  00030005     <DIR>     00030005 (aka System Fun Tools)
  484E4441 TIK 000002C4   484e4441.tik (aka DS Download Play)
  484E4541 TIK 000002C4   484e4541.tik (aka Pictochat)
  484E4950 TIK 000002C4   484e4950.tik (aka Nintendo DSi Camera)
  484E4A50 TIK 000002C4   484e4a50.tik (aka Nintendo Zone)
  484E4B50 TIK 000002C4   484e4b50.tik (aka Nintendo DSi Sound)
  00030004     <DIR>     00030004 (aka DSiware)
  484E4750 TIK 000002C4   484e4750.tik (aka Nintendo DSi Browser)
  4B414D56 TIK 000002C4   4b414d56.tik (aka Paper Plane)
  4B443956 TIK 000002C4   4b443956.tik (aka Dr. Mario)
  4B475556 TIK 000002C4   4b475556.tik (aka Flipnote Studio)
  4B4D3958 TIK 000002C4   4b4d3958.tik (aka Magic Made Fun: Deep Psyche)
  SHARED1      <DIR>    shared1
  TWLCFG0  DAT 00004000  TWLCFG0.dat
  TWLCFG1  DAT 00004000  TWLCFG1.dat
  SHARED2      <DIR>    shared2
  LAUNCHER     <DIR>     launcher
  WRAP     BIN 00004000   wrap.bin
  0000         00200000  0000
  IMPORT       <DIR>    import
  TMP          <DIR>    tmp
  ES           <DIR>     es
  WRITE        <DIR>      write
  PROGRESS     <DIR>    progress

DSi eMMC Partition 2 (FAT12)
  PHOTO        <DIR>    photo
  PRIVATE      <DIR>     private
  DS           <DIR>      ds
  APP          <DIR>       app
  484E494A     <DIR>        484E494A (aka Nintendo DSi Camera Stuff)
  PIT      BIN 00001F60      pit.bin
  DCIM         <DIR>     DCIM
  100NIN02     <DIR>      100NIN02
  HNI_0008 JPG 0000AB51    HNI_0008.JPG
  HNI_0009 JPG 00009A96    HNI_0009.JPG
  HNI_0010 JPG 0000932B    HNI_0010.JPG
  HNI_0011 JPG 00009CB8    HNI_0011.JPG
  HNI_0012 JPG 00009CA9    HNI_0012.JPG
  HNI_0013 JPG 00009A3B    HNI_0013.JPG

DSi eMMC Partition 3 (unformatted)
There's a small 3rd partition in MBR, but it's left unformatted (the VBR and FAT and everything is left zero-filled). Unknown if there are any cases where this partition is used, and if so: if it's meant to be encrypted or unencrypted. In case it's meant to be encrypted: Observe that the unformatted partition contains UNENCRYPTED zeroes (so trying to "decrypt" those zeroes would produce random garbage data).

SD Card
DSiware (including Browser and Flipnote) can be exported to SD Card (via System Menu, Data Managment).
Camera Photos and Frames can be exported (via Nintendo DSi Camera, Options, Copy) (Frames are some sort of gaudi-masks that can be used (and created) via one of the Camera special effect features; the mask uses YELLOW as transparent color). As on eMMC storage, all photos from internal camera are mirrored horizontally.
  PRIVATE      <DIR>    private
  DS           <DIR>     ds
  TITLE        <DIR>      title                                     ;\
  484E4750 BIN 9.180K      484E4750.bin (aka Nintendo DSi Browser)  ; dsiware
  4B475556 BIN 11.510K     4B475556.bin (aka Flipnote Studio)       ; games
  HNB_     LST 2K          HNB_.lst     (content: "VUGKPGNH")       ;/
  APP          <DIR>      app
  484E494A     <DIR>       484E494A (aka Nintendo DSi Camera Stuff) ;\
  PIT      BIN 47K          pit.bin                                 ; camera
  DCIM         <DIR>        DCIM                                    ; frames
  100NIN02     <DIR>         100NIN02                               ;
  HNI_0001 JPG 45K            HNI_0001.JPG  ;-frame/mask            ;/
  4B475556     <DIR>       4B475556 (aka Flipnote Studio Stuff)     ;\
  RECENT10 PLS 4K           recent10.pls                            ;
  MARK0    PLS 8K           mark0.pls                               ; flipnote
  MARK1    PLS 8K           mark1.pls                               ; stuff
  MARK2    PLS 8K           mark2.pls                               ;
  MARK3    PLS 8K           mark3.pls                               ;
  001          <DIR>        001                                     ;
  DIRMEMO2 LST 157K         dirmemo2.lst                            ;
  F08243~1 PPM 467K         F08243_0E5E2296197E5_000.ppm            ;/
  DCIM         <DIR>    DCIM
  101NIN02     <DIR>     101NIN02           ;<-- can be 100NIN02 thru 999NIN02
  HNI_0001 JPG 43K        HNI_0001.JPG      ;\dsi camera photos
  HNI_0002 JPG 17K        HNI_0002.JPG      ; (names are numbered differently
  HNI_0003 JPG 39K        HNI_0003.JPG      ;/as on eMMC where they came from)
Reportedly, the "Nintendo DSi Sound" application can also access audio files in AAC format, saved in any folders on SD Card.
Aside from DSi-related files, the SD Card can also contain whatever files from other computers.

Blocks
The System Menu, Data Management feature is referring to filesizes & free space in "Blocks" (aka 128Kbytes units, aka 1Mbit units).


DSi SD/MMC Summary of SD/MMC Files/Folders

File/folder names
The DSi is using weird numeric strings as file/folder names:
  000000vv Title Version (lowercase hex32bit) from tmd[1E4h] as carthdr[1Eh]
  4ggggggg Title ID Gamecode (hex) as carthdr[230h..233h]
  000300tt Title ID Filetype (hex) as carthdr[234h..237h]
  HNI_nnnn Camera photo/frame files (nnnn = 0001..0100 decimal)
  nnnNIN02 Camera photo/frame folders (nnn = 100..999 decimal)
The "000300tt" can be:
  00030000 ROM Cartridges (as so for ROMs, doesn't appear in SD/MMC files)
  00030004 DSiware (browser, flipnote, and games) (if any installed)
  00030005 System Fun Tools (camera, sound, zone, pictochat, ds download play)
  0003000f System Data (non-executable, without carthdr)
  00030015 System Base Tools (system settings, dsi shop, 3ds transfer tool)
  00030017 System Menu (launcher)
The "4ggggggg" can be (last two digits are region(s), or "41" for all regions):
  484e41gg System Menu (Launcher)
  484e42gg System Settings
  484e4341 Wifi Firmware (non-executable datafile) (all regions)
  484e4441 DS Download Play (all regions)
  484e4541 Pictochat (all regions) (no update available)
  484e46gg Nintendo DSi Shop
  484e47gg Nintendo DSi Browser
  484e4841 Nintendo DS Cart Whitelist (non-executable datafile) (all regions)
  484e49gg Nintendo DSi Camera
  484e4agg Nintendo Zone (doesn't exist in Korea)
  484e4bgg Nintendo DSi Sound
  484e4cgg Version Data (non-executable datafile)
  484e4fgg Nintendo 3DS Transfer Tool
  484E494A Nintendo DSi Camera Data (uppercase) ("japan") (aka all regions)
  4b44474a Dokodemo Wii no Ma (japan only)
  4b4755gg Flipnote Studio (doesn't exist in Korea/China)
  42383841 DS Internet settings (a new DSi tool on 3DS consoles)
  4bgggggg DSiware games... (whatever games you have purchased, if any)
These files can be stored in Internal eMMC, or on external SD card, and can be downloaded from Nintendo's server (when buying games, or updating system files).

DSi Internal eMMC
Internal eMMC can contain System files and any purchased DSiware games:
  FAT16:\ticket\000300tt\4ggggggg.tik (encrypted)      ;ticket (708 bytes)
  FAT16:\title\000300tt\4ggggggg\content\title.tmd     ;tmd (520 bytes)
  FAT16:\title\000300tt\4ggggggg\content\000000vv.app  ;executable (decrypted)
  FAT16:\title\000300tt\4ggggggg\data\public.sav       ;size as carthdr[238h]
  FAT16:\title\000300tt\4ggggggg\data\private.sav      ;size as carthdr[23Ch]
  FAT16:\title\000300tt\4ggggggg\data\ec.cfg           ;dsi shop only
  FAT16:\title\000300tt\4ggggggg\data\banner.sav       ;if carthdr[1BFh].bit2=1
Note that some of the above files are containing their own virtual filesystem inside of the eMMC's FAT16 filesystem (NitroROM filesystems in "000000vv.app" files, and FAT12 filesystems in "public.sav" and "private.sav" files).
The System tools (menu, settings, and shop) are also storing further data on FAT16 (outside of the ticket and title folders):
  FAT16:\shared1\TWLCFG0.dat            ;16K
  FAT16:\shared1\TWLCFG1.dat            ;16K
  FAT16:\shared2\launcher\wrap.bin      ;16K
  FAT16:\shared2\0000                   ;2048K (sound recorder)
  FAT16:\sys\log\product.log            ;573 bytes
  FAT16:\sys\log\sysmenu.log            ;16K
  FAT16:\sys\log\shop.log               ;32 bytes
  FAT16:\sys\HWINFO_S.dat               ;16K
  FAT16:\sys\HWINFO_N.dat               ;16K
  FAT16:\sys\cert.sys                   ;3904 bytes (or 2560 bytes)
  FAT16:\sys\HWID.sgn                   ;256 bytes (unknown purpose/content)
  FAT16:\sys\TWLFontTable.dat           ;843.1K (D2C40h bytes) (compressed)
  FAT16:\sys\dev.kp                     ;446 bytes (encrypted)
  FAT16:\import\                        ;empty folder
  FAT16:\progress\                      ;empty folder
  FAT16:\tmp\es\write\                  ;empty folder
The Camera is storing further data on the eMMC FAT12 partition:
  FAT12:\photo\DCIM\100NIN02\HNI_nnnn.JPG                        ;camera photos
  FAT12:\photo\private\ds\app\484E494A\pit.bin                   ;camera info
  FAT12:\photo\private\ds\app\484E494A\DCIM\100NIN02\HNI_nnnn.JPG;camera frames
And, there's a small 3rd eMMC partition in MBR, but it's left unformatted (the VBR and FAT and everything is left zero-filled).

DSi External SD Card
DSiware games (and browser and flipnote) can be copied to SD card (via System Menu, Data Managment) (however, the DSi doesn't seem to allow to execute files on SD card, so they can be used only if they are copied back to the DSi):
  SD:\private\ds\title\4GGGGGGG.bin    ;executable/data in one file (encrypted)
  SD:\private\ds\title\HNB_.lst        ;list of gamecodes
Camera data can be copied to SD card (via Nintendo DSi Camera, Options, Copy):
  SD:\DCIM\nnnNIN02\HNI_nnnn.JPG                            ;camera photos
  SD:\private\ds\app\484E494A\pit.bin                       ;camera info
  SD:\private\ds\app\484E494A\DCIM\nnnNIN02\HNI_nnnn.JPG    ;camera frames
Flipnote "movies" can be also saved on SD card:
  SD:\private\ds\app\4B4755GG\recent10.pls     ;Recently saved path/filenames
  SD:\private\ds\app\4B4755GG\mark0.pls        ;Heart sticker path/filenames
  SD:\private\ds\app\4B4755GG\mark1.pls        ;Crown sticker path/filenames
  SD:\private\ds\app\4B4755GG\mark2.pls        ;Music sticker path/filenames
  SD:\private\ds\app\4B4755GG\mark3.pls        ;Skull sticker path/filenames
  SD:\private\ds\app\4B4755GG\001\dirmemo2.lst ;List of all files in folder
  SD:\private\ds\app\4B4755GG\001\XNNNNN_NNNNNNNNNNNNN_NNN.ppm          ;normal
  SD:\private\ds\app\4B4755GG\YYYYMMDD\NNN\XNNNNN_NNNNNNNNNNNNN_NNN.ppm ;backup
  SD:\private\ds\app\4B4755GG\gif\XNNNNN_NNNNNNNNNNNNN_NNN.gif          ;gif
The Nintendo DSi Sound utility can read .AAC (and .M4A) files from SD card (though it doesn't seem to allow to save your own recordings to SD card?). There appears to be no special folder location, ie. the AAC/M4A files can be anywhere:
  SD:\...\*.aac
  SD:\...\*.m4a

DSi Shop and System Update Download URLs
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/tmd
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/cetk
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/000000vv
The "cetk" file contains the encrypted ticket. The "cetk" file is available only for freeware downloads (eg. system updates). Commercial DSi Shop titles can be downloaded the same way, except that the ticket must be somehow purchased/downloaded separetely.
Nintendo does keep hosting older "00000vv" versions (except, the original version, "00000000" isn't available in all cases; namely if the title was pre-installed on all DSi's then it would be pointless to provide it as update).

NUS Downloader Notation
The homebrew NUS Downloader utility for PCs comes up with its own renaming scheme:
  d:\...\TITLES\000300tt4ggggggg\ddd\000000vv      ;executable (encrypted)
  d:\...\TITLES\000300tt4ggggggg\ddd\000000vv.APP  ;executable (decrypted)
  d:\...\TITLES\000300tt4ggggggg\ddd\CETK          ;cetk (2468 bytes)
  d:\...\TITLES\000300tt4ggggggg\ddd\TMD           ;tmd (520 bytes)
Whereas, "ddd" is same as "000000vv" multiplied by 256 decimal (which is nonsense and redundant). The decrypted ".APP" file is generated only if the "common key" is found in 16-byte file "dsikey.bin".


DSi SD/MMC Images

Filesystem Viewer
no$gba debug version is allowing to view the filesystem tree from encrypted eMMC images (via menubar: Window, Filesystem), the filesystem viewer is also able to export single files from eMMC and SD images (by double-clicking separate files).

Emulation
No$gba emulates read/write-accesses to eMMC images.
Another idea for future would be using files & folders on the PC filesystem instead of a single image file (that might be easier to deal with in some cases, but for the reverse-engineering stage it's better to stick with original authentic images).

Encrypted eMMC Images
no$gba can emulate up to 12 consoles simultaneously, and expects the eMMC images having following filename(s), in no$gba folder:
  DSi-#.mmc             ;eMMC for machine 1..12 (# = 1..C hex)
the eMMC images are encrypted with per-console keys, so decryption won't work without knowing the console ID values. no$gba expects that info to be stored in a 40h-byte Footer at the end of the file:
  00000000h .. Encrypted eMMC image (usually 240Mbyte for DSi)
  0F000000h 16 Footer ID      ("DSi eMMC CID/CPU")
  0F000010h 16 eMMC CID       (dd ss ss ss ss 03 4D 30 30 46 50 41 00 00 15 00)
  0F000020h 8  CPU/Console ID (nn n1 nn nn nn nn xn 08)
  0F000028h 24 Reserved       (zerofilled)
Alternately, the "footer" can be stored in the zerofilled area at eMMC offset 000FF800h..000FF83Fh (using that area, the data can be kept in place even when using other tools; that were getting confused by the data appended at end of file).

SD Card Images
no$gba supports SD Card images in similar fashion as above eMMC images, but without needing any footer since there's encryption on SD cards. The image should contain a pre-formatted MBR and FAT (as real SD cards do).
  DSi-#.sd              ;SD Card for machine 1..12 (# = 1..C hex)
note: no$gba does currently support only 128MB SDSC images (the CID, CSD, OCR, SCR, SSR registers are hardcoded for images with 125698048 byte size), there is a .zip file with an empty pre-formatted SD image in the no$gba package (if you want to use that image: unzip it to the no$gba folder).

Dumping eMMC Images
DSiware exploits like sudokuhax are allowing to access SD/MMC hardware (so one could simply copy all eMMC sectors to a file on SD Card).
Unfortunately, most/other exploits don't have SD/MMC access, so dumping would work only when the eMMC chip to a SD/MMC card reader. For details, see:
AUX DSi SD/MMC Pin-Outs
For obtaining the Console IDs, see:
DSi Console IDs


DSi SD/MMC DSiware Files on Internal eMMC Storage

DSiware games (downloaded from DSi Shop), and pre-installed System Tools are consisting of following files:

FAT16:\title\000300tt\4ggggggg\content\000000vv.app ;executable (decrypted)
Contains the executable, with same header as used in Cartridge ROM images, and usually with a NitroROM File System (ie. a second virtual filesystem inside of the FAT16 filesystem).
DSi Cartridge Header
DS Cartridge NitroROM and NitroARC File Systems
Note: There are also three non-executable ".app" files without cartridge headers (Wifi Firmware, Version Data, and DS Cart Whitelist).

FAT16:\title\000300tt\4ggggggg\data\public.sav ;size as carthdr[238h]
FAT16:\title\000300tt\4ggggggg\data\private.sav ;size as carthdr[23Ch]
These files can contain whatever save data. The .sav files are usually containing a FAT12 with its own VBR, FAT, and Directories (so they use some virtual FAT12 inside of the real FAT16).
When exporting a game to SD Card (via System Settings, Data Managment), then public.sav (eg. used by Flipnote) will be included in the exported image, whilst private.sav (eg. used by DSi Browser) won't be included.

FAT16:\title\000300tt\4ggggggg\data\ec.cfg ;dsi shop only
Whatever extra file, encrypted, 134h bytes, used by DSi Shop only.

FAT16:\title\000300tt\4ggggggg\data\banner.sav ;if carthdr[1BFh].bit2=1
Custom icon, used by some games to indicate the game progress. Format is similar as Icon/Title, but containing only animated icon data (without title). For details, see:
DS Cartridge Icon/Title

FAT16:\title\000300tt\4ggggggg\content\title.tmd ;tmd (520 bytes)
FAT16:\ticket\000300tt\4ggggggg.tik (encrypted) ;ticket (708 bytes)
FAT16:\ticket\000300tt\00000000.tik (encrypted) ;multi-tik? (N*708 bytes?)
These files do contain title metadata (.tmd) and tickets (.tik).
DSi SD/MMC DSiware Tickets and Title metadata
The .tik files are encrypted with ES Block Encryption (using same key X/Y as for dev.kp):
  KEY_X[00h..03h] = 4E00004Ah                           ;\
  KEY_X[04h..07h] = 4A00004Eh                           ; same as for Tad
  KEY_X[08h..0Bh] = Port[4004D00h+4] xor C80C4B72h      ;
  KEY_X[0Ch..0Fh] = Port[4004D00h+0]                    ;/
  KEY_Y[00h..0Fh] = Constant (E5,CC,5A,8B,...)  ;from ARM7BIOS
DSi ES Block Encryption
Caution: There are some ways to modify .tmd files, but that can cause the whole title to be deleted when starting one of the following three tools:
  Data Management (in System Settings), DSi Shop, and 3DS transfer tool
These tools will delete the titles "content" folder (with .app and .tmd files) and the "data" folder (with .sav files). As a workaroung: Set read-only attribute for .tmd and .app files (the deletion aborts once when hitting a read-only file; with the files being processed as ordered in the directory).
Note: Tickets are kept stored in eMMC even after deleting titles (that's allowing to redownload the titles for free; at least that's been the case when the DSi shop was still online).

Below "wrap.bin" and "menusave.dat" files are containing lists of installed titles, however, it isn't neccessary to edit those files when manually installing .tmd/.app/.tik files.

FAT16:\shared2\launcher\wrap.bin (16Kbytes)
Contains a list of installed DSiware Title IDs (in no specific order).
  0000h 14h   SHA1 on entries [014h..03Fh]
  0014h 14h   SHA1 on entries [040h..177h]
  0028h 4     ID ("APWR") (aka 'WRAP' with mis-ordered letters)
  002Ch 4     Size of entries at [040h..177h] (00000138h, aka 39*8)
  0030h 10h   Zerofilled
  0040h 138h  Space for 39 Title IDs (as at cart[230h]) (8x00h=unused entry)
  0178h 3E88h Unknown (looks like random/garbage, or encrypted junk)

FAT16:\title\00030017\484e41gg\data\private.sav:\menusave.dat (System Menu)
This private.sav file contains a 4000h-byte FAT12 image. The FAT12 contains only one file: menusave.dat (154h bytes), containing a list of Title IDs (and their sort-order how they are arranged in System Menu; users can drag the icons to rearrange their ordering):
  0000h 4     ID ("TSSV")
  0004h 4     Zerofilled (used somehow, can be nonzero?)
  0008h 2     CRC16 on [000h..0153h], initial value 5356h, assume [008h]=0000h
  000Ah 6     Zerofilled
  0010h 39x8  Title IDs (gg,gg,gg,gg,tt,00,03,00) (0=NDS CartSlot or Unused)
  0148h 8     Zerofilled
  0150h 4     Index of NDS CartSlot Entry (0..39)
The current selection isn't stored in this file (instead, the Title ID of the most recently selected title is stored in the TWLCFGn.dat files).
Note that the "Nintendo Zone" utility isn't included in this list (even though it's present in title & ticket folders, and listed in wrap.bin).
The System Menu works even if data\private.sav doesn't exist (however, the sort-order is stored only if data\private.sav does exist).


DSi SD/MMC DSiware Files on External SD Card (.bin aka Tad Files)

The DSi can export applications from NAND to SD (via System Settings --> Data Managment). The ".bin" files created on SD are using the "Tad file structure", and alongsides, there's a "HNB_.lst" file containing a list of game codes.

SD:\private\ds\title\HNB_.lst (list of gamecodes) (1208 bytes)
  000h 1200  List of 300 gamecodes, spelled backwards (or zero = unused entry)
  4B0h 1     Language (0=Jap, 1=Eng, 2=Fre, 3=Ger, 4=Ita, 5=Spa, 6=Chi, 7=Kor?)
  4B1h 3     Zero
  4B4h 2     CRC16 on entries [000h..4B3h] (with initial value FFFFh)
  4B6h 2     Zero
For example, "VUGK" in HNB_.lst would indicate gamecode KGUV aka "Flipnote Studio" for EUR/AUS regions. And the corresponding SD Card file would be "SD:\private\ds\title\4B475556.bin" (with the 4-letter gamecode encoded as 8-digit uppercase HEX number). The full 16-digit on eMMC storage would be "00030004\4b475556" (in lowercase, and with the "00030004" implied for the DSiWare folder; files from system folders cannot be exported to SD Card).
The Language byte reflects the System Settings's language selection at time when the HNB_.lst was created or modified (unknown why that info is stored in the file).

SD:\private\ds\title\4GGGGGGG.bin (encrypted executable/data in one file)
  Offset   Size       Key  Description
  000000h  4000h+20h  FIX  Icon/Title
  004020h  B4h+20h    FIX  Header
  0040F4h  440h+20h   FIX  Cert (certificates/hashes)
  004554h  208h+20h   VAR  title.tmd (usually 208h bytes; but could be bigger)
  00477Ch  size+N*20h VAR  000000vv.app
  ...      0          ?    seven N/A parts (unknown if/when they are used)
  ...      size+N*20h FIX  public.sav  (if any)
  ...      ?          ?    banner.sav  (if any)
ES Block Encryption is used to encrypt the header block, cert block, and the 11 content parts. Each are their own seperate ES blocks.
DSi ES Block Encryption
Some of the above blocks use fixed keys (FIX):
  KEY_X[00h..0Fh] = Constant ("Nintendo DS",...)
  KEY_Y[00h..0Fh] = Constant (66,82,32,04,...)  ;from ARM7BIOS
  since above X/Y are constant, that gives a fixed normal key:
  KEY[00h..0Fh]   = Constant (3D,A3,EA,33,...)  ;as used in "dsi srl extract"
Other blocks use variable per-console keys (VAR):
  KEY_X[00h..03h] = 4E00004Ah                           ;\
  KEY_X[04h..07h] = 4A00004Eh                           ; same as for dev.kp
  KEY_X[08h..0Bh] = Port[4004D00h+4] xor C80C4B72h      ;
  KEY_X[0Ch..0Fh] = Port[4004D00h+0]                    ;/
  KEY_Y[00h..0Fh] = Constant (CC,FC,A7,03,...)  ;from ARM7BIOS
Without knowing the console-specifc Port[4004D00h] value, the data could be decrypted only by the DSi console that has originally exported the file to SD card.
However, Nintendo has somehow (maybe accidently) managed to store the Port[4004D00h] value as 16-digit ASCII string in the "TW cert"; which can be decrypted right from the SD card file (as done by the homebrew "dsi srl extract" utility).

Decrypted Icon/Title (at 0000h, size 4000h)
  0000h 23C0h  Icon/Title (usually 23C0h bytes) ;see carthdr[068h,208h]
  23C0h 1C40h  Zerofilled (padding to get 4000h byte size)

Decrypted Header block (at 4020h, size B4h)
  000h  4      Fixed ID "4ANT" (aka TNA4, spelled backwards)
  004h  2      Maker Code, spelled backwards ("10"=Nintendo) ;carthdr[010h]
  006h  1      Zero
  007h  1      Title version (vv)                            ;carthdr[01Eh]
  008h  6      DSi MAC Address, spelled backwards            ;wifi_flash[036h]
  00Eh  2      Zero
  010h  16     Some console ID from HWINFO_N.dat             ;datfile[8Ch..9Bh]
  020h  8      Title ID (gg gg gg gg 04 00 03 00)            ;carthdr[230h]
  028h  4      Size of title.tmd    (usually 208h+20h)
  02Ch  4      Size of 000000vv.app (size+N*20h)             ;carthdr[210h]
  030h  4*7    Size of seven N/A parts (0)
  04Ch  4      Size of public.sav   (size+N*20h)             ;carthdr[238h]
  050h  4      Size of banner.sav?  (usually 0)       ;carthdr[1BFh].bit2=1
  054h  4*8    List of eight Content IDs in same order as title.tmd
  074h  3Eh    Reserved section per tmds, uh? (mostly zero, plus garbage?)
  0B2h  2      Unknown (zero)

Decrypted Cert block (at 40F4h, size 460h)
  000h  20     SHA1 of Icon/Title
  014h  20     SHA1 of TNA4
  028h  20     SHA1 of title.tmd
  03Ch  20     SHA1 of 000000vv.app
  040h  20*7   SHA1 of seven N/A parts (unused, can be whatever garbage)
  0DCh  20     SHA1 of public.sav
  0F0h  20     SHA1 of banner.sav
  104h  3Ch    ECC signature of [000h..103h] with AP cert
  140h  180h   AP cert, signed by TW cert
  2C0h  180h   TW cert, specific to a console (see dev.kp)
More in depth, the above two cert's look as so:
  140h 4    Signature Type (00,01,00,02) (ECC, sect233r1, non-RSA)  ;\
  144h 3Ch  Signature Hex numbers... across... below?               ; AP cert
  180h 40h  Signature padding/alignment (zerofilled)                ; 180h-byte
  1C0h 40h  Signature Name "Root-CA..-MS..-TW..-08..", 00h-padded   ;
            "Root-CA00000001-MS00000008-TWxxxxxxxx-08nnnnnnnnnnn1nn";
  200h 4    Key Type (00,00,00,02)       (ECC, sect233r1, non-RSA)  ;
  204h 40h  Key Name "AP00030015484e42gg", 00h-padded ;sys.settings ;
  244h 4    Key Random/time/type/flags/chksum?   ;<-- ZERO here     ;
  248h 3Ch  Key Public ECC Key (point X,Y) (random/per game?)       ;
  284h 3Ch  Key padding/alignment (zerofilled)                      ;/
  2C0h 4    Signature Type (00,01,00,02) (ECC, sect233r1, non-RSA)  ;\
  2C4h 3Ch  Signature Hex numbers... across... below?               ; TW cert
  300h 40h  Signature padding/alignment (zerofilled)                ; 180h-byte
  340h 40h  Signature Name "Root-CA00000001-MS00000008", 00h-padded ; (same as
  380h 4    Key Type (00,00,00,02)       (ECC, sect233r1, non-RSA)  ; dev.kp,
  384h 40h  Key Name "TWxxxxxxxx-08nnnnnnnnnnn1nn", 00h-padded      ; excluding
  3C4h 4    Key Random/time/type/flags/chksum?                      ; private
  3C8h 3Ch  Key Public ECC Key (point X,Y)                          ; key)
  404h 3Ch  Key padding/alignment (zerofilled)                      ;/

Much like the Wii, the DSi carries with it a private ECC key that it can use to sign things, and a certificate signed by Nintendo that attests to the fact that the public ECC key belongs to a genuine DSi.


DSi SD/MMC DSiware Files from Nintendo's Server

http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/000000vv
The "000000vv" file contains the ".app" file (in encrypted form).
  Server:  "000000vv"      (AES-CBC encrypted, raw)
  eMMC:    "000000vv.app"  (decrypted, raw)
  SD Card: "GGGGGGGG.bin"  (ES-block encrypted, with extra data)
First, the encrypted Title Key must be decrypted (via AES-CBC):
  KEY[00h..0Fh] = Common Key (AF,1B,F5,16,...)        ;from ARM7BIOS
  IV[00h..07h]  = Title ID (00,03,00,tt,gg,gg,gg,gg)  ;from tik/cetk[1DCh]
  IV[08h..0Fh]  = Zerofilled                          ;padding
  Input: Encrypted Title Key                          ;from tik/cetk[1BFh]
  Output: Decrypted Title Key                         ;for use in next step
Then, the actual executable/file can be decrypted (also via AES-CBC):
  KEY[00h..0Fh] = Decrypted Title Key                 ;from above step
  IV[00h..01h]  = Usually Zero (or "Index" from tmd?) ;from tmd[1E8h+N*24h] ?
  IV[02h..0Fh]  = Zerofilled                          ;padding
  Input: Encrypted file "000000vv"                    ;from http download
  Output: Decrypted file "000000vv.app"               ;saved on eMMC
The above decryption steps do require a big-endian AES-CBC software implementation (the DSi hardware supports only little-endian, and it supports only AES-CTR and AES-CCM, and, especially, it supports only the "encrypt" key schedule, whilst AES-CBC would require a different "decrypt" key schedule).

http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/cetk
http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/tmd
http://nus.cdn.t.shop.nintendowifi.net/ccs/download/000300tt4ggggggg/tmd.nn
These files do contain tickets ("cetk"), and title metadata ("tmd" for newest version, plus "tmd.nn" for older versions; with nn=0,1,256,257,512 and the like).
DSi SD/MMC DSiware Tickets and Title metadata
The "cetk" file is available only for free system updates (not for titles sold commercially in DSi Shop).

Downloading
The files can be downloaded with normal web browsers. The homebrew "NUS Downloader" utility is also allowing to download those files (and to decrypt them, provided that the "cetk" is available).
For free system updates, tickets can be downloaded as "cetk" files. For titles sold commercially in DSi ship, tickets must be purchased somehow differently.
For example, the updates for DSi System Settings (EUR) can be downloaded from:
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/00030015484e4250/tmd
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/00030015484e4250/cetk
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/00030015484e4250/00000002
  http://nus.cdn.t.shop.nintendowifi.net/ccs/download/00030015484e4250/00000003
The tmd and cetk files are unencrypted. The 00000002 and 00000003 files are encrypted executables (containing System Settings v2 and v3).

Older Versions
Nintendo is usually keeping older "000000vv" files on their server, so one could still download those older versions.
The oldest/original version would be usually "00000000", however, in case of system files that are pre-installed on all consoles, only later versions are available as updates (ie. starting with "00000001", or for some reason, with "00000002", in case of system settings).
The tmd/cetk files are available only for the newest version (meaning that some cosmetic values like title size & title version are adjusted for the newest version; the cetk's AES-CBC key usually doesn't change for updates, so older versions can be still decrypted with newer cetk's).
Older versions are usually deleted on internal eMMC storage, so only the "000000vv.app" file exists.


DSi SD/MMC DSiware Tickets and Title metadata

Below describes the "raw" ticket+tmd formats. For more info on the data being stored/encrypted in various locations, see these chapters:
DSi SD/MMC DSiware Files on Internal eMMC Storage
DSi SD/MMC DSiware Files on External SD Card (.bin aka Tad Files)
DSi SD/MMC DSiware Files from Nintendo's Server

Ticket (cetk aka .tik)
Tickets exist as "cetk" files (as found on Nintendo's server), and as ".tik" files (as found in nand/ticket folder):
  Server:  "cetk"         unencrypted, 2468 bytes (2A4h+700h), tik+certificate
  eMMC:    "gggggggg.tik" encrypted,   708 bytes  (2A4h+20h),  tik+es_block
  SD Card: N/A            N/A, tickets aren't exported to SD card
Tickets are used for decrypting downloads from DSi shop. They are essentially containing a 16-byte AES-CBC decryption key, plus signatures and some other stuff.
  000h  4    Signature Type (00h,01h,00h,01h) (100h-byte RSA)
  004h  100h Signature RSA-OpenPGP-SHA1 across 140h..2A3h
  104h  3Ch  Signature padding/alignment (zerofilled)
  140h  40h  Signature Name "Root-CA00000001-XS00000006", 00h-padded
  180h  3Ch  ECDH data for one-time installation keys?   ;zero for free tik's
  1BCh  1    Zero (3DS: Ticket Version=1)
  1BDh  1    Zero (3DS: CaCrl Version=0)
  1BEh  1    Zero (3DS: SignerCrl Version=0)
  1BFh  10h  Encrypted AES-CBC Title Key
  1CFh  1    Zero
  1D0h  8    Ticket ID  (00,03,xx,xx,xx,xx,xx,xx) ?
  1D8h  4    Console ID (see dev.kp "TWxxxxxxxx", zero for free system updates)
  1DCh  8    Title ID       (00,03,00,17,"HNAP")                   ;cart[230h]
  1E4h  2    Zero (Wii: mostly FFFFh)
  1E6h  2    Title Version (vv,00) (LITTLE-ENDIAN!?)       ;NEWEST ;cart[01Eh]
  1E8h  4    Zero (Wii: Permitted Titles Mask)
  1ECh  4    Zero (Wii: Permit mask)
  1F0h  1    Zero (Wii: Allow Title Export using PRNG key, 0=No, 1=Yes)
  1F1h  1    Zero (Wii: Common Key Index, 0=Normal, 1=Korea) (DSi: Always 0)
  1F2h  2Ah  Zero
  21Ch  4    Zero (3DS: eShop Account ID?)
  220h  1    Zero
  221h  1    Unknown (01h) (Wii: Unknown, 00h=Non-VC, 01h=VC=VirtualConsole?)
  222h  20h  FFh-filled (Wii: Content access permissions, 1 bit per content)
  242h  20h  00h-filled (Wii: Content access permissions, 1 bit per content)
  262h  2    Zero
  264h  4    Zero   ;Wii: Time Limit Enable  (0=Disable, 1=Enable)
  268h  4    Zero   ;Wii: Time Limit Seconds (uh, seconds since/till when?)
  26Ch  38h  Zero   ;Wii: Seven more Time Limits (Enable, Seconds)
  2A4h  700h Certificates (see below) (only in "cetk", not in ".tik)
The Launcher checks some of the permission entries, but it doesn't check RSA for tickets, so one can create own/dummy tickets. The Console ID and Title ID might be also unchecked, so one could possibly simply copy/rename existing tickets (from the same console), or decrypt/copy/re-encrypt tickets (from other consoles).
Note: It seems to be possible to store multiple tickets in one .tik file (in that case each ticket is separately encrypted in 2A4h+20h bytes).

Title metadata (tmd aka .tmd)
Title metadata exists as "tmd" file (as found on Nintendo's server), and as ".tmd" file (as found in eMMC title folders), and it's also included in ".bin" files (in files exported to SD cards):
  Server:  "tmd"          unencrypted, 2312 bytes (208h+700h), tmd+certificate
  Server:  "tmd.nn"       as above, OLDER tmd versions (nn=0,1,256,257,512,etc)
  eMMC:    "title.tmd"    unencrypted, 520 bytes  (208h+0),    tmd
  SD Card: "GGGGGGGG.bin" encrypted, huge file, contains .app+tmd+sav files
Title metadata contains signatures and other useless stuff. One possibly useful feature is that it allows to define more than one "content" per title, however, that feature appears to be only used on Wii. DSi titles are usually having only one content (the ".app" file).
  000h        4    Signature Type (00h,01h,00h,01h) (100h-byte RSA)
  004h        100h Signature RSA-OpenPGP-SHA1 across 140h..207h
  104h        3Ch  Signature padding/alignment (zerofilled)
  140h        40h  Signature Name "Root-CA00000001-CP00000007", 00h-padded
  180h        1    TMD Version           (00h) (unlike 3DS)
  181h        1    ca_crl_version        (00h)
  182h        1    signer_crl_version    (00h)
  183h        1    Zero       (padding/align 4h)
  184h        8    System Version (0)
  18Ch        8    Title ID       (00,03,00,17,"HNAP")             ;cart[230h]
  194h        4    Title Type     (0)
  198h        2    Group ID       (eg. "01"=Nintendo)              ;cart[010h]
  19Ah        4    SD/MMC "public.sav" filesize in bytes  (0=none) ;cart[238h]
  19Eh        4    SD/MMC "private.sav" filesize in bytes (0=none) ;cart[23Ch]
  1A2h        4    Zero
  1A6h        1    Zero (3DS: SRL Flag)
  1A7h        3    Zero
  1AAh        10h  Parental Control Age Ratings                    ;cart[2F0h]
  1BAh        1Eh  Zerofilled
  1D8h        4    Access rights (0)
  1DCh        2    Title Version (vv,00) (LITTLE-ENDIAN!?) ;NEWEST ;cart[01Eh]
  1DEh        2    Number of contents (at 1E4h and up) (usually 00h,01h)
  1E0h        2    boot content index (0)
  1E2h        2    Zerofilled (padding/align 4h)
  1E4h+N*24h  4    Content ID    (00,00,00,vv) ;lowercase/hex ;"0000000vv.app"
  1E8h+N*24h  2    Content Index (00,00)
  1EAh+N*24h  2    Content Type  (00,01)  ;aka DSi .app
  1ECh+N*24h  8    Content Size  (00,00,00,00,00,19,E4,00) ;NEWEST ;cart[210h]
  1F4h+N*24h  14h  Content SHA1  (on decrypted ".app" file);NEWEST
  208h+..     700h Certificates (see below) (only in "tmd", not in ".tmd)
The Launcher does verify the .tmd's RSA signature, and uses the Title/Content IDs to create the path/filename for the .app file. The Version, Size, SHA1 entries are not verified, so one could use any .tmd version with any .app version (when renaming the .app to match the .tmd's Content ID, but that'd be a messy solution, and it's better to use the correct .tmd per .app).
Note: title.tmd is usually/always 208h bytes (one content), max permitted size is 49E4h (200h contents), a larger filesize can crash the firmware (used by Unlaunch.dsi exploit).

Certificates (at end of "cetk" and "tmd) (not in ".tik" or ".tmd)
  cert cetk tmd  siz  content
  000h 2A4h 208h 4    Signature Type (00h,01h,00h,01h)             ;\
  004h 2A8h 20Ch 100h Signature                                    ;
  104h 3A8h 30Ch 3Ch  Signature padding/alignment (zerofilled)     ;
  140h 3E4h 348h 40h  Signature Name "Root-CA00000001", 00h-padded ; 300h bytes
  180h 424h 388h 4    Key Type (00,00,00,01) (100h-byte RSA)       ;
  184h 428h 38Ch 40h  Key Name "XS00000006", 00h-padded            ;
  1C4h 468h 3CCh 4    Key Random/time/type/flags/chksum?           ;
  1C8h 46Ch 3D0h 100h Key Public RSA Key                           ;
  2C8h 56Ch 4D0h 4    Key Public RSA Exponent? (00,01,00,01)       ;
  2CCh 570h 4D4h 34h  Key padding/alignment (zerofilled)           ;/
  300h 5A4h 508h 4    Signature Type (00h,01h,00h,00h)             ;\
  304h 5A8h 50Ch 200h Signature                                    ;
  504h 7A8h 70Ch 3Ch  Signature padding/alignment (zerofilled)     ;
  540h 7E4h 748h 40h  Signature Name "Root" (padded with 00h)      ; 400h bytes
  580h 824h 788h 4    Key Type (00,00,00,01) (100h-byte RSA)       ;
  584h 828h 78Ch 40h  Key Name "CA00000001", 00h-padded            ;
  5C4h 868h 7CCh 4    Key Random/time/type/flags/chksum?           ;
  5C8h 86Ch 7D0h 100h Key Public RSA Key                           ;
  6C8h 86Ch 8D0h 4    Key Public RSA Exponent? (00,01,00,01)       ;
  6CCh 970h 8D4h 34h  Key padding/alignment (zerofilled)           ;/
Note: Above certificates should be just a 1:1 copy of the entries in cert.sys.
Note: "XS00000006" or "XS00000003" is found in cetk/tik's, in tmd's it's called "CP00000007".

Notes
The Title Version and Content Size/SHA1 entries are reflecting the NEWEST ".app" version (but the AES-CBC key should usually/always also work for older versions).
The homebrew NUS Downloader utility is saving TMD (520 bytes; with REMOVED certificate) and CETK (2468 bytes; with included certificate).


DSi SD/MMC Firmware dev.kp and cert.sys Certificate Files

FAT16:\sys\cert.sys ;3904 bytes (or 2560 bytes before DSi-Shop connection)
Data in this file is same on all retail DSi consoles (even for different regions like US and EUR and KOR).
  000h 300h  Public RSA Key "XS00000006" signed by "Root-CA00000001"
  300h 400h  Public RSA Key "CA00000001" signed by "Root"
  700h 300h  Public RSA Key "CP00000007" signed by "Root-CA00000001"
 Below NOT in Korea? Or NOT when notyet connected to DSi Shop?
  A00h 240h  Public ECC Key "MS00000008" signed by "Root-CA00000001"
  C40h 300h  Public RSA Key "XS00000003" signed by "Root-CA00000001"
The cert.sys for DSi debug version is different:
  000h 300h  Public RSA Key "CP00000005" signed by "Root-CA00000002"
  300h 300h  Public RSA Key "XS00000006" signed by "Root-CA00000002"
  600h 400h  Public RSA Key "CA00000002" signed by "Root"
  A00h 300h  Public RSA Key "CP00000007" signed by "Root-CA00000002"
More detailed, the retail version of cert.sys looks as so:
  000h 4    Signature Type (00,01,00,01) (100h-byte RSA)        ;\
  004h 100h Signature RSA-OpenPGP-SHA1 across 140h..2FFh        ;
  104h 3Ch  Signature padding/alignment (zerofilled)            ;
  140h 40h  Signature Name "Root-CA00000001", 00h-padded        ;
  180h 4    Key Type (00,00,00,01) (100h-byte RSA)              ;
  184h 40h  Key Name "XS00000006", 00h-padded                   ;
  1C4h 4    Key Random/time/type/flags/chksum?                  ;
  1C8h 100h Key Public RSA Key (92,FF,96,40..)                  ;
  2C8h 4    Key Public RSA Exponent? (00,01,00,01)              ;
  2CCh 34h  Key padding/alignment (zerofilled)                  ;/
  300h 4    Signature Type (00,01,00,00) (200h-byte RSA) (!)    ;\
  304h 200h Signature RSA-OpenPGP-SHA1 across 540h..6FFh        ;
  504h 3Ch  Signature padding/alignment (zerofilled)            ;
  540h 40h  Signature Name "Root", 00h-padded                   ;
  580h 4    Key Type (00,00,00,01) (100h-byte RSA)              ;
  584h 40h  Key Name "CA00000001", 00h-padded                   ;
  5C4h 4    Key Random/time/type/flags/chksum?                  ;
  5C8h 100h Key Public RSA Key (B2,79,C9,E2..)                  ;
  6C8h 4    Key Public RSA Exponent? (00,01,00,01)              ;
  6CCh 34h  Key padding/alignment (zerofilled)                  ;/
  700h 4    Signature Type (00,01,00,00) (100h-byte RSA)        ;\
  704h 100h Signature RSA-OpenPGP-SHA1 across 840h..9FFh        ;
  804h 3Ch  Signature padding/alignment (zerofilled)            ;
  840h 40h  Signature Name "Root-CA00000001", 00h-padded        ;
  880h 4    Key Type (00,00,00,01) (100h-byte RSA)              ;
  884h 40h  Key Name "CP00000007", 00h-padded                   ;
  8C4h 4    Key Random/time/type/flags/chksum?                  ;
  8C8h 100h Key Public RSA Key (93,BC,0D,1F..)                  ;
  9C8h 4    Key Public RSA Exponent? (00,01,00,01)              ;
  9CCh 34h  Key padding/alignment (zerofilled)                  ;/
 Below NOT when notyet connected to DSi Shop:
  A00h 4    Signature Type (00,01,00,01) (100h-byte RSA)        ;\
  A04h 100h Signature RSA-OpenPGP-SHA1 across B40h..C3Fh        ;
  B04h 3Ch  Signature padding/alignment (zerofilled)            ;
  B40h 40h  Signature Name "Root-CA00000001", 00h-padded        ;
  B80h 4    Key Type (00,00,00,02)   (ECC, sect233r1, non-RSA)  ;
  B84h 40h  Key Name "MS00000008", 00h-padded                   ;
  BC4h 4    Key Random/time/type/flags/chksum?                  ;
  BC8h 3Ch  Key Public ECC Key (point X,Y) (01,93,6D,08..)      ;
  C04h 3Ch  Key padding/alignment (zerofilled)                  ;/
  C40h 4    Signature Type (00,01,00,01) (100h-byte RSA)        ;\
  C44h 100h Signature RSA-OpenPGP-SHA1 across D80h..F3Fh        ;
  D44h 3Ch  Signature padding/alignment (zerofilled)            ;
  D80h 40h  Signature Name "Root-CA00000001", 00h-padded        ;
  DC0h 4    Key Type (00,00,00,01) (100h-byte RSA)              ;
  DC4h 40h  Key Name "XS00000003", 00h-padded                   ;
  E04h 4    Key Random/time/type/flags/chksum?                  ;
  E08h 100h Key Public RSA Key (AD,07,A9,37..)                  ;
  F08h 4    Key Public RSA Exponent? (00,01,00,01)              ;
  F0Ch 34h  Key padding/alignment (zerofilled)                  ;/
Cert chain for the DSi. Contains certificates with signed keys:
  Root-CA00000001:            used for signing the four certificates below
  Root-CA00000001-CP00000007: used for signing TMDs ("Content Protection"?)
  Root-CA00000001-MS00000008: used for signing per-console ECC keys ("Master"?)
  Root-CA00000001-XS00000003: used for signing tickets from the DSiWare Shop
  Root-CA00000001-XS00000006: used for signing (common) tickets ("access"?)
A similar file with the same name exists on the Wii.

FAT16:\sys\dev.kp ;446 bytes (encrypted), 414 bytes (when decrypted)
The dev.kp file is encrypted with ES Block Encryption (using same key X/Y as for .tik files):
  KEY_X[00h..03h] = 4E00004Ah                           ;\
  KEY_X[04h..07h] = 4A00004Eh                           ; same as for Tad
  KEY_X[08h..0Bh] = Port[4004D00h+4] xor C80C4B72h      ;
  KEY_X[0Ch..0Fh] = Port[4004D00h+0]                    ;/
  KEY_Y[00h..0Fh] = Constant (E5,CC,5A,8B,...)  ;from ARM7BIOS
DSi ES Block Encryption
The decrypted dev.kp contains following entries:
  000h 4    Signature Type (00,01,00,02) (ECC, sect233r1, non-RSA)  ;\
  004h 3Ch  Signature Hex numbers... across... below?               ;
  040h 40h  Signature padding/alignment (zerofilled)                ;
  080h 40h  Signature Name "Root-CA00000001-MS00000008", 00h-padded ;
  0C0h 4    Key Type (00,00,00,02)       (ECC, sect233r1, non-RSA)  ;
  0C4h 40h  Key Name "TWxxxxxxxx-08nnnnnnnnnnn1nn", 00h-padded      ;
  104h 4    Key Random/time/type/flags/chksum?                      ;
  108h 3Ch  Key Public ECC Key (point X,Y)       ;<-- public key    ;
  144h 3Ch  Key padding/alignment (zerofilled)                      ;
  180h 1Eh  Key Private ECC Key                  ;<-- private key   ;/
The "TWxxxxxxxx-08nnnnnnnnnnn1nn" string may vary:
  "TW" might be for DSi only (ie. it might be different on DSi XL or 3DS?)
  "xxxxxxxx" is 8-digit lower-case hex number (unknown where from; for .tik)
  "08nnnnnnnnnnn1nn" is 16-digit lower-case hex number (from Port 4004D00h)
Example:
  Signature across rest of block -- type = 0x00010002, ECC
  0000000: 00 01 00 02 00 db da 21 3b e1 f1 bf bb 4d dc 1d
  0000010: 60 29 da 19 42 1e 66 4f a8 e5 27 a1 d4 ea 46 7d
  0000020: 9b b4 00 95 c5 0d e8 fa ef a7 8d e9 bc 54 da c1
  0000030: 24 94 0b 7c ad a8 61 d5 05 97 c2 64 38 ad 18 f9

  0000040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0000050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0000060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0000070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  Key used to sign this cert (Root-CA00000001-MS00000008)
  0000080: 52 6f 6f 74 2d 43 41 30 30 30 30 30 30 30 31 2d  Root-CA00000001-
  0000090: 4d 53 30 30 30 30 30 30 30 38 00 00 00 00 00 00  MS00000008
  00000a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00000b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  Console ID string
  00000c0: 00 00 00 02 54 57 63 37 39 64 63 65 63 39 2d 30  ....TWc79dcec9-0
  00000d0: 38 61 32 30 32 38 37 30 31 30 38 34 31 31 38 00  8a2028701084118.
  00000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  Public ECC key (30 bytes, starting at 0x108)
  0000100: 00 00 00 00 6f dd de 42 01 e0 34 a3 19 bc a9 af
  0000110: 50 fe 8a ac 75 08 07 a9 3a 2c 21 51 93 ae 4a 90
  0000120: 6e 62 41 f1 a2 fe 00 00 3d 0a 13 97 da 53 17 98
  0000130: 69 38 65 67 ca f4 9c 87 ec 44 b7 eb d0 ec b8 3d
  0000140: 23 cf 7a 35 00 00 00 00 00 00 00 00 00 00 00 00
  0000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  Private per-console ECC key, used for signing files on SD
  0000180: 01 12 9d e0 77 82 44 d3 ee 99 ad ce e5 fa fa ed
  0000190: c9 ab 8e a1 f9 b5 c8 14 3c 74 74 f8 19 3a
Note that the console id itself is burned in an OTP area of the TWL CPU, and changing the contents of this file will not actually change the console id.
This file contains the unique per-console ECC private-public key pair, along with a certificate issued by Nintendo.
This file is created by the DSi Shop, with data from a SOAP reply. The SOAP request data includes the hw console id, and the 0x100-byte RSA signature stored in NAND file "HWID.sgn". Trying to send that request would require a NAND dump, but when you have a NAND dump already sending that request is pointless since you can grab dev.kp from NAND.
Sending that request is pointless anyway since the dev.kp data from the server is random. The returned dev.kp data from the server for the EC private/public keys are random, the ticket consoleID immediately following TW before - in the twcert keyid is random as well. DSi Shop and System Settings don't contain any code for deleting dev.kp. If you try to delete/rename dev.kp manually from NAND a new dev.kp will be generated by the shop, but then the server will return an error since the server account public dev.kp cert won't match.

Data management can't be accessed when dev.kp doesn't exist since you'd have no twcert to sign/verify tads with, like when you never connected the DSi Shop server.


DSi SD/MMC Firmware Certificate/Keys (DER)

.der files (ASN.1)
  DSi Version Data, narc:\NintendoCA-G2.der           (unencrypted)
  DSi Version Data, narc:\.twl-*.der                  (ES Block encrypted)
  DSi Browser, rom:\ca\*.ca                           (unencrypted)
  DSi is-twl-update, *.der (dev unit public keys)     (unencrypted, stringless)
  DSi Dokodemi, rom:key\pubkey.der (only 162 bytes)   (unencrypted, stringless)
  3DS browser applet, RomFS:\browser\rootca.pem       (ASCII BASE64 .der's)
  3DS System Data Archives 1, offline... cave.pem     (ASCII BASE64 .der)
  3DS Shared Data Archives, Non-Nintendo TLS, *.der   (unencrypted)
  3DS System Data Archives 1, ClCertA, RomFS:*.bin    (AES-CBC encrypted)
  3DS Nintendo Zone, RomFS:\certs\*.der               (unencrypted)
  3DS Nintendo Zone, RomFS:\certs\dev.pem             (ASCII BASE64 .der)
  3DS Nintendo Zone, RomFS:\certs\client.key          (ASCII BASE64 .der)
  3DS Miiverse olv applet, RomFS:\browser\cave.pem    (ASCII BASE64 .der)
  3DS Miiverse olv applet, RomFS:\browser\*.p12       (nested der-inside-der?)
For the BASE64 .pem variant, see:
3DS Files - BASE64 Encoding

There are two types of .der files:
Public keys with Certificates (these do usually contain lots of entries with many OIDs and name strings for certificate, company, country, email, etc).
Private keys (these do usually contain only a few entries, often without any OIDs at all, apart from the private key, they do usually also contain the public key & original prime numbers).

 _________________________ Tag,Length,Value Encoding __________________________

The files consist of several Tag-Length-Value (TLV) triplets. All data is in BIG-ENDIAN.

Tag
  bit6-7 class  (0=Universal, 1=Application, 2=Context-defined, 3=Private)
  bit5   form   (0=Primitive, 1=Constructed)
  bit4-0 number (0..1Fh)
Common are:
  BOOLEAN           UNIVERSAL  Primitive    00000001 (01h)
  INTEGER           UNIVERSAL  Primitive    00000010 (02h)
  BIT STRING        UNIVERSAL  Primitive    00000011 (03h)
  OCTET STRING      UNIVERSAL  Primitive    00000100 (04h)
  NULL              UNIVERSAL  Primitive    00000101 (05h)
  OBJECT IDENTIFIER UNIVERSAL  Primitive    00000110 (06h)
  UTF8String        UNIVERSAL  Primitive    00001100 (0Ch)
  PrintableString   UNIVERSAL  Primitive    00010011 (13h)
  TeletexString     UNIVERSAL  Primitive    00010100 (14h)
  IA5String         UNIVERSAL  Primitive    00010110 (16h)
  Time String                                        (17h)  in dsi version data
  BMPString         UNIVERSAL  Primitive    00011110 (1Eh)
  SEQUENCE          UNIVERSAL  Constructed  00110000 (30h)
  SEQUENCE OF       UNIVERSAL  Constructed  00110000 (30h)
  SET               UNIVERSAL  Constructed  00110001 (31h)
  SET OF            UNIVERSAL  Constructed  00110001 (31h)
  -unknown-         CONTEXT    Primitive             (80h) ;3ds miiverse .p12
  -unknown-         CONTEXT    Constructed           (A0h) ;dsi version (small)
  -unknown-         CONTEXT    Constructed           (A3h) ;dsi browser (big)

Length
The length encoding depends on bit7 of the first byte:
  when bit7=0 --> bit6-0 contain length (0..127 bytes)
  when bit7=1 --> bit6-0 contain number of following length bytes
The length does rarely exceed 16bits, the most common lengths are:
  len          = Length 0..127 bytes     (with len<80h)
  81h,len      = Length 128..255 bytes   (with len>7Fh)
  82h,msb,lsb  = Length 256..65535 bytes (with msb:len>00FFh)

 ___________________________________ Tag's ____________________________________

01h,Len,Value - BOOLEAN
Allows to define a boolean flag. Len is always 1, and value must be:
  value[0] = flag (00h=False, or FFh=True)

02h,Len,Value - INTEGER
Allows to define integer, including "large" values like RSA keys. Bit7 of the first byte is treated as sign bit, when storing unsigned values one must insert a leading 00h byte if the high bit is set.
  value[0..(len-1)] = data   ;(len)*8 bits (with sign bit in MSB of 1st byte)

03h,Len,Value - BIT STRING
Allows to define data that isn't a multiple of 8 bits. Or multiples of 8 bits are also working (when first byte is 00h), this sometimes used to store RSA keys as unsigned integers, or, more weirdly, it can also contain further Tag,Len,Value items (eg. SEQUENCE tags with separate RSA key and RSA exponent enclosed in the BIT string) (... somewhat as if the BIT string contains a child .der file?).
  value[0] = number of unused bits in LSB of last byte (0..7)
  value[1..(len-1)] = data   ;(len-1)*8-unused bits

04h,Len,Value - OCTET STRING
Allows to define data that is a multiple of 8 bits. This can contain general purpose stuff, including mixup's of flags, integers, arrays, text strings.
  value[1..(len-1)] = data   ;(len-1)*8 bits

05h,Len - NULL
Allows to define empty/zero data, Len must be 00h, and accordingly, value is 0-byte tall.

06h,Len,Value - OBJECT IDENTIFIER (OID)
OIDs can be used as prefix for other tags (eg. to indicate that the following tag(s) contain a username or email address). The OIDs are usually expressed as a series of decimal numbers separated by dots. In binary form, these are stored as follows:
  value[0] = 2nd+(1st*40)       ;\
  value[1] = 3rd                ; basic encoding for 7bit values
  value[2] = 4th                ;
  etc.                          ;/
There are some special cases: The 1st number must be 0..2. The 2nd number must be 0..39 when 1st=0..1 (there is no such limit when 1st=2).
Values bigger than 7bit are split into two or more 7bit fragments (with bit7=1 in the leading fragments, and bit7=0 in the last fragment), that variable-length encoding is used whenever "2nd+(1st*40)" or "3rd,4th,etc." are exceeding 7bits. For example,
  1.2.3.4.255        --> 2Ah, 03h, 04h, 81h,7Fh
  2.999.1234.1.2.3.4 --> 88h,37h, 89h,52h, 01h, 02h, 03h, 04h
There are millions of OID values (assigned by thousands of organizations), the OID's can be deciphered with online databases, for example,
  http://oidref.com/
However, DER certificates are usually containing only a few standard OID values. See the "OID Values" list below for the OID's found in DSi/3DS certificates.

0Ch,Len,Value - UTF8 String (Unicode byte & multibyte chars)
13h,Len,Value - Printable String (some ASCII A-Z,a-z,0-9,space,'()+,-./:=?)
14h,Len,Value - T61 Teletext String (ITU T.61) (extended 8bit ASCII)
16h,Len,Value - IA5 String (aka ISO 646, full 7bit ASCII with @&{}[] etc.)
17h,Len,Value - Time String (numeric chars "0-9" and timezone suffix)
1Eh,Len,Value - BMP String (aka UTF-16 Unicode) (two-byte chars)
Allows to define things like company/address/country strings, using various extended or restriceted variants of the ASCII character set. The most common type is Printable String (Tag=13h) for basic english, or IA5 String(Tag=16h) for email addresses with "@" characters.
  value[0..(len-1)] = text string
The Time String (Tag=17h) can contain UTC (GMT) time in different variants (without seconds, with seconds, or with seconds+century; and optional seconds fraction; terminated by a "Z" character, or by +/-HHMM timezone info):
  "YYMMDDHHMMZ"           ;\
  "YYMMDDHHMM+HHMM"       ; UTC Time without seconds, and optional timezone
  "YYMMDDHHMM-HHMM"       ;/
  "YYMMDDHHMMSSZ"         ;\
  "YYMMDDHHMMSS+HHMM"     ; UTC Time with seconds, and optional timezone
  "YYMMDDHHMMSS-HHMM"     ;/
  "YYYYMMDDHHMMSSZ"       ;\Generalized Time with seconds and century, and
  "YYYYMMDDHHMMSS.SSSSZ"  ;/optional seconds fraction (no trailing zeroes)

30h,Len,Value - Sequence (or Sequence of)
31h,Len,Value - Set (or Set of)
A0h,Len,Value - Undoc_A0h
A3h,Len,Value - Undoc_A3h
  value[0..(len-1)] = contains further Tag,Length,Data values
XXX

 _________________________________ OID Values _________________________________

  0.9.2342.19200300.100.1.*  /itu-t/data/pss/ucl/pilot/pilotAttributeType/..
  0.9.2342.19200300.100.1.1  ../userid                 ;unused
  0.9.2342.19200300.100.1.25 ../domainComponent        ;unused
  1.2.840.113533.7.65.*  /iso/member-body/us/nortelnetworks/entrust/nsn-ce/..
  1.2.840.113533.7.65.0  ../0                    ;dsi browser equifax_s_ca.ca
  1.2.840.113549.1.1.*   /iso/member-body/us/rsadsi/pkcs/pkcs-1/..
  1.2.840.113549.1.1.1   ../rsaEncryption
  1.2.840.113549.1.1.2   ../rsaEncryptionWithMD2       ;dsi browser rsa.ca
  1.2.840.113549.1.1.3   ../rsaEncryptionWithMD4       ;unused
  1.2.840.113549.1.1.4   ../rsaEncryptionWithMD5       ;dsi browser thawte.ca
  1.2.840.113549.1.1.5   ../rsaEncryptionWithSHA1
  1.2.840.113549.1.1.11  ../rsaEncryptionWithSHA256
  1.2.840.113549.1.1.12  ../rsaEncryptionWithSHA384    ;unused
  1.2.840.113549.1.1.13  ../rsaEncryptionWithSHA512    ;unused
  1.2.840.113549.1.1.14  ../rsaEncryptionWithSHA224    ;unused
  1.2.840.113549.1.7.*   /iso/member-body/us/rsadsi/pkcs/pkcs-7/..
  1.2.840.113549.1.7.1   ../data   ;for nested .der?   ;3ds miiverse olv applet
  1.2.840.113549.1.7.6   ../encryptedData              ;"inside" pkcs-7
  1.2.840.113549.1.9.*   /iso/member-body/us/rsadsi/pkcs/pkcs-9/..
  1.2.840.113549.1.9.1   ../emailAddress
  1.2.840.113549.1.9.21  ../localKeyID                 ;"inside" pkcs-7
  1.2.840.113549.1.12.1.*  /iso/member-body/us/rsadsi/pkcs/pkcs-12/PbeIds/..
  1.2.840.113549.1.12.1.3  ../pbeWithSHAAnd3-KeyTripleDES-CBC ;\inside pkcs-7
  1.2.840.113549.1.12.1.6  ../pbeWithSHAAnd40BitRC2-CBC       ;/
  1.2.840.113549.1.12.10.* /iso/member-body/us/rsadsi/pkcs/pkcs-12/Version1/.
  1.2.840.113549.1.12.10.1.2 ../BagIds/ShroudedKeyBag         ;-inside pkcs-7
  1.3.6.1.4.1.311.*      /iso/org/dod/internet/prv/enterprise/microsoft/..
  1.3.6.1.4.1.311.20.2   ../20/2/?  ;incomplete blurp? ;3ds browser securetrust
  1.3.6.1.4.1.311.21.1   ../21.1    ;unknown blurp?    ;3ds browser securetrust
  1.3.6.1.5.5.7.1.*      /iso/org/dod/internet/security/mechanisms/pkix/pe/..
  1.3.6.1.5.5.7.1.12     ../id-pe-logotype     ;3ds shared data TLS, CA_8.der
  1.3.14.3.2.*           /iso/org/oiw/secsig/algorithms/..
  1.3.14.3.2.26          ../hashAlgorithmIdentifier    ;3ds miiverse olv applet
  2.5.4.*                /joint/ds/attributeType/..
  2.5.4.3                ../commonName
  2.5.4.4                ../surname
  2.5.4.5                ../serialNumber
  2.5.4.6                ../countryName
  2.5.4.7                ../localityName
  2.5.4.8                ../stateOrProvinceName
  2.5.4.9                ../streetAddress
  2.5.4.10               ../organizationName
  2.5.4.11               ../organizationalUnit
  2.5.4.12               ../title
  2.5.4.42               ../givenName
  2.5.29.*               /joint/ds/certificateExtension/..
  2.5.29.14              ../subjectKeyIdentifier
  2.5.29.15              ../keyUsage
  2.5.29.16              ../privateKeyUsagePeriod  ;dsi browser equifax_s_ca.ca
  2.5.29.17              ../subjectAltName             ;3ds browser japnese gov
  2.5.29.18              ../issuerAltName              ;unused
  2.5.29.19              ../basicConstraints
  2.5.29.20              ../cRLNumber                  ;unused
  2.5.29.21              ../reasonCode                 ;unused
  2.5.29.22              ../expirationDate             ;unused
  2.5.29.23              ../instructionCode            ;unused
  2.5.29.24              ../invalidityDate             ;unused
  2.5.29.25              ../cRLDistributionPoints      ;unused
  2.5.29.26              ../issuingDistributionPoint   ;unused
  2.5.29.27              ../deltaCRLIndicator          ;unused
  2.5.29.28              ../issuingDistributionPoint   ;unused
  2.5.29.29              ../certificateIssuer          ;unused
  2.5.29.30              ../nameConstraints            ;unused
  2.5.29.31              ../cRLDistributionPoints
  2.5.29.32              ../certificatePolicies        ;dsi browser swiss_g2.ca
  2.5.29.33              ../policyMappings             ;unused
  2.5.29.34              ../policyConstraints          ;unused
  2.5.29.35              ../authorityKeyIdentifier
  2.5.29.36              ../policyConstraints          ;unused
  2.5.29.37              ../extKeyUsage                ;3ds browser usertrust
  2.16.840.1.113730.1.*  /joint/country/us/organization/netscape/cert-ext/..
  2.16.840.1.113730.1.1  ../cert-type               ;dsi browser tc_c2_ca.ca
  2.16.840.1.113730.1.8  ../ca-policy-url           ;dsi browser tc_c2_ca.ca
  2.16.840.1.113730.1.13 ../comment


DSi SD/MMC Firmware Font File

FAT16:\sys\TWLFontTable.dat ;843.1K (D2C40h bytes) (compressed) (Normal)
FAT16:\sys\TWLFontTable.dat ;568.1K (8E020h bytes) (compressed) (China)
FAT16:\sys\TWLFontTable.dat ;158.9K (27B80h bytes) (compressed) (Korea)
This file contains LZrev-compressed fonts in the NFTR (Nitro font) format.
This is the only real long filename that exceeds the 8.3 limit on the DSi (alternate short name is TWLFON~1.DAT). DSi software is often using a virtual filename "nand:/<sharedFont>" on ARM9 side, which is then replaced by "nand:/sys/TWLFontTable.dat" on ARM7 side.
The font can be used by DSiware titles (DSi ROM cartridges usually don't have eMMC access, and thus cannot use the font).
  0000h       80h  RSA-SHA1 on entries [0080h..009Fh] (23h,8Bh,F9h,08h,...)
  0080h       4    Date? (00h,31h,07h,08h=Normal, 00h,27h,05h,09h=China/Korea)
  0084h       1    Number of NFTR resources (NUM) (3=Normal, 9=China/Korea)
  0085h       1    Zerofilled
  0086h       1    Unknown (0=Normal, 4=China, 5=Korea)
  0087h       5    Zerofilled
  008Ch       14h  SHA1 on below resource headers at [00A0h+(0..NUM*40h-1)]
  00A0h+N*40h 20h  Resource Name in ASCII, padded with 00h
  00C0h+N*40h 4    Compressed Resource Size in .dat file   ;\compressed
  00C4h+N*40h 4    Compressed Resource Start in .dat file  ;/
  00C8h+N*40h 4    Decompressed Resource Size              ;-decompressed
  00CCh+N*40h 14h  SHA1 on Compressed Resource at [Start+0..Size-1]
  ...         ..   Compressed Font Resources (with 16-byte alignment padding)
The resources are containing the same font thrice (at three different sizes), normal consoles have only three resources (0,1,2), chinese/korean consoles have nine resources (six zerofilled 40h-byte entries, and three actually used entries: 3,4,5 for china, or 6,7,8 for korea). The name strings of the resources are:
  "TBF1_l.NFTR"     ;0 Large  16x21 pixels ;\Normal (blurry: 4 colors used)
  "TBF1_m.NFTR"     ;1 Medium 12x16 pixels ; 2bpp, 7365 characters, Unicode
  "TBF1_s.NFTR"     ;2 Small  10x12 pixels ;/
  "TBF1-cn_l.NFTR"  ;3 Large  16x21 pixels ;\China (crisp-clear: 2 colors used)
  "TBF1-cn_m.NFTR"  ;4 Medium 12x16 pixels ; 2bpp, 7848 characters, Unicode
  "TBF1-cn_s.NFTR"  ;5 Small  12x13 pixels ;/
  "TBF1-kr_l.NFTR"  ;6 Large  16x21 pixels ;\Korea (crisp-clear: 2 colors used)
  "TBF1-kr_m.NFTR"  ;7 Medium 12x16 pixels ; 2bpp, 3679 characters, Unicode
  "TBF1-kr_s.NFTR"  ;8 Small  12x12 pixels ;/
All characters have proportional width (as defined in the Character Width chunk), eg. the width of the 16x21 font can be max 16 pixels (plus spacing), but most of the characters are less than 16 pixels wide.
The character numbers in the Char Map chunks are 16bit Unicode, supporting ASCII, plus extra punctuation marks, european letters with accent marks, greek, cyrillic, math symbols, and thousands of japanese letters. There are also some custom nintendo-specific symbols (like buttons and Wii symbols).

Notes
The blurry japanese letters aren't actually legible (especially for the smaller font sizes). Also note that the size of small font varies for the three regions (ie. 10x12, 12x13, or 12x12).

LZrev Compressed Font Resource Format
  ..   uncompressed area (usually 15h bytes)
  ...  compressed area (decompressed backwards)
  ..   footer: padding (to 4-byte boundary)
  3    footer: size of footer+compressed area (offset to compressed.bottom)
  1    footer: size of footer (offset to compressed.top)
  4    footer: extra DEST size (offset to decompressed.top)
  ..   zeropadding to 10h-byte boundary
LZ Decompression Functions
The original decompression function can be found in Flipnote (EUR) at address 20BF8E4h (which is mainly doing error checking, and then calling the actual decompression function at 20BF938h) (Flipnote does also contain several custom fonts, the TWLFontTable.dat file is used only for Flipnote's "Help" function).

Nitro Font Resources
The format of the decompressed data is Nintendo's standard Nitro Font format:
DS Cartridge Nitro Font Resource Format


DS Cartridge Nitro Font Resource Format

Nitro Font Resource File formats (compressed & uncompressed)
Nitro Fonts are often found as .NFTR or .ZFTR files (within NitroROM filesystems). The DSi firmware does additionally contain Nitro Fonts in a .dat file (in the eMMC FAT16 filesystem).
  .NFTR  Raw uncompressed Nitro Font Resource
  .ZFTR  LZ11-compressed Nitro Font Resource
  .dat   Archive with three LZrev-compressed Nitro Font Resources (used on DSi)
The .ZFTR files are containing a 4-byte compression header, followed by the compressed data (starting with the first compression flag byte, following by the first chunk header). For details, see:
LZ Decompression Functions
The DSi's "\sys\TWLFontTable.dat" contains three fonts, using a special LZ compression variant (with the data decompressed backwards, starting at highest memory address). For details, see:
DSi SD/MMC Firmware Font File
Either way, the decompressed fonts are looking as follows:

Nitro Font Resource Header Chunk
  00h 4    Chunk ID "RTFN" (aka NFTR backwards, Nitro Font Resource)
  04h 2    Byte Order    (FEFFh) (indicates that above is to be read backwards)
  06h 2    Version       (0100h..0102h) (usually 0101h or 0102h)
  08h 4    Decompressed Resource Size (000A3278h) (including the NFTR header)
  0Ch 2    Offset to "FNIF" Chunk, aka Size of "RTFN" Chunk (0010h)
  0Eh 2    Total number of following Chunks (0003h+NumCharMaps) (0018h)

Font Info Chunk
  00h      4    Chunk ID "FNIF" (aka FINF backwards, Font Info)
  04h      4    Chunk Size (1Ch or 20h)
  08h      1    Unknown/unused (zero)
  09h xxx  1    Height                       ;or Height+/-1
  0Ah xxx  1    Unknown (usually 00h, or sometimes 1Fh maybe for chr(3Fh)="?")
  0Bh      2    Unknown/unused (zero)
  0Dh xxx  1    Width           ;\or Width+1
  0Eh xxx  1    Width_bis (?)   ;/
  0Fh      1    Encoding (0=UTF8, 1=Unicode, 2=SJIS, 3=CP1252) (usually 1)
  10h      4    Offset to Character Glyph chunk, plus 8
  14h      4    Offset to Character Width chunk, plus 8
  18h      4    Offset to first Character Map chunk, plus 8
  1Ch      (1)  Tile Height                                ;\present only
  1Dh xxx  (1)  Max Width or so +/-?                       ; when above
  1Eh      (1)  Underline location                         ; Chunk Size = 20h
  1Fh      (1)  Unknown/unused (zero)                      ;/(version 0102h)

Character Glyph Chunk (Tile Bitmaps)
  00h      4    Chunk ID "PLGC" (aka CGLP backwards, Character Glyph)
  04h      4    Chunk Size (10h+NumTiles*siz+padding)
  08h      1    Tile Width in pixels
  09h      1    Tile Height in pixels
  0Ah      2    Tile Size in bytes (siz=width*height*bpp+7)/8)
  0Ch      1    Underline location
  0Dh      1    Max proportional Width including left/right spacing
  0Eh      1    Tile Depth (bits per pixel) (usually 1 or 2, sometimes 3)
  0Fh      1    Tile Rotation (0=None/normal, other=see below)
  10h      ...  Tile Bitmaps
  ...      ...  Padding to 4-byte boundary (zerofilled)
All tiles are starting on a byte boundary. However, the separate scanlines aren't necessarily byte-aligned (for example, at 10pix width, a byte may contain rightmost pixels of one line, followed by leftmost pixels of next line).
Bit7 of the first byte of a bitmap is the MSB of the upper-left pixel, bit6..0 are then containing the LSB(s) of the pixel (if bpp>1), followed by the next pixels of the scanline, followed by further scanlines; the data is arranged as straight Width*Height bitmap (without splitting into 8x8 sub-tiles).
Colors are ranging from Zero (transparent/background color) to all bit(s) set (solid/text color).
The meaning of the Tile Rotation entry is unclear (one source claims 0=0', 1=90', 2=270', 3=180', and another source claims 0=0', 2=90', 4=180', 6=270', and for both sources, it's unclear if the rotation is meant to be clockwise or anti-clockwise).

Character Width Chunk
  00h      4    Chunk ID "HDWC" (aka CWDH backwards, Character Width)
  04h      4    Chunk Size (10h+NumTiles*3+padding)
  08h      2    First Tile Number (should be 0000h)
  0Ah      2    Last Tile Number  (should be NumTiles-1)
  0Ch      4    Unknown/unused (zero)
  10h+N*3  1    Left Spacing (to be inserted left of character bitmap)
  11h+N*3  1    Width of Character Bitmap (excluding left/right spacing)
  12h+N*3  1    Total Width of Character (including left/right spacing)
  ...      ...  Padding to 4-byte boundary (zerofilled)
Defines the proportional character width for each tile. Entry [11h+N*3] defines the width of the non-transparent character area (which left-aligned in the Tile Bitmap; any further pixels in the Bitmap are unused/zero). The other two entries define the left/right spacing that is needed to be added to the character.

Character Map(s) - Translation Tables for ASCII/JIS/etc to Tile Numbers?
  00h      4    Chunk ID "PAMC" (aka CMAP backwards, Character Map)
  04h      4    Chunk Size (14h+...+padding)
  08h      2    First Character (eg. 0020h=First ASCII Char)
  0Ah      2    Last Character  (eg. 007Eh=Last ASCII Char)
  0Ch      4    Map Type (0..2, for entry 14h and up, see there)
  10h      4    Offset to next Character Map, plus 8   (0=None, no further)
For Map Type0, Increasing TileNo's assigned to increasing CharNo's:
  14h      2    TileNo for First Char (and increasing for further chars)
  16h      2    Padding to 4-byte boundary (zerofilled)
For Map Type1, Custom TileNo's assigned to increasing CharNo's:
  14h+N*2  2    TileNo's for First..Last Char (FFFFh=None; no tile assigned)
  ...      0/2  Padding to 4-byte boundary (zerofilled)
For Map Type2, Custom TileNo's assigned to custom CharNo's:
  14h      2    Number of following Char=Tile groups...
  16h+N*4  2    Character Number
  18h+N*4  2    Tile Number
  ...      2    Padding to 4-byte boundary (zerofilled)
These chunks are containing tables for translating character numbers (eg. Unicode numbers, or whatever format is selected in the Font Info chunk) to actual Tile Numbers (ie. the way how tiles are ordered in the Glyph and Width chunks).
Font files can contain several Character Map chunks (eg. some Type0 chunks for Char 0020h..007Eh and Char 00A0h..00FFh, plus some Type1 chunks for areas like Char 037Eh..0451h, plus one large Type2 chunk for everything that wasn't defined in the other chunks; the First/Last Character entries are don't care for Type2, they are usually set to First=0000h and Last=FFFFh in that case). Characters that are NOT included in any of the tables should be treated as undefined (as so for any characters that are assigned as Tile=FFFFh in Type1 chunks).
Unicode character numbers are stored as 16bit values. Unknown how other character numbers like UTF8 or SJIS are stored.


LZ Decompression Functions

LZSS, Yaz0, LZ11 - Decompression for BIOS/SWI and ZFTR Font Files
LZSS/Yaz0/LZ11 are very similar formats, with small differences in the header and compression codes, which could be summarized as so:
  10,ss,ss,Ss   ;ID(10h), Size(Ssssss)          ;-LZSS header
  11,ss,ss,Ss   ;ID(11h), Size(Ssssss)          ;-LZ11 header
  "Yaz0",Ss,ss,ss,ss,0,0,0,0,0,0,0,0            ;-Yaz0 header
  Ff            ;Flags(Ff), each 8 entries      ;-Flags (bit7=first)
  1N,nn,nP,pp   ;Disp(Ppp)+1, Len(Nnnn)+111h    ;\
  0N,nP,pp      ;Disp(Ppp)+1, Len(Nn)+11h       ; LZ11, when flag=1
  NP,pp         ;Disp(Ppp)+1, Len(N)+1          ;/
  0P,pp,Nn      ;Disp(Ppp)+1, Len(Nn)+12h       ;\Yaz0, when flag=0
  NP,pp         ;Disp(Ppp)+1, Len(N)+2          ;/
  NP,pp         ;Disp(Ppp)+1, Len(N)+3          ;-LZSS, when flag=1
  Dd            ;Databyte(Dd)                   ;-When flag other than above
Below function can decompress LZSS data (as used by BIOS SWIs), and the LZ11 variant (with 11h in the header; as used by ZFTR font files, but not being compatible with the BIOS SWI functions on neither GBA nor NDS nor DSi).
  if src has "LZ77" or "CMPR" prefix then src=src+4    ;skip prefix (if any)
  typ=byte[src]
  if typ=59h                            ;YAZ0
    errif (bytes[src+0..3]<>"Yaz0") OR (bytes[src+8..15]<>0)
    fin=dst+BigEndian(word[src+04h]), src=src+16
  else                                  ;LZSS/LZ11
    fin=dst+(word[src]/100h), src=src+4
  endif
 @@collect_more:
  flagbits=[src], src=src+1, numflags=8
  if typ=59h then flagbits=flagbits XOR 0FFh    ;-invert for YAZ0
 @@decompress_lop:
  if dst>=fin then goto @@decompress_done
  if numflags=0 then goto @@collect_more
  numflags=numflags-1, flagbits=flagbits*2
  if (flagbits AND 100h)=0 then
    [dst]=[src], dst=dst+1, src=src+1
  else
    if typ=10h        ;LZ10 aka LZSS (BIOS SWI compatible)
      len=3
      len=len+[src]/10h, disp=001h+([src] AND 0Fh)*100h+[src+1], src=src+2
    elseif typ=11h    ;LZ11 (special extended format)
      if [src]/10h>1 then len=001h
      if [src]/10h<1 then len=011h+([src] AND 0Fh)*10h, src=src+1
      if [src]/10h=1 then len=111h+([src] AND 0Fh)*1000h+[src+1]*10h, src=src+2
      len=len+[src]/10h, disp=001h+([src] AND 0Fh)*100h+[src+1], src=src+2
    elseif typ=59h    ;YAZ0 (special extended format)
      len=[src]/10h, disp=001h+([src] AND 0Fh)*100h+[src+1], src=src+2
      if len=0 then len=[src]+12h, src=src+1, else len=len+02h
    endif
    for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  endif
  goto @@decompress_lop
 @@decompress_done:
  ret
The LZSS variant is implemented in GBA/NDS/DSi BIOS SWI functions:
BIOS Decompression Functions
LZSS and LS11 are used with many NDS/DSi/3DS files. LZSS/LZ11 can be detected by checking for 10h/11h in first byte, and additionally checking for:
  Extension is ".lz", ".lz77", ".LZ", or extension is preceeded by "_LZ."
  Less common extensions are ".l", ".lex", ".cmp" (and various others)
  Bytes[5..10] (after header+flags) contain IDs alike "NARC",FFFEh etc.
  File starts with "LZ77",10h or "CMPR",10h (both rather uncommon)
Prefix strings exist in a few LZSS files ("LZ77" in Super Mario 64 DS, or "CMPR" in Nanostray), then followed by normal LZSS data starting with type=10h.
Yaz0 files can be detected by checking for "Yaz0" in first 4 bytes. Yaz0 is used by a few titles only (eg. used by DSi Sound, rom:\texture.szs). Yaz0 is widely believed to use RLE compression (don't ask why).

LZrev - Reverse Decompression
  Used for DSi Font (within TWLFontTable.dat)
  Used for 3DS .code files (within NCCH ExeFS filesystems)
  Used for files with .blz extension (eg. in DSi Flipnote, DSi Paper Plane)
  Used for ALZ1+LZrev double compression with .blz extension (eg. DSi Dr Mario)
This function resembles LZSS, but with src/dst processed in reversed order (starting at highest memory location). Further differences are that the header is replaced by a footer, and, weirdly, data is copied from "disp+3" instead of "disp+1". The decompression is intended to use a single buffer for src/dst (so the source data will be overwritten during decompression) (in order to avoid overwriting still unprocessed data, some bytes near start of file are usually left uncompressed, eg. for the font files, decompression usually ends somewhere at fin=buf+15h rather than at fin=buf+0).
  dest_size=src_size+[src+src_size-4]   ;when dest_size is unknown (for 3DS)
  allocate buf(dest_size), copy "src_size" bytes from file to buf
  src=buf+src_size                      ;origin = pointing after footer
  dst=src+(word[src-4])-1               ;dst = src plus extra len
  fin=src-(word[src-8] AND 00FFFFFFh)   ;fin = src minus compressed_len
  src=src-(byte[src-5])-1               ;src = src minus footer_len
 @@collect_more:
  flagbits=[src], src=src-1, numflags=8
 @@decompress_lop:
  if src<=fin then goto @@decompress_done
  if numflags=0 then goto @@collect_more
  numflags=numflags-1, flagbits=flagbits*2
  if (flagbits AND 100h)=0 then
    [dst]=[src], dst=dst-1, src=src-1
  else
    len=([src]/10h)+3, disp=([src] AND 0Fh)*100h+([src-1])+3, src=src-2
    for i=1 to len, [dst]=[dst+disp], dst=dst-1, next i
  endif
  goto @@decompress_lop
 @@decompress_done:
  ret
Note: The footer_len at [src-5] is usually 08h+0..3 (with 0..3 padding bytes to make the footer entries & file size word aligned).

LZ/Huffman
Apart from the above chubby functions, there are at least two compression schemes trying to implement real serious compression:
GBA Cart e-Reader VPK Decompression
LZ Decompression Functions ASH0
Some titles contain regular .zip files (with Stored and Deflated files):
  DSi Browser (rom:\skin\std_skin.zip) -- corrupted .zip (with 0D,0A appended)
  DSi Shop    (rom:\skin\std_skin.zip) -- intact .zip (unlike above)
  3DS Browser applet (RomFS:\browser\page\..\*.zip)
ZIP Decompression

Others
Arika has brewed up a obscure compression+archive+encryption format:
DS Encrypted Arika Archives with ALZ1 compression
DS Files - Vicarious Vision GFC/GOB Archives with ZLIB compression


LZ Decompression Functions ASH0

ASH0 is used by several games on different consoles (eg. DSi Flipnote, rom:\SampleData.Eu\*.ash).

ash_decompress(source,dest)
  collected[0]=80000000h          ;stream 0 initially empty (endflag in bit31)
  collected[1]=80000000h          ;stream 1 initially empty (endflag in bit31)
  src[0]=source+0                 ;stream 0 start
  for i=0 to 3, id[i]=read_bits(0,8), next i, if id[0..3]<>'ASH0' then error
  dest_end=dest+read_bits(0,32)   ;size of decompressed data
  src[1]=source+read_bits(0,32)   ;stream 1 start
  load_huffman_tree(0,9)          ;load stream 0 tree (9bit len/data values)
  load_huffman_tree(1,11)         ;load stream 1 tree (11bit disp values)
 decompress_loop:
  temp=0, while temp<8000h do temp=tree[0][temp+read_bits(0,1)]
  if temp<8100h then
    [dest]=temp AND FFh, dest=dest+1      ;store one uncompressed data byte
  else
    disp=0, while disp<8000h do disp=tree[1][disp+read_bits(1,1)]
    len=temp+3-8100h, disp=disp+1-8000h
    for j=1 to len, [dest]=[dest-disp], dest=dest+1, next j
  if dest<dest_end then decompress_loop
  ret

read_bits(s,num)
  data=0
  for i=1 to num
   shl collected[s],1    ;move next bit to carry, or set zeroflag if empty
   if zeroflag
    collected[s]=[src[s]]*1000000h+[src[s]+1]*10000h+[src[s]+2]*100h+[src[s]+3]
    src[s]=src[s]+4      ;read data in 32bit units, in reversed byte-order
    carryflag=1          ;endbit
    rcl collected[s],1   ;move bit31 to carry (and endbit to bit0)
   rcl data,1            ;move carry to data
  next i
  ret(data)

load_huffman_tree(s,width)
  stacktop=sp
  tree_index=0
 load_lop:
  if getbits(0,1)=1
   push tree_index+1   ;right (bit0=right)      ;\
   push tree_index     ;left                    ; memorize left/right indices
   tree_index=tree_index+2                      ; and load more
   goto load_lop                                ;/
  dta=getbits(0,width)+8000h           ;get data (bit15=data)
 resolve_lop:
  pop idx                              ;parent index
  tree[s][idx]=dta                     ;store data (or child_index)
  if (idx AND 1)=0 then goto load_lop  ;load more (if it was left node)
  dta=idx-1   ;child_index (to be stored at next parent_index)
  if stacktop<>sp then goto resolve_lop
  ret
Note: The official max tree sizes appear to be:
  tree[0] = about 200h*6 halfwords
  tree[1] = about 800h*6 halfwords


ZIP Decompression

Overall ZIP structure
  Local file headers, with file data
  Central directory, with file headers, and optional signature
  End of central directory record, with optional comment

ZIP Local file header
  000h 4    local file header signature (04034B50h) ("PK",3,4)
  004h 2    version needed to extract (os*256+major*10+minor) (common=14h=v2.0)
  006h 2    general purpose bit flag  (common=0)
  008h 2    compression method (0=stored, 8=deflated, other=rare?)
  00Ah 2    last mod file time
  00Ch 2    last mod file date
  00Eh 4    crc32 of uncompressed file data (zero when size=0)
  012h 4    compressed size
  016h 4    uncompressed size
  01Ah 2    file name length
  01Ch 2    extra field length
  01Eh ..   file name (or "folder/file" name)
  ...  ..   extra field
  ...  ..   compressed file data

ZIP Central directory structure
Central directory entries:
  000h 4    central file header signature (02014B50h) ("PK",1,2)
  004h 2    version made by
  006h 2    version needed to extract
  008h 2    general purpose bit flag
  00Ah 2    compression method (0=stored, 8=deflated, other=rare?)
  00Ch 2    last mod file time
  00Eh 2    last mod file date
  010h 4    crc32 of uncompressed file data
  014h 4    compressed size
  018h 4    uncompressed size
  01Ch 2    file name length
  01Eh 2    extra field length
  020h 2    file comment length
  022h 2    disk number start
  024h 2    internal file attributes
  026h 4    external file attributes
  02Ah 4    offset of local file header (from begin of disk number [022h])
  02Eh ..   file name (or "folder/file" name)
  ...  ..   extra field
  ...  ..   file comment (usually ASCII text, if any)
Central directory signature (optional, after last directory entry)
  000h 4    header signature (05054B50h) ("PK",5,5)
  004h 2    size of data
  006h ..   signature data (variable size, whatever crap)

ZIP End of central directory record
  000h 4    end of central dir signature (06054B50h) ("PK",5,6)
  004h 2    number of this disk (usually 0000h)
  006h 2    number of disk with the start of central directory
  008h 2    total number of entries in the central directory on this disk
  00Ah 2    total number of entries in the central directory
  00Ch 4    size of the central directory
  010h 4    offset of start of central directory, on disk number [006h]
  014h 2    .ZIP file comment length (can be zero even if comment/junk follows)
  016h ..   .ZIP file comment (usually ASCII text, if any)

Official specs
The official ZIP specs can be reportedly found on pkware.com (but it's unknown which browsers are capable of viewing that webpage):
  http://support.pkware.com/home/pkzip/developer-tools/appnote
Alternately, the currently latest specs can be found here:
  http://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT  ;July 2020
That specs include info on rarely used things (including other compression methods, encryption, compressed directory entries, and support for 64bit offset/size values).

Inflate/Deflate
Inflate/Deflate is a common (de-)compression algorithm, used in ZIP files since 1991. And also used by ZLIB, GZIP, PNG. The DSi Browsers GET command includes the string "Accept-Encoding: deflate, gzip, x-gzip, identity", so it's apparently also used for internet transfers. In the PSX world, it's also used by the .CDZ cdrom-image format.
Inflate - Core Functions
Inflate - Initialization & Tree Creation
Inflate - Headers and Checksums
Note: Very old ZIP versions from 1989/1990 did use Shrink and Implode instead of Deflate.


Inflate - Core Functions

tinf_uncompress(dst,src)
 tinf_init()                    ;init constants (needed to be done only once)
 tinf_align_src_to_byte_boundary()
 repeat
  bfinal=tinf_getbit()          ;read final block flag (1 bit)
  btype=tinf_read_bits(2)       ;read block type (2 bits)
  if btype=0 then tinf_inflate_uncompressed_block()
  if btype=1 then tinf_build_fixed_trees(), tinf_inflate_compressed_block()
  if btype=2 then tinf_decode_dynamic_trees(), tinf_inflate_compressed_block()
  if btype=3 then ERROR         ;reserved
 until bfinal=1
 tinf_align_src_to_byte_boundary()
 ret

tinf_inflate_uncompressed_block()
 tinf_align_src_to_byte_boundary()
 len=LittleEndian16bit[src+0]                             ;get len
 if LittleEndian16bit[src+2]<>(len XOR FFFFh) then ERROR  ;verify inverse len
 src=src+4                                                ;skip len values
 for i=0 to len-1, [dst]=[src], dst=dst+1, src=src+1, next i    ;copy block
 ret

tinf_inflate_compressed_block()
 repeat
  sym1=tinf_decode_symbol(tinf_len_tree)
  if sym1<256
   [dst]=sym1, dst=dst+1
  if sym1>256
   len  = tinf_read_bits(length_bits[sym1-257])+length_base[sym1-257]
   sym2 = tinf_decode_symbol(tinf_dist_tree)
   dist = tinf_read_bits(dist_bits[sym2])+dist_base[sym2]
   for i=0 to len-1, [dst]=[dst-dist], dst=dst+1, next i
 until sym1=256
 ret

tinf_decode_symbol(tree)
 sum=0, cur=0, len=0
 repeat                         ;get more bits while code value is above sum
  cur=cur*2 + tinf_getbit()
  len=len+1
  sum=sum+tree.table[len]
  cur=cur-tree.table[len]
 until cur<0
 return tree.trans[sum+cur]

tinf_read_bits(num) ;get N bits from source stream
 val=0
 for i=0 to num-1, val=val+(tinf_getbit() shl i), next i
 return val

tinf_getbit() ;get one bit from source stream
 bit=tag AND 01h, tag=tag/2
 if tag=00h then tag=[src], src=src+1, bit=tag AND 01h, tag=tag/2+80h
 return bit

tinf_align_src_to_byte_boundary()
 tag=01h   ;empty/end-bit (discard any bits, align src to byte-boundary)
 ret


Inflate - Initialization & Tree Creation

tinf_init()
 tinf_build_bits_base(length_bits, length_base, 4, 3)
 length_bits[28]=0, length_base[28]=258
 tinf_build_bits_base(dist_bits, dist_base, 2, 1)
 ret

tinf_build_bits_base(bits,base,delta,base_val)
 for i=0 to 29
  bits[i]=min(0,i-delta)/delta
  base[i]=base_val
  base_val=base_val+(1 shl bits[i])
 ret

tinf_build_fixed_trees()
 for i=0 to 6, tinf_len_tree.table[i]=0, next i       ;[0..6]=0   ;len tree...
 tinf_len_tree.table[7,8,9]=24,152,112                ;[7..9]=24,152,112
 for i=0 to 23,  tinf_len_tree.trans[i+0]  =i+256, next i  ;[0..23]   =256..279
 for i=0 to 143, tinf_len_tree.trans[i+24] =i+0,   next i  ;[24..167] =0..143
 for i=0 to 7,   tinf_len_tree.trans[i+168]=i+280, next i  ;[168..175]=280..287
 for i=0 to 111, tinf_len_tree.trans[i+176]=i+144, next i  ;[176..287]=144..255
 for i=0 to 4, tinf_dist_tree.table[i]=0, next i   ;[0..4]=0,0,0,0,0 ;\dist
 tinf_dist_tree.table[5]=32                        ;[5]=32           ; tree
 for i=0 to 31, tinf_dist_tree.trans[i]=i, next i  ;[0..31]=0..31    ;/
 ret

tinf_decode_dynamic_trees()
 hlit  = tinf_read_bits(5)+257           ;get 5 bits HLIT (257-286)
 hdist = tinf_read_bits(5)+1             ;get 5 bits HDIST (1-32)
 hclen = tinf_read_bits(4)+4             ;get 4 bits HCLEN (4-19)
 for i=0 to 18, lengths[i]=0, next i
 for i=0 to hclen-1                      ;read lengths for code length alphabet
  lengths[clcidx[i]]=tinf_read_bits(3)   ;get 3 bits code length (0-7)
 tinf_build_tree(code_tree, lengths, 19) ;build code length tree
 for num=0 to hlit+hdist-1               ;decode code lengths for dynamic trees
  sym = tinf_decode_symbol(code_tree)
  len=1, val=sym                         ;default (for sym=0..15)
  if sym=16 then len=tinf_read_bits(2)+3, val=lengths[num-1] ;3..6 previous
  if sym=17 then len=tinf_read_bits(3)+3, val=0              ;3..10 zeroes
  if sym=18 then len=tinf_read_bits(7)+11, val=0             ;11..138 zeroes
  for i=1 to len, lengths[num]=val, num=num+1, next i
 tinf_build_tree(tinf_len_tree,  0,      hlit)    ;\build trees
 tinf_build_tree(tinf_dist_tree, 0+hlit, hdist)   ;/
 ret

tinf_build_tree(tree, first, num)
 for i=0 to 15, tree.table[i]=0, next i     ;clear code length count table
 ;scan symbol lengths, and sum code length counts...
 for i=0 to num-1, x=lengths[i+first], tree.table[x]=tree.table[x]+1, next i
 tree.table[0]=0
 sum=0          ;compute offset table for distribution sort
 for i=0 to 15, offs[i]=sum, sum=sum+tree.table[i], next i
 for i=0 to num-1  ;create code to symbol xlat table (symbols sorted by code)
  x=lengths[i+first], if x<>0 then tree.trans[offs[x]]=i, offs[x]=offs[x]+1
 next i
 ret

tinf_data
 clcidx[0..18] = 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15   ;constants

 typedef struct TINF_TREE:
   unsigned short table[16]     ;table of code length counts
   unsigned short trans[288]    ;code to symbol translation table

 TINF_TREE tinf_len_tree   ;length/symbol tree
 TINF_TREE tinf_dist_tree  ;distance tree
 TINF_TREE code_tree       ;temporary tree (for generating the dynamic trees)
 unsigned char lengths[288+32]   ;temporary 288+32 x 8bit ;\for dynamic tree
 unsigned short offs[16]         ;temporary 16 x 16bit    ;/creation

 unsigned char  length_bits[30]
 unsigned short length_base[30]
 unsigned char  dist_bits[30]
 unsigned short dist_base[30]


Inflate - Headers and Checksums

tinf_gzip_uncompress(dst, destLen, src, sourceLen)
 src_start=src, dst_start=dst                 ;memorize start addresses
 if (src[0]<>1fh or src[1]<>8Bh) then ERROR   ;check id bytes
 if (src[2]<>08h) then ERROR                  ;check method is deflate
 flg=src[3]                                   ;get flag byte
 if (flg AND 0E0h) then ERROR                 ;verify reserved bits
 src=src+10                                                 ;skip base header
 if (flg AND 04h) then src=src+2+LittleEndian16bit[src]     ;skip extra data
 if (flg AND 08h) then repeat, src=src+1, until [src-1]=00h ;skip file name
 if (flg AND 10h) then repeat, src=src+1, until [src-1]=00h ;skip file comment
 hcrc=(tinf_crc32(src_start, src-src_start) & 0000ffffh))   ;calc header crc
 if (flg AND 02h) then x=LittleEndian16bit[src], src=src+2  ;get header crc
 if (flg AND 02h) then if x<>hcrc then ERROR                ;verify header
 tinf_uncompress(dst, destLen, src, src_start+sourceLen-src-8)  ;----> inflate
 crc32=LittleEndian32bit[src], src=src+4   ;get crc32 of decompressed data
 dlen=LittleEndian32bit[src], src=src+4    ;get decompressed length
 if (dlen<>destLen) then ERROR                              ;verify dest len
 if (crc32<>tinf_crc32(dst_start,dlen)) then ERROR          ;verify crc32
 ret

tinf_quasijarus_uncompress(dst, destLen, src, sourceLen)
 src_start=src, dst_start=dst                 ;memorize start addresses
 if (src[0]<>1fh or src[1]<>A1h) then ERROR   ;check id bytes
 src=src+2                                    ;skip header
 tinf_uncompress(dst, destLen, src, sourceLen-0Ah)          ;----> inflate
 crc32=LittleEndian32bit[src], src=src+4   ;get crc32 of decompressed data
 dlen=LittleEndian32bit[src], src=src+4    ;get decompressed length
 if (dlen<>destLen) then ERROR                              ;verify dest len
 if (crc32<>tinf_crc32(dst_start,dlen)) then ERROR          ;verify crc32
 ret

tinf_zlib_uncompress(dst, destLen, src, sourceLen)
 src_start=src, dst_start=dst         ;memorize start addresses
 hdr=BigEndian16bit[src], src=src+2   ;get header
 if (hdr MOD 31)<>0 then ERROR        ;check header checksum (modulo)
 if (hdr AND 20h)>0 then ERROR        ;check there is no preset dictionary
 if (hdr AND 0F00h)<>0800h then ERROR ;check method is deflate
 if (had AND 0F000h)>7000h then ERROR ;check window size is valid
 tinf_uncompress(dst, destLen, src, sourceLen-6)      ;------> inflate
 chk=BigEndian32bit[src], src=src+4                   ;get data checksum
 if src-src_start<>sourceLen then ERROR               ;verify src len
 if dst-dst_start<>destLen then ERROR                 ;verify dst len
 if a32<>tinf_adler32(dst_start,destLen)) then ERROR  ;verify data checksum
 ret

tinf_adler32(src, length)
 s1=1, s2=0
 while (length>0)
  k=max(length,5552)    ;max length for avoiding 32bit overflow before mod
  for i=0 to k-1, s1=s1+[src], s2=s2+s1, src=src+1, next i
  s1=s1 mod 65521, s2=s2 mod 65521, length=length-k
 return (s2*10000h+s1)



PNG Bitmaps

Used by DSi Browser (rom:\*.png)

File Header
  000h 8    ID (89h,'PNG',0Dh,0Ah,1Ah,0Ah)
  008h ..   Chunks

Chunk Format
  000h 4    Chunk Size (LEN)                  ;big-endian
  004h 4    Chunk ID (4-letter ASCII) ("A..Z" and "a..z")
  008h LEN  Chunk Data
  ...  4    Chunk CRC32 on [004h+(0..LEN+3)]  ;big-endian
The Chunk ID is 4-letter ASCII, with upper/lowercase having special meanings:
  1st char  Uppercase=Critical (Basic)   Lowercase=Ancillary (Optional extras)
  2nd char  Uppercase=Public (Official)  Lowercase=Private (Custom extensions)
  3rd char  Uppercase=Normal             Lowercase=Reserved
  4th char  Uppercase=Unsafe to copy     Lowercase=Safe to copy
PNG Chunks
  IHDR v1.0  Image header (first chunk)                ;\
  PLTE v1.0  Palette (if any)                          ; Critical chunks
  IDAT v1.0  Image data (can be multiple IDAT chunks!) ; (aka the bitmap data)
  IEND v1.0  Image trailer (last chunk)                ;/
  tRNS v1.0  Transparency                              ;-Transparency
  cHRM v1.0  Primary chromaticities and white point    ;\
  gAMA v1.0  Image gamma                               ;
  iCCP v1.1  Embedded ICC profile                      ; Colour space info
  sBIT v1.0  Significant bits                          ;
  sRGB v1.1  Standard RGB colour space                 ;
  cICP v3rd  Coding-independent code points            ;/
  bKGD v1.0  Background colour                         ;\
  hIST v1.0  Image histogram                           ;
  pHYs v1.0  Physical pixel dimensions                 ; Miscellaneous info
  sPLT v1.1  Suggested palette                         ;
  eXIf v3rd  EXIF chunk (starts with "MM"=byteorder)   ;/
  tEXt v1.0  Textual data                              ;\Textual information
  zTXt v1.0  Compressed textual data                   ; (aka comments)
  iTXt v1.2  International textual data                ;/
  tIME v1.0  Image last-modification time              ;-Time stamp
  acTL v3rd  Animation Control Chunk                   ;\
  fcTL v3rd  Frame Control Chunk                       ; Animation (APNG)
  fdAT v3rd  Frame Data Chunk                          ;/
Note: There are some rules for the chunk ordering, see PNG specs for details.

IHDR Chunk (first chunk)
  000h 4    Chunk Size (always 0Dh)       ;big-endian
  004h 4    Chunk ID   ("IHDR")
  008h 4    Width in pixels  (0=invalid)  ;big-endian
  00Ch 4    Height in pixels (0=invalid)  ;big-endian
  010h 1    Bits per sample  (1,2,4,8,16) (allowed values depend on Color Type)
  011h 1    Color Type       (0,2,3,4,6)
  012h 1    Compression method  (always 0=Zlib-Deflate)
  013h 1    Filter method       (always 0=Adaptive; with subtype per line)
  014h 1    Interlace method    (0=None, 1=Adam7)
  015h 4    Chunk CRC32 on [004h..]       ;big-endian
The valid Color types and bits per sample are:
  Color type             (Samples)  Bits/sample     Bits/pixel
  0=Grayscale            (I)        1,2,4,8,16  --> 1,2,4,8,16
  2=Truecolor            (RGB)      8,16        --> 24,48
  3=Palette indices      (I)        1,2,4,8     --> 1,2,4,8
  4=Grayscale with alpha (IA)       8,16        --> 16,32
  6=Truecolor with alpha (RGBA)     8,16        --> 32,64

PLTE Chunk (required for Color type 3)
  000h 4    Chunk Size (LEN=NumColors*3) (3..300h)            ;big-endian
  004h 4    Chunk ID ("PLTE")
  008h LEN  Palette Data (three bytes per color, ordered R,G,B)
  ...  4    Chunk CRC32 on [004h+(0..LEN+3)]  ;big-endian
Additional Alpha values for each palette entry can be defined in tRNS chunk.

IDAT Chunk(s)
  000h 4    Chunk Size (LEN)                      ;big-endian
  004h 4    Chunk ID ("IDAT")
  008h LEN  Zlib-Deflate compressed image data
  ...  4    Chunk CRC32 on [004h+(0..LEN+3)]  ;big-endian
There may be multiple IDAT chunks; if so, they shall appear consecutively with no other "intervening" chunks. The compressed datastream is then the "concatenation" of the contents of the data fields of all the IDAT chunks.

IEND Chunk (last chunk)
  000h 4    Chunk Size (0)                    ;big-endian
  004h 4    Chunk ID ("IEND")
  008h 4    Chunk CRC32 on [004h..007h] (always AE426082h) ;big-endian

 _________________ Decompression, Unfiltering, Deinterlacing __________________

Overall image decoding flowchart
- merge SDAT chunk(s) into a continous bitstream (remove Chunk Headers/CRCs)
- decompress via Zlib-Inflate
- unfilter
- convert to desired color depth and RGBA bit-order
- deinterlace

Decompression
The merged IDAT chunks contain:
  000h 1   zlib compression method/flags code (usually 78h)
  001h 1   Additional flags/check bits        (usually 9Ch) (or DAh)
  002h ..  Compressed data blocks (deflate)
  ...  4   Adler32 checksum on decompressed data   ;big-endian
ZIP Decompression
"tinf_zlib_uncompress"
All scanlines are padded to 1-byte boundary, and all scanlines include a leading filter bytes. That is, the decompressed size is:
  decompressed_size = ((width*bpp+7)/8+1)*height
For interlaced images, compute the width & height for each pass, then compute the sum of the decompressed_size's.

Unfiltering
Pixels can have 1..64 bpp, but unfiltering is always done in BYTE units.
  for pass=1 to num_passes   ;for 7-pass interlacing
    calc width/height for current pass
    for x=1 to (bpp+7)/8 + (width*bpp+7)/8
      byte[dst]=00h, dst=dst+1            ;-pad topmost for unfiltering
    for y=1 to height
      filter = byte[src], src=src+1
      for x=1 to (bpp+7)/8
        byte[dst]=00h, dst=dst+1          ;-pad leftmost for unfiltering
      for x=1 to (width*bpp+7)/8
        left      = byte[dst-(bpp+7)/8]
        upper     = byte[dst-bytes_per_scanline]
        upperleft = byte[dst-bytes_per_scanline-(bpp+7)/8]
        if filter=0 then byte[dst]=byte[src]
        if filter=1 then byte[dst]=byte[src]+left
        if filter=2 then byte[dst]=byte[src]+upper
        if filter=3 then byte[dst]=byte[src]+(left+upper)/2
        if filter=4 then
          pa=abs(upper-upperleft)
          pb=abs(left-upperleft)
          pc=abs(left+upper-(upperleft*2))
          if pa<=pb AND pa<=pc then byte[dst]=byte[src]+left
          elseif pb<=pc then        byte[dst]=byte[src]+upper
          else                      byte[dst]=byte[src]+upperleft
        if filter>4 then error
        src=src+1, dst=dst+1
      next x