줄바꿈을 LF로 통일

서버에서 바로 빌드하고 고칠 수 있게 저장소 줄바꿈을 LF로 맞췄습니다.
CRLF로 들어가 있던 sh 빌드 스크립트도 이제 리눅스에서 그대로 돌아갑니다.
내용은 바뀌지 않았습니다.
This commit is contained in:
syskiller committed 2026-11-24 07:13:54 +09:00
1 parent 40615838ac
commit 2d48091205
623 files changed
+501372 -501365

No files matched your search

+674 -674
View File
File diff suppressed because it is too large. Load diff
+186 -186
View File
@@ -1,186 +1,186 @@
# TamaEmu for the Tamagotchi Paradise
An emulator for colour Tamagotchis (Epson S1C33) that runs on the Paradise.
The Studio builds it into the ROM together with the user's own firmware.
- `emu.bin`: the emulator program. It is copied to PRAM by the launcher and
runs from there.
- `stub_tpl.bin`: the launcher (hooks on the home screen, A+C held) with
placeholders that the Studio fills in.
- `src/core`: the emulator core, derived from
[tamaemu](https://github.com/maragotchi/tamaemu) by maragotchi (GPL-3.0),
with a JIT translator to Thumb-2 (`tc_jit.c`).
- `src/emu`: the Paradise side (display, keys, sound, flash, saving the state).
- `src/stub/stub.S`: the launcher.
- `src/tools`: Python versions of the ROM patching steps (for tests).
## Layout in the Paradise flash
| Offset | What |
| --- | --- |
| 0x0A0000 | emulator program (64 KB, copied to PRAM on start) |
| 0x0B0000 | launcher and home screen hooks |
| 0x0C0000 | run state (written by the emulator) |
| 0x940000 | guest firmware, packed in 64 KB blocks; blocks the guest writes stay unpacked and hold its save |
| packed cold blocks (1.7.3, menu only) | table (128 u32), per block 65 u32 part starts, LZ4 data in 1 KB parts |
| behind it, up to 0xD40000 | spare pages: a table (4 KB) and 8 KB pages for blocks that are empty in the firmware but written by the guest |
| 0x840000 to 0xD48000 | instead of the two rows above, for firmware that does not fit there (P's, 4U+, 4U); the menu's field saves then have no room |
## Writing the guest flash
The guest erases and programs its flash like the real chip. Parameter sectors
(8 KB) and, since v0.9.2, the 64 KB sectors are kept as 8 KB copies in RAM and
written back to the Paradise flash when the slots run out or the game is
quiet. Erasing a 64 KB sector erases the stored block right away. Blocks that
are empty in the firmware are not stored by the Studio; their written 8 KB
parts go into spare pages behind the packed firmware. The table (magic
"PMXP", checksum) is written after the page, so a power cut leaves either the
old or the new state.
Before v0.9.2 writes to 64 KB sectors were lost. The iD L then hung when it
saved something there, for example buying the mop in the Tamadepa (daily
items), and the long press saved that hung state.
Leaving with a long press does not save the session if the core stopped or
guest writes were lost. Pressing the wheel within the first 3 seconds after a
resumed start drops the saved session.
Settings flags bit 12 (0x1000, version 4 and up, build switch `SESS_FLAG`, 1.7.3 test7): no session. Leaving, the
autosave and an empty battery write only the guest flash (the toy's own save), never the run state; a session found at
the start is dropped and the guest boots from its own save.
## Autostart
With "Start when switched on" the stub decides once per boot, at the first
home screen call. Mailbox word 0x20000FFC survives a restart and the reset
button but not the Paradise's deep sleep: "PMXL" (written by the emulator when
going back) keeps the Paradise, "PMXR" (written by the stub) means a restart
while running, so the emulator starts. Without either, the seconds counter
0x45000304 tells power-on (counter new) from waking up (counter ran). The
"decided" flag is the UsageFault priority byte, which every reset clears.
## Clock
Each millisecond of the Paradise runs the guest for one millisecond of its
current clock. Since v0.9.3 the remainder of that division is carried over
(at 32768 Hz the guest used to get 32 instead of 32.768 cycles per ms, its
clock lost 2.3 percent). About once a second the emulator also compares the
guest time with the seconds counter of the Paradise (0x45000304) and adds
whole seconds to the guest clock when it fell behind, for example when busy
scenes (shopping, flash writes) made the emulator drop time. Implausible jumps
of the counter are ignored.
At the start (settings version 4, flag bit 1, set by the Studio's "Take the
clock from the Paradise at the start"): the emulator reads the Paradise's own
time from the SRAM before it overwrites it (`paraclock.h`: the base of days and
seconds next to the six display fields, checked against the seconds counter)
and sets the guest's RTC registers to it, after a resumed session and on a
fresh start. Nothing is caught up. Without the flag, or when the time is not
found, a resumed session moves the clock on by the pause as before.
## Download content (8 MB firmware)
Stores and routing follow tamaemu `tools/dlc.c`: a record is a TAMAGO block,
routed by type (0x4E), category (0x50) and flag (0x51) into one of nine stores
(meals, snacks, clothing, accessories, items, daily items, wallpapers, games,
destinations). A new record goes into the first erased slot.
## Build
```
sh src/emu/build.sh # clang, ld.lld, llvm-objcopy -> src/emu/emu.bin
```
Copy `src/emu/emu.bin` to `emu/emu.bin` (the Studio embeds that one). With `EMU_OVL` (on since 1.6.13 test10) the
build links with `link_ovl.ld`: the settings menus and the save code sit at the end of the image, in the translator's
room, and are copied back from the flash when they are needed.
Device simulation (Unicorn, private ROMs only): `node test/mkimg.js <paradise.bin> <firmware> emu.bin out.bin`, then
`python3 test/devemu.py src/emu/emu.elf out.bin <ms>` with `KEYS`, `SHOTS`, `OUT`, `LAGLOG`, `PROF`, `ROMHIST`.
Launcher template (link address 0x1009F000):
```
clang --target=thumbv7m-none-eabi -mcpu=cortex-m3 -x assembler-with-cpp -c src/stub/stub.S -o stub.o \
-DHOOKS=1 -DLIMIT=90 -DAPP_SRC=0x1234ABCD -DORIG0=0x22222221 -DORIG1=0x33333331 -DORIG2=0x44444441 -DORIG3=0x55555551
ld.lld --no-rosegment -Ttext=0x1009F000 -e start stub.o -o stub.elf
llvm-objcopy -O binary stub.elf stub_tpl.bin
```
Both results are byte-identical to the files shipped here.
With `-DFELD=1` (menu launcher) the stub has a second entry at +0x0C
(`start_src`, 1.6.0): it copies the 64 KB image at the XIP address in r0 to
PRAM and restarts, like `start` does with its own program. The menu starts
further programs through it. Since 1.6.6 it reads from the uncached flash
(r0 + 0x50011000): the cached window shows only 1 MB. Build the menu launcher
with the same line plus `-DFELD=1 -DFELD_SRC=0x6789EF01 -DAUTO=0x66666661`.
Since 1.6.8 the menu launcher also has the entry `launch` at +0x20 (start the
menu), keeps the menu address at +0x28 and has at +0x2C the entry for the start
device's trampolines (menu once the Paradise has a save, otherwise the original
handler in r12).
License: GNU GPL version 3 (see `LICENSE`).
## Code that overwrites itself
The translator throws away all translated code when the guest writes to an
a0ram page that holds translated code. Since v0.9.6 a page that causes this 8
times within about 0.1 s of guest time is run by the interpreter only, for
about 5 s, then it gets another chance. Before, Connect to a Plus Color on the
iD L (code at 0xC00 next to its data) caused thousands of flushes per second
and the emulator stood still on the device. Build switch `JIT_WHOT`.
## 4U NFC chip and the clock (1.6.8)
The 4U and 4U+ firmware polls its PN512 NFC chip over the IR UART all the time (about 4000 bytes per
second to 0x300B10). The Paradise has no such chip, so every poll ran into a timeout and the menus needed
two presses. `tc_periph.c` now answers like an idle PN512 (register writes acknowledged, commands done at
once, empty FIFO). On for device kinds 3 and 4; PMXC flags bit 2 switches it off (Studio: "4U: emulate the
NFC chip").
The guest's real-time clock counted in guest cycles. When the guest changed its clock (fast clock to
32768 Hz, for example the iD L when its display goes off) the part of a second already counted at the fast
clock counted as many seconds at the slow one: the clock jumped by minutes. With `RTC_MS` (build.sh) the
seconds and the 1 s / 1 min / 1 h interrupts follow the real milliseconds of the main loop
(`periph_rtc_ms`); only the 1/64 s interrupt stays in cycles. `clock_sync` keeps the comparison with the
Paradise's crystal: missing seconds are added, a guest clock ahead skips one ms in 16.
## Pictures and the Paradise's clock from the menu (1.6.8)
`LCD_QUIET`: the screen is updated only when the guest has written nothing to its LCD for 2 ms (at most every
40 ms, at the latest after 120 ms), so a picture is never shown half drawn.
The Paramix menu uses the Paradise's SRAM, where the Paradise keeps its clock. It looks the clock up at its own
start and leaves it in the mailbox at 0x20000FC0 (`paraclock.h`: `para_mailbox_put`, `para_mailbox`); a
program started from the menu takes it from there when its own search finds nothing.
- 1.6.8-test5 APP_SELF: the start check (pram_check: PRAM against the image in the flash) uses the program's own image. A further
TamaEmu of the menu has it right behind its guest area (spare_end, the settings there name the same guest and save); before, it
compared with 0x0A0000 and copied the main TamaEmu's settings over its own. Its own settings block is never replaced.
- 1.6.8-test5 BL_GUEST_PWM: the colour Tamas light their screen with T16 channel 2 (0x300796 bit 0, clock 0x3007E4 bit 3). The P's
sends Sleep Out every 20 minutes for about 9 s without starting it (PC test: 36 times in a night); the backlight now goes on only
with the guest's light, a key or a tone in the last second, and stays on while the LCD stays on.
## Infrared between two Paradise (TC_IRLINK, 1.6.9)
P's and iD L: the bytes the toy writes to its infrared UART (0x300B10, also SIO_TX 0x301704) go out as 'E' frames
over the UART on the contacts (`src/emu/plink.h`, 460800 8N1). Received bytes come in at the toy's byte rate
(divisor at 0x300B16/17, 576 kHz clock, 10 bits per byte) with the RX interrupt, only while the receiver is armed
(0x300B15); the P's also only in a session (its byte 0xDB3, as tamaemu's ir_mode_flag), otherwise the byte is
lost and the peer-detect flag (0x300287 bit 3) rises. TX ready (0x300B12 bit 1) and the TX interrupt follow the byte
time. All as in tamaemu's periph.c (Android TamaEmu), the bytes from the platform instead of link.c (no time stamps:
the devices pass them on at once). State outside `Emu`, so saved sessions stay valid. Not for the Plus Color (its
infrared is a GPIO) and the 4U/4U+ (their UART talks to the NFC chip).
Checked on the PC with two P's cores in lockstep (host harness): あそぶ, one あそびにいく, the other ともだちをよぶ,
ふたりで, かくれんぼ: both play, the guest goes home, the host gets Gotchi points. With 15 ms delay each way it still
works, with 30 ms it ends in つうしん しっぱい.
Room: `boot()` (everything before the translator starts) runs from `.initcode`, the translator's area later, and a
few rarely used functions are built small (minsize). The translator area is 11772 bytes (before: 11608).
Key with the screen dark (1.7.3 test7, switch EMU_KEY_AWAKE): a key woke the chip from deep sleep and reached the
guest, but once it was let go the program slept again before the guest had switched its screen on; the guest's
wake-up then waited for the next RTC second. Now the chip stays awake for 2 s after a key (g_btn_ms). devemu.py, iD L
dark at 200 s, key 150 ms in the middle of an RTC second: picture 663 ms after the key before.
# TamaEmu for the Tamagotchi Paradise
An emulator for colour Tamagotchis (Epson S1C33) that runs on the Paradise.
The Studio builds it into the ROM together with the user's own firmware.
- `emu.bin`: the emulator program. It is copied to PRAM by the launcher and
runs from there.
- `stub_tpl.bin`: the launcher (hooks on the home screen, A+C held) with
placeholders that the Studio fills in.
- `src/core`: the emulator core, derived from
[tamaemu](https://github.com/maragotchi/tamaemu) by maragotchi (GPL-3.0),
with a JIT translator to Thumb-2 (`tc_jit.c`).
- `src/emu`: the Paradise side (display, keys, sound, flash, saving the state).
- `src/stub/stub.S`: the launcher.
- `src/tools`: Python versions of the ROM patching steps (for tests).
## Layout in the Paradise flash
| Offset | What |
| --- | --- |
| 0x0A0000 | emulator program (64 KB, copied to PRAM on start) |
| 0x0B0000 | launcher and home screen hooks |
| 0x0C0000 | run state (written by the emulator) |
| 0x940000 | guest firmware, packed in 64 KB blocks; blocks the guest writes stay unpacked and hold its save |
| packed cold blocks (1.7.3, menu only) | table (128 u32), per block 65 u32 part starts, LZ4 data in 1 KB parts |
| behind it, up to 0xD40000 | spare pages: a table (4 KB) and 8 KB pages for blocks that are empty in the firmware but written by the guest |
| 0x840000 to 0xD48000 | instead of the two rows above, for firmware that does not fit there (P's, 4U+, 4U); the menu's field saves then have no room |
## Writing the guest flash
The guest erases and programs its flash like the real chip. Parameter sectors
(8 KB) and, since v0.9.2, the 64 KB sectors are kept as 8 KB copies in RAM and
written back to the Paradise flash when the slots run out or the game is
quiet. Erasing a 64 KB sector erases the stored block right away. Blocks that
are empty in the firmware are not stored by the Studio; their written 8 KB
parts go into spare pages behind the packed firmware. The table (magic
"PMXP", checksum) is written after the page, so a power cut leaves either the
old or the new state.
Before v0.9.2 writes to 64 KB sectors were lost. The iD L then hung when it
saved something there, for example buying the mop in the Tamadepa (daily
items), and the long press saved that hung state.
Leaving with a long press does not save the session if the core stopped or
guest writes were lost. Pressing the wheel within the first 3 seconds after a
resumed start drops the saved session.
Settings flags bit 12 (0x1000, version 4 and up, build switch `SESS_FLAG`, 1.7.3 test7): no session. Leaving, the
autosave and an empty battery write only the guest flash (the toy's own save), never the run state; a session found at
the start is dropped and the guest boots from its own save.
## Autostart
With "Start when switched on" the stub decides once per boot, at the first
home screen call. Mailbox word 0x20000FFC survives a restart and the reset
button but not the Paradise's deep sleep: "PMXL" (written by the emulator when
going back) keeps the Paradise, "PMXR" (written by the stub) means a restart
while running, so the emulator starts. Without either, the seconds counter
0x45000304 tells power-on (counter new) from waking up (counter ran). The
"decided" flag is the UsageFault priority byte, which every reset clears.
## Clock
Each millisecond of the Paradise runs the guest for one millisecond of its
current clock. Since v0.9.3 the remainder of that division is carried over
(at 32768 Hz the guest used to get 32 instead of 32.768 cycles per ms, its
clock lost 2.3 percent). About once a second the emulator also compares the
guest time with the seconds counter of the Paradise (0x45000304) and adds
whole seconds to the guest clock when it fell behind, for example when busy
scenes (shopping, flash writes) made the emulator drop time. Implausible jumps
of the counter are ignored.
At the start (settings version 4, flag bit 1, set by the Studio's "Take the
clock from the Paradise at the start"): the emulator reads the Paradise's own
time from the SRAM before it overwrites it (`paraclock.h`: the base of days and
seconds next to the six display fields, checked against the seconds counter)
and sets the guest's RTC registers to it, after a resumed session and on a
fresh start. Nothing is caught up. Without the flag, or when the time is not
found, a resumed session moves the clock on by the pause as before.
## Download content (8 MB firmware)
Stores and routing follow tamaemu `tools/dlc.c`: a record is a TAMAGO block,
routed by type (0x4E), category (0x50) and flag (0x51) into one of nine stores
(meals, snacks, clothing, accessories, items, daily items, wallpapers, games,
destinations). A new record goes into the first erased slot.
## Build
```
sh src/emu/build.sh # clang, ld.lld, llvm-objcopy -> src/emu/emu.bin
```
Copy `src/emu/emu.bin` to `emu/emu.bin` (the Studio embeds that one). With `EMU_OVL` (on since 1.6.13 test10) the
build links with `link_ovl.ld`: the settings menus and the save code sit at the end of the image, in the translator's
room, and are copied back from the flash when they are needed.
Device simulation (Unicorn, private ROMs only): `node test/mkimg.js <paradise.bin> <firmware> emu.bin out.bin`, then
`python3 test/devemu.py src/emu/emu.elf out.bin <ms>` with `KEYS`, `SHOTS`, `OUT`, `LAGLOG`, `PROF`, `ROMHIST`.
Launcher template (link address 0x1009F000):
```
clang --target=thumbv7m-none-eabi -mcpu=cortex-m3 -x assembler-with-cpp -c src/stub/stub.S -o stub.o \
-DHOOKS=1 -DLIMIT=90 -DAPP_SRC=0x1234ABCD -DORIG0=0x22222221 -DORIG1=0x33333331 -DORIG2=0x44444441 -DORIG3=0x55555551
ld.lld --no-rosegment -Ttext=0x1009F000 -e start stub.o -o stub.elf
llvm-objcopy -O binary stub.elf stub_tpl.bin
```
Both results are byte-identical to the files shipped here.
With `-DFELD=1` (menu launcher) the stub has a second entry at +0x0C
(`start_src`, 1.6.0): it copies the 64 KB image at the XIP address in r0 to
PRAM and restarts, like `start` does with its own program. The menu starts
further programs through it. Since 1.6.6 it reads from the uncached flash
(r0 + 0x50011000): the cached window shows only 1 MB. Build the menu launcher
with the same line plus `-DFELD=1 -DFELD_SRC=0x6789EF01 -DAUTO=0x66666661`.
Since 1.6.8 the menu launcher also has the entry `launch` at +0x20 (start the
menu), keeps the menu address at +0x28 and has at +0x2C the entry for the start
device's trampolines (menu once the Paradise has a save, otherwise the original
handler in r12).
License: GNU GPL version 3 (see `LICENSE`).
## Code that overwrites itself
The translator throws away all translated code when the guest writes to an
a0ram page that holds translated code. Since v0.9.6 a page that causes this 8
times within about 0.1 s of guest time is run by the interpreter only, for
about 5 s, then it gets another chance. Before, Connect to a Plus Color on the
iD L (code at 0xC00 next to its data) caused thousands of flushes per second
and the emulator stood still on the device. Build switch `JIT_WHOT`.
## 4U NFC chip and the clock (1.6.8)
The 4U and 4U+ firmware polls its PN512 NFC chip over the IR UART all the time (about 4000 bytes per
second to 0x300B10). The Paradise has no such chip, so every poll ran into a timeout and the menus needed
two presses. `tc_periph.c` now answers like an idle PN512 (register writes acknowledged, commands done at
once, empty FIFO). On for device kinds 3 and 4; PMXC flags bit 2 switches it off (Studio: "4U: emulate the
NFC chip").
The guest's real-time clock counted in guest cycles. When the guest changed its clock (fast clock to
32768 Hz, for example the iD L when its display goes off) the part of a second already counted at the fast
clock counted as many seconds at the slow one: the clock jumped by minutes. With `RTC_MS` (build.sh) the
seconds and the 1 s / 1 min / 1 h interrupts follow the real milliseconds of the main loop
(`periph_rtc_ms`); only the 1/64 s interrupt stays in cycles. `clock_sync` keeps the comparison with the
Paradise's crystal: missing seconds are added, a guest clock ahead skips one ms in 16.
## Pictures and the Paradise's clock from the menu (1.6.8)
`LCD_QUIET`: the screen is updated only when the guest has written nothing to its LCD for 2 ms (at most every
40 ms, at the latest after 120 ms), so a picture is never shown half drawn.
The Paramix menu uses the Paradise's SRAM, where the Paradise keeps its clock. It looks the clock up at its own
start and leaves it in the mailbox at 0x20000FC0 (`paraclock.h`: `para_mailbox_put`, `para_mailbox`); a
program started from the menu takes it from there when its own search finds nothing.
- 1.6.8-test5 APP_SELF: the start check (pram_check: PRAM against the image in the flash) uses the program's own image. A further
TamaEmu of the menu has it right behind its guest area (spare_end, the settings there name the same guest and save); before, it
compared with 0x0A0000 and copied the main TamaEmu's settings over its own. Its own settings block is never replaced.
- 1.6.8-test5 BL_GUEST_PWM: the colour Tamas light their screen with T16 channel 2 (0x300796 bit 0, clock 0x3007E4 bit 3). The P's
sends Sleep Out every 20 minutes for about 9 s without starting it (PC test: 36 times in a night); the backlight now goes on only
with the guest's light, a key or a tone in the last second, and stays on while the LCD stays on.
## Infrared between two Paradise (TC_IRLINK, 1.6.9)
P's and iD L: the bytes the toy writes to its infrared UART (0x300B10, also SIO_TX 0x301704) go out as 'E' frames
over the UART on the contacts (`src/emu/plink.h`, 460800 8N1). Received bytes come in at the toy's byte rate
(divisor at 0x300B16/17, 576 kHz clock, 10 bits per byte) with the RX interrupt, only while the receiver is armed
(0x300B15); the P's also only in a session (its byte 0xDB3, as tamaemu's ir_mode_flag), otherwise the byte is
lost and the peer-detect flag (0x300287 bit 3) rises. TX ready (0x300B12 bit 1) and the TX interrupt follow the byte
time. All as in tamaemu's periph.c (Android TamaEmu), the bytes from the platform instead of link.c (no time stamps:
the devices pass them on at once). State outside `Emu`, so saved sessions stay valid. Not for the Plus Color (its
infrared is a GPIO) and the 4U/4U+ (their UART talks to the NFC chip).
Checked on the PC with two P's cores in lockstep (host harness): あそぶ, one あそびにいく, the other ともだちをよぶ,
ふたりで, かくれんぼ: both play, the guest goes home, the host gets Gotchi points. With 15 ms delay each way it still
works, with 30 ms it ends in つうしん しっぱい.
Room: `boot()` (everything before the translator starts) runs from `.initcode`, the translator's area later, and a
few rarely used functions are built small (minsize). The translator area is 11772 bytes (before: 11608).
Key with the screen dark (1.7.3 test7, switch EMU_KEY_AWAKE): a key woke the chip from deep sleep and reached the
guest, but once it was let go the program slept again before the guest had switched its screen on; the guest's
wake-up then waited for the next RTC second. Now the chip stays awake for 2 s after a key (g_btn_ms). devemu.py, iD L
dark at 200 s, key 150 ms in the middle of an RTC second: picture 663 ms after the key before.
File diff suppressed because it is too large. Load diff
+232 -232
View File
@@ -1,232 +1,232 @@
/* Lean core for colour Tamagotchis (S1C33), derived from tamaemu
* (github.com/maragotchi/tamaemu, GPL-3.0). For Paradise apps without an
* operating system: no stdio, no floating point, fixed memory blocks. */
#ifndef TC_H
#define TC_H
#include <stdint.h>
#include <stdbool.h>
/* Only needed at startup: placed at the end of the image, the translator takes the space afterwards */
#if defined(__arm__) && !defined(TC_HOST)
#ifdef EMU_OVL
/* 1.6.13 test10: start code for size (the program image is full) */
#define TC_INIT __attribute__((section(".initcode"), noinline, minsize))
#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline, minsize))
#else
#define TC_INIT __attribute__((section(".initcode"), noinline))
/* at the very end: writes the fixed routines to the start of the area */
#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline))
#endif
/* 1.6.8: rarely run code, small (0x20000000 is only 4 KB, mirrored; the SRAM is full) */
#define TC_SRAM __attribute__((noinline, minsize))
#else
#define TC_SRAM
#define TC_INIT
#define TC_INIT_LAST
#endif
#include <stddef.h>
#ifdef TC_HOST
#include <string.h>
#else
void *memset(void *d, int c, size_t n);
void *memcpy(void *d, const void *s, size_t n);
#endif
typedef struct DeviceProfile {
uint32_t rom_base, rom_size;
uint32_t a0ram_base, a0ram_size;
uint32_t ivram_base, ivram_size;
uint32_t dstram_base, dstram_size;
uint32_t io_base, io_end, io_size;
uint32_t lcd_cmd_addr, lcd_data_addr;
bool flash_top_boot;
bool debug_strap_high;
bool has_sleep_flag;
uint32_t sleep_flag;
uint32_t ttbr_reset;
uint32_t osc3_hz;
uint8_t ir_gpio_rx_bit;
bool ir_gpio;
bool nfc_pn512; /* 4U/4U+: the PN512 NFC chip answers on the IR UART (1.6.8) */
} DeviceProfile;
#define A0RAM_MAX 0x00008000u
#define IVRAM_MAX 0x00003000u
#define DSTRAM_MAX 0x00001000u
#define IORAM_MAX 0x00002000u
#define GRAM_W 128
#define GRAM_H 128
typedef struct Lcd {
uint16_t (*gram)[GRAM_W]; /* 128x128, located in fast PRAM */
uint8_t cmd;
int argc;
uint8_t args[16];
int xs, xe, ys, ye, cx, cy;
uint8_t madctl, colmod;
bool sleep_out, disp_on, inverted;
uint8_t pix_buf[3];
int pix_n;
/* changed area since the last fetch */
int dx0, dy0, dx1, dy1;
} Lcd;
typedef struct Cmu {
uint8_t unlocked;
uint32_t sccr, pllc, opt;
uint32_t osc3_hz, mclk_hz;
} Cmu;
typedef struct T16 { uint16_t counter; uint8_t a_fired; uint32_t accum; } T16;
/* Writable flash sectors live in RAM (overlay), the rest is read
* directly from the Paradise flash (XIP). */
#define OVL_SLOTS 8
#define OVL_SIZE 0x2000u /* one 8 KB parameter sector per slot */
typedef struct Overlay {
uint32_t base[OVL_SLOTS]; /* ROM offset of the sector, 0xFFFFFFFF = free */
uint8_t *mem[OVL_SLOTS];
int n;
} Overlay;
typedef struct Emu {
uint32_t r[16];
uint32_t sp, alr, ahr, ttbr, idir, dbbr;
uint32_t pc;
/* Translator (tc_jit.c): fields near the start so the generated code
* reaches them with short offsets. */
uint32_t nzcv; /* flags in ARM format, C = not guest C */
int32_t jit_left; /* remaining cycles (r10) */
uint32_t jit_bias; /* exit request from a helper */
uint32_t jit_a0; /* target address of a0ram */
uint32_t jit_h[9]; /* target addresses of the helpers */
uint32_t jit_flush; /* flush the cache at the next stop */
int flash_busy; /* kept up front: the translator reads ROM directly */
bool flash_autoselect; /* as long as both are zero */
uint32_t jit_rom[128]; /* ROM per 64 KB as target address (0 = helper), see jit_rom_update */
uint32_t jit_par[8]; /* parameter block per 8 KB (overlay or original) */
uint32_t jit_parb; /* offset of the parameter block */
uint8_t jit_map[128]; /* a0ram pages (256 B) with translated code */
uint32_t jit_slot[600]; /* jump targets of the exits (chaining without changing code) */
uint32_t jit_itab[2 * 256];/* jump targets: (guest pc, code|1), direct mapped */
uint8_t f_n, f_z, f_v, f_c, f_ie;
uint8_t il;
uint32_t psr_rest;
int ext_count;
uint32_t ext_val[2];
bool halted, halt_hard;
uint64_t wake_at;
uint64_t cycles;
uint64_t evt; /* next stop of the fast core */
bool stopped;
uint32_t stop_pc, stop_code;
DeviceProfile dev;
const uint8_t *rom; /* original in flash (uncached window) */
const uint8_t *rom_fast; /* only for tc_cpu.c (reference on the host) */
uint32_t rom_fast_len;
/* ROM in 64 KB blocks: rom_src = data (0 = erased, reads 0xFF),
* rom_blk = fast read pointer (0 = via mem_read, e.g. parameter block) */
const uint8_t *rom_src[128];
const uint8_t *rom_blk[128];
uint32_t par_base; /* 64 KB with 8 KB parameter sectors */
/* Instruction window: host pointer for pc in [fw_lo, fw_lo+fw_len) */
const uint8_t *fw_ptr; uint32_t fw_lo, fw_len;
Overlay ovl;
uint8_t a0ram[A0RAM_MAX];
uint8_t ivram[IVRAM_MAX];
uint8_t dstram[DSTRAM_MAX];
uint8_t ioram[IORAM_MAX];
Cmu cmu;
Lcd lcd;
T16 t16[6];
uint32_t pending_irq;
uint8_t pending_level;
bool wake_req;
uint64_t last_tick;
uint8_t btn_mask;
uint32_t rtc_cyc, rtc_irq_cyc;
int flash_state;
bool flash_dirty;
uint16_t flash_op_data;
bool flash_toggle;
uint32_t flash_lost_writes; /* write attempts without a free slot */
uint64_t lcd_writes;
uint32_t ovl_blk[4]; /* 64 KB blocks outside the parameter block with a written copy (bit per block) */
uint32_t flash_big_ops; /* erases and writes in 64 KB sectors (for the display) */
/* Blocks without their own storage (erased in the original): written 8 KB parts live in
* spare pages (device). pg_blk: bit per block, pg_map: page index per 8 KB (0xFF = erased). */
const uint8_t *pg_base;
uint32_t pg_blk[4];
uint8_t pg_map[1024];
} Emu;
/* cpu */
void cpu_reset(Emu *e);
void cpu_step(Emu *e);
/* mem */
uint8_t mem_read8 (Emu *e, uint32_t a);
uint16_t mem_read16(Emu *e, uint32_t a);
uint32_t mem_read32(Emu *e, uint32_t a);
void mem_write8 (Emu *e, uint32_t a, uint8_t v);
void mem_write16(Emu *e, uint32_t a, uint16_t v);
void mem_write32(Emu *e, uint32_t a, uint32_t v);
void tc_fetch_window(Emu *e, uint32_t pc);
/* periph */
uint8_t periph_read8 (Emu *e, uint32_t a);
uint32_t periph_read32(Emu *e, uint32_t a);
void periph_write8 (Emu *e, uint32_t a, uint8_t v);
void periph_write32(Emu *e, uint32_t a, uint32_t v);
void periph_tick(Emu *e, uint32_t cycles);
uint32_t periph_next(Emu *e);
void periph_rtc_advance(Emu *e, uint32_t n);
void periph_rtc_ms(Emu *e);
extern uint32_t g_tc_rtc_wr; /* writes of the guest to its clock registers (1.6.8) */
#ifdef TC_IRLINK
/* 1.6.9: infrared to another Paradise (tc_periph.c); the platform passes the bytes */
void tc_ir_setup(uint32_t mode_flag, uint32_t ctx_ptr);
int tc_ir_avail(void);
int tc_ir_in(void);
void tc_ir_out(uint8_t b);
#endif
void periph_rtc_set(Emu *e, uint32_t t); /* local time, seconds since 1970 */
uint32_t periph_rtc_get(Emu *e); /* 1.7.2 test16: the guest clock, 0 = stopped or not a date */
void periph_buttons(Emu *e, uint8_t mask);
void periph_init(Emu *e);
/* lcd */
void lcd_cmd (Emu *e, uint8_t c);
void lcd_data(Emu *e, uint8_t d);
/* device */
void tc_profile_plus_color(DeviceProfile *d);
void tc_profile_idl(DeviceProfile *d);
void tc_rom_linear(Emu *e, const uint8_t *rom);
void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots);
/* Runs until cycles >= ziel; returns true if stopped (error). */
bool tc_run(Emu *e, uint64_t ziel);
void tc_exec(Emu *e, uint64_t ziel);
/* translator */
void jit_init(Emu *e, uint8_t *buf, uint32_t tgt, uint32_t size);
void jit_exec(Emu *e, uint64_t ziel);
void jit_flush_all(Emu *e);
uint32_t periph_tone_hz(Emu *e); /* guest tone in Hz, 0 = silent */
/* All overlay slots in use: write one back and free it (device). */
extern int (*tc_ovl_evict)(Emu *e);
/* Erase a 64 KB sector of the guest in the backing store (host image or Paradise flash).
* Returns 1 if done. Without it, such erases are lost as before. */
extern int (*tc_big_erase)(Emu *e, uint32_t base);
#ifdef TC_LZ
extern const uint8_t *tc_lz_tab; /* 1.7.3 GUEST_LZ: table of the packed cold blocks (0 = none) */
extern uint32_t tc_lz_gone[4];
#endif
void tc_ovl_free(Emu *e, int i); /* release a slot without writing it back */
void tc_blk_update(Emu *e, uint32_t blk); /* fast pointers of a 64 KB block after a change */
void jit_rom_update(Emu *e, uint32_t off); /* ROM offset: recompute the entry */
extern uint32_t (*jit_tgt_of)(const uint8_t *p); /* host pointer -> target address (test bench) */
extern int jit_enabled;
/* Platform: enter generated code, or sync the instruction cache */
uint32_t jit_enter(Emu *e, uint32_t code);
extern volatile uint32_t jit_dbg[44];
void jit_stage_setup(uint8_t *stage, uint32_t size);
extern uint32_t jit_st_copy;
extern void (*jit_bad_hook)(Emu *e);
void jit_sync(uint32_t lo, uint32_t hi);
void tc_exec(Emu *e, uint64_t ziel);
#endif
/* Lean core for colour Tamagotchis (S1C33), derived from tamaemu
* (github.com/maragotchi/tamaemu, GPL-3.0). For Paradise apps without an
* operating system: no stdio, no floating point, fixed memory blocks. */
#ifndef TC_H
#define TC_H
#include <stdint.h>
#include <stdbool.h>
/* Only needed at startup: placed at the end of the image, the translator takes the space afterwards */
#if defined(__arm__) && !defined(TC_HOST)
#ifdef EMU_OVL
/* 1.6.13 test10: start code for size (the program image is full) */
#define TC_INIT __attribute__((section(".initcode"), noinline, minsize))
#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline, minsize))
#else
#define TC_INIT __attribute__((section(".initcode"), noinline))
/* at the very end: writes the fixed routines to the start of the area */
#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline))
#endif
/* 1.6.8: rarely run code, small (0x20000000 is only 4 KB, mirrored; the SRAM is full) */
#define TC_SRAM __attribute__((noinline, minsize))
#else
#define TC_SRAM
#define TC_INIT
#define TC_INIT_LAST
#endif
#include <stddef.h>
#ifdef TC_HOST
#include <string.h>
#else
void *memset(void *d, int c, size_t n);
void *memcpy(void *d, const void *s, size_t n);
#endif
typedef struct DeviceProfile {
uint32_t rom_base, rom_size;
uint32_t a0ram_base, a0ram_size;
uint32_t ivram_base, ivram_size;
uint32_t dstram_base, dstram_size;
uint32_t io_base, io_end, io_size;
uint32_t lcd_cmd_addr, lcd_data_addr;
bool flash_top_boot;
bool debug_strap_high;
bool has_sleep_flag;
uint32_t sleep_flag;
uint32_t ttbr_reset;
uint32_t osc3_hz;
uint8_t ir_gpio_rx_bit;
bool ir_gpio;
bool nfc_pn512; /* 4U/4U+: the PN512 NFC chip answers on the IR UART (1.6.8) */
} DeviceProfile;
#define A0RAM_MAX 0x00008000u
#define IVRAM_MAX 0x00003000u
#define DSTRAM_MAX 0x00001000u
#define IORAM_MAX 0x00002000u
#define GRAM_W 128
#define GRAM_H 128
typedef struct Lcd {
uint16_t (*gram)[GRAM_W]; /* 128x128, located in fast PRAM */
uint8_t cmd;
int argc;
uint8_t args[16];
int xs, xe, ys, ye, cx, cy;
uint8_t madctl, colmod;
bool sleep_out, disp_on, inverted;
uint8_t pix_buf[3];
int pix_n;
/* changed area since the last fetch */
int dx0, dy0, dx1, dy1;
} Lcd;
typedef struct Cmu {
uint8_t unlocked;
uint32_t sccr, pllc, opt;
uint32_t osc3_hz, mclk_hz;
} Cmu;
typedef struct T16 { uint16_t counter; uint8_t a_fired; uint32_t accum; } T16;
/* Writable flash sectors live in RAM (overlay), the rest is read
* directly from the Paradise flash (XIP). */
#define OVL_SLOTS 8
#define OVL_SIZE 0x2000u /* one 8 KB parameter sector per slot */
typedef struct Overlay {
uint32_t base[OVL_SLOTS]; /* ROM offset of the sector, 0xFFFFFFFF = free */
uint8_t *mem[OVL_SLOTS];
int n;
} Overlay;
typedef struct Emu {
uint32_t r[16];
uint32_t sp, alr, ahr, ttbr, idir, dbbr;
uint32_t pc;
/* Translator (tc_jit.c): fields near the start so the generated code
* reaches them with short offsets. */
uint32_t nzcv; /* flags in ARM format, C = not guest C */
int32_t jit_left; /* remaining cycles (r10) */
uint32_t jit_bias; /* exit request from a helper */
uint32_t jit_a0; /* target address of a0ram */
uint32_t jit_h[9]; /* target addresses of the helpers */
uint32_t jit_flush; /* flush the cache at the next stop */
int flash_busy; /* kept up front: the translator reads ROM directly */
bool flash_autoselect; /* as long as both are zero */
uint32_t jit_rom[128]; /* ROM per 64 KB as target address (0 = helper), see jit_rom_update */
uint32_t jit_par[8]; /* parameter block per 8 KB (overlay or original) */
uint32_t jit_parb; /* offset of the parameter block */
uint8_t jit_map[128]; /* a0ram pages (256 B) with translated code */
uint32_t jit_slot[600]; /* jump targets of the exits (chaining without changing code) */
uint32_t jit_itab[2 * 256];/* jump targets: (guest pc, code|1), direct mapped */
uint8_t f_n, f_z, f_v, f_c, f_ie;
uint8_t il;
uint32_t psr_rest;
int ext_count;
uint32_t ext_val[2];
bool halted, halt_hard;
uint64_t wake_at;
uint64_t cycles;
uint64_t evt; /* next stop of the fast core */
bool stopped;
uint32_t stop_pc, stop_code;
DeviceProfile dev;
const uint8_t *rom; /* original in flash (uncached window) */
const uint8_t *rom_fast; /* only for tc_cpu.c (reference on the host) */
uint32_t rom_fast_len;
/* ROM in 64 KB blocks: rom_src = data (0 = erased, reads 0xFF),
* rom_blk = fast read pointer (0 = via mem_read, e.g. parameter block) */
const uint8_t *rom_src[128];
const uint8_t *rom_blk[128];
uint32_t par_base; /* 64 KB with 8 KB parameter sectors */
/* Instruction window: host pointer for pc in [fw_lo, fw_lo+fw_len) */
const uint8_t *fw_ptr; uint32_t fw_lo, fw_len;
Overlay ovl;
uint8_t a0ram[A0RAM_MAX];
uint8_t ivram[IVRAM_MAX];
uint8_t dstram[DSTRAM_MAX];
uint8_t ioram[IORAM_MAX];
Cmu cmu;
Lcd lcd;
T16 t16[6];
uint32_t pending_irq;
uint8_t pending_level;
bool wake_req;
uint64_t last_tick;
uint8_t btn_mask;
uint32_t rtc_cyc, rtc_irq_cyc;
int flash_state;
bool flash_dirty;
uint16_t flash_op_data;
bool flash_toggle;
uint32_t flash_lost_writes; /* write attempts without a free slot */
uint64_t lcd_writes;
uint32_t ovl_blk[4]; /* 64 KB blocks outside the parameter block with a written copy (bit per block) */
uint32_t flash_big_ops; /* erases and writes in 64 KB sectors (for the display) */
/* Blocks without their own storage (erased in the original): written 8 KB parts live in
* spare pages (device). pg_blk: bit per block, pg_map: page index per 8 KB (0xFF = erased). */
const uint8_t *pg_base;
uint32_t pg_blk[4];
uint8_t pg_map[1024];
} Emu;
/* cpu */
void cpu_reset(Emu *e);
void cpu_step(Emu *e);
/* mem */
uint8_t mem_read8 (Emu *e, uint32_t a);
uint16_t mem_read16(Emu *e, uint32_t a);
uint32_t mem_read32(Emu *e, uint32_t a);
void mem_write8 (Emu *e, uint32_t a, uint8_t v);
void mem_write16(Emu *e, uint32_t a, uint16_t v);
void mem_write32(Emu *e, uint32_t a, uint32_t v);
void tc_fetch_window(Emu *e, uint32_t pc);
/* periph */
uint8_t periph_read8 (Emu *e, uint32_t a);
uint32_t periph_read32(Emu *e, uint32_t a);
void periph_write8 (Emu *e, uint32_t a, uint8_t v);
void periph_write32(Emu *e, uint32_t a, uint32_t v);
void periph_tick(Emu *e, uint32_t cycles);
uint32_t periph_next(Emu *e);
void periph_rtc_advance(Emu *e, uint32_t n);
void periph_rtc_ms(Emu *e);
extern uint32_t g_tc_rtc_wr; /* writes of the guest to its clock registers (1.6.8) */
#ifdef TC_IRLINK
/* 1.6.9: infrared to another Paradise (tc_periph.c); the platform passes the bytes */
void tc_ir_setup(uint32_t mode_flag, uint32_t ctx_ptr);
int tc_ir_avail(void);
int tc_ir_in(void);
void tc_ir_out(uint8_t b);
#endif
void periph_rtc_set(Emu *e, uint32_t t); /* local time, seconds since 1970 */
uint32_t periph_rtc_get(Emu *e); /* 1.7.2 test16: the guest clock, 0 = stopped or not a date */
void periph_buttons(Emu *e, uint8_t mask);
void periph_init(Emu *e);
/* lcd */
void lcd_cmd (Emu *e, uint8_t c);
void lcd_data(Emu *e, uint8_t d);
/* device */
void tc_profile_plus_color(DeviceProfile *d);
void tc_profile_idl(DeviceProfile *d);
void tc_rom_linear(Emu *e, const uint8_t *rom);
void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots);
/* Runs until cycles >= ziel; returns true if stopped (error). */
bool tc_run(Emu *e, uint64_t ziel);
void tc_exec(Emu *e, uint64_t ziel);
/* translator */
void jit_init(Emu *e, uint8_t *buf, uint32_t tgt, uint32_t size);
void jit_exec(Emu *e, uint64_t ziel);
void jit_flush_all(Emu *e);
uint32_t periph_tone_hz(Emu *e); /* guest tone in Hz, 0 = silent */
/* All overlay slots in use: write one back and free it (device). */
extern int (*tc_ovl_evict)(Emu *e);
/* Erase a 64 KB sector of the guest in the backing store (host image or Paradise flash).
* Returns 1 if done. Without it, such erases are lost as before. */
extern int (*tc_big_erase)(Emu *e, uint32_t base);
#ifdef TC_LZ
extern const uint8_t *tc_lz_tab; /* 1.7.3 GUEST_LZ: table of the packed cold blocks (0 = none) */
extern uint32_t tc_lz_gone[4];
#endif
void tc_ovl_free(Emu *e, int i); /* release a slot without writing it back */
void tc_blk_update(Emu *e, uint32_t blk); /* fast pointers of a 64 KB block after a change */
void jit_rom_update(Emu *e, uint32_t off); /* ROM offset: recompute the entry */
extern uint32_t (*jit_tgt_of)(const uint8_t *p); /* host pointer -> target address (test bench) */
extern int jit_enabled;
/* Platform: enter generated code, or sync the instruction cache */
uint32_t jit_enter(Emu *e, uint32_t code);
extern volatile uint32_t jit_dbg[44];
void jit_stage_setup(uint8_t *stage, uint32_t size);
extern uint32_t jit_st_copy;
extern void (*jit_bad_hook)(Emu *e);
void jit_sync(uint32_t lo, uint32_t hi);
void tc_exec(Emu *e, uint64_t ziel);
#endif
+9 -9
View File
@@ -1,9 +1,9 @@
/* One translation unit for the whole core, so the compiler can inline. */
#include "tc_mem.c"
#include "tc_periph.c"
#include "tc_lcd.c"
#include "tc_core.c"
#include "tc_fast.c"
#ifdef TC_JIT
#include "tc_jit.c"
#endif
/* One translation unit for the whole core, so the compiler can inline. */
#include "tc_mem.c"
#include "tc_periph.c"
#include "tc_lcd.c"
#include "tc_core.c"
#include "tc_fast.c"
#ifdef TC_JIT
#include "tc_jit.c"
#endif
+100 -100
View File
@@ -1,100 +1,100 @@
#include "tc.h"
TC_INIT void tc_profile_idl(DeviceProfile *d)
{
memset(d, 0, sizeof *d);
d->rom_base = 0x02000000u; d->rom_size = 0x00800000u;
d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u;
d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u;
d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u;
d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u;
d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u;
d->flash_top_boot = false;
d->debug_strap_high = false;
d->has_sleep_flag = true; d->sleep_flag = 0x00000FD8u;
d->ttbr_reset = 0x02400000u;
d->osc3_hz = 18432000u;
}
TC_INIT void tc_profile_plus_color(DeviceProfile *d)
{
memset(d, 0, sizeof *d);
d->rom_base = 0x00C00000u; d->rom_size = 0x00400000u;
d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u;
d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u;
d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u;
d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u;
d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u;
d->flash_top_boot = true;
#ifdef TC_STRAP_TEST
d->debug_strap_high = false; /* test only */
#else
d->debug_strap_high = true;
#endif
d->has_sleep_flag = true; d->sleep_flag = 0x00000368u;
d->ttbr_reset = 0x00C00000u;
d->osc3_hz = 20000000u;
d->ir_gpio = true; d->ir_gpio_rx_bit = 5;
}
TC_INIT void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots)
{
DeviceProfile d = e->dev;
memset(e, 0, sizeof *e);
e->dev = d;
e->rom = rom_xip;
e->rom_fast = rom_xip; e->rom_fast_len = 0;
e->par_base = d.flash_top_boot ? d.rom_size - 0x10000u : 0;
if (rom_xip) tc_rom_linear(e, rom_xip);
e->lcd.gram = gram;
for (int i = 0; i < OVL_SLOTS; i++) { e->ovl.base[i] = 0xFFFFFFFFu; e->ovl.mem[i] = 0; }
for (int i = 0; i < slots && i < OVL_SLOTS; i++) e->ovl.mem[i] = ovl_pool + (uint32_t)i * OVL_SIZE;
e->ovl.n = 0;
e->lcd.xe = 131; e->lcd.ye = 161;
e->lcd.dx0 = 0; e->lcd.dy0 = 0; e->lcd.dx1 = 127; e->lcd.dy1 = 127;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
periph_init(e);
cpu_reset(e);
}
uint32_t tc_halt_steps;
/* ROM is contiguous from rom (fill the block tables). */
TC_INIT __attribute__((minsize)) void tc_rom_linear(Emu *e, const uint8_t *rom)
{
for (uint32_t i = 0; i < 128; i++) {
e->rom_src[i] = (i << 16) < e->dev.rom_size ? rom + (i << 16) : 0;
e->rom_blk[i] = e->rom_src[i];
}
e->rom_blk[e->par_base >> 16] = 0;
}
bool tc_run(Emu *e, uint64_t ziel)
{
while (e->cycles < ziel) {
if (e->stopped) return true;
if (e->halted) {
if (e->pending_irq || e->wake_req || (!e->halt_hard && e->cycles >= e->wake_at)) {
e->halted = false;
} else {
/* Sleeping CPU: fast forward time in steps instead of cycle by cycle. */
uint64_t step = ziel - e->cycles;
#ifdef TC_JIT
{ uint32_t nx = periph_next(e); if (step > nx) step = nx; tc_halt_steps++; }
#else
if (step > 1024) step = 1024;
#endif
if (!e->halt_hard && e->wake_at > e->cycles && e->wake_at - e->cycles < step) step = e->wake_at - e->cycles;
if (!step) step = 1;
e->cycles += step;
periph_tick(e, (uint32_t)(e->cycles - e->last_tick));
e->last_tick = e->cycles;
continue;
}
}
#ifdef TC_JIT
if (jit_enabled) { jit_exec(e, ziel); continue; }
#endif
tc_exec(e, ziel);
}
return e->stopped;
}
#include "tc.h"
TC_INIT void tc_profile_idl(DeviceProfile *d)
{
memset(d, 0, sizeof *d);
d->rom_base = 0x02000000u; d->rom_size = 0x00800000u;
d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u;
d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u;
d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u;
d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u;
d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u;
d->flash_top_boot = false;
d->debug_strap_high = false;
d->has_sleep_flag = true; d->sleep_flag = 0x00000FD8u;
d->ttbr_reset = 0x02400000u;
d->osc3_hz = 18432000u;
}
TC_INIT void tc_profile_plus_color(DeviceProfile *d)
{
memset(d, 0, sizeof *d);
d->rom_base = 0x00C00000u; d->rom_size = 0x00400000u;
d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u;
d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u;
d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u;
d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u;
d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u;
d->flash_top_boot = true;
#ifdef TC_STRAP_TEST
d->debug_strap_high = false; /* test only */
#else
d->debug_strap_high = true;
#endif
d->has_sleep_flag = true; d->sleep_flag = 0x00000368u;
d->ttbr_reset = 0x00C00000u;
d->osc3_hz = 20000000u;
d->ir_gpio = true; d->ir_gpio_rx_bit = 5;
}
TC_INIT void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots)
{
DeviceProfile d = e->dev;
memset(e, 0, sizeof *e);
e->dev = d;
e->rom = rom_xip;
e->rom_fast = rom_xip; e->rom_fast_len = 0;
e->par_base = d.flash_top_boot ? d.rom_size - 0x10000u : 0;
if (rom_xip) tc_rom_linear(e, rom_xip);
e->lcd.gram = gram;
for (int i = 0; i < OVL_SLOTS; i++) { e->ovl.base[i] = 0xFFFFFFFFu; e->ovl.mem[i] = 0; }
for (int i = 0; i < slots && i < OVL_SLOTS; i++) e->ovl.mem[i] = ovl_pool + (uint32_t)i * OVL_SIZE;
e->ovl.n = 0;
e->lcd.xe = 131; e->lcd.ye = 161;
e->lcd.dx0 = 0; e->lcd.dy0 = 0; e->lcd.dx1 = 127; e->lcd.dy1 = 127;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
periph_init(e);
cpu_reset(e);
}
uint32_t tc_halt_steps;
/* ROM is contiguous from rom (fill the block tables). */
TC_INIT __attribute__((minsize)) void tc_rom_linear(Emu *e, const uint8_t *rom)
{
for (uint32_t i = 0; i < 128; i++) {
e->rom_src[i] = (i << 16) < e->dev.rom_size ? rom + (i << 16) : 0;
e->rom_blk[i] = e->rom_src[i];
}
e->rom_blk[e->par_base >> 16] = 0;
}
bool tc_run(Emu *e, uint64_t ziel)
{
while (e->cycles < ziel) {
if (e->stopped) return true;
if (e->halted) {
if (e->pending_irq || e->wake_req || (!e->halt_hard && e->cycles >= e->wake_at)) {
e->halted = false;
} else {
/* Sleeping CPU: fast forward time in steps instead of cycle by cycle. */
uint64_t step = ziel - e->cycles;
#ifdef TC_JIT
{ uint32_t nx = periph_next(e); if (step > nx) step = nx; tc_halt_steps++; }
#else
if (step > 1024) step = 1024;
#endif
if (!e->halt_hard && e->wake_at > e->cycles && e->wake_at - e->cycles < step) step = e->wake_at - e->cycles;
if (!step) step = 1;
e->cycles += step;
periph_tick(e, (uint32_t)(e->cycles - e->last_tick));
e->last_tick = e->cycles;
continue;
}
}
#ifdef TC_JIT
if (jit_enabled) { jit_exec(e, ziel); continue; }
#endif
tc_exec(e, ziel);
}
return e->stopped;
}
+629 -629
View File
File diff suppressed because it is too large. Load diff
+500 -500
View File
@@ -1,500 +1,500 @@
/* Fast interpreter for S1C33 (same semantics as tc_cpu.c, which is derived
* from tamaemu cpu.c). Hot state lives in local variables so the compiler
* keeps it in registers. Verified by lockstep runs against tc_cpu.c. */
#include "tc.h"
#ifdef ROMSTAT
__attribute__((section(".stats"), used)) volatile uint32_t tc_rom_hits[128]; /* stats build: reads per 64 KB guest block */
#define ROMHIT(o) (tc_rom_hits[((o) >> 16) & 127]++)
#else
#define ROMHIT(o) ((void)0)
#endif
#define SEXT(v, bits) ((uint32_t)(((uint32_t)(v) ^ (1u << ((bits) - 1))) - (1u << ((bits) - 1))))
static inline uint8_t *f_ramp(Emu *e, uint32_t a, uint32_t n)
{
if (a <= A0RAM_MAX - n) return e->a0ram + a;
uint32_t o = a - 0x80000u;
if (o <= IVRAM_MAX - n) return e->ivram + o;
o = a - 0x84000u;
if (o <= DSTRAM_MAX - n) return e->dstram + o;
return 0;
}
#ifdef TC_JIT
/* Write to RAM that has already been translated: discard all translations */
#ifdef JIT_WHOT
/* v0.9.6: a0ram pages whose code keeps getting overwritten (iD L, Connect to Plus Color: code at 0xC00
* next to its data) are no longer translated. Before, every write threw away all translations, thousands
* of times per second, and the emulator stood still on the device. */
uint8_t jit_wcnt[128], jit_nojit[128];
uint64_t jit_wwin, jit_nojit_at;
#define JIT_WWIN 2000000u /* window for counting (about 0.1 s of guest time) */
#define JIT_NOJIT 100000000u /* after about 5 s the pages get another chance */
static void jit_cw_note(Emu *e, uint32_t a, uint32_t n)
{
if (e->cycles - jit_wwin > JIT_WWIN) { memset(jit_wcnt, 0, sizeof jit_wcnt); jit_wwin = e->cycles; }
for (uint32_t p = a >> 8; p <= ((a + n - 1) >> 8) && p < 128u; p++)
if (e->jit_map[p] && ++jit_wcnt[p] >= 8u) { jit_nojit[p] = 1; jit_wcnt[p] = 0; jit_nojit_at = e->cycles; }
}
static int jit_nojit_pc(Emu *e, uint32_t pc)
{
if (!jit_nojit[pc >> 8]) return 0;
if (e->cycles - jit_nojit_at > JIT_NOJIT) { memset(jit_nojit, 0, sizeof jit_nojit); return 0; }
return 1;
}
#else
#define jit_cw_note(e, a, n) ((void)0)
#endif
__attribute__((noinline)) static void jit_cw_chk(Emu *e, uint32_t a, uint32_t n)
{
if (e->jit_map[a >> 8] | e->jit_map[(a + n - 1) >> 8]) { jit_cw_note(e, a, n); e->jit_flush = 1; memset(e->jit_map, 0, sizeof e->jit_map); }
}
#endif
#ifdef TC_STATS
void stat_acc(uint32_t a, int w);
#define FST(a, w) stat_acc((a), (w))
#else
#define FST(a, w) ((void)0)
#endif
static inline uint32_t f_rd8(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 1); if (p) return *p;
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) return b[o & 0xFFFFu]; }
return mem_read8(e, a);
}
static inline uint32_t f_rd16(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 2); if (p) return (uint32_t)(p[0] | (p[1] << 8));
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFEu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)(q[0] | (q[1] << 8)); } }
return mem_read16(e, a);
}
static inline uint32_t f_rd32(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 4); if (p) return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFCu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)q[0] | ((uint32_t)q[1] << 8) | ((uint32_t)q[2] << 16) | ((uint32_t)q[3] << 24); } }
return mem_read32(e, a);
}
static inline void f_wr8(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 1); if (p) *p = (uint8_t)v; else mem_write8(e, a, (uint8_t)v); }
static inline void f_wr16(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 2); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } else mem_write16(e, a, (uint16_t)v); }
static inline void f_wr32(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 4); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } else mem_write32(e, a, v); }
/* Flags in one word: bit3 N, bit2 Z, bit1 V, bit0 C */
#define FN (fl >> 3 & 1)
#define FZ (fl >> 2 & 1)
#define FV (fl >> 1 & 1)
#define FC (fl & 1)
#define NZ(r) do { uint32_t _r = (r); fl = (fl & 3u) | ((_r >> 31) << 3) | ((uint32_t)(_r == 0) << 2); } while (0)
#define SCARRY(a, b) ((((~((a) ^ (b))) & ((a) ^ ((a) + (b)))) >> 31))
#define SBORROW(a, b) (((((a) ^ (b)) & ((a) ^ ((a) - (b)))) >> 31))
#define PUSH(v) do { sp -= 4; WR32(sp, (v)); } while (0)
#define POP() (sp += 4, f_rd32(e, sp - 4))
#define PSR_PACK() ((e->psr_rest & ~0xF1Fu) | FN | (FZ << 1) | (FV << 2) | (FC << 3) | ((uint32_t)e->f_ie << 4) | ((uint32_t)(e->il & 0xF) << 8))
#define PSR_UNPACK(v) do { uint32_t _v = (v); fl = ((_v & 1) << 3) | (((_v >> 1) & 1) << 2) | (((_v >> 2) & 1) << 1) | ((_v >> 3) & 1); \
e->f_ie = (_v >> 4) & 1; e->il = (_v >> 8) & 0xF; e->psr_rest = _v; chk = 1; } while (0)
static inline uint32_t op_add(uint32_t a, uint32_t b, uint32_t *fl)
{ uint32_t r = a + b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SCARRY(a, b) << 1) | (uint32_t)(r < a); return r; }
static inline uint32_t op_sub(uint32_t a, uint32_t b, uint32_t *fl)
{ uint32_t r = a - b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SBORROW(a, b) << 1) | (uint32_t)(a < b); return r; }
#define ADD(a, b) op_add((a), (b), &fl)
#define SUB(a, b) op_sub((a), (b), &fl)
#define CMP(a, b) ((void)op_sub((a), (b), &fl))
#define LOG(r) ({ uint32_t _q = (r); fl = (fl & 1u) | ((_q >> 31) << 3) | ((uint32_t)(_q == 0) << 2); _q; })
/* Deferred jump effect after the delay slot */
enum { D_NONE, D_JP, D_CALL, D_RET };
static inline int cond_ok(int op, uint32_t fl)
{
uint32_t fn = fl >> 3 & 1, fz = fl >> 2 & 1, fv = fl >> 1 & 1, fc = fl & 1;
switch (op) {
case 4: return !fz && fn == fv;
case 5: return fn == fv;
case 6: return fn != fv;
case 7: return fz || fn != fv;
case 8: return !fz && !fc;
case 9: return !fc;
case 10: return fc;
case 11: return fz || fc;
case 12: return fz;
case 13: return !fz;
default: return 1;
}
}
static int pc_ok(Emu *e, uint32_t a)
{
const DeviceProfile *d = &e->dev;
return a - d->rom_base < d->rom_size || a - d->a0ram_base < d->a0ram_size ||
a - d->ivram_base < d->ivram_size || a - d->dstram_base < d->dstram_size;
}
/* Runs until cycles >= ziel (target), or the CPU sleeps or stops. Peripherals
* are ticked every TICK cycles. */
#define TICK 256
__attribute__((minsize)) void tc_exec(Emu *e, uint64_t ziel)
{
uint32_t pc = e->pc, sp = e->sp;
uint32_t fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c;
int32_t left;
#define CYC() (e->evt - (uint64_t)(int64_t)left)
#define r (e->r)
const uint8_t *fwp = e->fw_ptr; uint32_t fwlo = e->fw_lo, fwlen = e->fw_len;
int slot = 0;
#define dkind (e->ext_count)
#define dtarget (e->ext_val[0])
dkind = D_NONE;
#define SYNC_OUT() do { e->pc = pc; e->sp = sp; e->f_n = FN; e->f_z = FZ; e->f_v = FV; e->f_c = FC; e->cycles = CYC(); } while (0)
#define SYNC_IN() do { pc = e->pc; sp = e->sp; fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c; left = (int32_t)(e->evt - e->cycles); \
fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len; } while (0)
/* Write to RAM that has already been translated: discard all translations */
#ifdef TC_JIT
#define JCW(a, n) do { if ((a) <= A0RAM_MAX - (n)) jit_cw_chk(e, (a), (n)); } while (0)
#else
#define JCW(a, n) ((void)0)
#endif
#define WR8(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 1); if (_p) { *_p = (uint8_t)_v; JCW(_a, 1); } \
else { SYNC_OUT(); mem_write8(e, _a, (uint8_t)_v); SYNC_IN(); chk = 1; } } while (0)
#define WR16(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 2); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); JCW(_a, 2); } \
else { SYNC_OUT(); mem_write16(e, _a, (uint16_t)_v); SYNC_IN(); chk = 1; } } while (0)
#define WR32(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 4); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); _p[2] = (uint8_t)(_v >> 16); _p[3] = (uint8_t)(_v >> 24); JCW(_a, 4); } \
else { SYNC_OUT(); mem_write32(e, _a, _v); SYNC_IN(); chk = 1; } } while (0)
#define NEXT_EVT(c) do { uint64_t _n = (e->last_tick + TICK < ziel) ? e->last_tick + TICK : ziel; e->evt = _n; left = (int32_t)(_n - (c)); } while (0)
#define FORCE_EVT() do { uint64_t _c = CYC(); e->evt = _c; left = 0; } while (0)
NEXT_EVT(e->cycles);
int chk = 1; /* check for interrupts (after peripherals, I/O, PSR) */
if (e->halted || e->stopped) goto out;
for (;;) {
int in_slot = slot; slot = 0;
if (!in_slot && chk) {
chk = 0;
if (e->pending_irq && e->f_ie && e->pending_level > e->il) {
uint32_t vec = e->pending_irq;
PUSH(pc);
PUSH(PSR_PACK());
e->f_ie = 0;
e->il = e->pending_level;
pc = f_rd32(e, e->ttbr + vec * 4);
e->pending_irq = 0;
}
}
/* Fetch */
if (pc - fwlo >= fwlen) {
pc &= 0x0FFFFFFFu;
if (!pc_ok(e, pc)) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = pc; break; }
tc_fetch_window(e, pc); fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len;
}
#define FETCH(a) ((a) - fwlo < fwlen ? *(const uint16_t *)(fwp + ((a) - fwlo)) : (uint16_t)f_rd16(e, (a)))
uint32_t hw = FETCH(pc);
int ext_n = 0; uint32_t ext0 = 0, ext1 = 0;
while ((hw >> 13) == 6) {
if (ext_n == 0) ext0 = hw & 0x1FFF; else if (ext_n == 1) ext1 = hw & 0x1FFF;
ext_n++;
pc += 2; left--;
hw = FETCH(pc);
if (ext_n > 2) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = hw; goto out; }
}
if (ext_n > 2) ext_n = 2;
uint32_t iaddr = pc;
pc += 2; left--;
int rd = hw & 0xF, rs = (hw >> 4) & 0xF;
switch (hw >> 13) {
case 0: {
int op1 = (hw >> 9) & 0xF, d = (hw >> 8) & 1;
if (op1 <= 3) {
int cnst = (hw >> 4) & 3;
if (cnst == 0) {
int op2 = (hw >> 6) & 3;
switch (op1 * 8 + d * 4 + op2) {
case 0: break;
case 1: e->halted = true; e->halt_hard = !(e->cmu.opt & 0x3E00); e->wake_at = CYC() + 20000; FORCE_EVT(); break;
case 2: e->halted = true; e->halt_hard = true; FORCE_EVT(); break;
case 8: for (int i = rd; i >= 0; i--) PUSH(r[i]); break;
case 9: for (int i = 0; i <= rd; i++) r[i] = POP(); break;
case 11: pc = iaddr + r[rd]; break;
case 15: dkind = D_JP; dtarget = iaddr + r[rd]; slot = 1; break;
case 16: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
case 17: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
case 18: { uint32_t vec = 12 + (hw & 3);
PUSH(pc); PUSH(PSR_PACK()); e->f_ie = 0;
pc = f_rd32(e, e->ttbr + vec * 4); break; }
case 19: { PSR_UNPACK(POP()); pc = POP(); break; }
case 24: { uint32_t t = r[rd]; PUSH(pc); pc = t; break; }
case 25: pc = POP(); break;
case 26: pc = r[rd]; break;
case 28: dkind = D_CALL; dtarget = r[rd]; slot = 1; break;
case 29: dkind = D_RET; slot = 1; break;
case 30: dkind = D_JP; dtarget = r[rd]; slot = 1; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
} else if (cnst == 1 && op1 == 0) {
switch ((hw >> 6) & 7) {
case 0: PUSH(r[rd]); break;
case 1: r[rd] = POP(); break;
case 2: if ((hw & 0xF) == 2) PUSH(e->alr);
else if ((hw & 0xF) == 3) { PUSH(e->ahr); PUSH(e->alr); }
else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break;
case 3: if ((hw & 0xF) == 2) e->alr = POP();
else if ((hw & 0xF) == 3) { e->alr = POP(); e->ahr = POP(); }
else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break;
case 7: fl = 0; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
} else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; }
} else {
uint32_t u8 = hw & 0xFF, target;
if (ext_n == 0) target = iaddr + SEXT(u8, 8) * 2;
else if (ext_n == 1) target = iaddr + ((SEXT(ext0, 13) << 9) | (u8 << 1));
else target = iaddr + (((ext0 & 0x1ff8) << 19) | (ext1 << 9) | (u8 << 1));
if (in_slot) break; /* branch in a delay slot: ignored, like the original */
if (op1 == 14) {
if (d) { dkind = D_CALL; dtarget = target; slot = 1; }
else { PUSH(pc); pc = target; }
} else if (op1 == 15) {
if (d) { dkind = D_JP; dtarget = target; slot = 1; } else pc = target;
} else {
int taken = cond_ok(op1, fl);
if (d) { dkind = taken ? D_JP : D_NONE; dtarget = target; slot = 1; }
else if (taken) pc = target;
}
}
break;
}
case 1: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
if (op2 == 3) {
uint32_t n = ((hw >> 4) & 0xF) + 16, a = r[rd], q;
switch (op1) {
case 0: q = a >> n; break;
case 1: case 3: q = a << n; break;
case 2: q = (uint32_t)((int32_t)a >> n); break;
case 4: q = (a >> n) | (a << (32 - n)); break;
case 5: q = (a << n) | (a >> (32 - n)); break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; q = a; break;
}
r[rd] = q; NZ(q);
break;
}
if (op2 == 2) {
uint32_t imm = (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
switch (op1) {
case 0: r[rd] = ext_n ? ADD(r[rs], imm) : ADD(r[rd], r[rs]); break;
case 1: r[rd] = ext_n ? SUB(r[rs], imm) : SUB(r[rd], r[rs]); break;
case 2: if (ext_n) CMP(r[rs], imm); else CMP(r[rd], r[rs]); break;
case 3: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = r[rs]; break;
case 4: r[rd] = ext_n ? LOG(r[rs] & imm) : LOG(r[rd] & r[rs]); break;
case 5: r[rd] = ext_n ? LOG(r[rs] | imm) : LOG(r[rd] | r[rs]); break;
case 6: r[rd] = ext_n ? LOG(r[rs] ^ imm) : LOG(r[rd] ^ r[rs]); break;
case 7: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = LOG(~r[rs]); break;
}
break;
}
{
uint32_t addr = r[rs];
int postinc = (op2 == 1);
if (ext_n) {
if (postinc) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; }
addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
}
switch (op1) {
case 0: r[rd] = SEXT(f_rd8(e, addr), 8); if (postinc) r[rs] += 1; break;
case 1: r[rd] = f_rd8(e, addr); if (postinc) r[rs] += 1; break;
case 2: r[rd] = SEXT(f_rd16(e, addr), 16); if (postinc) r[rs] += 2; break;
case 3: r[rd] = f_rd16(e, addr); if (postinc) r[rs] += 2; break;
case 4: r[rd] = f_rd32(e, addr); if (postinc) r[rs] += 4; break;
case 5: WR8(addr, r[rd]); if (postinc) r[rs] += 1; break;
case 6: WR16(addr, r[rd]); if (postinc) r[rs] += 2; break;
case 7: WR32(addr, r[rd]); if (postinc) r[rs] += 4; break;
}
break;
}
}
case 2: {
int op1 = (hw >> 10) & 7;
uint32_t imm6 = (hw >> 4) & 0x3F, off;
if (ext_n == 0) { static const uint8_t scale[8] = {1,1,2,2,4,1,2,4}; off = imm6 * scale[op1]; }
else if (ext_n == 1) off = (ext0 << 6) | imm6;
else off = (ext0 << 19) | (ext1 << 6) | imm6;
uint32_t addr = sp + off;
switch (op1) {
case 0: r[rd] = SEXT(f_rd8(e, addr), 8); break;
case 1: r[rd] = f_rd8(e, addr); break;
case 2: r[rd] = SEXT(f_rd16(e, addr), 16); break;
case 3: r[rd] = f_rd16(e, addr); break;
case 4: r[rd] = f_rd32(e, addr); break;
case 5: WR8(addr, r[rd]); break;
case 6: WR16(addr, r[rd]); break;
case 7: WR32(addr, r[rd]); break;
}
break;
}
case 3: {
int op1 = (hw >> 10) & 7;
uint32_t imm6 = (hw >> 4) & 0x3F, imm;
if (ext_n == 0) imm = (op1 == 0 || op1 == 1) ? imm6 : SEXT(imm6, 6);
else if (ext_n == 1) { imm = (ext0 << 6) | imm6; if (!(op1 == 0 || op1 == 1)) imm = SEXT(imm, 19); }
else imm = (ext0 << 19) | (ext1 << 6) | imm6;
switch (op1) {
case 0: r[rd] = ADD(r[rd], imm); break;
case 1: r[rd] = SUB(r[rd], imm); break;
case 2: CMP(r[rd], imm); break;
case 3: r[rd] = imm; break;
case 4: r[rd] = LOG(r[rd] & imm); break;
case 5: r[rd] = LOG(r[rd] | imm); break;
case 6: r[rd] = LOG(r[rd] ^ imm); break;
case 7: r[rd] = LOG(~imm); break;
}
break;
}
case 4: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
if (op1 == 0) { sp += (uint32_t)(hw & 0x3FF) * 4; break; }
if (op1 == 1) { sp -= (uint32_t)(hw & 0x3FF) * 4; break; }
uint32_t amt = ((op2 == 0) ? ((hw >> 4) & 0xF) : r[rs]) & 31, a = r[rd], q;
switch (op1) {
case 2: q = a >> amt; r[rd] = q; NZ(q); break;
case 3: case 5: q = a << amt; r[rd] = q; NZ(q); break;
case 4:
if (op2 == 2) { uint32_t v = r[rs]; r[rd] = (v << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24); }
else { q = (uint32_t)((int32_t)a >> amt); r[rd] = q; NZ(q); }
break;
case 6:
if (op2 == 2) { uint32_t v = r[rs];
r[rd] = ((v & 0x00FF0000) << 8) | ((v >> 8) & 0x00FF0000) | ((v & 0x000000FF) << 8) | ((v >> 8) & 0x000000FF); }
else { q = amt ? ((a >> amt) | (a << (32 - amt))) : a; r[rd] = q; NZ(q); }
break;
case 7: q = amt ? ((a << amt) | (a >> (32 - amt))) : a; r[rd] = q; NZ(q); break;
}
break;
}
case 5: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
switch (op1 * 4 + op2) {
case 0: { uint32_t v = r[rs];
switch (hw & 0xF) {
case 0: PSR_UNPACK(v); break;
case 1: sp = v; break;
case 2: e->alr = v; break;
case 3: e->ahr = v; break;
case 8: e->ttbr = v; break;
case 10: e->idir = v; break;
case 11: e->dbbr = v; break;
case 15: pc = v; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
} break; }
case 1: r[rd] = SEXT(r[rs] & 0xFF, 8); break;
case 2: e->alr = (uint32_t)((int32_t)SEXT(r[rd] & 0xFFFF, 16) * (int32_t)SEXT(r[rs] & 0xFFFF, 16)); break;
case 4: {
uint32_t v;
switch (rs) {
case 0: v = PSR_PACK(); break;
case 1: v = sp; break;
case 2: v = e->alr; break;
case 3: v = e->ahr; break;
case 8: v = e->ttbr; break;
case 10: v = e->idir; break;
case 11: v = e->dbbr; break;
case 15: v = iaddr; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; v = 0; break;
}
r[rd] = v; break; }
case 5: r[rd] = r[rs] & 0xFF; break;
case 6: e->alr = (r[rd] & 0xFFFF) * (r[rs] & 0xFFFF); break;
case 8: case 12: case 16: case 20: {
uint32_t addr = r[rs];
if (ext_n) addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
int pos = hw & 7;
uint32_t b = f_rd8(e, addr);
switch (op1) {
case 2: fl = (fl & ~4u) | ((uint32_t)(((b >> pos) & 1) == 0) << 2); break;
case 3: WR8(addr, b & ~(1u << pos)); break;
case 4: WR8(addr, b | (1u << pos)); break;
case 5: WR8(addr, b ^ (1u << pos)); break;
}
break; }
case 9: r[rd] = SEXT(r[rs] & 0xFFFF, 16); break;
case 10: { int64_t p = (int64_t)(int32_t)r[rd] * (int32_t)r[rs];
e->alr = (uint32_t)p; e->ahr = (uint32_t)((uint64_t)p >> 32); break; }
case 13: r[rd] = r[rs] & 0xFFFF; break;
case 14: { uint64_t p = (uint64_t)r[rd] * r[rs]; e->alr = (uint32_t)p; e->ahr = (uint32_t)(p >> 32); break; }
case 17: case 21: break;
case 24: { uint32_t a = r[rd], b = r[rs], cz = FC, s = a + b;
uint32_t v = SCARRY(a, b) ^ SCARRY(s, cz), c = (s < a) || ((s + cz) < s);
uint32_t q = s + cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; }
case 28: { uint32_t a = r[rd], b = r[rs], cz = FC, dd = a - b;
uint32_t v = SBORROW(a, b) || SBORROW(dd, cz), c = (a < b) || (dd < cz);
uint32_t q = dd - cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; }
case 31: {
int op3 = (hw >> 6) & 3, imm5 = hw & 0x1F;
if (op3 == 0) break;
if (op3 == 1 || op3 == 2) {
int val = (op3 == 1);
switch (imm5) {
case 0: fl = (fl & ~8u) | ((uint32_t)val << 3); break;
case 1: fl = (fl & ~4u) | ((uint32_t)val << 2); break;
case 2: fl = (fl & ~2u) | ((uint32_t)val << 1); break;
case 3: fl = (fl & ~1u) | (uint32_t)val; break;
case 4: e->f_ie = val; chk = 1; break;
default: break;
}
break;
}
e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; }
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
break;
}
default:
e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
if (in_slot) {
int k = dkind; dkind = D_NONE;
if (k == D_JP) pc = dtarget;
else if (k == D_CALL) { PUSH(pc); pc = dtarget; }
else if (k == D_RET) pc = POP();
}
if (left <= 0 && !slot) {
uint64_t cyc = CYC();
if (e->halted || e->stopped) break;
if (cyc - e->last_tick >= TICK) {
SYNC_OUT();
periph_tick(e, (uint32_t)(cyc - e->last_tick));
e->last_tick = cyc;
SYNC_IN();
chk = 1;
}
if (cyc >= ziel) break;
NEXT_EVT(cyc);
}
}
out:
#undef r
SYNC_OUT();
e->fw_ptr = fwp; e->fw_lo = fwlo; e->fw_len = fwlen;
}
#ifndef TC_WITH_REF
void cpu_reset(Emu *e)
{
memset(e->r, 0, sizeof e->r);
e->sp = 0; e->alr = e->ahr = 0;
e->ttbr = e->dev.ttbr_reset;
e->idir = e->dbbr = 0;
e->f_n = e->f_z = e->f_v = e->f_c = e->f_ie = 0;
e->il = 0; e->psr_rest = 0;
e->ext_count = 0;
e->halted = false; e->halt_hard = false;
e->stopped = false;
e->pc = mem_read32(e, e->ttbr);
}
#endif
/* Fast interpreter for S1C33 (same semantics as tc_cpu.c, which is derived
* from tamaemu cpu.c). Hot state lives in local variables so the compiler
* keeps it in registers. Verified by lockstep runs against tc_cpu.c. */
#include "tc.h"
#ifdef ROMSTAT
__attribute__((section(".stats"), used)) volatile uint32_t tc_rom_hits[128]; /* stats build: reads per 64 KB guest block */
#define ROMHIT(o) (tc_rom_hits[((o) >> 16) & 127]++)
#else
#define ROMHIT(o) ((void)0)
#endif
#define SEXT(v, bits) ((uint32_t)(((uint32_t)(v) ^ (1u << ((bits) - 1))) - (1u << ((bits) - 1))))
static inline uint8_t *f_ramp(Emu *e, uint32_t a, uint32_t n)
{
if (a <= A0RAM_MAX - n) return e->a0ram + a;
uint32_t o = a - 0x80000u;
if (o <= IVRAM_MAX - n) return e->ivram + o;
o = a - 0x84000u;
if (o <= DSTRAM_MAX - n) return e->dstram + o;
return 0;
}
#ifdef TC_JIT
/* Write to RAM that has already been translated: discard all translations */
#ifdef JIT_WHOT
/* v0.9.6: a0ram pages whose code keeps getting overwritten (iD L, Connect to Plus Color: code at 0xC00
* next to its data) are no longer translated. Before, every write threw away all translations, thousands
* of times per second, and the emulator stood still on the device. */
uint8_t jit_wcnt[128], jit_nojit[128];
uint64_t jit_wwin, jit_nojit_at;
#define JIT_WWIN 2000000u /* window for counting (about 0.1 s of guest time) */
#define JIT_NOJIT 100000000u /* after about 5 s the pages get another chance */
static void jit_cw_note(Emu *e, uint32_t a, uint32_t n)
{
if (e->cycles - jit_wwin > JIT_WWIN) { memset(jit_wcnt, 0, sizeof jit_wcnt); jit_wwin = e->cycles; }
for (uint32_t p = a >> 8; p <= ((a + n - 1) >> 8) && p < 128u; p++)
if (e->jit_map[p] && ++jit_wcnt[p] >= 8u) { jit_nojit[p] = 1; jit_wcnt[p] = 0; jit_nojit_at = e->cycles; }
}
static int jit_nojit_pc(Emu *e, uint32_t pc)
{
if (!jit_nojit[pc >> 8]) return 0;
if (e->cycles - jit_nojit_at > JIT_NOJIT) { memset(jit_nojit, 0, sizeof jit_nojit); return 0; }
return 1;
}
#else
#define jit_cw_note(e, a, n) ((void)0)
#endif
__attribute__((noinline)) static void jit_cw_chk(Emu *e, uint32_t a, uint32_t n)
{
if (e->jit_map[a >> 8] | e->jit_map[(a + n - 1) >> 8]) { jit_cw_note(e, a, n); e->jit_flush = 1; memset(e->jit_map, 0, sizeof e->jit_map); }
}
#endif
#ifdef TC_STATS
void stat_acc(uint32_t a, int w);
#define FST(a, w) stat_acc((a), (w))
#else
#define FST(a, w) ((void)0)
#endif
static inline uint32_t f_rd8(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 1); if (p) return *p;
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) return b[o & 0xFFFFu]; }
return mem_read8(e, a);
}
static inline uint32_t f_rd16(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 2); if (p) return (uint32_t)(p[0] | (p[1] << 8));
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFEu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)(q[0] | (q[1] << 8)); } }
return mem_read16(e, a);
}
static inline uint32_t f_rd32(Emu *e, uint32_t a)
{
FST(a, 0);
uint8_t *p = f_ramp(e, a, 4); if (p) return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
uint32_t o = a - e->dev.rom_base;
if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFCu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)q[0] | ((uint32_t)q[1] << 8) | ((uint32_t)q[2] << 16) | ((uint32_t)q[3] << 24); } }
return mem_read32(e, a);
}
static inline void f_wr8(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 1); if (p) *p = (uint8_t)v; else mem_write8(e, a, (uint8_t)v); }
static inline void f_wr16(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 2); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } else mem_write16(e, a, (uint16_t)v); }
static inline void f_wr32(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 4); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } else mem_write32(e, a, v); }
/* Flags in one word: bit3 N, bit2 Z, bit1 V, bit0 C */
#define FN (fl >> 3 & 1)
#define FZ (fl >> 2 & 1)
#define FV (fl >> 1 & 1)
#define FC (fl & 1)
#define NZ(r) do { uint32_t _r = (r); fl = (fl & 3u) | ((_r >> 31) << 3) | ((uint32_t)(_r == 0) << 2); } while (0)
#define SCARRY(a, b) ((((~((a) ^ (b))) & ((a) ^ ((a) + (b)))) >> 31))
#define SBORROW(a, b) (((((a) ^ (b)) & ((a) ^ ((a) - (b)))) >> 31))
#define PUSH(v) do { sp -= 4; WR32(sp, (v)); } while (0)
#define POP() (sp += 4, f_rd32(e, sp - 4))
#define PSR_PACK() ((e->psr_rest & ~0xF1Fu) | FN | (FZ << 1) | (FV << 2) | (FC << 3) | ((uint32_t)e->f_ie << 4) | ((uint32_t)(e->il & 0xF) << 8))
#define PSR_UNPACK(v) do { uint32_t _v = (v); fl = ((_v & 1) << 3) | (((_v >> 1) & 1) << 2) | (((_v >> 2) & 1) << 1) | ((_v >> 3) & 1); \
e->f_ie = (_v >> 4) & 1; e->il = (_v >> 8) & 0xF; e->psr_rest = _v; chk = 1; } while (0)
static inline uint32_t op_add(uint32_t a, uint32_t b, uint32_t *fl)
{ uint32_t r = a + b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SCARRY(a, b) << 1) | (uint32_t)(r < a); return r; }
static inline uint32_t op_sub(uint32_t a, uint32_t b, uint32_t *fl)
{ uint32_t r = a - b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SBORROW(a, b) << 1) | (uint32_t)(a < b); return r; }
#define ADD(a, b) op_add((a), (b), &fl)
#define SUB(a, b) op_sub((a), (b), &fl)
#define CMP(a, b) ((void)op_sub((a), (b), &fl))
#define LOG(r) ({ uint32_t _q = (r); fl = (fl & 1u) | ((_q >> 31) << 3) | ((uint32_t)(_q == 0) << 2); _q; })
/* Deferred jump effect after the delay slot */
enum { D_NONE, D_JP, D_CALL, D_RET };
static inline int cond_ok(int op, uint32_t fl)
{
uint32_t fn = fl >> 3 & 1, fz = fl >> 2 & 1, fv = fl >> 1 & 1, fc = fl & 1;
switch (op) {
case 4: return !fz && fn == fv;
case 5: return fn == fv;
case 6: return fn != fv;
case 7: return fz || fn != fv;
case 8: return !fz && !fc;
case 9: return !fc;
case 10: return fc;
case 11: return fz || fc;
case 12: return fz;
case 13: return !fz;
default: return 1;
}
}
static int pc_ok(Emu *e, uint32_t a)
{
const DeviceProfile *d = &e->dev;
return a - d->rom_base < d->rom_size || a - d->a0ram_base < d->a0ram_size ||
a - d->ivram_base < d->ivram_size || a - d->dstram_base < d->dstram_size;
}
/* Runs until cycles >= ziel (target), or the CPU sleeps or stops. Peripherals
* are ticked every TICK cycles. */
#define TICK 256
__attribute__((minsize)) void tc_exec(Emu *e, uint64_t ziel)
{
uint32_t pc = e->pc, sp = e->sp;
uint32_t fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c;
int32_t left;
#define CYC() (e->evt - (uint64_t)(int64_t)left)
#define r (e->r)
const uint8_t *fwp = e->fw_ptr; uint32_t fwlo = e->fw_lo, fwlen = e->fw_len;
int slot = 0;
#define dkind (e->ext_count)
#define dtarget (e->ext_val[0])
dkind = D_NONE;
#define SYNC_OUT() do { e->pc = pc; e->sp = sp; e->f_n = FN; e->f_z = FZ; e->f_v = FV; e->f_c = FC; e->cycles = CYC(); } while (0)
#define SYNC_IN() do { pc = e->pc; sp = e->sp; fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c; left = (int32_t)(e->evt - e->cycles); \
fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len; } while (0)
/* Write to RAM that has already been translated: discard all translations */
#ifdef TC_JIT
#define JCW(a, n) do { if ((a) <= A0RAM_MAX - (n)) jit_cw_chk(e, (a), (n)); } while (0)
#else
#define JCW(a, n) ((void)0)
#endif
#define WR8(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 1); if (_p) { *_p = (uint8_t)_v; JCW(_a, 1); } \
else { SYNC_OUT(); mem_write8(e, _a, (uint8_t)_v); SYNC_IN(); chk = 1; } } while (0)
#define WR16(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 2); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); JCW(_a, 2); } \
else { SYNC_OUT(); mem_write16(e, _a, (uint16_t)_v); SYNC_IN(); chk = 1; } } while (0)
#define WR32(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 4); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); _p[2] = (uint8_t)(_v >> 16); _p[3] = (uint8_t)(_v >> 24); JCW(_a, 4); } \
else { SYNC_OUT(); mem_write32(e, _a, _v); SYNC_IN(); chk = 1; } } while (0)
#define NEXT_EVT(c) do { uint64_t _n = (e->last_tick + TICK < ziel) ? e->last_tick + TICK : ziel; e->evt = _n; left = (int32_t)(_n - (c)); } while (0)
#define FORCE_EVT() do { uint64_t _c = CYC(); e->evt = _c; left = 0; } while (0)
NEXT_EVT(e->cycles);
int chk = 1; /* check for interrupts (after peripherals, I/O, PSR) */
if (e->halted || e->stopped) goto out;
for (;;) {
int in_slot = slot; slot = 0;
if (!in_slot && chk) {
chk = 0;
if (e->pending_irq && e->f_ie && e->pending_level > e->il) {
uint32_t vec = e->pending_irq;
PUSH(pc);
PUSH(PSR_PACK());
e->f_ie = 0;
e->il = e->pending_level;
pc = f_rd32(e, e->ttbr + vec * 4);
e->pending_irq = 0;
}
}
/* Fetch */
if (pc - fwlo >= fwlen) {
pc &= 0x0FFFFFFFu;
if (!pc_ok(e, pc)) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = pc; break; }
tc_fetch_window(e, pc); fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len;
}
#define FETCH(a) ((a) - fwlo < fwlen ? *(const uint16_t *)(fwp + ((a) - fwlo)) : (uint16_t)f_rd16(e, (a)))
uint32_t hw = FETCH(pc);
int ext_n = 0; uint32_t ext0 = 0, ext1 = 0;
while ((hw >> 13) == 6) {
if (ext_n == 0) ext0 = hw & 0x1FFF; else if (ext_n == 1) ext1 = hw & 0x1FFF;
ext_n++;
pc += 2; left--;
hw = FETCH(pc);
if (ext_n > 2) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = hw; goto out; }
}
if (ext_n > 2) ext_n = 2;
uint32_t iaddr = pc;
pc += 2; left--;
int rd = hw & 0xF, rs = (hw >> 4) & 0xF;
switch (hw >> 13) {
case 0: {
int op1 = (hw >> 9) & 0xF, d = (hw >> 8) & 1;
if (op1 <= 3) {
int cnst = (hw >> 4) & 3;
if (cnst == 0) {
int op2 = (hw >> 6) & 3;
switch (op1 * 8 + d * 4 + op2) {
case 0: break;
case 1: e->halted = true; e->halt_hard = !(e->cmu.opt & 0x3E00); e->wake_at = CYC() + 20000; FORCE_EVT(); break;
case 2: e->halted = true; e->halt_hard = true; FORCE_EVT(); break;
case 8: for (int i = rd; i >= 0; i--) PUSH(r[i]); break;
case 9: for (int i = 0; i <= rd; i++) r[i] = POP(); break;
case 11: pc = iaddr + r[rd]; break;
case 15: dkind = D_JP; dtarget = iaddr + r[rd]; slot = 1; break;
case 16: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
case 17: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
case 18: { uint32_t vec = 12 + (hw & 3);
PUSH(pc); PUSH(PSR_PACK()); e->f_ie = 0;
pc = f_rd32(e, e->ttbr + vec * 4); break; }
case 19: { PSR_UNPACK(POP()); pc = POP(); break; }
case 24: { uint32_t t = r[rd]; PUSH(pc); pc = t; break; }
case 25: pc = POP(); break;
case 26: pc = r[rd]; break;
case 28: dkind = D_CALL; dtarget = r[rd]; slot = 1; break;
case 29: dkind = D_RET; slot = 1; break;
case 30: dkind = D_JP; dtarget = r[rd]; slot = 1; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
} else if (cnst == 1 && op1 == 0) {
switch ((hw >> 6) & 7) {
case 0: PUSH(r[rd]); break;
case 1: r[rd] = POP(); break;
case 2: if ((hw & 0xF) == 2) PUSH(e->alr);
else if ((hw & 0xF) == 3) { PUSH(e->ahr); PUSH(e->alr); }
else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break;
case 3: if ((hw & 0xF) == 2) e->alr = POP();
else if ((hw & 0xF) == 3) { e->alr = POP(); e->ahr = POP(); }
else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break;
case 7: fl = 0; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
} else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; }
} else {
uint32_t u8 = hw & 0xFF, target;
if (ext_n == 0) target = iaddr + SEXT(u8, 8) * 2;
else if (ext_n == 1) target = iaddr + ((SEXT(ext0, 13) << 9) | (u8 << 1));
else target = iaddr + (((ext0 & 0x1ff8) << 19) | (ext1 << 9) | (u8 << 1));
if (in_slot) break; /* branch in a delay slot: ignored, like the original */
if (op1 == 14) {
if (d) { dkind = D_CALL; dtarget = target; slot = 1; }
else { PUSH(pc); pc = target; }
} else if (op1 == 15) {
if (d) { dkind = D_JP; dtarget = target; slot = 1; } else pc = target;
} else {
int taken = cond_ok(op1, fl);
if (d) { dkind = taken ? D_JP : D_NONE; dtarget = target; slot = 1; }
else if (taken) pc = target;
}
}
break;
}
case 1: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
if (op2 == 3) {
uint32_t n = ((hw >> 4) & 0xF) + 16, a = r[rd], q;
switch (op1) {
case 0: q = a >> n; break;
case 1: case 3: q = a << n; break;
case 2: q = (uint32_t)((int32_t)a >> n); break;
case 4: q = (a >> n) | (a << (32 - n)); break;
case 5: q = (a << n) | (a >> (32 - n)); break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; q = a; break;
}
r[rd] = q; NZ(q);
break;
}
if (op2 == 2) {
uint32_t imm = (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
switch (op1) {
case 0: r[rd] = ext_n ? ADD(r[rs], imm) : ADD(r[rd], r[rs]); break;
case 1: r[rd] = ext_n ? SUB(r[rs], imm) : SUB(r[rd], r[rs]); break;
case 2: if (ext_n) CMP(r[rs], imm); else CMP(r[rd], r[rs]); break;
case 3: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = r[rs]; break;
case 4: r[rd] = ext_n ? LOG(r[rs] & imm) : LOG(r[rd] & r[rs]); break;
case 5: r[rd] = ext_n ? LOG(r[rs] | imm) : LOG(r[rd] | r[rs]); break;
case 6: r[rd] = ext_n ? LOG(r[rs] ^ imm) : LOG(r[rd] ^ r[rs]); break;
case 7: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = LOG(~r[rs]); break;
}
break;
}
{
uint32_t addr = r[rs];
int postinc = (op2 == 1);
if (ext_n) {
if (postinc) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; }
addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
}
switch (op1) {
case 0: r[rd] = SEXT(f_rd8(e, addr), 8); if (postinc) r[rs] += 1; break;
case 1: r[rd] = f_rd8(e, addr); if (postinc) r[rs] += 1; break;
case 2: r[rd] = SEXT(f_rd16(e, addr), 16); if (postinc) r[rs] += 2; break;
case 3: r[rd] = f_rd16(e, addr); if (postinc) r[rs] += 2; break;
case 4: r[rd] = f_rd32(e, addr); if (postinc) r[rs] += 4; break;
case 5: WR8(addr, r[rd]); if (postinc) r[rs] += 1; break;
case 6: WR16(addr, r[rd]); if (postinc) r[rs] += 2; break;
case 7: WR32(addr, r[rd]); if (postinc) r[rs] += 4; break;
}
break;
}
}
case 2: {
int op1 = (hw >> 10) & 7;
uint32_t imm6 = (hw >> 4) & 0x3F, off;
if (ext_n == 0) { static const uint8_t scale[8] = {1,1,2,2,4,1,2,4}; off = imm6 * scale[op1]; }
else if (ext_n == 1) off = (ext0 << 6) | imm6;
else off = (ext0 << 19) | (ext1 << 6) | imm6;
uint32_t addr = sp + off;
switch (op1) {
case 0: r[rd] = SEXT(f_rd8(e, addr), 8); break;
case 1: r[rd] = f_rd8(e, addr); break;
case 2: r[rd] = SEXT(f_rd16(e, addr), 16); break;
case 3: r[rd] = f_rd16(e, addr); break;
case 4: r[rd] = f_rd32(e, addr); break;
case 5: WR8(addr, r[rd]); break;
case 6: WR16(addr, r[rd]); break;
case 7: WR32(addr, r[rd]); break;
}
break;
}
case 3: {
int op1 = (hw >> 10) & 7;
uint32_t imm6 = (hw >> 4) & 0x3F, imm;
if (ext_n == 0) imm = (op1 == 0 || op1 == 1) ? imm6 : SEXT(imm6, 6);
else if (ext_n == 1) { imm = (ext0 << 6) | imm6; if (!(op1 == 0 || op1 == 1)) imm = SEXT(imm, 19); }
else imm = (ext0 << 19) | (ext1 << 6) | imm6;
switch (op1) {
case 0: r[rd] = ADD(r[rd], imm); break;
case 1: r[rd] = SUB(r[rd], imm); break;
case 2: CMP(r[rd], imm); break;
case 3: r[rd] = imm; break;
case 4: r[rd] = LOG(r[rd] & imm); break;
case 5: r[rd] = LOG(r[rd] | imm); break;
case 6: r[rd] = LOG(r[rd] ^ imm); break;
case 7: r[rd] = LOG(~imm); break;
}
break;
}
case 4: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
if (op1 == 0) { sp += (uint32_t)(hw & 0x3FF) * 4; break; }
if (op1 == 1) { sp -= (uint32_t)(hw & 0x3FF) * 4; break; }
uint32_t amt = ((op2 == 0) ? ((hw >> 4) & 0xF) : r[rs]) & 31, a = r[rd], q;
switch (op1) {
case 2: q = a >> amt; r[rd] = q; NZ(q); break;
case 3: case 5: q = a << amt; r[rd] = q; NZ(q); break;
case 4:
if (op2 == 2) { uint32_t v = r[rs]; r[rd] = (v << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24); }
else { q = (uint32_t)((int32_t)a >> amt); r[rd] = q; NZ(q); }
break;
case 6:
if (op2 == 2) { uint32_t v = r[rs];
r[rd] = ((v & 0x00FF0000) << 8) | ((v >> 8) & 0x00FF0000) | ((v & 0x000000FF) << 8) | ((v >> 8) & 0x000000FF); }
else { q = amt ? ((a >> amt) | (a << (32 - amt))) : a; r[rd] = q; NZ(q); }
break;
case 7: q = amt ? ((a << amt) | (a >> (32 - amt))) : a; r[rd] = q; NZ(q); break;
}
break;
}
case 5: {
int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3;
switch (op1 * 4 + op2) {
case 0: { uint32_t v = r[rs];
switch (hw & 0xF) {
case 0: PSR_UNPACK(v); break;
case 1: sp = v; break;
case 2: e->alr = v; break;
case 3: e->ahr = v; break;
case 8: e->ttbr = v; break;
case 10: e->idir = v; break;
case 11: e->dbbr = v; break;
case 15: pc = v; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break;
} break; }
case 1: r[rd] = SEXT(r[rs] & 0xFF, 8); break;
case 2: e->alr = (uint32_t)((int32_t)SEXT(r[rd] & 0xFFFF, 16) * (int32_t)SEXT(r[rs] & 0xFFFF, 16)); break;
case 4: {
uint32_t v;
switch (rs) {
case 0: v = PSR_PACK(); break;
case 1: v = sp; break;
case 2: v = e->alr; break;
case 3: v = e->ahr; break;
case 8: v = e->ttbr; break;
case 10: v = e->idir; break;
case 11: v = e->dbbr; break;
case 15: v = iaddr; break;
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; v = 0; break;
}
r[rd] = v; break; }
case 5: r[rd] = r[rs] & 0xFF; break;
case 6: e->alr = (r[rd] & 0xFFFF) * (r[rs] & 0xFFFF); break;
case 8: case 12: case 16: case 20: {
uint32_t addr = r[rs];
if (ext_n) addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1);
int pos = hw & 7;
uint32_t b = f_rd8(e, addr);
switch (op1) {
case 2: fl = (fl & ~4u) | ((uint32_t)(((b >> pos) & 1) == 0) << 2); break;
case 3: WR8(addr, b & ~(1u << pos)); break;
case 4: WR8(addr, b | (1u << pos)); break;
case 5: WR8(addr, b ^ (1u << pos)); break;
}
break; }
case 9: r[rd] = SEXT(r[rs] & 0xFFFF, 16); break;
case 10: { int64_t p = (int64_t)(int32_t)r[rd] * (int32_t)r[rs];
e->alr = (uint32_t)p; e->ahr = (uint32_t)((uint64_t)p >> 32); break; }
case 13: r[rd] = r[rs] & 0xFFFF; break;
case 14: { uint64_t p = (uint64_t)r[rd] * r[rs]; e->alr = (uint32_t)p; e->ahr = (uint32_t)(p >> 32); break; }
case 17: case 21: break;
case 24: { uint32_t a = r[rd], b = r[rs], cz = FC, s = a + b;
uint32_t v = SCARRY(a, b) ^ SCARRY(s, cz), c = (s < a) || ((s + cz) < s);
uint32_t q = s + cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; }
case 28: { uint32_t a = r[rd], b = r[rs], cz = FC, dd = a - b;
uint32_t v = SBORROW(a, b) || SBORROW(dd, cz), c = (a < b) || (dd < cz);
uint32_t q = dd - cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; }
case 31: {
int op3 = (hw >> 6) & 3, imm5 = hw & 0x1F;
if (op3 == 0) break;
if (op3 == 1 || op3 == 2) {
int val = (op3 == 1);
switch (imm5) {
case 0: fl = (fl & ~8u) | ((uint32_t)val << 3); break;
case 1: fl = (fl & ~4u) | ((uint32_t)val << 2); break;
case 2: fl = (fl & ~2u) | ((uint32_t)val << 1); break;
case 3: fl = (fl & ~1u) | (uint32_t)val; break;
case 4: e->f_ie = val; chk = 1; break;
default: break;
}
break;
}
e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; }
default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
break;
}
default:
e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break;
}
if (in_slot) {
int k = dkind; dkind = D_NONE;
if (k == D_JP) pc = dtarget;
else if (k == D_CALL) { PUSH(pc); pc = dtarget; }
else if (k == D_RET) pc = POP();
}
if (left <= 0 && !slot) {
uint64_t cyc = CYC();
if (e->halted || e->stopped) break;
if (cyc - e->last_tick >= TICK) {
SYNC_OUT();
periph_tick(e, (uint32_t)(cyc - e->last_tick));
e->last_tick = cyc;
SYNC_IN();
chk = 1;
}
if (cyc >= ziel) break;
NEXT_EVT(cyc);
}
}
out:
#undef r
SYNC_OUT();
e->fw_ptr = fwp; e->fw_lo = fwlo; e->fw_len = fwlen;
}
#ifndef TC_WITH_REF
void cpu_reset(Emu *e)
{
memset(e->r, 0, sizeof e->r);
e->sp = 0; e->alr = e->ahr = 0;
e->ttbr = e->dev.ttbr_reset;
e->idir = e->dbbr = 0;
e->f_n = e->f_z = e->f_v = e->f_c = e->f_ie = 0;
e->il = 0; e->psr_rest = 0;
e->ext_count = 0;
e->halted = false; e->halt_hard = false;
e->stopped = false;
e->pc = mem_read32(e, e->ttbr);
}
#endif
+1793 -1793
View File
File diff suppressed because it is too large. Load diff
+90 -90
View File
@@ -1,90 +1,90 @@
/* LCD controller of the colour Tamagotchi, based on tamaemu lcd.c. Tracks the
* changed area so only that part is sent to the Paradise panel. */
#include "tc.h"
static void finish_cmd(Emu *e)
{
Lcd *l = &e->lcd;
switch (l->cmd) {
case 0x2A: if (l->argc >= 4) { l->xs = (l->args[0] << 8) | l->args[1];
l->xe = (l->args[2] << 8) | l->args[3];
l->cx = l->xs; } break;
case 0x2B: if (l->argc >= 4) { l->ys = (l->args[0] << 8) | l->args[1];
l->ye = (l->args[2] << 8) | l->args[3];
l->cy = l->ys; } break;
default: break;
}
}
#ifdef LCD_ROWS
/* v0.8.19: additionally the changed range per row (outside of Emu, so the save format stays the same).
* lcd_rall: redraw the whole frame (commands like invert, sleep). */
uint8_t lcd_rx0[GRAM_H], lcd_rx1[GRAM_H], lcd_rall = 1;
#endif
static void mark(Lcd *l, int x, int y)
{
if (x < l->dx0) l->dx0 = x;
if (x > l->dx1) l->dx1 = x;
if (y < l->dy0) l->dy0 = y;
if (y > l->dy1) l->dy1 = y;
#ifdef LCD_ROWS
if ((unsigned)y < GRAM_H) { if (x < lcd_rx0[y]) lcd_rx0[y] = (uint8_t)x; if (x > lcd_rx1[y]) lcd_rx1[y] = (uint8_t)x; }
#endif
}
static void mark_all(Lcd *l)
{
mark(l, 0, 0); mark(l, 127, 127);
#ifdef LCD_ROWS
lcd_rall = 1;
#endif
}
void lcd_cmd(Emu *e, uint8_t c)
{
Lcd *l = &e->lcd;
#ifdef LCDCMD_DEBUG
if(c==1||c==0x10||c==0x11||c==0x28||c==0x29) printf("LCDCMD %02x at %.3f\n", c, (double)e->cycles/e->dev.osc3_hz);
#endif
finish_cmd(e);
l->cmd = c; l->argc = 0; l->pix_n = 0;
switch (c) {
case 0x01: l->madctl = 0; l->sleep_out = false; l->disp_on = false; l->inverted = false;
l->xs = 0; l->xe = 131; l->ys = 0; l->ye = 161; break;
case 0x10: l->sleep_out = false; mark_all(l); break;
case 0x11: l->sleep_out = true; mark_all(l); break;
case 0x20: l->inverted = false; mark_all(l); break;
case 0x21: l->inverted = true; mark_all(l); break;
case 0x28: l->disp_on = false; mark_all(l); break;
case 0x29: l->disp_on = true; mark_all(l); break;
case 0x2C: l->cx = l->xs; l->cy = l->ys; break;
default: break;
}
}
void lcd_data(Emu *e, uint8_t d)
{
Lcd *l = &e->lcd;
if (l->cmd == 0x2C) {
int bpp = ((l->colmod & 0x0F) == 0x05) ? 2 : 3;
l->pix_buf[l->pix_n++] = d;
if (l->pix_n >= bpp) {
uint16_t p;
if (bpp == 2) p = (uint16_t)((l->pix_buf[0] << 8) | l->pix_buf[1]);
else {
uint32_t r6 = l->pix_buf[0] >> 2, g6 = l->pix_buf[1] >> 2, b6 = l->pix_buf[2] >> 2;
p = (uint16_t)(((r6 >> 1) << 11) | (g6 << 5) | (b6 >> 1));
}
l->pix_n = 0;
int x = l->cx, y = l->cy;
if (x >= 0 && x < GRAM_W && y >= 0 && y < GRAM_H) {
if (l->gram[y][x] != p) { l->gram[y][x] = p; mark(l, x, y); }
}
if (++l->cx > l->xe) { l->cx = l->xs; if (++l->cy > l->ye) l->cy = l->ys; }
}
return;
}
if (l->argc < 16) l->args[l->argc] = d;
l->argc++;
if (l->cmd == 0x36 && l->argc == 1) { l->madctl = d; mark_all(l); }
if (l->cmd == 0x3A && l->argc == 1) l->colmod = d;
}
/* LCD controller of the colour Tamagotchi, based on tamaemu lcd.c. Tracks the
* changed area so only that part is sent to the Paradise panel. */
#include "tc.h"
static void finish_cmd(Emu *e)
{
Lcd *l = &e->lcd;
switch (l->cmd) {
case 0x2A: if (l->argc >= 4) { l->xs = (l->args[0] << 8) | l->args[1];
l->xe = (l->args[2] << 8) | l->args[3];
l->cx = l->xs; } break;
case 0x2B: if (l->argc >= 4) { l->ys = (l->args[0] << 8) | l->args[1];
l->ye = (l->args[2] << 8) | l->args[3];
l->cy = l->ys; } break;
default: break;
}
}
#ifdef LCD_ROWS
/* v0.8.19: additionally the changed range per row (outside of Emu, so the save format stays the same).
* lcd_rall: redraw the whole frame (commands like invert, sleep). */
uint8_t lcd_rx0[GRAM_H], lcd_rx1[GRAM_H], lcd_rall = 1;
#endif
static void mark(Lcd *l, int x, int y)
{
if (x < l->dx0) l->dx0 = x;
if (x > l->dx1) l->dx1 = x;
if (y < l->dy0) l->dy0 = y;
if (y > l->dy1) l->dy1 = y;
#ifdef LCD_ROWS
if ((unsigned)y < GRAM_H) { if (x < lcd_rx0[y]) lcd_rx0[y] = (uint8_t)x; if (x > lcd_rx1[y]) lcd_rx1[y] = (uint8_t)x; }
#endif
}
static void mark_all(Lcd *l)
{
mark(l, 0, 0); mark(l, 127, 127);
#ifdef LCD_ROWS
lcd_rall = 1;
#endif
}
void lcd_cmd(Emu *e, uint8_t c)
{
Lcd *l = &e->lcd;
#ifdef LCDCMD_DEBUG
if(c==1||c==0x10||c==0x11||c==0x28||c==0x29) printf("LCDCMD %02x at %.3f\n", c, (double)e->cycles/e->dev.osc3_hz);
#endif
finish_cmd(e);
l->cmd = c; l->argc = 0; l->pix_n = 0;
switch (c) {
case 0x01: l->madctl = 0; l->sleep_out = false; l->disp_on = false; l->inverted = false;
l->xs = 0; l->xe = 131; l->ys = 0; l->ye = 161; break;
case 0x10: l->sleep_out = false; mark_all(l); break;
case 0x11: l->sleep_out = true; mark_all(l); break;
case 0x20: l->inverted = false; mark_all(l); break;
case 0x21: l->inverted = true; mark_all(l); break;
case 0x28: l->disp_on = false; mark_all(l); break;
case 0x29: l->disp_on = true; mark_all(l); break;
case 0x2C: l->cx = l->xs; l->cy = l->ys; break;
default: break;
}
}
void lcd_data(Emu *e, uint8_t d)
{
Lcd *l = &e->lcd;
if (l->cmd == 0x2C) {
int bpp = ((l->colmod & 0x0F) == 0x05) ? 2 : 3;
l->pix_buf[l->pix_n++] = d;
if (l->pix_n >= bpp) {
uint16_t p;
if (bpp == 2) p = (uint16_t)((l->pix_buf[0] << 8) | l->pix_buf[1]);
else {
uint32_t r6 = l->pix_buf[0] >> 2, g6 = l->pix_buf[1] >> 2, b6 = l->pix_buf[2] >> 2;
p = (uint16_t)(((r6 >> 1) << 11) | (g6 << 5) | (b6 >> 1));
}
l->pix_n = 0;
int x = l->cx, y = l->cy;
if (x >= 0 && x < GRAM_W && y >= 0 && y < GRAM_H) {
if (l->gram[y][x] != p) { l->gram[y][x] = p; mark(l, x, y); }
}
if (++l->cx > l->xe) { l->cx = l->xs; if (++l->cy > l->ye) l->cy = l->ys; }
}
return;
}
if (l->argc < 16) l->args[l->argc] = d;
l->argc++;
if (l->cmd == 0x36 && l->argc == 1) { l->madctl = d; mark_all(l); }
if (l->cmd == 0x3A && l->argc == 1) l->colmod = d;
}
+372 -372
View File
@@ -1,372 +1,372 @@
/* Memory map, based on tamaemu mem.c. ROM reads directly from the Paradise flash,
* written sectors are kept as a copy in RAM. */
#include "tc.h"
#define DEV const DeviceProfile *dev = &e->dev
#define FLASH_BUSY_READS 3
/* Sector for a ROM offset (top 64 KB: 8 KB sectors, otherwise 64 KB). */
static void sector_of(Emu *e, uint32_t off, uint32_t *base, uint32_t *size)
{
DEV;
if (dev->flash_top_boot && off >= dev->rom_size - 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; }
else if (!dev->flash_top_boot && off < 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; }
else { *base = off & ~0xFFFFu; *size = 0x10000; }
}
/* Pointer to the current byte (overlay or original). Erased
* blocks read 0xFF. */
static const uint8_t rom_ff[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
/* Start of the stored 8 KB part (0 = erased). */
static inline const uint8_t *rom_chunk(Emu *e, uint32_t base)
{
uint32_t b = (base >> 16) & 127u;
if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) {
uint8_t k = e->pg_map[(base >> 13) & 1023u];
return k == 0xFFu ? 0 : e->pg_base + (uint32_t)k * 0x2000u;
}
const uint8_t *p = e->rom_src[b];
return p ? p + (base & 0xE000u) : 0;
}
#ifdef TC_LZ
/* 1.7.3 GUEST_LZ: cold blocks of the firmware packed in 1 KB parts (LZ4 blocks, written by the Studio). A part the guest
* reads is unpacked into one of two 1 KB buffers in the RAM at 0x20000400 (free there: 0x20000000..0x400 belongs to the
* boot, the mailboxes are at 0x20000FC0). Table: 128 u32 offsets of the block's part list (0 = not packed), per block
* 65 u32 starts (same start as the next one = erased part, 1024 bytes = stored as is). Written parts (spare pages) win. */
const uint8_t *tc_lz_tab;
uint32_t tc_lz_gone[4]; /* packed blocks the guest erased: they read empty */
#define LZ_RAM ((uint8_t *)0x20000400u)
static uint32_t lz_tag[2], lz_rr; /* part number + 1 in each buffer (0 = empty) */
static uint32_t lz_n(const uint8_t **ps, uint32_t n)
{
if (n == 15u) { uint32_t x; do { x = *(*ps)++; n += x; } while (x == 255u); }
return n;
}
__attribute__((noinline, minsize)) static void lz_dec(uint8_t *d, const uint8_t *s)
{
uint8_t *end = d + 0x400u;
for (;;) {
uint32_t t = *s++, n = lz_n(&s, t >> 4);
while (n-- && d < end) *d++ = *s++;
if (d >= end) return;
const uint8_t *m = d - ((uint32_t)s[0] | ((uint32_t)s[1] << 8)); s += 2;
n = lz_n(&s, t & 15u) + 4u;
while (n-- && d < end) *d++ = *m++;
}
}
/* the 1 KB part at ROM offset off, unpacked (0 = the block is not packed) */
__attribute__((noinline, minsize)) static const uint8_t *lz_part(uint32_t off)
{
uint32_t b = (off >> 16) & 127u, tag = (off >> 10) + 1u;
const uint32_t *t = (const uint32_t *)tc_lz_tab;
if (!t || ((tc_lz_gone[b >> 5] >> (b & 31u)) & 1u) || !t[b]) return 0;
for (uint32_t k = 0; k < 2u; k++) if (lz_tag[k] == tag) return LZ_RAM + (k << 10);
const uint32_t *l = (const uint32_t *)(tc_lz_tab + t[b]) + ((off >> 10) & 63u);
uint32_t a = l[0], z = l[1], i = lz_rr; lz_rr ^= 1u;
uint8_t *d = LZ_RAM + (i << 10);
if (z == a) memset(d, 0xFF, 0x400u);
else if (z - a >= 0x400u) memcpy(d, tc_lz_tab + a, 0x400u);
else lz_dec(d, tc_lz_tab + a);
lz_tag[i] = tag;
return d;
}
/* an 8 KB copy for a written sector (0 = the block is not packed) */
__attribute__((noinline, minsize)) static int lz_fill(uint8_t *d, uint32_t base)
{
if (!lz_part(base)) return 0;
for (uint32_t k = 0; k < OVL_SIZE; k += 0x400u) memcpy(d + k, lz_part(base + k), 0x400u);
return 1;
}
#endif
static inline const uint8_t *rom_src_ptr(Emu *e, uint32_t off)
{
uint32_t b = (off >> 16) & 127u;
if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) {
const uint8_t *c = rom_chunk(e, off & ~0x1FFFu);
#ifdef TC_LZ
if (!c) { const uint8_t *z = lz_part(off); if (z) return z + (off & 0x3FFu); }
#endif
return c ? c + (off & 0x1FFFu) : rom_ff;
}
const uint8_t *p = e->rom_src[b];
return p ? p + (off & 0xFFFFu) : rom_ff;
}
/* Slow path: parameter block, written copies, spare pages, erased blocks. */
__attribute__((noinline)) static const uint8_t *rom_slow(Emu *e, uint32_t off)
{
for (int i = 0; i < e->ovl.n; i++)
if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]);
return rom_src_ptr(e, off);
}
/* rom_blk is set only for blocks without written copies (see tc_blk_update). */
static inline const uint8_t *rom_ptr(Emu *e, uint32_t off)
{
const uint8_t *b = e->rom_blk[(off >> 16) & 127u];
return b ? b + (off & 0xFFFFu) : rom_slow(e, off);
}
/* Get a writable copy of the sector (create it if needed). Only
* 8 KB sectors fit in a slot; writes to larger sectors are lost. */
int (*tc_ovl_evict)(Emu *e);
#ifdef TC_LZ
__attribute__((noinline, minsize)) /* 1.7.3: room for the unpacking (only when the guest writes its flash) */
#endif
static uint8_t *rom_wptr(Emu *e, uint32_t off)
{
for (int i = 0; i < e->ovl.n; i++)
if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]);
uint32_t base, size; sector_of(e, off, &base, &size);
if (size > OVL_SIZE) {
/* 64 KB sector: kept in 8 KB parts like the parameter sectors (v0.9.2). Before, these
* writes were lost and the guest could hang or crash (for example when buying an item). */
if (!tc_big_erase) { e->flash_lost_writes++; return 0; }
base = off & ~(OVL_SIZE - 1u);
}
for (int pass = 0; pass < 2; pass++) {
if (pass && !(tc_ovl_evict && tc_ovl_evict(e))) break;
for (int i = 0; i < OVL_SLOTS; i++)
if (e->ovl.mem[i] && e->ovl.base[i] == 0xFFFFFFFFu) {
e->ovl.base[i] = base;
{ const uint8_t *c = rom_chunk(e, base);
if (c) memcpy(e->ovl.mem[i], c, OVL_SIZE);
#ifdef TC_LZ
else if (lz_fill(e->ovl.mem[i], base)) {}
#endif
else memset(e->ovl.mem[i], 0xFF, OVL_SIZE); }
if (i >= e->ovl.n) e->ovl.n = i + 1;
if (base - e->par_base >= 0x10000u) {
uint32_t b = (base >> 16) & 127u;
e->ovl_blk[b >> 5] |= 1u << (b & 31u);
tc_blk_update(e, b);
}
#ifdef TC_JIT
else jit_rom_update(e, base);
#endif
return e->ovl.mem[i] + (off - base);
}
}
e->flash_lost_writes++;
return 0;
}
int (*tc_big_erase)(Emu *e, uint32_t base);
/* Fast read pointers of a 64 KB block: direct only while no written copy exists. */
__attribute__((noinline)) void tc_blk_update(Emu *e, uint32_t b)
{
b &= 127u;
if ((b << 16) - e->par_base < 0x10000u) return;
int busy = (int)(((e->ovl_blk[b >> 5] | e->pg_blk[b >> 5]) >> (b & 31u)) & 1u);
e->rom_blk[b] = busy ? 0 : e->rom_src[b];
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
#ifdef TC_JIT
jit_rom_update(e, b << 16);
e->jit_flush = 1; /* translated code may have read this block */
#endif
}
__attribute__((noinline)) void tc_ovl_free(Emu *e, int i)
{
uint32_t base = e->ovl.base[i];
if (base == 0xFFFFFFFFu) return;
e->ovl.base[i] = 0xFFFFFFFFu;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
if (base - e->par_base < 0x10000u) {
#ifdef TC_JIT
jit_rom_update(e, base);
#endif
return;
}
uint32_t b = (base >> 16) & 127u;
for (int k = 0; k < e->ovl.n; k++) if (e->ovl.base[k] != 0xFFFFFFFFu && ((e->ovl.base[k] >> 16) & 127u) == b) return;
e->ovl_blk[b >> 5] &= ~(1u << (b & 31u));
tc_blk_update(e, b);
}
static void flash_erase_sector(Emu *e, uint32_t off)
{
uint32_t base, size; sector_of(e, off, &base, &size);
uint8_t *p = 0;
if (size > OVL_SIZE) {
/* drop the written copies of this sector, then erase the backing store */
for (int i = 0; i < e->ovl.n; i++) if (e->ovl.base[i] - base < size) tc_ovl_free(e, i);
e->flash_big_ops++;
if (!(tc_big_erase && tc_big_erase(e, base))) e->flash_lost_writes++;
tc_blk_update(e, base >> 16);
} else p = rom_wptr(e, base);
if (p) memset(p, 0xFF, size);
e->flash_dirty = true;
e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
e->flash_op_data = 0xFFFF;
e->flash_toggle = false;
}
static uint16_t flash_status(Emu *e)
{
e->flash_toggle = !e->flash_toggle;
uint16_t s = 0;
if (!((e->flash_op_data >> 7) & 1)) s |= 0x80;
if (e->flash_toggle) s |= 0x40;
if (--e->flash_busy <= 0) e->flash_busy = 0;
return s;
}
static void flash_write(Emu *e, uint32_t a, uint32_t v, int size)
{
DEV;
uint32_t off = a - dev->rom_base;
uint8_t d = (uint8_t)v;
if (e->flash_state == 3) {
uint16_t final = 0;
for (int i = 0; i < size; i++) {
uint32_t o = (off + (uint32_t)i) & (dev->rom_size - 1);
uint8_t *p = rom_wptr(e, o);
uint8_t nb = p ? (*p &= (uint8_t)(v >> (8 * i))) : rom_ptr(e, o)[0];
final |= (uint16_t)nb << (8 * i);
}
e->flash_dirty = true;
e->flash_state = 0;
e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
e->flash_op_data = size >= 2 ? final : (uint16_t)(0xFF00 | final);
e->flash_toggle = false;
return;
}
if (d == 0xF0) { e->flash_state = 0; e->flash_autoselect = false; return; }
switch (e->flash_state) {
case 0: if (d == 0xAA) e->flash_state = 1; break;
case 1: e->flash_state = (d == 0x55) ? 2 : 0; break;
case 2:
if (d == 0xA0) e->flash_state = 3;
else if (d == 0x80) e->flash_state = 4;
else if (d == 0x90) { e->flash_autoselect = true; e->flash_state = 0; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; }
else e->flash_state = 0;
break;
case 4: e->flash_state = (d == 0xAA) ? 5 : 0; break;
case 5: e->flash_state = (d == 0x55) ? 6 : 0; break;
case 6:
if (d == 0x30) flash_erase_sector(e, off);
e->flash_state = 0; /* chip erase (0x10) is ignored */
break;
default: e->flash_state = 0; break;
}
}
static uint8_t flash_read8(Emu *e, uint32_t a)
{
DEV;
if (e->flash_busy) return (uint8_t)flash_status(e);
if (e->flash_autoselect) {
uint32_t w = (a - dev->rom_base) >> 1;
if ((w & 0xFF) == 0) return (a & 1) ? 0x00 : 0x01;
return (a & 1) ? 0x22 : 0xF6;
}
return *rom_ptr(e, a - dev->rom_base);
}
#ifdef LCDRD_DEBUG
extern uint32_t g_lcdrd, g_lcdrd_pc[16]; extern int g_np;
#endif
uint8_t mem_read8(Emu *e, uint32_t a)
{
DEV;
#ifdef LCDRD_DEBUG
if (a == dev->lcd_cmd_addr || a == dev->lcd_data_addr) { g_lcdrd++; int k; for (k = 0; k < g_np && g_lcdrd_pc[k] != e->pc; k++); if (k == g_np && g_np < 16) g_lcdrd_pc[g_np++] = e->pc; }
#endif
if (a - dev->rom_base < dev->rom_size) {
if (e->flash_busy || e->flash_autoselect) return flash_read8(e, a);
return *rom_ptr(e, a - dev->rom_base);
}
if (a - dev->a0ram_base < dev->a0ram_size) return e->a0ram[a - dev->a0ram_base];
if (a - dev->io_base < dev->io_size) return periph_read8(e, a);
if (a - dev->ivram_base < dev->ivram_size) return e->ivram[a - dev->ivram_base];
if (a - dev->dstram_base < dev->dstram_size) return e->dstram[a - dev->dstram_base];
return 0;
}
void mem_write8(Emu *e, uint32_t a, uint8_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size) { e->a0ram[a - dev->a0ram_base] = v; return; }
if (a == dev->lcd_cmd_addr) { e->lcd_writes++; lcd_cmd(e, v); return; }
if (a == dev->lcd_data_addr) { e->lcd_writes++; lcd_data(e, v); return; }
if (a - dev->io_base < dev->io_size) { periph_write8(e, a, v); return; }
if (a - dev->ivram_base < dev->ivram_size) { e->ivram[a - dev->ivram_base] = v; return; }
if (a - dev->dstram_base < dev->dstram_size) { e->dstram[a - dev->dstram_base] = v; return; }
if (a - dev->rom_base < dev->rom_size) { flash_write(e, a, v, 1); return; }
}
uint16_t mem_read16(Emu *e, uint32_t a)
{
DEV;
if (a - dev->rom_base < dev->rom_size - 1) {
if (e->flash_busy) return flash_status(e);
if (e->flash_autoselect)
return (uint16_t)(flash_read8(e, a) | (flash_read8(e, a + 1) << 8));
const uint8_t *p = rom_ptr(e, a - dev->rom_base);
return (uint16_t)(p[0] | (p[1] << 8));
}
if (a - dev->a0ram_base < dev->a0ram_size - 1) {
const uint8_t *p = e->a0ram + (a - dev->a0ram_base);
return (uint16_t)(p[0] | (p[1] << 8));
}
return (uint16_t)(mem_read8(e, a) | (mem_read8(e, a + 1) << 8));
}
uint32_t mem_read32(Emu *e, uint32_t a)
{
DEV;
if (a - dev->rom_base < dev->rom_size - 3) {
if (e->flash_busy || e->flash_autoselect)
return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16);
const uint8_t *p = rom_ptr(e, a - dev->rom_base);
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
if (a - dev->a0ram_base < dev->a0ram_size - 3) {
const uint8_t *p = e->a0ram + (a - dev->a0ram_base);
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
if (a - dev->io_base < dev->io_size - 3) return periph_read32(e, a);
return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16);
}
void mem_write16(Emu *e, uint32_t a, uint16_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size - 1) {
e->a0ram[a - dev->a0ram_base] = (uint8_t)v;
e->a0ram[a - dev->a0ram_base + 1] = (uint8_t)(v >> 8);
return;
}
if (a - dev->rom_base < dev->rom_size - 1) { flash_write(e, a, v, 2); return; }
mem_write8(e, a, (uint8_t)v);
mem_write8(e, a + 1, (uint8_t)(v >> 8));
}
void mem_write32(Emu *e, uint32_t a, uint32_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size - 3) {
uint8_t *p = e->a0ram + (a - dev->a0ram_base);
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
return;
}
if (a - dev->io_base < dev->io_size - 3) { periph_write32(e, a, v); return; }
if (a - dev->rom_base < dev->rom_size - 3) {
flash_write(e, a, v & 0xFFFF, 2);
flash_write(e, a + 2, v >> 16, 2);
return;
}
mem_write16(e, a, (uint16_t)v);
mem_write16(e, a + 2, (uint16_t)(v >> 16));
}
/* Set the instruction window for fast fetch (or clear it if none fits). */
void tc_fetch_window(Emu *e, uint32_t pc)
{
DEV;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
if (pc - dev->rom_base < dev->rom_size && !e->flash_busy && !e->flash_autoselect) {
/* 64 KB window of the block */
const uint8_t *b = e->rom_blk[(pc - dev->rom_base) >> 16];
if (!b) return;
e->fw_ptr = b; e->fw_lo = pc & ~0xFFFFu; e->fw_len = 0x10000u; return; }
if (pc - dev->a0ram_base < dev->a0ram_size) { e->fw_ptr = e->a0ram; e->fw_lo = dev->a0ram_base; e->fw_len = dev->a0ram_size; return; }
if (pc - dev->ivram_base < dev->ivram_size) { e->fw_ptr = e->ivram; e->fw_lo = dev->ivram_base; e->fw_len = dev->ivram_size; return; }
if (pc - dev->dstram_base < dev->dstram_size) { e->fw_ptr = e->dstram; e->fw_lo = dev->dstram_base; e->fw_len = dev->dstram_size; return; }
}
/* Memory map, based on tamaemu mem.c. ROM reads directly from the Paradise flash,
* written sectors are kept as a copy in RAM. */
#include "tc.h"
#define DEV const DeviceProfile *dev = &e->dev
#define FLASH_BUSY_READS 3
/* Sector for a ROM offset (top 64 KB: 8 KB sectors, otherwise 64 KB). */
static void sector_of(Emu *e, uint32_t off, uint32_t *base, uint32_t *size)
{
DEV;
if (dev->flash_top_boot && off >= dev->rom_size - 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; }
else if (!dev->flash_top_boot && off < 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; }
else { *base = off & ~0xFFFFu; *size = 0x10000; }
}
/* Pointer to the current byte (overlay or original). Erased
* blocks read 0xFF. */
static const uint8_t rom_ff[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
/* Start of the stored 8 KB part (0 = erased). */
static inline const uint8_t *rom_chunk(Emu *e, uint32_t base)
{
uint32_t b = (base >> 16) & 127u;
if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) {
uint8_t k = e->pg_map[(base >> 13) & 1023u];
return k == 0xFFu ? 0 : e->pg_base + (uint32_t)k * 0x2000u;
}
const uint8_t *p = e->rom_src[b];
return p ? p + (base & 0xE000u) : 0;
}
#ifdef TC_LZ
/* 1.7.3 GUEST_LZ: cold blocks of the firmware packed in 1 KB parts (LZ4 blocks, written by the Studio). A part the guest
* reads is unpacked into one of two 1 KB buffers in the RAM at 0x20000400 (free there: 0x20000000..0x400 belongs to the
* boot, the mailboxes are at 0x20000FC0). Table: 128 u32 offsets of the block's part list (0 = not packed), per block
* 65 u32 starts (same start as the next one = erased part, 1024 bytes = stored as is). Written parts (spare pages) win. */
const uint8_t *tc_lz_tab;
uint32_t tc_lz_gone[4]; /* packed blocks the guest erased: they read empty */
#define LZ_RAM ((uint8_t *)0x20000400u)
static uint32_t lz_tag[2], lz_rr; /* part number + 1 in each buffer (0 = empty) */
static uint32_t lz_n(const uint8_t **ps, uint32_t n)
{
if (n == 15u) { uint32_t x; do { x = *(*ps)++; n += x; } while (x == 255u); }
return n;
}
__attribute__((noinline, minsize)) static void lz_dec(uint8_t *d, const uint8_t *s)
{
uint8_t *end = d + 0x400u;
for (;;) {
uint32_t t = *s++, n = lz_n(&s, t >> 4);
while (n-- && d < end) *d++ = *s++;
if (d >= end) return;
const uint8_t *m = d - ((uint32_t)s[0] | ((uint32_t)s[1] << 8)); s += 2;
n = lz_n(&s, t & 15u) + 4u;
while (n-- && d < end) *d++ = *m++;
}
}
/* the 1 KB part at ROM offset off, unpacked (0 = the block is not packed) */
__attribute__((noinline, minsize)) static const uint8_t *lz_part(uint32_t off)
{
uint32_t b = (off >> 16) & 127u, tag = (off >> 10) + 1u;
const uint32_t *t = (const uint32_t *)tc_lz_tab;
if (!t || ((tc_lz_gone[b >> 5] >> (b & 31u)) & 1u) || !t[b]) return 0;
for (uint32_t k = 0; k < 2u; k++) if (lz_tag[k] == tag) return LZ_RAM + (k << 10);
const uint32_t *l = (const uint32_t *)(tc_lz_tab + t[b]) + ((off >> 10) & 63u);
uint32_t a = l[0], z = l[1], i = lz_rr; lz_rr ^= 1u;
uint8_t *d = LZ_RAM + (i << 10);
if (z == a) memset(d, 0xFF, 0x400u);
else if (z - a >= 0x400u) memcpy(d, tc_lz_tab + a, 0x400u);
else lz_dec(d, tc_lz_tab + a);
lz_tag[i] = tag;
return d;
}
/* an 8 KB copy for a written sector (0 = the block is not packed) */
__attribute__((noinline, minsize)) static int lz_fill(uint8_t *d, uint32_t base)
{
if (!lz_part(base)) return 0;
for (uint32_t k = 0; k < OVL_SIZE; k += 0x400u) memcpy(d + k, lz_part(base + k), 0x400u);
return 1;
}
#endif
static inline const uint8_t *rom_src_ptr(Emu *e, uint32_t off)
{
uint32_t b = (off >> 16) & 127u;
if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) {
const uint8_t *c = rom_chunk(e, off & ~0x1FFFu);
#ifdef TC_LZ
if (!c) { const uint8_t *z = lz_part(off); if (z) return z + (off & 0x3FFu); }
#endif
return c ? c + (off & 0x1FFFu) : rom_ff;
}
const uint8_t *p = e->rom_src[b];
return p ? p + (off & 0xFFFFu) : rom_ff;
}
/* Slow path: parameter block, written copies, spare pages, erased blocks. */
__attribute__((noinline)) static const uint8_t *rom_slow(Emu *e, uint32_t off)
{
for (int i = 0; i < e->ovl.n; i++)
if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]);
return rom_src_ptr(e, off);
}
/* rom_blk is set only for blocks without written copies (see tc_blk_update). */
static inline const uint8_t *rom_ptr(Emu *e, uint32_t off)
{
const uint8_t *b = e->rom_blk[(off >> 16) & 127u];
return b ? b + (off & 0xFFFFu) : rom_slow(e, off);
}
/* Get a writable copy of the sector (create it if needed). Only
* 8 KB sectors fit in a slot; writes to larger sectors are lost. */
int (*tc_ovl_evict)(Emu *e);
#ifdef TC_LZ
__attribute__((noinline, minsize)) /* 1.7.3: room for the unpacking (only when the guest writes its flash) */
#endif
static uint8_t *rom_wptr(Emu *e, uint32_t off)
{
for (int i = 0; i < e->ovl.n; i++)
if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]);
uint32_t base, size; sector_of(e, off, &base, &size);
if (size > OVL_SIZE) {
/* 64 KB sector: kept in 8 KB parts like the parameter sectors (v0.9.2). Before, these
* writes were lost and the guest could hang or crash (for example when buying an item). */
if (!tc_big_erase) { e->flash_lost_writes++; return 0; }
base = off & ~(OVL_SIZE - 1u);
}
for (int pass = 0; pass < 2; pass++) {
if (pass && !(tc_ovl_evict && tc_ovl_evict(e))) break;
for (int i = 0; i < OVL_SLOTS; i++)
if (e->ovl.mem[i] && e->ovl.base[i] == 0xFFFFFFFFu) {
e->ovl.base[i] = base;
{ const uint8_t *c = rom_chunk(e, base);
if (c) memcpy(e->ovl.mem[i], c, OVL_SIZE);
#ifdef TC_LZ
else if (lz_fill(e->ovl.mem[i], base)) {}
#endif
else memset(e->ovl.mem[i], 0xFF, OVL_SIZE); }
if (i >= e->ovl.n) e->ovl.n = i + 1;
if (base - e->par_base >= 0x10000u) {
uint32_t b = (base >> 16) & 127u;
e->ovl_blk[b >> 5] |= 1u << (b & 31u);
tc_blk_update(e, b);
}
#ifdef TC_JIT
else jit_rom_update(e, base);
#endif
return e->ovl.mem[i] + (off - base);
}
}
e->flash_lost_writes++;
return 0;
}
int (*tc_big_erase)(Emu *e, uint32_t base);
/* Fast read pointers of a 64 KB block: direct only while no written copy exists. */
__attribute__((noinline)) void tc_blk_update(Emu *e, uint32_t b)
{
b &= 127u;
if ((b << 16) - e->par_base < 0x10000u) return;
int busy = (int)(((e->ovl_blk[b >> 5] | e->pg_blk[b >> 5]) >> (b & 31u)) & 1u);
e->rom_blk[b] = busy ? 0 : e->rom_src[b];
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
#ifdef TC_JIT
jit_rom_update(e, b << 16);
e->jit_flush = 1; /* translated code may have read this block */
#endif
}
__attribute__((noinline)) void tc_ovl_free(Emu *e, int i)
{
uint32_t base = e->ovl.base[i];
if (base == 0xFFFFFFFFu) return;
e->ovl.base[i] = 0xFFFFFFFFu;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
if (base - e->par_base < 0x10000u) {
#ifdef TC_JIT
jit_rom_update(e, base);
#endif
return;
}
uint32_t b = (base >> 16) & 127u;
for (int k = 0; k < e->ovl.n; k++) if (e->ovl.base[k] != 0xFFFFFFFFu && ((e->ovl.base[k] >> 16) & 127u) == b) return;
e->ovl_blk[b >> 5] &= ~(1u << (b & 31u));
tc_blk_update(e, b);
}
static void flash_erase_sector(Emu *e, uint32_t off)
{
uint32_t base, size; sector_of(e, off, &base, &size);
uint8_t *p = 0;
if (size > OVL_SIZE) {
/* drop the written copies of this sector, then erase the backing store */
for (int i = 0; i < e->ovl.n; i++) if (e->ovl.base[i] - base < size) tc_ovl_free(e, i);
e->flash_big_ops++;
if (!(tc_big_erase && tc_big_erase(e, base))) e->flash_lost_writes++;
tc_blk_update(e, base >> 16);
} else p = rom_wptr(e, base);
if (p) memset(p, 0xFF, size);
e->flash_dirty = true;
e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
e->flash_op_data = 0xFFFF;
e->flash_toggle = false;
}
static uint16_t flash_status(Emu *e)
{
e->flash_toggle = !e->flash_toggle;
uint16_t s = 0;
if (!((e->flash_op_data >> 7) & 1)) s |= 0x80;
if (e->flash_toggle) s |= 0x40;
if (--e->flash_busy <= 0) e->flash_busy = 0;
return s;
}
static void flash_write(Emu *e, uint32_t a, uint32_t v, int size)
{
DEV;
uint32_t off = a - dev->rom_base;
uint8_t d = (uint8_t)v;
if (e->flash_state == 3) {
uint16_t final = 0;
for (int i = 0; i < size; i++) {
uint32_t o = (off + (uint32_t)i) & (dev->rom_size - 1);
uint8_t *p = rom_wptr(e, o);
uint8_t nb = p ? (*p &= (uint8_t)(v >> (8 * i))) : rom_ptr(e, o)[0];
final |= (uint16_t)nb << (8 * i);
}
e->flash_dirty = true;
e->flash_state = 0;
e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
e->flash_op_data = size >= 2 ? final : (uint16_t)(0xFF00 | final);
e->flash_toggle = false;
return;
}
if (d == 0xF0) { e->flash_state = 0; e->flash_autoselect = false; return; }
switch (e->flash_state) {
case 0: if (d == 0xAA) e->flash_state = 1; break;
case 1: e->flash_state = (d == 0x55) ? 2 : 0; break;
case 2:
if (d == 0xA0) e->flash_state = 3;
else if (d == 0x80) e->flash_state = 4;
else if (d == 0x90) { e->flash_autoselect = true; e->flash_state = 0; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; }
else e->flash_state = 0;
break;
case 4: e->flash_state = (d == 0xAA) ? 5 : 0; break;
case 5: e->flash_state = (d == 0x55) ? 6 : 0; break;
case 6:
if (d == 0x30) flash_erase_sector(e, off);
e->flash_state = 0; /* chip erase (0x10) is ignored */
break;
default: e->flash_state = 0; break;
}
}
static uint8_t flash_read8(Emu *e, uint32_t a)
{
DEV;
if (e->flash_busy) return (uint8_t)flash_status(e);
if (e->flash_autoselect) {
uint32_t w = (a - dev->rom_base) >> 1;
if ((w & 0xFF) == 0) return (a & 1) ? 0x00 : 0x01;
return (a & 1) ? 0x22 : 0xF6;
}
return *rom_ptr(e, a - dev->rom_base);
}
#ifdef LCDRD_DEBUG
extern uint32_t g_lcdrd, g_lcdrd_pc[16]; extern int g_np;
#endif
uint8_t mem_read8(Emu *e, uint32_t a)
{
DEV;
#ifdef LCDRD_DEBUG
if (a == dev->lcd_cmd_addr || a == dev->lcd_data_addr) { g_lcdrd++; int k; for (k = 0; k < g_np && g_lcdrd_pc[k] != e->pc; k++); if (k == g_np && g_np < 16) g_lcdrd_pc[g_np++] = e->pc; }
#endif
if (a - dev->rom_base < dev->rom_size) {
if (e->flash_busy || e->flash_autoselect) return flash_read8(e, a);
return *rom_ptr(e, a - dev->rom_base);
}
if (a - dev->a0ram_base < dev->a0ram_size) return e->a0ram[a - dev->a0ram_base];
if (a - dev->io_base < dev->io_size) return periph_read8(e, a);
if (a - dev->ivram_base < dev->ivram_size) return e->ivram[a - dev->ivram_base];
if (a - dev->dstram_base < dev->dstram_size) return e->dstram[a - dev->dstram_base];
return 0;
}
void mem_write8(Emu *e, uint32_t a, uint8_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size) { e->a0ram[a - dev->a0ram_base] = v; return; }
if (a == dev->lcd_cmd_addr) { e->lcd_writes++; lcd_cmd(e, v); return; }
if (a == dev->lcd_data_addr) { e->lcd_writes++; lcd_data(e, v); return; }
if (a - dev->io_base < dev->io_size) { periph_write8(e, a, v); return; }
if (a - dev->ivram_base < dev->ivram_size) { e->ivram[a - dev->ivram_base] = v; return; }
if (a - dev->dstram_base < dev->dstram_size) { e->dstram[a - dev->dstram_base] = v; return; }
if (a - dev->rom_base < dev->rom_size) { flash_write(e, a, v, 1); return; }
}
uint16_t mem_read16(Emu *e, uint32_t a)
{
DEV;
if (a - dev->rom_base < dev->rom_size - 1) {
if (e->flash_busy) return flash_status(e);
if (e->flash_autoselect)
return (uint16_t)(flash_read8(e, a) | (flash_read8(e, a + 1) << 8));
const uint8_t *p = rom_ptr(e, a - dev->rom_base);
return (uint16_t)(p[0] | (p[1] << 8));
}
if (a - dev->a0ram_base < dev->a0ram_size - 1) {
const uint8_t *p = e->a0ram + (a - dev->a0ram_base);
return (uint16_t)(p[0] | (p[1] << 8));
}
return (uint16_t)(mem_read8(e, a) | (mem_read8(e, a + 1) << 8));
}
uint32_t mem_read32(Emu *e, uint32_t a)
{
DEV;
if (a - dev->rom_base < dev->rom_size - 3) {
if (e->flash_busy || e->flash_autoselect)
return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16);
const uint8_t *p = rom_ptr(e, a - dev->rom_base);
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
if (a - dev->a0ram_base < dev->a0ram_size - 3) {
const uint8_t *p = e->a0ram + (a - dev->a0ram_base);
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
if (a - dev->io_base < dev->io_size - 3) return periph_read32(e, a);
return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16);
}
void mem_write16(Emu *e, uint32_t a, uint16_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size - 1) {
e->a0ram[a - dev->a0ram_base] = (uint8_t)v;
e->a0ram[a - dev->a0ram_base + 1] = (uint8_t)(v >> 8);
return;
}
if (a - dev->rom_base < dev->rom_size - 1) { flash_write(e, a, v, 2); return; }
mem_write8(e, a, (uint8_t)v);
mem_write8(e, a + 1, (uint8_t)(v >> 8));
}
void mem_write32(Emu *e, uint32_t a, uint32_t v)
{
DEV;
if (a - dev->a0ram_base < dev->a0ram_size - 3) {
uint8_t *p = e->a0ram + (a - dev->a0ram_base);
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
return;
}
if (a - dev->io_base < dev->io_size - 3) { periph_write32(e, a, v); return; }
if (a - dev->rom_base < dev->rom_size - 3) {
flash_write(e, a, v & 0xFFFF, 2);
flash_write(e, a + 2, v >> 16, 2);
return;
}
mem_write16(e, a, (uint16_t)v);
mem_write16(e, a + 2, (uint16_t)(v >> 16));
}
/* Set the instruction window for fast fetch (or clear it if none fits). */
void tc_fetch_window(Emu *e, uint32_t pc)
{
DEV;
e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu;
if (pc - dev->rom_base < dev->rom_size && !e->flash_busy && !e->flash_autoselect) {
/* 64 KB window of the block */
const uint8_t *b = e->rom_blk[(pc - dev->rom_base) >> 16];
if (!b) return;
e->fw_ptr = b; e->fw_lo = pc & ~0xFFFFu; e->fw_len = 0x10000u; return; }
if (pc - dev->a0ram_base < dev->a0ram_size) { e->fw_ptr = e->a0ram; e->fw_lo = dev->a0ram_base; e->fw_len = dev->a0ram_size; return; }
if (pc - dev->ivram_base < dev->ivram_size) { e->fw_ptr = e->ivram; e->fw_lo = dev->ivram_base; e->fw_len = dev->ivram_size; return; }
if (pc - dev->dstram_base < dev->dstram_size) { e->fw_ptr = e->dstram; e->fw_lo = dev->dstram_base; e->fw_len = dev->dstram_size; return; }
}
+583 -583
View File
File diff suppressed because it is too large. Load diff
+319 -319
View File
@@ -1,319 +1,319 @@
/* 1.6.6: "reset?" question when the wheel is pressed in the first 3 s after a resumed start (TamaEmu,
* T18Emu). Before, the session was thrown away at once, a press meant for the menu lost the game.
* A = yes, B or the wheel = no.
* 1.6.8 (OPT_MENU): settings on the device with a short press on the wheel (volume, brightness, screen off),
* drawn like the menu of T7Emu and V1Emu: its 5x7 font, its colours (green screen, dark ink), title, line,
* the chosen line dark. */
#include "hw.h"
#include "ask.h"
#ifdef BAT_SHOW
#include "batt.h"
#endif
static const char FK[] = " %\'-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const u8 FG[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x19,0x19,0x02,0x04,0x08,0x13,0x13,0x04,0x04,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x0c,0x01,0x01,0x02,0x04,0x08,0x10,0x10,0x0e,0x11,0x13,0x15,0x19,0x11,0x0e,0x04,0x0c,0x04,0x04,0x04,0x04,0x0e,0x0e,0x11,0x01,0x02,0x04,0x08,0x1f,0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e,0x02,0x06,0x0a,0x12,0x1f,0x02,0x02,0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e,0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e,0x1f,0x01,0x02,0x04,0x08,0x08,0x08,0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e,0x00,0x04,0x04,0x00,0x04,0x04,0x00,0x0e,0x11,0x01,0x02,0x04,0x00,0x04,0x0e,0x11,0x11,0x1f,0x11,0x11,0x11,0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e,0x0e,0x11,0x10,0x10,0x10,0x11,0x0e,0x1e,0x11,0x11,0x11,0x11,0x11,0x1e,0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f,0x1f,0x10,0x10,0x1e,0x10,0x10,0x10,0x0e,0x11,0x10,0x17,0x11,0x11,0x0f,0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x07,0x02,0x02,0x02,0x02,0x12,0x0c,0x11,0x12,0x14,0x18,0x14,0x12,0x11,0x10,0x10,0x10,0x10,0x10,0x10,0x1f,0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x11,0x19,0x15,0x13,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x1e,0x11,0x11,0x1e,0x10,0x10,0x10,0x0e,0x11,0x11,0x11,0x15,0x12,0x0d,0x1e,0x11,0x11,0x1e,0x14,0x12,0x11,0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e,0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0a,0x04,0x11,0x11,0x11,0x15,0x15,0x15,0x0a,0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x1f,0x01,0x02,0x04,0x08,0x10,0x1f};
static const u8 *ask_glyph(char c) { if (c >= 'a' && c <= 'z') c = (char)(c - 32); for (int i = 0; FK[i]; i++) if (FK[i] == c) return FG + 7 * i; return FG; }
static int slen(const char *s) { int n = 0; while (s && s[n]) n++; return n; }
/* one text line from y0 (7 rows, scale 1 or 2); x0 < 0: centred */
static void ask_line(u16 *row, int y, int y0, const char *s, u16 fg, int x0, int sc)
{
if (!s || y < y0 || y >= y0 + 7 * sc) return;
int n = slen(s);
if (x0 < 0) x0 = (128 - n * 6 * sc + sc) / 2;
int gy = (y - y0) / sc;
for (int i = 0; i < n; i++) {
u8 g = ask_glyph(s[i])[gy];
for (int cx = 0; cx < 5 * sc; cx++) if (g & (0x10 >> (cx / sc))) { int x = x0 + i * 6 * sc + cx; if (x >= 0 && x < 128) row[x] = fg; }
}
}
static void ask_release(void) { for (u32 t = 0; hw_buttons() && t < 50000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); }
#if defined(OPT_MENU) || defined(ASK_NUM)
/* 1.6.8 (test41): the keys bounce; one press of B counted once or twice. A state counts only when it held for
* 20 samples about 1 ms apart. */
static void ask_ms(void) { for (volatile u32 i = 0; i < 16000u; i++) { } hw_wdt_feed(); }
static u32 ask_stable(void)
{
u32 v = hw_buttons();
for (int n = 0; n < 20; ) { ask_ms(); u32 w = hw_buttons(); if (w == v) n++; else { v = w; n = 0; } }
return v;
}
static void ask_release_db(void) { while (ask_stable()) { } }
static u32 ask_press_db(void) { u32 b; while (!(b = ask_stable())) { } return b; }
#endif
/* colours of the T7Emu menu with its default screen colour: background, 90 %, 60 %, ink */
#define C_BG 0xAE66u
#define C_LINE 0x6BE4u
#define C_INK 0x0000u
int hw_ask_reset(int en)
{
const char *l1 = en ? "RESET?" : "ZURUECKSETZEN?", *l2 = en ? "A YES" : "A JA", *l3 = en ? "B NO" : "B NEIN";
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) row[x] = C_BG;
ask_line(row, y, 36, l1, C_INK, -1, 1); ask_line(row, y, 60, l2, C_INK, -1, 1); ask_line(row, y, 76, l3, C_INK, -1, 1);
hw_px_row(row, 128);
}
hw_px_end();
hw_backlight(1);
ask_release(); /* the wheel let go first */
int r = 0;
for (u32 t = 0; ; t++) {
if ((t & 0xFFFFu) == 0) hw_wdt_feed();
u32 b = hw_buttons();
if (b & BTN_A) { r = 1; break; }
if (b & (BTN_B | BTN_WHEEL)) { r = 0; break; }
}
ask_release();
return r;
}
#ifdef ASK_NUM
/* test30: a number on the device (Gotchi Points, Tamapoints): A next digit, B the digit + 1, C keep, the wheel
* back without change. Returns 1 when kept (*v is the new value, at most max). */
int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en)
{
u8 dg[8]; u32 t = *v > max ? max : *v; int pos = 0;
if (digits > 8) digits = 8;
for (int i = digits - 1; i >= 0; i--) { dg[i] = (u8)(t % 10u); t /= 10u; }
ask_release_db();
for (;;) {
char num[9]; for (int i = 0; i < digits; i++) num[i] = (char)('0' + dg[i]); num[digits] = 0;
int x0 = (128 - digits * 12 + 2) / 2;
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) row[x] = C_BG;
if (y == 32) for (int x = 0; x < 128; x++) row[x] = C_LINE;
if (y >= 50 && y < 66) for (int x = x0 + pos * 12 - 1; x < x0 + pos * 12 + 11; x++) if (x >= 0 && x < 128) row[x] = C_INK;
ask_line(row, y, 22, title, C_INK, -1, 1);
for (int i = 0; i < digits; i++) { char c[2] = { num[i], 0 }; ask_line(row, y, 51, c, i == pos ? C_BG : C_INK, x0 + i * 12, 2); }
ask_line(row, y, 80, en ? "A NEXT B CHANGE" : "A WEITER B AENDERN", C_INK, -1, 1);
ask_line(row, y, 92, en ? "C OK" : "C OK", C_INK, -1, 1);
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & BTN_WHEEL) return 0;
if (b & BTN_C) {
u32 n = 0; for (int i = 0; i < digits; i++) n = n * 10u + dg[i];
*v = n > max ? max : n; return 1;
}
if (b & BTN_A) pos = (pos + 1) % digits;
if (b & BTN_B) dg[pos] = (u8)((dg[pos] + 1u) % 10u);
}
}
#endif
#ifdef OPT_MENU
/* Settings: o holds them as the flags of the program (bits 16-17 volume, 18-19 brightness, 20-22 screen off).
* A next line, B change, C or the wheel: close. Returns the new bits. */
static const char *const VOL_DE[4] = { "Normal", "Leise", "Laut", "Aus" }, *const VOL_EN[4] = { "Normal", "Quiet", "Loud", "Off" };
/* 1.6.8 (test45): the light in 11 steps, bits 24-27 = step + 1 (0 = the old bits 18-19: 100, 75, 50, 25 %).
* Step 0 = 100 %, then 5, 10, 20 .. 90 %: B goes up, after 100 % it starts at 5 % again. */
#ifdef ASK_OVL
/* 1.6.13 test10 (TamaEmu EMU_OVL): the menus live in the program's overlay (loaded when opened); these few are needed
* while the game runs and stay */
#define ASK_KEEP __attribute__((section(".text.keep_ask")))
#define ASK_KEEPD __attribute__((section(".rodata.keep_ask")))
#else
#define ASK_KEEP
#define ASK_KEEPD
#endif
ASK_KEEPD static const u8 OPT_LV[11] = { 100, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90 };
ASK_KEEPD static const u8 OPT_OLD[4] = { 0, 8, 6, 3 }; /* the old bits 18-19: 100, 75, 50, 25 % */
ASK_KEEP static u32 opt_step(u32 o) { u32 n = (o >> 24) & 15u; if (n && n <= 11u) return n - 1u; return OPT_OLD[(o >> 18) & 3u]; }
ASK_KEEP u32 opt_light_pct(u32 o) { return OPT_LV[opt_step(o)]; }
static void pct_txt(char *t, u32 p) { u32 n = 0; if (p >= 100u) t[n++] = '1'; if (p >= 10u) t[n++] = (char)('0' + (p / 10u) % 10u); t[n++] = (char)('0' + p % 10u); t[n++] = '%'; t[n] = 0; }
#ifdef ASK_DIM
/* 1.6.13 test7 (T18Emu): dimming as in T7Emu, device-only bits: 12-14 dim after (0 never, then as the screen off
* times), 8-11 dim to (DIM_P[(n + 4) mod 10], 0 = 10 %, at most the light). Screen off 0 = never (the game still turns the
* picture off itself, as the original); bit 15 never: the screen stays on (the game does not fall asleep). */
ASK_KEEPD static const u8 DIM_P[10] = { 1, 2, 3, 5, 10, 15, 20, 30, 40, 50 };
ASK_KEEP u32 opt_dim_pct(u32 o) { u32 p = DIM_P[(((o >> 8) & 15u) + 4u) % 10u], l = opt_light_pct(o); return p < l ? p : l; }
#ifdef ASK_NEVER
/* T18Emu: screen off "never" (bit 15), the game kept awake */
static const char *const OFF_DE[9] = { "Auto", "Nie", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[9] = { "Auto", "Never", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define OFF_K 9u
#else
/* TamaEmu (test10): Auto (as the game) and the times */
static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define OFF_K 8u
#endif
#define MY 4
#else
static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define MY 22
#endif
#ifdef ASK_EXTRA
static u32 opts_menu(u32 o, int en, const char *const *ex, int nex);
u32 hw_opts_menu(u32 o, int en) { return opts_menu(o, en, 0, 0); }
/* 1.6.8 (test47): one more line (T18Emu: grow up); chosen with B: the result has bit 31 set */
u32 hw_opts_menu_x(u32 o, int en, const char *extra) { return opts_menu(o, en, &extra, extra ? 1 : 0); }
/* test30: up to 3 more lines (0 = left out); the chosen one: bit 31 and its index in bits 28-30 */
u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex) { return opts_menu(o, en, ex, nex); }
#ifndef ASK_SLIM /* test30: TamaEmu only needs the extra lines (its program space is nearly full) */
/* a list to choose from (up to 8 lines at a time, scrolls): A next, B take, C or the wheel back (-1) */
int hw_list_menu(const char *title, const char *const *it, int n)
{
int sel = 0, top = 0;
ask_release_db();
for (;;) {
if (sel < top) top = sel;
if (sel >= top + 8) top = sel - 7;
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
int my = y - 14;
int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < 8 && top + k < n && (my - 12) % 10 < 9;
u16 bg = (in && top + k == sel) ? C_INK : C_BG;
for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg;
ask_line(row, my, 1, title, C_INK, 2, 1);
for (int i = 0; i < 8 && top + i < n; i++) ask_line(row, my, 13 + i * 10, it[top + i], top + i == sel ? C_BG : C_INK, 2, 1);
if (top > 0 && my >= 2 && my < 6) for (int x = 122 - (my - 2); x <= 122 + (my - 2); x++) row[x] = C_LINE; /* more above */
if (top + 8 < n && my >= 2 && my < 6) for (int x = 114 - (5 - my); x <= 114 + (5 - my); x++) row[x] = C_LINE; /* more below */
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & (BTN_C | BTN_WHEEL)) return -1;
if (b & BTN_A) sel = (sel + 1) % n;
if (b & BTN_B) return sel;
}
}
/* test47: a 64x64 picture (256 colours RGB565, then 4096 indices; p in the flash, read uncached) twice as big, with
* "B OK C BACK" below. 1 = B, 0 = C or the wheel. */
int hw_pic_ask(const volatile u8 *p, int en)
{
u16 row[128], pal[256];
for (int i = 0; i < 256; i++) pal[i] = (u16)(p[2 * i] | (p[2 * i + 1] << 8));
ask_release_db();
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
if (y < 116) { const volatile u8 *q = p + 512 + (y >> 1) * 64; for (int x = 0; x < 128; x++) row[x] = pal[q[x >> 1]]; }
else { for (int x = 0; x < 128; x++) row[x] = C_BG; ask_line(row, y, 118, en ? "B OK C BACK" : "B OK C ZURUECK", C_INK, -1, 1); }
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
return (b & BTN_B) ? 1 : 0;
}
#endif
static u32 opts_menu(u32 o, int en, const char *const *ex, int nex)
#else
u32 hw_opts_menu(u32 o, int en)
#endif
{
int sel = 0;
#ifdef ASK_EXTRA
const char *xl[3]; int nx = 0, xi[3];
for (int i = 0; i < nex && nx < 3; i++) if (ex[i]) { xl[nx] = ex[i]; xi[nx] = i; nx++; }
#else
const int nx = 0;
#endif
ask_release_db();
for (;;) {
u32 v = (o >> 16) & 3u, d = opt_step(o), s = (o >> 20) & 7u;
#ifdef ASK_DIM
#ifdef ASK_NEVER
u32 a = (o >> 12) & 7u, ok = (o & 0x8000u) ? 1u : s ? s + 1u : 0u; /* screen off: Auto, Never, the times */
#define OFF_TIMES (OFF_EN + 1)
#else
u32 a = (o >> 12) & 7u, ok = s;
#define OFF_TIMES OFF_EN
#endif
u8 it[6]; int ns = 0; it[ns++] = 0; it[ns++] = 1; it[ns++] = 3; if (a) it[ns++] = 4; it[ns++] = 2; /* dim to: only when dimming */
#ifdef ASK_LANG
it[ns++] = 5; /* test8: the language, set on the device (bits 0-1: 0 as the Studio, 1 German, 2 English) */
#endif
char pt[6]; pct_txt(pt, opt_dim_pct(o));
static const char *const TD[8] = { 0, "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
const char *lab[6] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach",
en ? "Dim after" : "Dimmen nach", en ? "Dim to" : "Dimmen auf", en ? "Language" : "Sprache" };
const char *val[6] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[ok], a ? (en ? OFF_TIMES : TD)[a] : (en ? "Never" : "Nie"), pt,
en ? "English" : "Deutsch" };
#else
static const u8 it[3] = { 0, 1, 2 }; const int ns = 3;
const char *lab[3] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach" };
const char *val[3] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[s] };
#endif
int nl = ns + nx; if (sel >= nl) sel = 0;
char dt[6]; pct_txt(dt, OPT_LV[d]); val[1] = dt;
#ifdef BAT_SHOW
char bt[12]; bat_text(bt); /* test17: the battery, below the lines (not chosen) */
int by = 13 + nl * 10 + 8;
#endif
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
int my = y - MY;
u16 bg = C_BG;
int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < nl && (my - 12) % 10 < 9; /* the chosen line: rows y-1 .. y+7 */
if (in && k == sel) bg = C_INK;
for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg;
ask_line(row, my, 1, en ? "SETTINGS" : "EINSTELLUNGEN", C_INK, 2, 1);
for (int i = 0; i < ns; i++) {
u16 fg = i == sel ? C_BG : C_INK; int yy = 13 + i * 10; const char *vv = val[it[i]];
ask_line(row, my, yy, lab[it[i]], fg, 2, 1);
ask_line(row, my, yy, vv, fg, 128 - 2 - 6 * slen(vv), 1);
}
#ifdef ASK_EXTRA
for (int i = 0; i < nx; i++) {
#ifdef ASK_LANG
/* test9: "German|English" in one line, so it follows the language right away */
char xt[20]; { const char *p = xl[i], *q = p; while (*q && *q != '|') q++;
if (*q && en) p = q + 1, q = p + slen(p);
int n = 0; while (p < q && n < 19) xt[n++] = *p++; xt[n] = 0; }
ask_line(row, my, 13 + 10 * (ns + i), xt, sel == ns + i ? C_BG : C_INK, 2, 1);
#else
ask_line(row, my, 13 + 10 * (ns + i), xl[i], sel == ns + i ? C_BG : C_INK, 2, 1);
#endif
}
#endif
#ifdef BAT_SHOW
ask_line(row, my, by, en ? "Battery" : "Batterie", C_LINE, 2, 1);
ask_line(row, my, by, bt, C_LINE, 128 - 2 - 6 * slen(bt), 1);
#endif
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & (BTN_C | BTN_WHEEL)) return o;
if (b & BTN_A) sel = (sel + 1) % nl;
#ifdef ASK_EXTRA
if ((b & BTN_B) && sel >= ns) return o | 0x80000000u | ((u32)xi[sel - ns] << 28);
#endif
if (b & BTN_B) {
int w = it[sel];
if (w == 0) o = (o & ~(3u << 16)) | (((v + 1) & 3u) << 16);
else if (w == 1) {
o = (o & ~((3u << 18) | (15u << 24))) | ((((d + 1u) % 11u) + 1u) << 24);
#ifdef BL_PWM
hw_bl_set(opt_light_pct(o)); /* 1.6.8: seen right away */
#endif
}
#ifdef ASK_DIM
else if (w == 3) { a = (a + 1) & 7u; if (a && s && s <= a) s = a < 7u ? a + 1u : 0u; /* off stays after dimming */
o = (o & ~((7u << 12) | (7u << 20))) | (a << 12) | (s << 20); }
else if (w == 4) o = (o & ~(15u << 8)) | (((((o >> 8) & 15u) + 1u) % 10u) << 8);
#ifdef ASK_LANG
else if (w == 5) { en = !en; o = (o & ~3u) | (en ? 2u : 1u); }
#endif
#ifdef ASK_NEVER
else { do { ok = (ok + 1u) % OFF_K; s = ok >= 2u ? ok - 1u : 0u; } while (s && a && s <= a);
o = (o & ~((7u << 20) | 0x8000u)) | (s << 20) | (ok == 1u ? 0x8000u : 0u); }
#else
else { do s = (s + 1u) & 7u; while (s && a && s <= a); o = (o & ~(7u << 20)) | (s << 20); }
#endif
#else
else o = (o & ~(7u << 20)) | (((s + 1) & 7u) << 20);
#endif
}
}
}
#endif
/* 1.6.6: "reset?" question when the wheel is pressed in the first 3 s after a resumed start (TamaEmu,
* T18Emu). Before, the session was thrown away at once, a press meant for the menu lost the game.
* A = yes, B or the wheel = no.
* 1.6.8 (OPT_MENU): settings on the device with a short press on the wheel (volume, brightness, screen off),
* drawn like the menu of T7Emu and V1Emu: its 5x7 font, its colours (green screen, dark ink), title, line,
* the chosen line dark. */
#include "hw.h"
#include "ask.h"
#ifdef BAT_SHOW
#include "batt.h"
#endif
static const char FK[] = " %\'-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const u8 FG[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x19,0x19,0x02,0x04,0x08,0x13,0x13,0x04,0x04,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x0c,0x01,0x01,0x02,0x04,0x08,0x10,0x10,0x0e,0x11,0x13,0x15,0x19,0x11,0x0e,0x04,0x0c,0x04,0x04,0x04,0x04,0x0e,0x0e,0x11,0x01,0x02,0x04,0x08,0x1f,0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e,0x02,0x06,0x0a,0x12,0x1f,0x02,0x02,0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e,0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e,0x1f,0x01,0x02,0x04,0x08,0x08,0x08,0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e,0x00,0x04,0x04,0x00,0x04,0x04,0x00,0x0e,0x11,0x01,0x02,0x04,0x00,0x04,0x0e,0x11,0x11,0x1f,0x11,0x11,0x11,0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e,0x0e,0x11,0x10,0x10,0x10,0x11,0x0e,0x1e,0x11,0x11,0x11,0x11,0x11,0x1e,0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f,0x1f,0x10,0x10,0x1e,0x10,0x10,0x10,0x0e,0x11,0x10,0x17,0x11,0x11,0x0f,0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x07,0x02,0x02,0x02,0x02,0x12,0x0c,0x11,0x12,0x14,0x18,0x14,0x12,0x11,0x10,0x10,0x10,0x10,0x10,0x10,0x1f,0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x11,0x19,0x15,0x13,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x1e,0x11,0x11,0x1e,0x10,0x10,0x10,0x0e,0x11,0x11,0x11,0x15,0x12,0x0d,0x1e,0x11,0x11,0x1e,0x14,0x12,0x11,0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e,0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0a,0x04,0x11,0x11,0x11,0x15,0x15,0x15,0x0a,0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x1f,0x01,0x02,0x04,0x08,0x10,0x1f};
static const u8 *ask_glyph(char c) { if (c >= 'a' && c <= 'z') c = (char)(c - 32); for (int i = 0; FK[i]; i++) if (FK[i] == c) return FG + 7 * i; return FG; }
static int slen(const char *s) { int n = 0; while (s && s[n]) n++; return n; }
/* one text line from y0 (7 rows, scale 1 or 2); x0 < 0: centred */
static void ask_line(u16 *row, int y, int y0, const char *s, u16 fg, int x0, int sc)
{
if (!s || y < y0 || y >= y0 + 7 * sc) return;
int n = slen(s);
if (x0 < 0) x0 = (128 - n * 6 * sc + sc) / 2;
int gy = (y - y0) / sc;
for (int i = 0; i < n; i++) {
u8 g = ask_glyph(s[i])[gy];
for (int cx = 0; cx < 5 * sc; cx++) if (g & (0x10 >> (cx / sc))) { int x = x0 + i * 6 * sc + cx; if (x >= 0 && x < 128) row[x] = fg; }
}
}
static void ask_release(void) { for (u32 t = 0; hw_buttons() && t < 50000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); }
#if defined(OPT_MENU) || defined(ASK_NUM)
/* 1.6.8 (test41): the keys bounce; one press of B counted once or twice. A state counts only when it held for
* 20 samples about 1 ms apart. */
static void ask_ms(void) { for (volatile u32 i = 0; i < 16000u; i++) { } hw_wdt_feed(); }
static u32 ask_stable(void)
{
u32 v = hw_buttons();
for (int n = 0; n < 20; ) { ask_ms(); u32 w = hw_buttons(); if (w == v) n++; else { v = w; n = 0; } }
return v;
}
static void ask_release_db(void) { while (ask_stable()) { } }
static u32 ask_press_db(void) { u32 b; while (!(b = ask_stable())) { } return b; }
#endif
/* colours of the T7Emu menu with its default screen colour: background, 90 %, 60 %, ink */
#define C_BG 0xAE66u
#define C_LINE 0x6BE4u
#define C_INK 0x0000u
int hw_ask_reset(int en)
{
const char *l1 = en ? "RESET?" : "ZURUECKSETZEN?", *l2 = en ? "A YES" : "A JA", *l3 = en ? "B NO" : "B NEIN";
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) row[x] = C_BG;
ask_line(row, y, 36, l1, C_INK, -1, 1); ask_line(row, y, 60, l2, C_INK, -1, 1); ask_line(row, y, 76, l3, C_INK, -1, 1);
hw_px_row(row, 128);
}
hw_px_end();
hw_backlight(1);
ask_release(); /* the wheel let go first */
int r = 0;
for (u32 t = 0; ; t++) {
if ((t & 0xFFFFu) == 0) hw_wdt_feed();
u32 b = hw_buttons();
if (b & BTN_A) { r = 1; break; }
if (b & (BTN_B | BTN_WHEEL)) { r = 0; break; }
}
ask_release();
return r;
}
#ifdef ASK_NUM
/* test30: a number on the device (Gotchi Points, Tamapoints): A next digit, B the digit + 1, C keep, the wheel
* back without change. Returns 1 when kept (*v is the new value, at most max). */
int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en)
{
u8 dg[8]; u32 t = *v > max ? max : *v; int pos = 0;
if (digits > 8) digits = 8;
for (int i = digits - 1; i >= 0; i--) { dg[i] = (u8)(t % 10u); t /= 10u; }
ask_release_db();
for (;;) {
char num[9]; for (int i = 0; i < digits; i++) num[i] = (char)('0' + dg[i]); num[digits] = 0;
int x0 = (128 - digits * 12 + 2) / 2;
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) row[x] = C_BG;
if (y == 32) for (int x = 0; x < 128; x++) row[x] = C_LINE;
if (y >= 50 && y < 66) for (int x = x0 + pos * 12 - 1; x < x0 + pos * 12 + 11; x++) if (x >= 0 && x < 128) row[x] = C_INK;
ask_line(row, y, 22, title, C_INK, -1, 1);
for (int i = 0; i < digits; i++) { char c[2] = { num[i], 0 }; ask_line(row, y, 51, c, i == pos ? C_BG : C_INK, x0 + i * 12, 2); }
ask_line(row, y, 80, en ? "A NEXT B CHANGE" : "A WEITER B AENDERN", C_INK, -1, 1);
ask_line(row, y, 92, en ? "C OK" : "C OK", C_INK, -1, 1);
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & BTN_WHEEL) return 0;
if (b & BTN_C) {
u32 n = 0; for (int i = 0; i < digits; i++) n = n * 10u + dg[i];
*v = n > max ? max : n; return 1;
}
if (b & BTN_A) pos = (pos + 1) % digits;
if (b & BTN_B) dg[pos] = (u8)((dg[pos] + 1u) % 10u);
}
}
#endif
#ifdef OPT_MENU
/* Settings: o holds them as the flags of the program (bits 16-17 volume, 18-19 brightness, 20-22 screen off).
* A next line, B change, C or the wheel: close. Returns the new bits. */
static const char *const VOL_DE[4] = { "Normal", "Leise", "Laut", "Aus" }, *const VOL_EN[4] = { "Normal", "Quiet", "Loud", "Off" };
/* 1.6.8 (test45): the light in 11 steps, bits 24-27 = step + 1 (0 = the old bits 18-19: 100, 75, 50, 25 %).
* Step 0 = 100 %, then 5, 10, 20 .. 90 %: B goes up, after 100 % it starts at 5 % again. */
#ifdef ASK_OVL
/* 1.6.13 test10 (TamaEmu EMU_OVL): the menus live in the program's overlay (loaded when opened); these few are needed
* while the game runs and stay */
#define ASK_KEEP __attribute__((section(".text.keep_ask")))
#define ASK_KEEPD __attribute__((section(".rodata.keep_ask")))
#else
#define ASK_KEEP
#define ASK_KEEPD
#endif
ASK_KEEPD static const u8 OPT_LV[11] = { 100, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90 };
ASK_KEEPD static const u8 OPT_OLD[4] = { 0, 8, 6, 3 }; /* the old bits 18-19: 100, 75, 50, 25 % */
ASK_KEEP static u32 opt_step(u32 o) { u32 n = (o >> 24) & 15u; if (n && n <= 11u) return n - 1u; return OPT_OLD[(o >> 18) & 3u]; }
ASK_KEEP u32 opt_light_pct(u32 o) { return OPT_LV[opt_step(o)]; }
static void pct_txt(char *t, u32 p) { u32 n = 0; if (p >= 100u) t[n++] = '1'; if (p >= 10u) t[n++] = (char)('0' + (p / 10u) % 10u); t[n++] = (char)('0' + p % 10u); t[n++] = '%'; t[n] = 0; }
#ifdef ASK_DIM
/* 1.6.13 test7 (T18Emu): dimming as in T7Emu, device-only bits: 12-14 dim after (0 never, then as the screen off
* times), 8-11 dim to (DIM_P[(n + 4) mod 10], 0 = 10 %, at most the light). Screen off 0 = never (the game still turns the
* picture off itself, as the original); bit 15 never: the screen stays on (the game does not fall asleep). */
ASK_KEEPD static const u8 DIM_P[10] = { 1, 2, 3, 5, 10, 15, 20, 30, 40, 50 };
ASK_KEEP u32 opt_dim_pct(u32 o) { u32 p = DIM_P[(((o >> 8) & 15u) + 4u) % 10u], l = opt_light_pct(o); return p < l ? p : l; }
#ifdef ASK_NEVER
/* T18Emu: screen off "never" (bit 15), the game kept awake */
static const char *const OFF_DE[9] = { "Auto", "Nie", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[9] = { "Auto", "Never", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define OFF_K 9u
#else
/* TamaEmu (test10): Auto (as the game) and the times */
static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define OFF_K 8u
#endif
#define MY 4
#else
static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
#define MY 22
#endif
#ifdef ASK_EXTRA
static u32 opts_menu(u32 o, int en, const char *const *ex, int nex);
u32 hw_opts_menu(u32 o, int en) { return opts_menu(o, en, 0, 0); }
/* 1.6.8 (test47): one more line (T18Emu: grow up); chosen with B: the result has bit 31 set */
u32 hw_opts_menu_x(u32 o, int en, const char *extra) { return opts_menu(o, en, &extra, extra ? 1 : 0); }
/* test30: up to 3 more lines (0 = left out); the chosen one: bit 31 and its index in bits 28-30 */
u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex) { return opts_menu(o, en, ex, nex); }
#ifndef ASK_SLIM /* test30: TamaEmu only needs the extra lines (its program space is nearly full) */
/* a list to choose from (up to 8 lines at a time, scrolls): A next, B take, C or the wheel back (-1) */
int hw_list_menu(const char *title, const char *const *it, int n)
{
int sel = 0, top = 0;
ask_release_db();
for (;;) {
if (sel < top) top = sel;
if (sel >= top + 8) top = sel - 7;
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
int my = y - 14;
int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < 8 && top + k < n && (my - 12) % 10 < 9;
u16 bg = (in && top + k == sel) ? C_INK : C_BG;
for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg;
ask_line(row, my, 1, title, C_INK, 2, 1);
for (int i = 0; i < 8 && top + i < n; i++) ask_line(row, my, 13 + i * 10, it[top + i], top + i == sel ? C_BG : C_INK, 2, 1);
if (top > 0 && my >= 2 && my < 6) for (int x = 122 - (my - 2); x <= 122 + (my - 2); x++) row[x] = C_LINE; /* more above */
if (top + 8 < n && my >= 2 && my < 6) for (int x = 114 - (5 - my); x <= 114 + (5 - my); x++) row[x] = C_LINE; /* more below */
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & (BTN_C | BTN_WHEEL)) return -1;
if (b & BTN_A) sel = (sel + 1) % n;
if (b & BTN_B) return sel;
}
}
/* test47: a 64x64 picture (256 colours RGB565, then 4096 indices; p in the flash, read uncached) twice as big, with
* "B OK C BACK" below. 1 = B, 0 = C or the wheel. */
int hw_pic_ask(const volatile u8 *p, int en)
{
u16 row[128], pal[256];
for (int i = 0; i < 256; i++) pal[i] = (u16)(p[2 * i] | (p[2 * i + 1] << 8));
ask_release_db();
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
if (y < 116) { const volatile u8 *q = p + 512 + (y >> 1) * 64; for (int x = 0; x < 128; x++) row[x] = pal[q[x >> 1]]; }
else { for (int x = 0; x < 128; x++) row[x] = C_BG; ask_line(row, y, 118, en ? "B OK C BACK" : "B OK C ZURUECK", C_INK, -1, 1); }
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
return (b & BTN_B) ? 1 : 0;
}
#endif
static u32 opts_menu(u32 o, int en, const char *const *ex, int nex)
#else
u32 hw_opts_menu(u32 o, int en)
#endif
{
int sel = 0;
#ifdef ASK_EXTRA
const char *xl[3]; int nx = 0, xi[3];
for (int i = 0; i < nex && nx < 3; i++) if (ex[i]) { xl[nx] = ex[i]; xi[nx] = i; nx++; }
#else
const int nx = 0;
#endif
ask_release_db();
for (;;) {
u32 v = (o >> 16) & 3u, d = opt_step(o), s = (o >> 20) & 7u;
#ifdef ASK_DIM
#ifdef ASK_NEVER
u32 a = (o >> 12) & 7u, ok = (o & 0x8000u) ? 1u : s ? s + 1u : 0u; /* screen off: Auto, Never, the times */
#define OFF_TIMES (OFF_EN + 1)
#else
u32 a = (o >> 12) & 7u, ok = s;
#define OFF_TIMES OFF_EN
#endif
u8 it[6]; int ns = 0; it[ns++] = 0; it[ns++] = 1; it[ns++] = 3; if (a) it[ns++] = 4; it[ns++] = 2; /* dim to: only when dimming */
#ifdef ASK_LANG
it[ns++] = 5; /* test8: the language, set on the device (bits 0-1: 0 as the Studio, 1 German, 2 English) */
#endif
char pt[6]; pct_txt(pt, opt_dim_pct(o));
static const char *const TD[8] = { 0, "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" };
const char *lab[6] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach",
en ? "Dim after" : "Dimmen nach", en ? "Dim to" : "Dimmen auf", en ? "Language" : "Sprache" };
const char *val[6] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[ok], a ? (en ? OFF_TIMES : TD)[a] : (en ? "Never" : "Nie"), pt,
en ? "English" : "Deutsch" };
#else
static const u8 it[3] = { 0, 1, 2 }; const int ns = 3;
const char *lab[3] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach" };
const char *val[3] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[s] };
#endif
int nl = ns + nx; if (sel >= nl) sel = 0;
char dt[6]; pct_txt(dt, OPT_LV[d]); val[1] = dt;
#ifdef BAT_SHOW
char bt[12]; bat_text(bt); /* test17: the battery, below the lines (not chosen) */
int by = 13 + nl * 10 + 8;
#endif
u16 row[128];
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
int my = y - MY;
u16 bg = C_BG;
int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < nl && (my - 12) % 10 < 9; /* the chosen line: rows y-1 .. y+7 */
if (in && k == sel) bg = C_INK;
for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg;
ask_line(row, my, 1, en ? "SETTINGS" : "EINSTELLUNGEN", C_INK, 2, 1);
for (int i = 0; i < ns; i++) {
u16 fg = i == sel ? C_BG : C_INK; int yy = 13 + i * 10; const char *vv = val[it[i]];
ask_line(row, my, yy, lab[it[i]], fg, 2, 1);
ask_line(row, my, yy, vv, fg, 128 - 2 - 6 * slen(vv), 1);
}
#ifdef ASK_EXTRA
for (int i = 0; i < nx; i++) {
#ifdef ASK_LANG
/* test9: "German|English" in one line, so it follows the language right away */
char xt[20]; { const char *p = xl[i], *q = p; while (*q && *q != '|') q++;
if (*q && en) p = q + 1, q = p + slen(p);
int n = 0; while (p < q && n < 19) xt[n++] = *p++; xt[n] = 0; }
ask_line(row, my, 13 + 10 * (ns + i), xt, sel == ns + i ? C_BG : C_INK, 2, 1);
#else
ask_line(row, my, 13 + 10 * (ns + i), xl[i], sel == ns + i ? C_BG : C_INK, 2, 1);
#endif
}
#endif
#ifdef BAT_SHOW
ask_line(row, my, by, en ? "Battery" : "Batterie", C_LINE, 2, 1);
ask_line(row, my, by, bt, C_LINE, 128 - 2 - 6 * slen(bt), 1);
#endif
hw_px_row(row, 128);
}
hw_px_end();
u32 b = ask_press_db();
ask_release_db();
if (b & (BTN_C | BTN_WHEEL)) return o;
if (b & BTN_A) sel = (sel + 1) % nl;
#ifdef ASK_EXTRA
if ((b & BTN_B) && sel >= ns) return o | 0x80000000u | ((u32)xi[sel - ns] << 28);
#endif
if (b & BTN_B) {
int w = it[sel];
if (w == 0) o = (o & ~(3u << 16)) | (((v + 1) & 3u) << 16);
else if (w == 1) {
o = (o & ~((3u << 18) | (15u << 24))) | ((((d + 1u) % 11u) + 1u) << 24);
#ifdef BL_PWM
hw_bl_set(opt_light_pct(o)); /* 1.6.8: seen right away */
#endif
}
#ifdef ASK_DIM
else if (w == 3) { a = (a + 1) & 7u; if (a && s && s <= a) s = a < 7u ? a + 1u : 0u; /* off stays after dimming */
o = (o & ~((7u << 12) | (7u << 20))) | (a << 12) | (s << 20); }
else if (w == 4) o = (o & ~(15u << 8)) | (((((o >> 8) & 15u) + 1u) % 10u) << 8);
#ifdef ASK_LANG
else if (w == 5) { en = !en; o = (o & ~3u) | (en ? 2u : 1u); }
#endif
#ifdef ASK_NEVER
else { do { ok = (ok + 1u) % OFF_K; s = ok >= 2u ? ok - 1u : 0u; } while (s && a && s <= a);
o = (o & ~((7u << 20) | 0x8000u)) | (s << 20) | (ok == 1u ? 0x8000u : 0u); }
#else
else { do s = (s + 1u) & 7u; while (s && a && s <= a); o = (o & ~(7u << 20)) | (s << 20); }
#endif
#else
else o = (o & ~(7u << 20)) | (((s + 1) & 7u) << 20);
#endif
}
}
}
#endif
+16 -16
View File
@@ -1,16 +1,16 @@
#ifndef ASK_H
#define ASK_H
int hw_ask_reset(int en); /* 1 = yes (A), 0 = no (B or wheel); waits for the keys to be released */
#ifdef ASK_NUM
int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en); /* test30: 1 = kept */
#endif
#ifdef OPT_MENU
u32 hw_opts_menu(u32 o, int en);
u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex); /* test30: chosen extra: bit 31, index in 28-30 */
u32 opt_light_pct(u32 o);
u32 opt_dim_pct(u32 o); /* ASK_DIM: the dim level, at most the light */
u32 hw_opts_menu_x(u32 o, int en, const char *extra); /* ASK_EXTRA (T18Emu): one more line, bit 31 = chosen */
int hw_list_menu(const char *title, const char *const *it, int n);
int hw_pic_ask(const volatile u8 *p, int en); /* test47: a 64x64 picture, B ok (1), C back (0) */ /* 1.6.8 (test45): the light in percent from the flag bits */ /* 1.6.8: settings on the device; o, result: flag bits 16..22 */
#endif
#endif
#ifndef ASK_H
#define ASK_H
int hw_ask_reset(int en); /* 1 = yes (A), 0 = no (B or wheel); waits for the keys to be released */
#ifdef ASK_NUM
int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en); /* test30: 1 = kept */
#endif
#ifdef OPT_MENU
u32 hw_opts_menu(u32 o, int en);
u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex); /* test30: chosen extra: bit 31, index in 28-30 */
u32 opt_light_pct(u32 o);
u32 opt_dim_pct(u32 o); /* ASK_DIM: the dim level, at most the light */
u32 hw_opts_menu_x(u32 o, int en, const char *extra); /* ASK_EXTRA (T18Emu): one more line, bit 31 = chosen */
int hw_list_menu(const char *title, const char *const *it, int n);
int hw_pic_ask(const volatile u8 *p, int en); /* test47: a 64x64 picture, B ok (1), C back (0) */ /* 1.6.8 (test45): the light in percent from the flag bits */ /* 1.6.8: settings on the device; o, result: flag bits 16..22 */
#endif
#endif
+97 -97
View File
@@ -1,97 +1,97 @@
/* batt.h - 1.6.9 test17 (switch BAT_SHOW): the battery voltage, as the Paradise firmware measures it.
* Found in the firmware (and the Paradise emulator capybara): SAR ADC at 0x4003A000, channel 4 (P0.6, ADP bits 13..15),
* ADM bit 15 on and bit 0 starts a conversion, the result in ADR bits 6..15 (10 bits). The firmware takes
* volts = sample * 0xD33300 / 2^32 (3.3 V for 1024) and switches off below 2.2 V ("replace the battery").
* Header only. Author: mameise */
#ifndef BATT_H
#define BATT_H
#include "io.h"
#define BAT_ADP REG(0x4003A000u)
#define BAT_ADM REG(0x4003A004u)
#define BAT_ADR REG(0x4003A008u)
/* millivolts, 0 = no reading (8 conversions, each waited for at most about 2 ms) */
__attribute__((noinline, unused)) static u32 bat_mv(void)
{
REG(0x45000100u) |= 1u << 12; /* SAR ADC clock */
BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; /* channel 4 */
BAT_ADM |= 0x8000u; /* on */
u32 sum = 0, n = 0;
for (int i = 0; i < 8; i++) {
BAT_ADM |= 1u;
u32 t = 0; while (!(BAT_ADM & 2u) && ++t < 100000u) { }
if (t >= 100000u) break;
sum += (BAT_ADR >> 6) & 0x3FFu; n++;
}
return n ? sum * 3300u / (n * 1024u) : 0u;
}
/* 2 x AAA: 3.0 V and more full, 2.2 V the Paradise switches off */
static inline u32 bat_pct(u32 mv) { return mv >= 3000u ? 100u : mv <= 2200u ? 0u : (mv - 2200u) * 100u / 800u; }
/* "2.84V 80%" (or "?" without a reading) into s (12 bytes) */
__attribute__((noinline, unused)) static void bat_text(char *s)
{
u32 mv = bat_mv(), k = 0;
if (!mv) { s[0] = '?'; s[1] = 0; return; }
#ifdef BAT_SMOOTH
/* 1.6.13 test7: steadier (the reading moved with the load, e.g. while scrolling a menu): v = f v + (1 - f) new,
* f = 7/8, in 1/16 mV; the first reading is taken as it is */
{ static u32 g_bat16; u32 n = mv << 4; g_bat16 = g_bat16 ? (g_bat16 * 7u + n + 4u) >> 3 : n; mv = (g_bat16 + 8u) >> 4; }
#endif
u32 p = bat_pct(mv);
s[k++] = (char)('0' + mv / 1000u); s[k++] = '.'; s[k++] = (char)('0' + (mv / 100u) % 10u); s[k++] = (char)('0' + (mv / 10u) % 10u); s[k++] = 'V'; s[k++] = ' ';
if (p >= 100u) s[k++] = '1';
if (p >= 10u) s[k++] = (char)('0' + (p / 10u) % 10u);
s[k++] = (char)('0' + p % 10u); s[k++] = '%'; s[k] = 0;
}
#ifdef BAT_GUARD
/* test21 (switch BAT_GUARD): the Paradise firmware switches itself off below 2.2 V; under an emulator it ran on until
* the power broke down, perhaps in the middle of a flash write (a lost save). Read every 20 s: two readings in a row
* below BAT_LOW_MV and the app saves everything once and switches off (nothing is written any more). */
#ifndef BAT_LOW_MV
#define BAT_LOW_MV 2210u /* test23: 2.21 V (was 2.25 V), the Paradise itself goes off at 2.2 V */
#endif
__attribute__((noinline, unused, minsize)) static int bat_is_low(void)
{
REG(0x45000100u) |= 1u << 12; BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; BAT_ADM |= 0x8000u;
u32 s = 0;
for (int i = 0; i < 4; i++) { BAT_ADM |= 1u; u32 t = 0; while (!(BAT_ADM & 2u)) if (++t > 100000u) return 0; s += (BAT_ADR >> 6) & 0x3FFu; }
return s < BAT_LOW_MV * 4096u / 3300u;
}
#ifdef BAT_PIC
/* test23 (switch BAT_PIC): the Paradise's own "battery empty" picture (sprite 53 of the ROM) before switching off, as
* the Paradise does. The Studio puts it at 0xFFF000 (last sector of the rescue block): "BAT1", byte count, 16 colours
* (RGB565), then one byte per run: colour << 4 | (length - 1), 128 x 128 pixels row by row. Shown for about 3 s (the caller is at full clock). */
#include "hw.h"
#ifndef BAT_PIC_ATTR
#define BAT_PIC_ATTR __attribute__((noinline, unused, minsize))
#endif
BAT_PIC_ATTR static void bat_pic(void)
{
const volatile u32 *h = (const volatile u32 *)0x60FFF000u;
u32 n = h[1];
if (h[0] != 0x31544142u || n > 4000u) return;
u16 pal[16], row[128]; u32 x = 0, y = 0;
for (u32 i = 0; i < 8u; i++) { u32 w = h[2 + i]; pal[2 * i] = (u16)w; pal[2 * i + 1] = (u16)(w >> 16); }
hw_px_begin(0, 0, 128, 128);
for (u32 i = 0; i < n && y < 128u; i++) {
u32 b = (h[10 + (i >> 2)] >> ((i & 3u) * 8u)) & 0xFFu, k = (b & 15u) + 1u;
while (k--) { row[x++] = pal[b >> 4]; if (x == 128u) { hw_px_row(row, 128); x = 0; y++; } }
}
hw_px_end();
hw_backlight(1);
REG(0xE000EDFCu) |= 1u << 24; REG(0xE0001000u) |= 1u; /* cycle counter: about 3 s at 96 MHz */
for (u32 c0 = REG(0xE0001004u); REG(0xE0001004u) - c0 < 288000000u; ) hw_wdt_feed();
}
#define BAT_PIC_SHOW() bat_pic()
#else
#define BAT_PIC_SHOW() ((void)0)
#endif
/* called every second or so: 1 once the battery is low */
__attribute__((noinline, unused, minsize)) static int bat_guard_tick(void)
{
static u8 c, n;
if (++c < 20u) return 0;
c = 0; n = bat_is_low() ? (u8)(n + 1u) : 0u;
return n >= 2u;
}
#endif
#endif
/* batt.h - 1.6.9 test17 (switch BAT_SHOW): the battery voltage, as the Paradise firmware measures it.
* Found in the firmware (and the Paradise emulator capybara): SAR ADC at 0x4003A000, channel 4 (P0.6, ADP bits 13..15),
* ADM bit 15 on and bit 0 starts a conversion, the result in ADR bits 6..15 (10 bits). The firmware takes
* volts = sample * 0xD33300 / 2^32 (3.3 V for 1024) and switches off below 2.2 V ("replace the battery").
* Header only. Author: mameise */
#ifndef BATT_H
#define BATT_H
#include "io.h"
#define BAT_ADP REG(0x4003A000u)
#define BAT_ADM REG(0x4003A004u)
#define BAT_ADR REG(0x4003A008u)
/* millivolts, 0 = no reading (8 conversions, each waited for at most about 2 ms) */
__attribute__((noinline, unused)) static u32 bat_mv(void)
{
REG(0x45000100u) |= 1u << 12; /* SAR ADC clock */
BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; /* channel 4 */
BAT_ADM |= 0x8000u; /* on */
u32 sum = 0, n = 0;
for (int i = 0; i < 8; i++) {
BAT_ADM |= 1u;
u32 t = 0; while (!(BAT_ADM & 2u) && ++t < 100000u) { }
if (t >= 100000u) break;
sum += (BAT_ADR >> 6) & 0x3FFu; n++;
}
return n ? sum * 3300u / (n * 1024u) : 0u;
}
/* 2 x AAA: 3.0 V and more full, 2.2 V the Paradise switches off */
static inline u32 bat_pct(u32 mv) { return mv >= 3000u ? 100u : mv <= 2200u ? 0u : (mv - 2200u) * 100u / 800u; }
/* "2.84V 80%" (or "?" without a reading) into s (12 bytes) */
__attribute__((noinline, unused)) static void bat_text(char *s)
{
u32 mv = bat_mv(), k = 0;
if (!mv) { s[0] = '?'; s[1] = 0; return; }
#ifdef BAT_SMOOTH
/* 1.6.13 test7: steadier (the reading moved with the load, e.g. while scrolling a menu): v = f v + (1 - f) new,
* f = 7/8, in 1/16 mV; the first reading is taken as it is */
{ static u32 g_bat16; u32 n = mv << 4; g_bat16 = g_bat16 ? (g_bat16 * 7u + n + 4u) >> 3 : n; mv = (g_bat16 + 8u) >> 4; }
#endif
u32 p = bat_pct(mv);
s[k++] = (char)('0' + mv / 1000u); s[k++] = '.'; s[k++] = (char)('0' + (mv / 100u) % 10u); s[k++] = (char)('0' + (mv / 10u) % 10u); s[k++] = 'V'; s[k++] = ' ';
if (p >= 100u) s[k++] = '1';
if (p >= 10u) s[k++] = (char)('0' + (p / 10u) % 10u);
s[k++] = (char)('0' + p % 10u); s[k++] = '%'; s[k] = 0;
}
#ifdef BAT_GUARD
/* test21 (switch BAT_GUARD): the Paradise firmware switches itself off below 2.2 V; under an emulator it ran on until
* the power broke down, perhaps in the middle of a flash write (a lost save). Read every 20 s: two readings in a row
* below BAT_LOW_MV and the app saves everything once and switches off (nothing is written any more). */
#ifndef BAT_LOW_MV
#define BAT_LOW_MV 2210u /* test23: 2.21 V (was 2.25 V), the Paradise itself goes off at 2.2 V */
#endif
__attribute__((noinline, unused, minsize)) static int bat_is_low(void)
{
REG(0x45000100u) |= 1u << 12; BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; BAT_ADM |= 0x8000u;
u32 s = 0;
for (int i = 0; i < 4; i++) { BAT_ADM |= 1u; u32 t = 0; while (!(BAT_ADM & 2u)) if (++t > 100000u) return 0; s += (BAT_ADR >> 6) & 0x3FFu; }
return s < BAT_LOW_MV * 4096u / 3300u;
}
#ifdef BAT_PIC
/* test23 (switch BAT_PIC): the Paradise's own "battery empty" picture (sprite 53 of the ROM) before switching off, as
* the Paradise does. The Studio puts it at 0xFFF000 (last sector of the rescue block): "BAT1", byte count, 16 colours
* (RGB565), then one byte per run: colour << 4 | (length - 1), 128 x 128 pixels row by row. Shown for about 3 s (the caller is at full clock). */
#include "hw.h"
#ifndef BAT_PIC_ATTR
#define BAT_PIC_ATTR __attribute__((noinline, unused, minsize))
#endif
BAT_PIC_ATTR static void bat_pic(void)
{
const volatile u32 *h = (const volatile u32 *)0x60FFF000u;
u32 n = h[1];
if (h[0] != 0x31544142u || n > 4000u) return;
u16 pal[16], row[128]; u32 x = 0, y = 0;
for (u32 i = 0; i < 8u; i++) { u32 w = h[2 + i]; pal[2 * i] = (u16)w; pal[2 * i + 1] = (u16)(w >> 16); }
hw_px_begin(0, 0, 128, 128);
for (u32 i = 0; i < n && y < 128u; i++) {
u32 b = (h[10 + (i >> 2)] >> ((i & 3u) * 8u)) & 0xFFu, k = (b & 15u) + 1u;
while (k--) { row[x++] = pal[b >> 4]; if (x == 128u) { hw_px_row(row, 128); x = 0; y++; } }
}
hw_px_end();
hw_backlight(1);
REG(0xE000EDFCu) |= 1u << 24; REG(0xE0001000u) |= 1u; /* cycle counter: about 3 s at 96 MHz */
for (u32 c0 = REG(0xE0001004u); REG(0xE0001004u) - c0 < 288000000u; ) hw_wdt_feed();
}
#define BAT_PIC_SHOW() bat_pic()
#else
#define BAT_PIC_SHOW() ((void)0)
#endif
/* called every second or so: 1 once the battery is low */
__attribute__((noinline, unused, minsize)) static int bat_guard_tick(void)
{
static u8 c, n;
if (++c < 20u) return 0;
c = 0; n = bat_is_low() ? (u8)(n + 1u) : 0u;
return n >= 2u;
}
#endif
#endif
+11 -11
View File
@@ -1,11 +1,11 @@
#!/bin/sh
set -e
cd "$(dirname "$0")"
CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -O2 -g -fno-common -Wall -Wno-initializer-overrides -Wno-unused-const-variable -fno-builtin-memset -DTC_JIT -DJIT_HASH=512 -DJIT_HWRITE -DNOSRAMWATCH -DJIT_STAGE -DROM_CACHED -DTONE_FIX -DHW_TONE_RESTART -DWAKE_WHEEL -DBL_BLACK -DBL_OFFFIX -DBL_SLEEP -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DLCD_ROWS -DLCD_SKIP -DGFLUSH_STEP -DCLEAN -DGFLUSH_DARK -DGFLUSH_IDLE -DJIT_WHOT -DRTC_MS -DLCD_QUIET -DHW_OPTS -DSESS_ONCE -DSESS_AUTO -DOPT_MENU -DASK_EXTRA -DASK_SLIM -DASK_NUM -DEMU_CARE -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DAPP_SELF -DBL_GUEST_PWM -DTC_IRLINK -DBAT_SHOW -DCLK_ECO -DECO_LAG=50 -DEMU_OVL -DASK_OVL -DDISP_PACK -DASK_DIM -DEMU_DIM -DASK_LANG -DBAT_SMOOTH -DEMU_PW -DJIT_HOT=8 -DEMU_TONE_Q -DEMU_TONE_GAP -DEMU_TQ_DROP -DTONE_SAFE -DEMU_DATE_FIX -DBAT_GUARD -DBAT_PIC -DLIBC_ALIAS -DHW_COLD_MIN -DLK_SYNC -DTC_LZ -DCLK_DISC -DSESS_FLAG -DEMU_KEY_AWAKE -DLZ_GONE -DLIBC_WORD -DID_STRAP -mllvm -arm-load-store-opt=false $XCF"
O=""
for f in main.c hw.c ask.c libc.c flash.c state.c ../core/tc_all.c; do
n=$(basename $f .c); X=""; [ "$n" = ask ] && X=-Oz; [ "$n" = hw ] && X=-Os; [ "$n" = state ] && X=-Os; [ "$n" = flash ] && X=-Os; case "$CF" in *-DLIBC_WORD*) [ "$n" = libc ] && X=-Os;; esac; case "$CF" in *-DEMU_TONE_Q*) [ "$n" = state ] && X=-Oz; [ "$n" = flash ] && X=-Oz;; esac; case "$CF" in *-DEMU_OVL*) [ "$n" != tc_all ] && X="$X -mno-outline";; esac; clang $CF $X -c $f -o $n.o; O="$O $n.o"; done
LDS=link.ld; case "$CF" in *-DEMU_OVL*) LDS=link_ovl.ld;; esac
ld.lld -T $LDS --no-rosegment $O -o emu.elf
llvm-objcopy -O binary -j .text -j .data -j .init emu.elf emu.bin
llvm-size emu.elf; ls -l emu.bin
#!/bin/sh
set -e
cd "$(dirname "$0")"
CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -O2 -g -fno-common -Wall -Wno-initializer-overrides -Wno-unused-const-variable -fno-builtin-memset -DTC_JIT -DJIT_HASH=512 -DJIT_HWRITE -DNOSRAMWATCH -DJIT_STAGE -DROM_CACHED -DTONE_FIX -DHW_TONE_RESTART -DWAKE_WHEEL -DBL_BLACK -DBL_OFFFIX -DBL_SLEEP -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DLCD_ROWS -DLCD_SKIP -DGFLUSH_STEP -DCLEAN -DGFLUSH_DARK -DGFLUSH_IDLE -DJIT_WHOT -DRTC_MS -DLCD_QUIET -DHW_OPTS -DSESS_ONCE -DSESS_AUTO -DOPT_MENU -DASK_EXTRA -DASK_SLIM -DASK_NUM -DEMU_CARE -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DAPP_SELF -DBL_GUEST_PWM -DTC_IRLINK -DBAT_SHOW -DCLK_ECO -DECO_LAG=50 -DEMU_OVL -DASK_OVL -DDISP_PACK -DASK_DIM -DEMU_DIM -DASK_LANG -DBAT_SMOOTH -DEMU_PW -DJIT_HOT=8 -DEMU_TONE_Q -DEMU_TONE_GAP -DEMU_TQ_DROP -DTONE_SAFE -DEMU_DATE_FIX -DBAT_GUARD -DBAT_PIC -DLIBC_ALIAS -DHW_COLD_MIN -DLK_SYNC -DTC_LZ -DCLK_DISC -DSESS_FLAG -DEMU_KEY_AWAKE -DLZ_GONE -DLIBC_WORD -DID_STRAP -mllvm -arm-load-store-opt=false $XCF"
O=""
for f in main.c hw.c ask.c libc.c flash.c state.c ../core/tc_all.c; do
n=$(basename $f .c); X=""; [ "$n" = ask ] && X=-Oz; [ "$n" = hw ] && X=-Os; [ "$n" = state ] && X=-Os; [ "$n" = flash ] && X=-Os; case "$CF" in *-DLIBC_WORD*) [ "$n" = libc ] && X=-Os;; esac; case "$CF" in *-DEMU_TONE_Q*) [ "$n" = state ] && X=-Oz; [ "$n" = flash ] && X=-Oz;; esac; case "$CF" in *-DEMU_OVL*) [ "$n" != tc_all ] && X="$X -mno-outline";; esac; clang $CF $X -c $f -o $n.o; O="$O $n.o"; done
LDS=link.ld; case "$CF" in *-DEMU_OVL*) LDS=link_ovl.ld;; esac
ld.lld -T $LDS --no-rosegment $O -o emu.elf
llvm-objcopy -O binary -j .text -j .data -j .init emu.elf emu.bin
llvm-size emu.elf; ls -l emu.bin
+6 -6
View File
@@ -1,6 +1,6 @@
/* disp_pack.h - generated from disp_power.h (the same sequence, packed: switch DISP_PACK). 1.6.13 (TamaEmu: room in the
* program): addresses and values each from a table, one byte per index. Author: mameise */
#define DISP_PACK_N 262
__attribute__((section(".initdata"))) static const unsigned int disp_pack_a[36]={0x45000020,0x45000210,0x45000214,0x45000218,0x45000204,0x45000200,0x4003a000,0x4003a004,0x40038000,0x40038014,0x40038018,0x40038004,0x40038008,0x4003800c,0x40038010,0x40007034,0x4001803c,0x4001903c,0x4001a03c,0x40018004,0x40018000,0x40018008,0x40019004,0x40019000,0x40019008,0x4001a004,0x4001a000,0x4001a008,0x40003000,0x40003018,0x4000301c,0x40003020,0x40003024,0x40003014,0x40003008,0x4000303c};
__attribute__((section(".initdata"))) static const unsigned int disp_pack_v[73]={0x40,0x0,0xe0,0x42,0x8000,0x8001,0xf0,0xa001,0x18005da0,0xffc,0x1,0x10,0x18000ba0,0xffffffff,0xfffff5df,0x30,0xfffffffe,0x15008a56,0x15008a55,0xfffffffd,0x15008a59,0xfffffffb,0x15008a65,0xfffffff7,0x15008a95,0x20,0xffffffef,0x15008855,0xffffffcf,0x15008055,0xffffff4f,0xfffffecf,0x15028055,0xfffffdcf,0x15088055,0xfffffbcf,0x15208055,0xfffff7cf,0x15808055,0xffffefcf,0x16008055,0xffffdfcf,0x19008055,0xffffbfcf,0x25008055,0xa00,0x55995800,0xa20,0xfffff59f,0x55996800,0xfffff55f,0x55999800,0xfffff4df,0x559a5800,0x820,0xfffff1df,0x55a95800,0x220,0xffffe5df,0x56995800,0xffffd5df,0x59995800,0xffffb5df,0x65995800,0xffff75df,0x95995800,0x52,0x50,0x58,0x60,0x90,0x2,0x1f};
__attribute__((section(".initdata"))) static const unsigned char disp_pack_i[262][2]={{0,0},{1,1},{2,1},{3,1},{4,1},{5,2},{4,1},{5,2},{0,3},{6,4},{7,4},{7,5},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{15,1},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{16,13},{17,14},{18,13},{19,15},{20,16},{21,17},{19,15},{20,16},{21,18},{19,15},{20,19},{21,20},{19,15},{20,19},{21,18},{19,15},{20,21},{21,22},{19,15},{20,21},{21,18},{19,15},{20,23},{21,24},{19,15},{20,23},{21,18},{19,25},{20,26},{21,18},{19,15},{20,26},{21,27},{19,11},{20,28},{21,27},{19,15},{20,28},{21,29},{19,15},{20,30},{21,29},{19,15},{20,30},{21,29},{19,15},{20,31},{21,32},{19,15},{20,31},{21,29},{19,15},{20,33},{21,34},{19,15},{20,33},{21,29},{19,15},{20,35},{21,36},{19,15},{20,35},{21,29},{19,15},{20,37},{21,38},{19,15},{20,37},{21,29},{19,15},{20,39},{21,40},{19,15},{20,39},{21,29},{19,15},{20,41},{21,42},{19,15},{20,41},{21,29},{19,15},{20,43},{21,44},{19,15},{20,43},{21,29},{22,45},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,48},{24,49},{22,47},{23,48},{24,46},{22,47},{23,50},{24,51},{22,47},{23,50},{24,46},{22,47},{23,52},{24,53},{22,47},{23,52},{24,46},{22,54},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46},{22,57},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,58},{24,59},{22,47},{23,58},{24,46},{22,47},{23,60},{24,61},{22,47},{23,60},{24,46},{22,47},{23,62},{24,63},{22,47},{23,62},{24,46},{22,47},{23,64},{24,65},{22,47},{23,64},{24,46},{25,1},{26,16},{27,66},{25,1},{26,16},{27,67},{25,1},{26,19},{27,68},{25,1},{26,19},{27,67},{25,1},{26,21},{27,69},{25,1},{26,21},{27,67},{25,1},{26,23},{27,70},{25,1},{26,23},{27,67},{28,1},{29,1},{30,1},{31,1},{32,1},{33,1},{28,71},{34,1},{35,72},{28,10},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46}};
/* disp_pack.h - generated from disp_power.h (the same sequence, packed: switch DISP_PACK). 1.6.13 (TamaEmu: room in the
* program): addresses and values each from a table, one byte per index. Author: mameise */
#define DISP_PACK_N 262
__attribute__((section(".initdata"))) static const unsigned int disp_pack_a[36]={0x45000020,0x45000210,0x45000214,0x45000218,0x45000204,0x45000200,0x4003a000,0x4003a004,0x40038000,0x40038014,0x40038018,0x40038004,0x40038008,0x4003800c,0x40038010,0x40007034,0x4001803c,0x4001903c,0x4001a03c,0x40018004,0x40018000,0x40018008,0x40019004,0x40019000,0x40019008,0x4001a004,0x4001a000,0x4001a008,0x40003000,0x40003018,0x4000301c,0x40003020,0x40003024,0x40003014,0x40003008,0x4000303c};
__attribute__((section(".initdata"))) static const unsigned int disp_pack_v[73]={0x40,0x0,0xe0,0x42,0x8000,0x8001,0xf0,0xa001,0x18005da0,0xffc,0x1,0x10,0x18000ba0,0xffffffff,0xfffff5df,0x30,0xfffffffe,0x15008a56,0x15008a55,0xfffffffd,0x15008a59,0xfffffffb,0x15008a65,0xfffffff7,0x15008a95,0x20,0xffffffef,0x15008855,0xffffffcf,0x15008055,0xffffff4f,0xfffffecf,0x15028055,0xfffffdcf,0x15088055,0xfffffbcf,0x15208055,0xfffff7cf,0x15808055,0xffffefcf,0x16008055,0xffffdfcf,0x19008055,0xffffbfcf,0x25008055,0xa00,0x55995800,0xa20,0xfffff59f,0x55996800,0xfffff55f,0x55999800,0xfffff4df,0x559a5800,0x820,0xfffff1df,0x55a95800,0x220,0xffffe5df,0x56995800,0xffffd5df,0x59995800,0xffffb5df,0x65995800,0xffff75df,0x95995800,0x52,0x50,0x58,0x60,0x90,0x2,0x1f};
__attribute__((section(".initdata"))) static const unsigned char disp_pack_i[262][2]={{0,0},{1,1},{2,1},{3,1},{4,1},{5,2},{4,1},{5,2},{0,3},{6,4},{7,4},{7,5},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{15,1},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{16,13},{17,14},{18,13},{19,15},{20,16},{21,17},{19,15},{20,16},{21,18},{19,15},{20,19},{21,20},{19,15},{20,19},{21,18},{19,15},{20,21},{21,22},{19,15},{20,21},{21,18},{19,15},{20,23},{21,24},{19,15},{20,23},{21,18},{19,25},{20,26},{21,18},{19,15},{20,26},{21,27},{19,11},{20,28},{21,27},{19,15},{20,28},{21,29},{19,15},{20,30},{21,29},{19,15},{20,30},{21,29},{19,15},{20,31},{21,32},{19,15},{20,31},{21,29},{19,15},{20,33},{21,34},{19,15},{20,33},{21,29},{19,15},{20,35},{21,36},{19,15},{20,35},{21,29},{19,15},{20,37},{21,38},{19,15},{20,37},{21,29},{19,15},{20,39},{21,40},{19,15},{20,39},{21,29},{19,15},{20,41},{21,42},{19,15},{20,41},{21,29},{19,15},{20,43},{21,44},{19,15},{20,43},{21,29},{22,45},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,48},{24,49},{22,47},{23,48},{24,46},{22,47},{23,50},{24,51},{22,47},{23,50},{24,46},{22,47},{23,52},{24,53},{22,47},{23,52},{24,46},{22,54},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46},{22,57},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,58},{24,59},{22,47},{23,58},{24,46},{22,47},{23,60},{24,61},{22,47},{23,60},{24,46},{22,47},{23,62},{24,63},{22,47},{23,62},{24,46},{22,47},{23,64},{24,65},{22,47},{23,64},{24,46},{25,1},{26,16},{27,66},{25,1},{26,16},{27,67},{25,1},{26,19},{27,68},{25,1},{26,19},{27,67},{25,1},{26,21},{27,69},{25,1},{26,21},{27,67},{25,1},{26,23},{27,70},{25,1},{26,23},{27,67},{28,1},{29,1},{30,1},{31,1},{32,1},{33,1},{28,71},{34,1},{35,72},{28,10},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46}};
+5 -5
View File
@@ -1,5 +1,5 @@
// Extracted from the REAL Flash Utility (same PRAM/post-reset context as
// our app). Order kept word for word. clk tail (reset release) first,
// then display/GPIO/backlight registers.
__attribute__((section(".initdata"))) static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001aLine truncated
#define DISP_POWER_N 262
// Extracted from the REAL Flash Utility (same PRAM/post-reset context as
// our app). Order kept word for word. clk tail (reset release) first,
// then display/GPIO/backlight registers.
__attribute__((section(".initdata"))) static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001aLine truncated
#define DISP_POWER_N 262
+80 -80
View File
@@ -1,80 +1,80 @@
/* eco.h - 1.6.9 test22 (switch CLK_ECO): a lower clock while the screen is off, to save the batteries.
* The Paradise runs at 96 MHz; the old toys need a fraction of it when nothing is drawn. Every 500 ms the core's own
* cycle counter (DWT CYCCNT, it stands while the core sleeps in WFI) tells how busy the emulation was: below 35 % one
* step down (half the clock), above 80 % one step up, down to 12 MHz (AHB / 8). If the emulation falls behind anyway,
* straight back to full speed and for 5 minutes one step less deep. Full speed at once
* for a key, the screen on, a tone or link traffic. Header only. Author: mameise */
#ifndef ECO_H
#define ECO_H
#include "hw.h"
#ifndef ECO_SH
#define ECO_SH 3u /* lowest: 96 MHz >> 3 = 12 MHz */
#endif
#ifndef ECO_LAG
#define ECO_LAG 25 /* ms behind: too slow (the apps drop time only beyond 50 ms) */
#endif
#define ECO_DEMCR REG(0xE000EDFCu)
#define ECO_DWT_CTRL REG(0xE0001000u)
#define ECO_CYC REG(0xE0001004u)
#ifdef ECO_DEBUG
__attribute__((used)) volatile u32 g_eco_dbg[4]; /* tests: ups, last lag, last busy, want_low drops */
#endif
static u32 g_eco_hold, g_eco_t0, g_eco_c0, g_eco_on, g_eco_max = ECO_SH, g_eco_max_until;
/* too slow: full speed, wait longer before the next try. Also called from the apps' catch-up loops. */
__attribute__((noinline, unused, minsize)) static void eco_up(u32 now, u32 core_hz)
{
/* this step was too slow: back to full speed at once, then at most one step less deep for 5 minutes */
#ifdef ECO_DEBUG
g_eco_dbg[0]++;
#endif
if (g_hw_clk_sh) { g_eco_max = g_hw_clk_sh - 1u; g_eco_max_until = now + 300000u; hw_clk_shift(0, core_hz); g_eco_hold = now + 2000u; }
g_eco_t0 = now; g_eco_c0 = ECO_CYC;
}
#define ECO_CHECK(now, lag, hz) do { if (g_hw_clk_sh && (int)(lag) > ECO_LAG) eco_up((now), (hz)); } while (0)
#ifdef ECO_RTC
/* test27 (switch ECO_RTC): the millisecond tick against the Paradise's seconds counter (crystal). Every 4 whole
* seconds at one clock step: if fewer than 3800 ms were counted, the missing ms are returned (the program adds them
* to its tick, the emulation catches up) and that clock step is not used again until the next start. */
static u32 g_er_s, g_er_ms, g_er_n, g_er_sh;
__attribute__((used)) volatile u32 g_eco_bad, g_eco_fix[2]; /* clock steps found wrong; corrections, ms added */
__attribute__((noinline, unused, minsize)) static u32 eco_rtc(u32 now, u32 core_hz)
{
u32 s = REG(0x45000304u), add = 0;
if (s == g_er_s) return 0;
if (s - g_er_s == 1u && g_er_sh == g_hw_clk_sh) {
if (!g_er_n) { g_er_n = 1; g_er_ms = now; } /* a window starts at a change of the second */
else if (++g_er_n >= 5u) {
u32 d = now - g_er_ms;
if (d + 200u < 4000u) {
add = 4000u - d; g_eco_fix[0]++; g_eco_fix[1] += add;
if (g_hw_clk_sh) { g_eco_bad |= 1u << g_hw_clk_sh; hw_clk_shift(0, core_hz); }
}
g_er_n = 1; g_er_ms = now + add; g_er_sh = g_hw_clk_sh;
}
} else { g_er_n = 0; g_er_sh = g_hw_clk_sh; } /* first call, a second missed or another clock step: wait */
g_er_s = s;
return add;
}
#define ECO_BAD(sh) ((g_eco_bad >> (sh)) & 1u)
#else
#define ECO_BAD(sh) 0u
#endif
/* want_low: screen off, no key, no tone, no link; lag: how many ms the emulation is behind now; core_hz: SysTick base */
__attribute__((noinline, unused, minsize)) static void eco_poll(u32 now, int want_low, int lag, u32 core_hz)
{
u32 sh = g_hw_clk_sh;
if (!g_eco_on) { ECO_DEMCR |= 1u << 24; ECO_DWT_CTRL |= 1u; g_eco_on = 1; g_eco_t0 = now; g_eco_c0 = ECO_CYC; }
#ifdef ECO_DEBUG
if (!want_low && sh) g_eco_dbg[3]++;
if (lag > (int)g_eco_dbg[1]) g_eco_dbg[1] = (u32)lag;
#endif
if (!want_low) { if (sh) hw_clk_shift(0, core_hz); g_eco_hold = now + 1000u; g_eco_t0 = now; g_eco_c0 = ECO_CYC; return; }
if (lag > ECO_LAG) { eco_up(now, core_hz); return; }
if (now - g_eco_t0 < 500u) return;
u32 cyc = ECO_CYC - g_eco_c0, avail = (core_hz >> sh) / 1000u * (now - g_eco_t0), busy = avail >= 100u ? cyc / (avail / 100u) : 100u;
g_eco_t0 = now; g_eco_c0 = ECO_CYC;
if (busy > 80u && sh) { hw_clk_shift(sh - 1u, core_hz); g_eco_hold = now + 2000u; return; }
if (g_eco_max < ECO_SH && (int)(now - g_eco_max_until) >= 0) g_eco_max++;
if (busy < 35u && sh < g_eco_max && !ECO_BAD(sh + 1u) && (int)(now - g_eco_hold) >= 0) hw_clk_shift(sh + 1u, core_hz);
}
#endif
/* eco.h - 1.6.9 test22 (switch CLK_ECO): a lower clock while the screen is off, to save the batteries.
* The Paradise runs at 96 MHz; the old toys need a fraction of it when nothing is drawn. Every 500 ms the core's own
* cycle counter (DWT CYCCNT, it stands while the core sleeps in WFI) tells how busy the emulation was: below 35 % one
* step down (half the clock), above 80 % one step up, down to 12 MHz (AHB / 8). If the emulation falls behind anyway,
* straight back to full speed and for 5 minutes one step less deep. Full speed at once
* for a key, the screen on, a tone or link traffic. Header only. Author: mameise */
#ifndef ECO_H
#define ECO_H
#include "hw.h"
#ifndef ECO_SH
#define ECO_SH 3u /* lowest: 96 MHz >> 3 = 12 MHz */
#endif
#ifndef ECO_LAG
#define ECO_LAG 25 /* ms behind: too slow (the apps drop time only beyond 50 ms) */
#endif
#define ECO_DEMCR REG(0xE000EDFCu)
#define ECO_DWT_CTRL REG(0xE0001000u)
#define ECO_CYC REG(0xE0001004u)
#ifdef ECO_DEBUG
__attribute__((used)) volatile u32 g_eco_dbg[4]; /* tests: ups, last lag, last busy, want_low drops */
#endif
static u32 g_eco_hold, g_eco_t0, g_eco_c0, g_eco_on, g_eco_max = ECO_SH, g_eco_max_until;
/* too slow: full speed, wait longer before the next try. Also called from the apps' catch-up loops. */
__attribute__((noinline, unused, minsize)) static void eco_up(u32 now, u32 core_hz)
{
/* this step was too slow: back to full speed at once, then at most one step less deep for 5 minutes */
#ifdef ECO_DEBUG
g_eco_dbg[0]++;
#endif
if (g_hw_clk_sh) { g_eco_max = g_hw_clk_sh - 1u; g_eco_max_until = now + 300000u; hw_clk_shift(0, core_hz); g_eco_hold = now + 2000u; }
g_eco_t0 = now; g_eco_c0 = ECO_CYC;
}
#define ECO_CHECK(now, lag, hz) do { if (g_hw_clk_sh && (int)(lag) > ECO_LAG) eco_up((now), (hz)); } while (0)
#ifdef ECO_RTC
/* test27 (switch ECO_RTC): the millisecond tick against the Paradise's seconds counter (crystal). Every 4 whole
* seconds at one clock step: if fewer than 3800 ms were counted, the missing ms are returned (the program adds them
* to its tick, the emulation catches up) and that clock step is not used again until the next start. */
static u32 g_er_s, g_er_ms, g_er_n, g_er_sh;
__attribute__((used)) volatile u32 g_eco_bad, g_eco_fix[2]; /* clock steps found wrong; corrections, ms added */
__attribute__((noinline, unused, minsize)) static u32 eco_rtc(u32 now, u32 core_hz)
{
u32 s = REG(0x45000304u), add = 0;
if (s == g_er_s) return 0;
if (s - g_er_s == 1u && g_er_sh == g_hw_clk_sh) {
if (!g_er_n) { g_er_n = 1; g_er_ms = now; } /* a window starts at a change of the second */
else if (++g_er_n >= 5u) {
u32 d = now - g_er_ms;
if (d + 200u < 4000u) {
add = 4000u - d; g_eco_fix[0]++; g_eco_fix[1] += add;
if (g_hw_clk_sh) { g_eco_bad |= 1u << g_hw_clk_sh; hw_clk_shift(0, core_hz); }
}
g_er_n = 1; g_er_ms = now + add; g_er_sh = g_hw_clk_sh;
}
} else { g_er_n = 0; g_er_sh = g_hw_clk_sh; } /* first call, a second missed or another clock step: wait */
g_er_s = s;
return add;
}
#define ECO_BAD(sh) ((g_eco_bad >> (sh)) & 1u)
#else
#define ECO_BAD(sh) 0u
#endif
/* want_low: screen off, no key, no tone, no link; lag: how many ms the emulation is behind now; core_hz: SysTick base */
__attribute__((noinline, unused, minsize)) static void eco_poll(u32 now, int want_low, int lag, u32 core_hz)
{
u32 sh = g_hw_clk_sh;
if (!g_eco_on) { ECO_DEMCR |= 1u << 24; ECO_DWT_CTRL |= 1u; g_eco_on = 1; g_eco_t0 = now; g_eco_c0 = ECO_CYC; }
#ifdef ECO_DEBUG
if (!want_low && sh) g_eco_dbg[3]++;
if (lag > (int)g_eco_dbg[1]) g_eco_dbg[1] = (u32)lag;
#endif
if (!want_low) { if (sh) hw_clk_shift(0, core_hz); g_eco_hold = now + 1000u; g_eco_t0 = now; g_eco_c0 = ECO_CYC; return; }
if (lag > ECO_LAG) { eco_up(now, core_hz); return; }
if (now - g_eco_t0 < 500u) return;
u32 cyc = ECO_CYC - g_eco_c0, avail = (core_hz >> sh) / 1000u * (now - g_eco_t0), busy = avail >= 100u ? cyc / (avail / 100u) : 100u;
g_eco_t0 = now; g_eco_c0 = ECO_CYC;
if (busy > 80u && sh) { hw_clk_shift(sh - 1u, core_hz); g_eco_hold = now + 2000u; return; }
if (g_eco_max < ECO_SH && (int)(now - g_eco_max_until) >= 0) g_eco_max++;
if (busy < 35u && sh < g_eco_max && !ECO_BAD(sh + 1u) && (int)(now - g_eco_hold) >= 0) hw_clk_shift(sh + 1u, core_hz);
}
#endif
+20 -20
View File
@@ -1,20 +1,20 @@
/* exitkey.h - test24 (switch EXIT_KEY): how to go back to the Paradise or the menu, chosen in the Studio (tab Menu) for
* every program. The Studio writes "EX" << 16 | mode into the last word of the program's vector table (0x13C, IRQ 63,
* never used); without it the program's own way stays. Modes: 0 wheel held (as before), 1 wheel and A held, 2 wheel
* and C held, 3 wheel held 5 s. Header only. Author: mameise */
#ifndef EXITKEY_H
#define EXITKEY_H
#include "hw.h"
#ifdef EXIT_KEY
/* the wheel held for held ms (def: the program's own time): 1 = go back */
__attribute__((noinline, unused, minsize)) static int exit_now(u32 held, u32 def)
{
u32 v = *(volatile const u32 *)0x13Cu, m = (v >> 16) == 0x5845u ? (v & 3u) : 0u;
if (m == 1u || m == 2u) return held > 300u && (hw_buttons() & (m == 1u ? BTN_A : BTN_C)) != 0u;
return held > (m == 3u ? 5000u : def);
}
#define EXIT_NOW(held, def) exit_now((held), (def))
#else
#define EXIT_NOW(held, def) ((held) > (def))
#endif
#endif
/* exitkey.h - test24 (switch EXIT_KEY): how to go back to the Paradise or the menu, chosen in the Studio (tab Menu) for
* every program. The Studio writes "EX" << 16 | mode into the last word of the program's vector table (0x13C, IRQ 63,
* never used); without it the program's own way stays. Modes: 0 wheel held (as before), 1 wheel and A held, 2 wheel
* and C held, 3 wheel held 5 s. Header only. Author: mameise */
#ifndef EXITKEY_H
#define EXITKEY_H
#include "hw.h"
#ifdef EXIT_KEY
/* the wheel held for held ms (def: the program's own time): 1 = go back */
__attribute__((noinline, unused, minsize)) static int exit_now(u32 held, u32 def)
{
u32 v = *(volatile const u32 *)0x13Cu, m = (v >> 16) == 0x5845u ? (v & 3u) : 0u;
if (m == 1u || m == 2u) return held > 300u && (hw_buttons() & (m == 1u ? BTN_A : BTN_C)) != 0u;
return held > (m == 3u ? 5000u : def);
}
#define EXIT_NOW(held, def) exit_now((held), (def))
#else
#define EXIT_NOW(held, def) ((held) > (def))
#endif
#endif
+95 -95
View File
@@ -1,95 +1,95 @@
/* Write the Paradise flash: erase and program a sector, exactly like the
* mameise flash app (confirmed on the device). Runs from PRAM; nothing may be
* read from the XIP window while writing. */
#include "io.h"
#include "flash.h"
#define F_DMEM REG(FCTL+0x100)
#define F_DLEN REG(FCTL+0x104)
#define F_DCTL REG(FCTL+0x108)
#define F_DFLA REG(FCTL+0x10C)
static void feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; }
static void wait_loop(u32 n){ for(volatile u32 i=0;i<n;i++){ if((i & 0xFFFFu)==0) feed(); } }
/* Read the flash status register, exactly like the Paradise firmware (PRAM 0x5808
* with -1): set read command bit 14, wait until it clears, byte from 0x14. */
static u32 flash_status(void)
{
REG(FCTL+0x004) |= 0x4000u;
for(u32 g=0; (REG(FCTL+0x004)&0x4000u) && g<1000000u; g++){}
return REG(FCTL+0x014) & 0xFFu;
}
/* Wait until the flash is ready (WIP = bit 0), like the firmware after
* erasing (0x38B0) and programming (0x3D28). Upper limit as before. */
static void wait_ready(void)
{
wait_loop(2000u);
for(u32 i=0;i<400000u;i++){
if(!(flash_status() & 1u)) return;
if((i & 0xFFu)==0) feed();
}
}
void flash_erase4k(u32 addr)
{
u32 a1=addr>>1;
REG(FCTL+0x008)=(a1>>16)&0xFFFFu;
REG(FCTL+0x00C)=a1 & 0xFFFFu;
REG(FCTL+0x004)=0x00000400u;
for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
wait_ready();
}
void flash_prog4k(u32 addr, const void *src)
{
u32 a1=addr>>1;
u32 hi=(a1>>16)&0xFFFFu;
u32 lo=a1 & 0xFFFFu;
flash_erase4k(addr);
/* program */
REG(FCTL+0x008)=0x3000u | hi;
REG(FCTL+0x00C)=lo;
REG(FCTL+0x004)=0x00000400u;
REG(FCTL+0x004)=0x00004000u;
REG(FCTL+0x000)=0x0000d080u;
REG(FCTL+0x020)=0;
REG(FCTL+0x010)=0;
REG(FCTL+0x000)=0x0000d082u;
F_DFLA=0x60000000u | (addr & 0x00FFFFFFu);
F_DLEN=0x1000u; F_DMEM=(u32)src;
F_DCTL=0u;
F_DCTL=1u;
for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
wait_ready();
}
void flash_read(u32 addr, void *dst, u32 len)
{
const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu));
u8 *d=(u8*)dst;
for(u32 i=0;i<len;i++) d[i]=s[i];
}
int flash_same(u32 addr, const void *src, u32 len)
{
const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu));
const u8 *p=(const u8*)src;
for(u32 i=0;i<len;i++) if(s[i]!=p[i]) return 0;
return 1;
}
/* Write the sector only if it differs. Returns 1 if written. */
int flash_update4k(u32 addr, const void *src)
{
if(flash_same(addr, src, 0x1000u)) return 0;
flash_prog4k(addr, src);
return 1;
}
int flash_isff(u32 addr, u32 len)
{
const volatile u32 *s=(const volatile u32*)(0x60000000u + (addr & 0x00FFFFFFu));
for(u32 i=0;i<len/4u;i++) if(s[i]!=0xFFFFFFFFu) return 0;
return 1;
}
/* Write the Paradise flash: erase and program a sector, exactly like the
* mameise flash app (confirmed on the device). Runs from PRAM; nothing may be
* read from the XIP window while writing. */
#include "io.h"
#include "flash.h"
#define F_DMEM REG(FCTL+0x100)
#define F_DLEN REG(FCTL+0x104)
#define F_DCTL REG(FCTL+0x108)
#define F_DFLA REG(FCTL+0x10C)
static void feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; }
static void wait_loop(u32 n){ for(volatile u32 i=0;i<n;i++){ if((i & 0xFFFFu)==0) feed(); } }
/* Read the flash status register, exactly like the Paradise firmware (PRAM 0x5808
* with -1): set read command bit 14, wait until it clears, byte from 0x14. */
static u32 flash_status(void)
{
REG(FCTL+0x004) |= 0x4000u;
for(u32 g=0; (REG(FCTL+0x004)&0x4000u) && g<1000000u; g++){}
return REG(FCTL+0x014) & 0xFFu;
}
/* Wait until the flash is ready (WIP = bit 0), like the firmware after
* erasing (0x38B0) and programming (0x3D28). Upper limit as before. */
static void wait_ready(void)
{
wait_loop(2000u);
for(u32 i=0;i<400000u;i++){
if(!(flash_status() & 1u)) return;
if((i & 0xFFu)==0) feed();
}
}
void flash_erase4k(u32 addr)
{
u32 a1=addr>>1;
REG(FCTL+0x008)=(a1>>16)&0xFFFFu;
REG(FCTL+0x00C)=a1 & 0xFFFFu;
REG(FCTL+0x004)=0x00000400u;
for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
wait_ready();
}
void flash_prog4k(u32 addr, const void *src)
{
u32 a1=addr>>1;
u32 hi=(a1>>16)&0xFFFFu;
u32 lo=a1 & 0xFFFFu;
flash_erase4k(addr);
/* program */
REG(FCTL+0x008)=0x3000u | hi;
REG(FCTL+0x00C)=lo;
REG(FCTL+0x004)=0x00000400u;
REG(FCTL+0x004)=0x00004000u;
REG(FCTL+0x000)=0x0000d080u;
REG(FCTL+0x020)=0;
REG(FCTL+0x010)=0;
REG(FCTL+0x000)=0x0000d082u;
F_DFLA=0x60000000u | (addr & 0x00FFFFFFu);
F_DLEN=0x1000u; F_DMEM=(u32)src;
F_DCTL=0u;
F_DCTL=1u;
for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); }
wait_ready();
}
void flash_read(u32 addr, void *dst, u32 len)
{
const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu));
u8 *d=(u8*)dst;
for(u32 i=0;i<len;i++) d[i]=s[i];
}
int flash_same(u32 addr, const void *src, u32 len)
{
const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu));
const u8 *p=(const u8*)src;
for(u32 i=0;i<len;i++) if(s[i]!=p[i]) return 0;
return 1;
}
/* Write the sector only if it differs. Returns 1 if written. */
int flash_update4k(u32 addr, const void *src)
{
if(flash_same(addr, src, 0x1000u)) return 0;
flash_prog4k(addr, src);
return 1;
}
int flash_isff(u32 addr, u32 len)
{
const volatile u32 *s=(const volatile u32*)(0x60000000u + (addr & 0x00FFFFFFu));
for(u32 i=0;i<len/4u;i++) if(s[i]!=0xFFFFFFFFu) return 0;
return 1;
}
+10 -10
View File
@@ -1,10 +1,10 @@
#ifndef FLASH_H
#define FLASH_H
#include "io.h"
void flash_prog4k(u32 addr, const void *src);
void flash_read(u32 addr, void *dst, u32 len);
int flash_same(u32 addr, const void *src, u32 len);
int flash_update4k(u32 addr, const void *src);
void flash_erase4k(u32 addr);
int flash_isff(u32 addr, u32 len);
#endif
#ifndef FLASH_H
#define FLASH_H
#include "io.h"
void flash_prog4k(u32 addr, const void *src);
void flash_read(u32 addr, void *dst, u32 len);
int flash_same(u32 addr, const void *src, u32 len);
int flash_update4k(u32 addr, const void *src);
void flash_erase4k(u32 addr);
int flash_isff(u32 addr, u32 len);
#endif
+48 -48
View File
@@ -1,48 +1,48 @@
/* 1.7.2 test14 (GPLAY): play time in DOOM, Wolfenstein, Game Boy and Master System earns Tamapoints for the Paradise.
* Also Pokemon mini and Arduboy (1.7.3). Time counts between two key presses that lie at most 60 s apart (the Paradise's seconds counter 0x45000304, it runs
* in every program). Going back, 10 points per whole minute go into the money of the settings block 0xEFE000/0xEFF000
* (both copies, new CRC, as the menu sets Tamapoints), when the menu's settings block has the flag F_GPLAY (64): the
* Studio sets it with the checkbox in the Menu tab, only in a ROM with the Paradise. The rest of a minute stays. */
#ifndef GPLAY_H
#define GPLAY_H
#include <stdint.h>
extern uint32_t g_gp_secs, g_gp_last;
#define GP_CNT (*(volatile uint32_t *)0x45000304u)
#define GP_RATE 10u
#define GP_MAX 99999u
#define GP_F 64u
static inline void gp_key(uint32_t b)
{
if (!b) return;
uint32_t s = GP_CNT, d = s - g_gp_last;
if (g_gp_last && d <= 60u) g_gp_secs += d;
g_gp_last = s;
}
#ifdef GP_POINTS /* the part that writes (with paraback.h: flash_read, flash_update4k, pb_crc) */
static inline uint32_t gp_u32(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8 | (uint32_t)b[o + 2] << 16 | (uint32_t)b[o + 3] << 24; }
/* b: 4 KB buffer. Returns the points added. */
__attribute__((noinline, unused, minsize)) PB_ATTR static uint32_t para_points(uint8_t *b)
{
uint32_t add = g_gp_secs / 60u * GP_RATE, mo = 0;
if (!add) return 0;
for (uint32_t p = 0x90000u; p < 0x110000u && !mo; p += 0x1000u) {
flash_read(p + 0x140u, b, 264u);
if (gp_u32(b, 0) == 0x444C4546u && gp_u32(b, 4) >= 9u && (gp_u32(b, 36) & GP_F)) mo = gp_u32(b, 260);
}
if (!mo || mo + 4u > 0x1000u) return 0;
flash_read(0xEFE000u, b, 0x1000u);
uint32_t c = pb_crc(b);
if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0;
uint32_t m = gp_u32(b, mo), n = m + add;
if (m > GP_MAX) return 0; /* not a money field as we know it */
if (n > GP_MAX) n = GP_MAX;
b[mo] = (uint8_t)n; b[mo + 1] = (uint8_t)(n >> 8); b[mo + 2] = (uint8_t)(n >> 16); b[mo + 3] = (uint8_t)(n >> 24);
c = pb_crc(b);
pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu);
flash_update4k(0xEFE000u, b);
flash_update4k(0xEFF000u, b);
g_gp_secs %= 60u;
return n - m;
}
#endif
#endif
/* 1.7.2 test14 (GPLAY): play time in DOOM, Wolfenstein, Game Boy and Master System earns Tamapoints for the Paradise.
* Also Pokemon mini and Arduboy (1.7.3). Time counts between two key presses that lie at most 60 s apart (the Paradise's seconds counter 0x45000304, it runs
* in every program). Going back, 10 points per whole minute go into the money of the settings block 0xEFE000/0xEFF000
* (both copies, new CRC, as the menu sets Tamapoints), when the menu's settings block has the flag F_GPLAY (64): the
* Studio sets it with the checkbox in the Menu tab, only in a ROM with the Paradise. The rest of a minute stays. */
#ifndef GPLAY_H
#define GPLAY_H
#include <stdint.h>
extern uint32_t g_gp_secs, g_gp_last;
#define GP_CNT (*(volatile uint32_t *)0x45000304u)
#define GP_RATE 10u
#define GP_MAX 99999u
#define GP_F 64u
static inline void gp_key(uint32_t b)
{
if (!b) return;
uint32_t s = GP_CNT, d = s - g_gp_last;
if (g_gp_last && d <= 60u) g_gp_secs += d;
g_gp_last = s;
}
#ifdef GP_POINTS /* the part that writes (with paraback.h: flash_read, flash_update4k, pb_crc) */
static inline uint32_t gp_u32(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8 | (uint32_t)b[o + 2] << 16 | (uint32_t)b[o + 3] << 24; }
/* b: 4 KB buffer. Returns the points added. */
__attribute__((noinline, unused, minsize)) PB_ATTR static uint32_t para_points(uint8_t *b)
{
uint32_t add = g_gp_secs / 60u * GP_RATE, mo = 0;
if (!add) return 0;
for (uint32_t p = 0x90000u; p < 0x110000u && !mo; p += 0x1000u) {
flash_read(p + 0x140u, b, 264u);
if (gp_u32(b, 0) == 0x444C4546u && gp_u32(b, 4) >= 9u && (gp_u32(b, 36) & GP_F)) mo = gp_u32(b, 260);
}
if (!mo || mo + 4u > 0x1000u) return 0;
flash_read(0xEFE000u, b, 0x1000u);
uint32_t c = pb_crc(b);
if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0;
uint32_t m = gp_u32(b, mo), n = m + add;
if (m > GP_MAX) return 0; /* not a money field as we know it */
if (n > GP_MAX) n = GP_MAX;
b[mo] = (uint8_t)n; b[mo + 1] = (uint8_t)(n >> 8); b[mo + 2] = (uint8_t)(n >> 16); b[mo + 3] = (uint8_t)(n >> 24);
c = pb_crc(b);
pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu);
flash_update4k(0xEFE000u, b);
flash_update4k(0xEFF000u, b);
g_gp_secs %= 60u;
return n - m;
}
#endif
#endif
+471 -471
View File
@@ -1,471 +1,471 @@
/* Paradise hardware (SNC73410), taken from the mameise flash app
* (display confirmed on the device). Runs from PRAM 0 after SYSRESETREQ. */
#include "io.h"
#ifdef HW_COLD_MIN
#define HCOLD __attribute__((minsize)) /* test21: rarely called, smaller (room in TamaEmu's 64 KB) */
#else
#define HCOLD
#endif
#include "hw.h"
#ifdef DISP_PACK
#include "disp_pack.h"
#else
#include "disp_power.h"
#endif
#define PANEL 0x4000E000u
#define FCTL_ 0x40022000u
#define F_STAT REG(FCTL_+0x000)
static void udelay(volatile u32 n){ while(n--) __asm__ volatile("nop"); }
#define MS(x) udelay((u32)(x)*16000u)
#define BB(reg,bit) (*(volatile u32*)(0x42000000u + (((u32)(reg)-0x40000000u)<<5) + ((u32)(bit)<<2)))
#define GPIO0 0x40018000u
#define GPIO1 0x40019000u
#define GPIO2 0x4001A000u
#define LCD_RST(v) (BB(GPIO0+0x00,4)=(v))
#define LCD_DC(v) (BB(GPIO0+0x00,5)=(v))
#define SPI_CTRL REG(PANEL+0x00)
#define SPI_STAT REG(PANEL+0x0C)
#define SPI_DATA REG(PANEL+0x1C)
#define SPIWAIT 200000u
#define CT2 0x40002000u
TC_INIT static void clock_init(void){
REG(CLK+0x00) |= 1u;
REG(CLK+0x0C) = 0;
REG(CLK+0x00) = 0x41u;
{ u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; }
REG(CLK+0x18) = 0x21u;
REG(CLK+0x50) = 0;
REG(CLK+0x10C) = 0x001FFFFDu;
REG(CLK+0x110) = 0;
REG(CLK+0x108) = 0;
REG(CLK+0x10) = 0;
REG(CLK+0x00) |= 0x10u;
for(u32 g=0; !((REG(CLK+0x08) >> 4) & 1u) && g<4000000u; g++){}
REG(CLK+0x00) |= 0x4000u;
REG(CLK+0x04) &= ~1u;
REG(CLK+0x00) |= 0x8000u;
for(u32 g=0; !((REG(CLK+0x08) >> 6) & 1u) && g<4000000u; g++){}
{ u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; }
for(u32 g=0; ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) && g<4000000u; g++){} /* bounded: never hang forever */
REG(CLK+0x100) = 0x00157EB7u;
}
TC_INIT static void flashctl_init(void){
/* 1.4.2: enable XIP. We read through the 0x60000000 window that the
* XIP block maps in. Without XIP, only the config register (0x40) shows there, not
* the flash data. The real Flash Utility does this at startup; our app did not
* do it after reset until now. That was exactly what was missing. */
REG(0x4002F004u)=0x60011000u;
REG(0x4002F000u)=0x00000003u;
/* 1.4.1: controller init word for word like the real Flash Utility (0x40022000).
* This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), otherwise
* the chip only returns its config register (0x40) instead of the flash data. */
F_STAT=0x0000d018u;
F_STAT=0x0000d000u;
F_STAT=0x0000d080u;
F_STAT=0x0000d088u;
REG(FCTL+0x008)=0x00003077u; /* read command/mode */
REG(FCTL+0x00C)=0x0000f000u;
REG(FCTL+0x004)=0x00000400u;
REG(FCTL+0x004)=0x00004000u;
}
TC_INIT static void wdt_off(void){
/* Set up the system/power block EXACTLY like the real Flash Utility. The only
point where we deliberately deviated before (bit0 of 0x40008000) could be the
master enable for the display domain. The FU runs with bit0=1 without a
reset, so we copy it 1:1 and feed the watchdog in the loop. */
REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */
REG(0x40008000u)=0x5AFA0000u; /* unlock */
REG(0x40008004u)=0x5AFA0002u;
REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */
REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */
/* Do NOT set bit0 (watchdog enable): otherwise it reset the Tama during
display initialisation (back to the planet). */
}
TC_INIT static void mailbox_clear(void){
REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0;
}
TC_INIT static void periph_enable(void){ REG(CLK+0x20)=0x40u; }
TC_INIT static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); }
TC_INIT static void pin_mux(void){
static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22,
0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f};
static const u8 m8[]={0,1,2,3};
static const u8 m4[]={0x15,0x17};
for(unsigned i=0;i<sizeof m12;i++) pin_set(m12[i],0xC);
for(unsigned i=0;i<sizeof m8;i++) pin_set(m8[i],0x8);
for(unsigned i=0;i<sizeof m4;i++) pin_set(m4[i],0x4);
}
TC_INIT static void display_power(void){
/* Sequence from the real FU (clock enable, pin setup, timer CT32B3, GPIO1).
As in the FU, 0x45000210..218 get the current contents of the GPIO
data registers (the emulator had returned 0 there). */
#ifdef DISP_PACK
for(unsigned i=0;i<DISP_PACK_N;i++){
u32 a=disp_pack_a[disp_pack_i[i][0]], v=disp_pack_v[disp_pack_i[i][1]];
#else
for(unsigned i=0;i<DISP_POWER_N;i++){
u32 a=disp_power_seq[i][0], v=disp_power_seq[i][1];
#endif
if(a>=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u);
REG(a)=v;
}
/* make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), supply (P1.9 low) */
LCD_RST(1); BB(GPIO0+0x04,4)=1;
LCD_DC(0); BB(GPIO0+0x04,5)=1;
BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1;
BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1;
MS(20);
}
TC_INIT static void spi_init(void){
/* like FU 0x3f44, as read-modify-write */
#ifdef LCD_FASTCLK
REG(PANEL+0x08)=0; /* clock divider: experiment v0.8.18, twice as fast? */
#else
REG(PANEL+0x08)=1; /* clock divider */
#endif
SPI_CTRL &= ~(1u<<18);
REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u;
SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u;
REG(PANEL+0x20)=0;
SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */
REG(PANEL+0x24) |= 0x80000000u;
REG(PANEL+0x24) &= ~0xFF0000u;
REG(PANEL+0x24) |= 0x80000000u;
REG(PANEL+0x24) &= ~0xFFu;
SPI_CTRL |= 1u; /* SPI on */
SPI_CTRL |= 0xC0u; /* clear FIFOs */
}
static void spi_tx(const u8* p, u32 n){
for(u32 i=0;i<n;i++){
for(u32 g=0; (SPI_STAT & 2u) && g<SPIWAIT; g++){}
SPI_DATA=p[i];
}
udelay(8);
for(u32 g=0; (SPI_STAT & 0x10u) && g<SPIWAIT; g++){}
SPI_CTRL |= 0xC0u;
}
static void lcd_cmd(u8 c, const u8* par, u32 n){
LCD_DC(0); spi_tx(&c,1);
if(n){ LCD_DC(1); spi_tx(par,n); LCD_DC(0); }
}
static const u8 p36[]={0x08}, p3a[]={0x05}, p26[]={0x01},
pb1[]={0x08,0x3b,0x3b}, pb2[]={0x08,0x3b,0x3b}, pb3[]={0x08,0x3b,0x3b,0x08,0x3b,0x3b},
pb4[]={0x03}, pc0[]={0xe0,0x00,0x84}, pc1[]={0xc4}, pc2[]={0x0d,0x00}, pc3[]={0x8d,0x2a},
pc4[]={0x8d,0xee}, pc5[]={0x06},
pe0[]={0x0d,0x17,0x16,0x28,0x3f,0x39,0x30,0x31,0x2c,0x28,0x2f,0x39,0x00,0x04,0x01,0x10},
pe1[]={0x0a,0x15,0x18,0x25,0x3f,0x37,0x2e,0x30,0x2f,0x2c,0x33,0x3f,0x00,0x03,0x04,0x10},
p35[]={0x00}, pcas0[]={0x00,0x02,0x00,0x83}, pras0[]={0x00,0x01,0x00,0x81},
pcas[]={0x00,0x02,0x00,0x81}, pras[]={0x00,0x01,0x00,0x80};
TC_INIT static void display_init(void){
spi_init();
LCD_RST(1); MS(10); LCD_RST(0); MS(20); LCD_RST(1); MS(150); /* panel reset */
lcd_cmd(0x11,0,0); MS(150); /* SLPOUT */
lcd_cmd(0x36,p36,1); lcd_cmd(0x3a,p3a,1); lcd_cmd(0x26,p26,1); lcd_cmd(0x20,0,0);
lcd_cmd(0xb1,pb1,3); lcd_cmd(0xb2,pb2,3); lcd_cmd(0xb3,pb3,6); lcd_cmd(0xb4,pb4,1);
lcd_cmd(0xc0,pc0,3); lcd_cmd(0xc1,pc1,1); lcd_cmd(0xc2,pc2,2); lcd_cmd(0xc3,pc3,2);
lcd_cmd(0xc4,pc4,2); lcd_cmd(0xc5,pc5,1);
lcd_cmd(0xe0,pe0,16); lcd_cmd(0xe1,pe1,16);
lcd_cmd(0x35,p35,1);
lcd_cmd(0x29,0,0); MS(20); /* DISPON */
lcd_cmd(0x2a,pcas0,4); lcd_cmd(0x2b,pras0,4);
lcd_cmd(0x11,0,0); MS(150);
}
static u32 g_pwm_mctrl; /* 1.6.8 (test44, BL_MR3RST): MCTRL left at 0x400 for the dimmed light, see bl_apply */
HCOLD static void pwm2p(u32 mr1, u32 per, int first){
if(first) REG(CT2+0x34)=0;
REG(CT2+0x00)=0;
REG(CT2+0x18)=0; REG(CT2+0x1C)=0; REG(CT2+0x20)=0; REG(CT2+0x24)=0;
REG(CT2+0x14)=0;
REG(CT2+0x00)=2; REG(CT2+0x08)=0; REG(CT2+0x00)=0;
REG(CT2+0x14)=0x400u;
REG(CT2+0x24)=per;
REG(CT2+0x1C)=mr1;
REG(CT2+0x14)=g_pwm_mctrl;
REG(CT2+0x34)=0x00200002u;
REG(CT2+0x00)=2;
REG(CT2+0x3C)=0x1Fu;
REG(CT2+0x00)=1;
}
static void pwm2(u32 mr1, int first){ pwm2p(mr1, 0x17700u, first); }
#ifdef BL_PWM
/* 1.6.8 (test42): the light in percent, exactly as the Paradise firmware sets it. Traced in the Paradise
* emulator: its brightness setting (settings block byte 8, bits 0..2) only changes timer 2 MR1:
* 0x13EC0 / 0x10680 / 0xCE40 for 85 / 70 / 55 % of the period 0x17700, MR1 = period at the start (full).
* Same register sequence as pwm2. */
static u32 g_bl_pct = 100u, g_bl_on = 1u;
#ifdef BL_MR3RST
/* 1.6.8 (test44): test42 had no effect on the device. With MCTRL 0 after the setup (as the firmware writes it)
* the counter never restarts at MR3: one period lasts 2^32 cycles (60 s), the output is the same level all the
* time, whatever MR1 is (also why the 1.6.6 tests showed nothing). MR3RST kept: a real 750 Hz PWM. The output
* goes high at the MR1 match; high is light (MR1 = 0 was always bright), so MR1 = the dark part of the period. */
static void bl_apply(int first){ u32 p = g_bl_pct;
if(p >= 100u){ g_pwm_mctrl = 0u; pwm2(0x17700u, first); return; } /* full: exactly as before */
g_pwm_mctrl = 0x400u; pwm2(0x17700u - 0x17700u * p / 100u, first); g_pwm_mctrl = 0u; }
#else
static void bl_apply(int first){ u32 p = g_bl_pct; pwm2(p >= 100u ? 0x17700u : (0x17700u * p / 100u ? 0x17700u * p / 100u : 1u), first); }
#endif
void hw_bl_set(u32 pct){ if(pct > 100u) pct = 100u; if(pct == g_bl_pct) return; g_bl_pct = pct; if(g_bl_on) bl_apply(0); }
#endif
TC_INIT static void backlight_on(void){
REG(0x40007034u)=0;
pwm2(0x17700u,1);
REG(0x40009000u)=0x5AFA0000u; REG(0x40008000u)=0x5AFA0000u; /* like FU */
REG(0x40018034u)=0x15555155u; REG(0x40019034u)=0x55540140u;
#ifdef BL_PWM
bl_apply(0);
#else
pwm2(0,0);
#endif
REG(CLK+0x20)=0x42u;
}
/* ---------------- own additions ---------------- */
/* Buzzer on timer 7, started and stopped exactly like the firmware does:
* period in 72 MHz cycles, short pulse (quiet, as on the Paradise). */
#define CT7 0x40007000u
#ifdef TONE_FIX
/* v0.8.15: the counter runs periodically (MCTRL bit 10 = restart at MR3, like the backlight with 0x400).
* Before, MCTRL ended up at 0: only a single pulse per call, so a click instead of a tone.
* If only the pitch changes, only MR0/MR3 are updated (no restart, no click). */
#ifdef HW_OPTS
/* 1.6.8: volume and brightness set in the Studio (TamaEmu, T18Emu). Volume: pulse length (0 off, 1 quiet 1/128,
* 2 normal 1/32 as before, 3 loud 1/8 of the period). Brightness: the pixels darkened (0 = 100 %, 1 75, 2 50, 3 25 %). */
u32 g_hw_vol = 2u, g_hw_dim = 0u;
static const u8 VOL_SH[4] = { 5, 7, 5, 3 };
#endif
#ifdef HW_VOL5
/* 1.6.12 test3 (T7Emu): volume in 5 steps by the pulse length: 0 off, 1 1/32 of the period (as before), 2 1/8,
* 3 1/4, 4 1/2 (a square wave, the loudest the buzzer gets) */
u32 g_hw_vol5 = 1u;
static const u8 VOL5_SH[5] = { 5, 5, 3, 2, 1 };
#endif
#ifdef CLK_ECO
u32 g_hw_clk_sh; /* 1.6.9 test22: AHB clock divided by 2^sh (eco.h); the tone timer runs on the divided clock too */
u32 g_hw_tone_hz;
#define TONE_CLK (72000000u >> g_hw_clk_sh)
#else
#define TONE_CLK 72000000u
#endif
#ifdef HW_TONE_IRQSAFE
/* 1.6.12 test4 (T7Emu): the tone is also set from the SysTick (T7_TONE_ISR); a call from the main loop must not be
* cut in the middle of the register writes */
static void hw_tone_raw(u32 hz);
void hw_tone(u32 hz){ u32 pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); hw_tone_raw(hz); __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); }
HCOLD static void hw_tone_raw(u32 hz){
#else
HCOLD void hw_tone(u32 hz){
#endif
static u32 on;
#ifdef HW_OPTS
if(!g_hw_vol) hz = 0;
#endif
#ifdef HW_VOL5
if(!g_hw_vol5) hz = 0;
#endif
#ifdef CLK_ECO
g_hw_tone_hz = hz;
#endif
if(!hz){ REG(CT7+0x34)=0; REG(CT7+0x00)=0; on=0; return; }
#ifdef HW_OPTS
u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL_SH[g_hw_vol & 3u]);
#elif defined(HW_VOL5)
u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL5_SH[g_hw_vol5 > 4u ? 4u : g_hw_vol5]);
#else
u32 per = TONE_CLK / hz, mr0 = per - per/32u;
#endif
#ifndef HW_TONE_RESTART
/* 1.7.4 HW_TONE_RESTART: a new pitch written into the running timer left the buzzer silent on the device (GBEmu
* test39; users: the sound cuts off in the emulators). With it every new pitch starts the timer anew below. */
if(on){ REG(CT7+0x24)=per; REG(CT7+0x18)=mr0;
#ifdef TONE_SAFE /* 1.6.9 test38 (GBEmu): a shorter period below the running counter left the buzzer silent until the
* 32-bit counter wrapped (~60 s); then the counter starts again */
if(REG(CT7+0x08) >= per){ REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=1; }
#endif
return; }
#endif
REG(CT7+0x34)=0;
REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0;
REG(CT7+0x18)=mr0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0;
REG(CT7+0x24)=per;
REG(CT7+0x14)=0x400u;
REG(CT7+0x34)=0x00100001u;
REG(CT7+0x3C)=0x1Fu;
REG(CT7+0x00)=1;
on=1;
}
#else
void hw_tone(u32 hz){
if(!hz){ REG(CT7+0x34)=0; return; }
u32 per = 72000000u / hz, mr0 = per - per/32u;
REG(CT7+0x34)=0;
REG(CT7+0x00)=0;
REG(CT7+0x18)=0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0; REG(CT7+0x24)=0;
REG(CT7+0x14)=0;
REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0;
REG(CT7+0x14)=0x600u;
REG(CT7+0x24)=per;
REG(CT7+0x18)=mr0;
REG(CT7+0x14)=0;
REG(CT7+0x34)=0x00100001u;
REG(CT7+0x00)=2;
REG(CT7+0x3C)=0x1Fu;
REG(CT7+0x00)=1;
}
#endif
void hw_bl_pwm_off(void){ REG(CT2+0x00)=0; REG(CT2+0x34)=0; } /* backlight off only (when leaving) */
#ifdef HW_BL_LEVELS /* 1.6.6 tests (T7 dimming): the PWM had no visible effect on the device */
/* 1.6.6 test: backlight in percent through the PWM (MR1: 0 = full; near the period = dark), panel stays on */
void hw_bl_level(u32 pct){ if(pct>=100u) pwm2(0u,0); else pwm2(0x17700u - 0x17700u*pct/100u, 0); }
/* 1.6.6 test: which setting dims on the device? m bit 0: MR1 = pct of the period (else the rest of it),
* bit 1: 20 kHz (else 750 Hz like the Paradise firmware) */
void hw_bl_test(u32 m, u32 pct){
u32 per = (m & 2u) ? 3600u : 0x17700u;
u32 mr1 = (m & 1u) ? per*pct/100u : per - per*pct/100u;
pwm2p(mr1, per, 0);
}
#endif
#ifdef BL_SLEEP
/* v0.8.18: off = put the display to sleep (DISPOFF, SLPIN) and stop the backlight timer,
* PWM output off (like panel_down in the Flash Tool). On = SLPOUT, short wait, DISPON, backlight restart.
* MR1 values alone (v0.8.17) had no effect on the device. */
static int is_on=1;
#ifdef WAKE_ASYNC
/* test14: switching the panel on in steps from the main loop (SLPOUT, 125 ms later DISPON, 20 ms later the light),
* hw_backlight(1) waited 145 ms and the emulator fell behind (the ring of a call in standby ran slow).
* Returns 0 when the panel is on already. */
int hw_wake_step(int ph){
#ifdef HW_WAKE_ABORT
if(ph==0){ if(is_on) return 0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); return 1; } /* 1.7.2 test17: woken ahead, nobody came: asleep again */
#endif
if(ph==1){ if(is_on) return 0; lcd_cmd(0x11,0,0); return 1; }
if(ph==2){ lcd_cmd(0x29,0,0); return 1; }
#ifdef BL_PWM
g_bl_on=1u; bl_apply(1);
#else
pwm2(0u,1);
#endif
is_on=1; return 1;
}
#endif
HCOLD void hw_backlight(int on){
#ifndef WAKE_QUICK
/* 1.6.8: the panel needs 120 ms after SLPOUT; switched on earlier it showed white for a moment. Its picture is
* kept while it sleeps, so after the wait it shows the old picture, the light comes last. */
#ifdef BL_PWM
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); g_bl_on=1u; bl_apply(1); is_on=1; }
#else
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); pwm2(0u,1); is_on=1; }
#endif
#else
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(10); lcd_cmd(0x29,0,0); pwm2(0u,1); is_on=1; }
#endif
else { if(!is_on) return; REG(CT2+0x00)=0; REG(CT2+0x34)=0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); is_on=0;
#ifdef BL_PWM
g_bl_on=0u;
#endif
}
}
#elif defined(BL_OFFFIX)
/* v0.8.17: duty 0 = full brightness. MR1 equal to the period (0x17700) never matches, so it stayed bright.
* One cycle before the end of the period is practically dark. */
void hw_backlight(int on){ pwm2(on ? 0u : 0x176FFu, 0); }
#else
void hw_backlight(int on){ pwm2(on ? 0u : 0x17700u, 0); }
#endif
void hw_wdt_feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; }
TC_INIT void hw_init(void){
wdt_off(); mailbox_clear(); clock_init(); periph_enable(); flashctl_init(); pin_mux();
display_power(); display_init(); backlight_on();
/* buttons: P0.8 wheel, P0.9 A, P0.10 C, P0.11 B as inputs (active low) */
REG(GPIO0+0x04) &= ~((1u<<8)|(1u<<9)|(1u<<10)|(1u<<11));
flashctl_init();
}
#ifdef GPLAY
#include "gplay.h"
uint32_t g_gp_secs, g_gp_last;
#endif
u32 hw_buttons(void){
u32 d = REG(GPIO0+0x00);
u32 b = 0;
if(!(d & (1u<<9))) b |= BTN_A;
if(!(d & (1u<<11))) b |= BTN_B;
if(!(d & (1u<<10))) b |= BTN_C;
if(!(d & (1u<<8))) b |= BTN_WHEEL;
#ifdef GPLAY
gp_key(b);
#endif
return b;
}
/* Send rectangle x0..x1-1, y0..y1-1 from a 128-wide framebuffer (RGB565) to the panel. */
void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1){
u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)};
u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)};
lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4);
LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); }
LCD_DC(1);
for(u32 y=y0;y<y1;y++){
const u16* r=fb+y*stride;
for(u32 x=x0;x<x1;x++){
u8 two[2]={(u8)(r[x]>>8),(u8)r[x]};
spi_tx(&two[0],1); spi_tx(&two[1],1); /* byte by byte like the FU (1.3.8) */
}
}
LCD_DC(0);
}
#ifdef FAST_LCD
/* v0.8.17: display output in one piece per rectangle and 16 bytes per SPI pass (like the gamma tables
* of the display setup, which run this way on the device). Before, per byte: wait, delay of 8, wait. */
void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1){
u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)};
u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)};
lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4);
LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); }
LCD_DC(1);
}
#ifdef HW_OPTS
__attribute__((noinline, minsize)) static u32 px_dim(u32 v, u32 d){ u32 q=(v>>2)&0x39E7u; return d==1u ? v-q : d==2u ? (v>>1)&0x7BEFu : q; }
#endif
void hw_px_row(const u16* r, u32 n){
u8 b[16]; u32 k=0;
#ifdef HW_OPTS
#ifdef BL_PWM
u32 d=0; /* the light is dimmed instead */
#else
u32 d=g_hw_dim;
#endif
#pragma clang loop unroll(disable)
for(u32 i=0;i<n;i++){ u32 v=r[i]; if(d) v=px_dim(v,d); b[k++]=(u8)(v>>8); b[k++]=(u8)v; if(k==16u){ spi_tx(b,16); k=0; } }
#else
for(u32 i=0;i<n;i++){ b[k++]=(u8)(r[i]>>8); b[k++]=(u8)r[i]; if(k==16u){ spi_tx(b,16); k=0; } }
#endif
if(k) spi_tx(b,k);
}
void hw_px_end(void){ LCD_DC(0); }
#endif
/* Back to the Paradise: firmware routine that reloads the encrypted PRAM image
and restarts (flash 0x110568, XIP 0x100FF569). */
#ifdef CLK_ECO
/* 1.6.9 test22: the AHB prescaler (SYS_AHBCP 0x45000010, Sonix TRM: SYSCLK / 2^sh for the core, the memory and, through
* APB, the peripherals). SysTick keeps its 1 ms, a playing tone keeps its pitch. Only while the screen is off. */
__attribute__((minsize)) void hw_clk_shift(u32 sh, u32 core_hz){
if(sh > 3u) sh = 3u;
if(sh == g_hw_clk_sh) return;
REG(0x45000010u) = sh; g_hw_clk_sh = sh;
__asm__ volatile("dsb\n isb");
REG(0xE000E014u) = (core_hz >> sh) / 1000u - 1u; REG(0xE000E018u) = 0;
if(g_hw_tone_hz) hw_tone(g_hw_tone_hz);
}
#endif
void hw_back_to_paradise(void){
__asm__ volatile("cpsid i");
#ifdef CLK_ECO
REG(0x45000010u) = 0; /* the Paradise runs at full speed again */
#endif
((void(*)(void))(PARADISE_REBOOT|1u))();
for(;;){}
}
/* Paradise hardware (SNC73410), taken from the mameise flash app
* (display confirmed on the device). Runs from PRAM 0 after SYSRESETREQ. */
#include "io.h"
#ifdef HW_COLD_MIN
#define HCOLD __attribute__((minsize)) /* test21: rarely called, smaller (room in TamaEmu's 64 KB) */
#else
#define HCOLD
#endif
#include "hw.h"
#ifdef DISP_PACK
#include "disp_pack.h"
#else
#include "disp_power.h"
#endif
#define PANEL 0x4000E000u
#define FCTL_ 0x40022000u
#define F_STAT REG(FCTL_+0x000)
static void udelay(volatile u32 n){ while(n--) __asm__ volatile("nop"); }
#define MS(x) udelay((u32)(x)*16000u)
#define BB(reg,bit) (*(volatile u32*)(0x42000000u + (((u32)(reg)-0x40000000u)<<5) + ((u32)(bit)<<2)))
#define GPIO0 0x40018000u
#define GPIO1 0x40019000u
#define GPIO2 0x4001A000u
#define LCD_RST(v) (BB(GPIO0+0x00,4)=(v))
#define LCD_DC(v) (BB(GPIO0+0x00,5)=(v))
#define SPI_CTRL REG(PANEL+0x00)
#define SPI_STAT REG(PANEL+0x0C)
#define SPI_DATA REG(PANEL+0x1C)
#define SPIWAIT 200000u
#define CT2 0x40002000u
TC_INIT static void clock_init(void){
REG(CLK+0x00) |= 1u;
REG(CLK+0x0C) = 0;
REG(CLK+0x00) = 0x41u;
{ u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; }
REG(CLK+0x18) = 0x21u;
REG(CLK+0x50) = 0;
REG(CLK+0x10C) = 0x001FFFFDu;
REG(CLK+0x110) = 0;
REG(CLK+0x108) = 0;
REG(CLK+0x10) = 0;
REG(CLK+0x00) |= 0x10u;
for(u32 g=0; !((REG(CLK+0x08) >> 4) & 1u) && g<4000000u; g++){}
REG(CLK+0x00) |= 0x4000u;
REG(CLK+0x04) &= ~1u;
REG(CLK+0x00) |= 0x8000u;
for(u32 g=0; !((REG(CLK+0x08) >> 6) & 1u) && g<4000000u; g++){}
{ u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; }
for(u32 g=0; ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) && g<4000000u; g++){} /* bounded: never hang forever */
REG(CLK+0x100) = 0x00157EB7u;
}
TC_INIT static void flashctl_init(void){
/* 1.4.2: enable XIP. We read through the 0x60000000 window that the
* XIP block maps in. Without XIP, only the config register (0x40) shows there, not
* the flash data. The real Flash Utility does this at startup; our app did not
* do it after reset until now. That was exactly what was missing. */
REG(0x4002F004u)=0x60011000u;
REG(0x4002F000u)=0x00000003u;
/* 1.4.1: controller init word for word like the real Flash Utility (0x40022000).
* This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), otherwise
* the chip only returns its config register (0x40) instead of the flash data. */
F_STAT=0x0000d018u;
F_STAT=0x0000d000u;
F_STAT=0x0000d080u;
F_STAT=0x0000d088u;
REG(FCTL+0x008)=0x00003077u; /* read command/mode */
REG(FCTL+0x00C)=0x0000f000u;
REG(FCTL+0x004)=0x00000400u;
REG(FCTL+0x004)=0x00004000u;
}
TC_INIT static void wdt_off(void){
/* Set up the system/power block EXACTLY like the real Flash Utility. The only
point where we deliberately deviated before (bit0 of 0x40008000) could be the
master enable for the display domain. The FU runs with bit0=1 without a
reset, so we copy it 1:1 and feed the watchdog in the loop. */
REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */
REG(0x40008000u)=0x5AFA0000u; /* unlock */
REG(0x40008004u)=0x5AFA0002u;
REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */
REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */
/* Do NOT set bit0 (watchdog enable): otherwise it reset the Tama during
display initialisation (back to the planet). */
}
TC_INIT static void mailbox_clear(void){
REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0;
}
TC_INIT static void periph_enable(void){ REG(CLK+0x20)=0x40u; }
TC_INIT static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); }
TC_INIT static void pin_mux(void){
static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22,
0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f};
static const u8 m8[]={0,1,2,3};
static const u8 m4[]={0x15,0x17};
for(unsigned i=0;i<sizeof m12;i++) pin_set(m12[i],0xC);
for(unsigned i=0;i<sizeof m8;i++) pin_set(m8[i],0x8);
for(unsigned i=0;i<sizeof m4;i++) pin_set(m4[i],0x4);
}
TC_INIT static void display_power(void){
/* Sequence from the real FU (clock enable, pin setup, timer CT32B3, GPIO1).
As in the FU, 0x45000210..218 get the current contents of the GPIO
data registers (the emulator had returned 0 there). */
#ifdef DISP_PACK
for(unsigned i=0;i<DISP_PACK_N;i++){
u32 a=disp_pack_a[disp_pack_i[i][0]], v=disp_pack_v[disp_pack_i[i][1]];
#else
for(unsigned i=0;i<DISP_POWER_N;i++){
u32 a=disp_power_seq[i][0], v=disp_power_seq[i][1];
#endif
if(a>=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u);
REG(a)=v;
}
/* make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), supply (P1.9 low) */
LCD_RST(1); BB(GPIO0+0x04,4)=1;
LCD_DC(0); BB(GPIO0+0x04,5)=1;
BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1;
BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1;
MS(20);
}
TC_INIT static void spi_init(void){
/* like FU 0x3f44, as read-modify-write */
#ifdef LCD_FASTCLK
REG(PANEL+0x08)=0; /* clock divider: experiment v0.8.18, twice as fast? */
#else
REG(PANEL+0x08)=1; /* clock divider */
#endif
SPI_CTRL &= ~(1u<<18);
REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u;
SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u;
REG(PANEL+0x20)=0;
SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */
REG(PANEL+0x24) |= 0x80000000u;
REG(PANEL+0x24) &= ~0xFF0000u;
REG(PANEL+0x24) |= 0x80000000u;
REG(PANEL+0x24) &= ~0xFFu;
SPI_CTRL |= 1u; /* SPI on */
SPI_CTRL |= 0xC0u; /* clear FIFOs */
}
static void spi_tx(const u8* p, u32 n){
for(u32 i=0;i<n;i++){
for(u32 g=0; (SPI_STAT & 2u) && g<SPIWAIT; g++){}
SPI_DATA=p[i];
}
udelay(8);
for(u32 g=0; (SPI_STAT & 0x10u) && g<SPIWAIT; g++){}
SPI_CTRL |= 0xC0u;
}
static void lcd_cmd(u8 c, const u8* par, u32 n){
LCD_DC(0); spi_tx(&c,1);
if(n){ LCD_DC(1); spi_tx(par,n); LCD_DC(0); }
}
static const u8 p36[]={0x08}, p3a[]={0x05}, p26[]={0x01},
pb1[]={0x08,0x3b,0x3b}, pb2[]={0x08,0x3b,0x3b}, pb3[]={0x08,0x3b,0x3b,0x08,0x3b,0x3b},
pb4[]={0x03}, pc0[]={0xe0,0x00,0x84}, pc1[]={0xc4}, pc2[]={0x0d,0x00}, pc3[]={0x8d,0x2a},
pc4[]={0x8d,0xee}, pc5[]={0x06},
pe0[]={0x0d,0x17,0x16,0x28,0x3f,0x39,0x30,0x31,0x2c,0x28,0x2f,0x39,0x00,0x04,0x01,0x10},
pe1[]={0x0a,0x15,0x18,0x25,0x3f,0x37,0x2e,0x30,0x2f,0x2c,0x33,0x3f,0x00,0x03,0x04,0x10},
p35[]={0x00}, pcas0[]={0x00,0x02,0x00,0x83}, pras0[]={0x00,0x01,0x00,0x81},
pcas[]={0x00,0x02,0x00,0x81}, pras[]={0x00,0x01,0x00,0x80};
TC_INIT static void display_init(void){
spi_init();
LCD_RST(1); MS(10); LCD_RST(0); MS(20); LCD_RST(1); MS(150); /* panel reset */
lcd_cmd(0x11,0,0); MS(150); /* SLPOUT */
lcd_cmd(0x36,p36,1); lcd_cmd(0x3a,p3a,1); lcd_cmd(0x26,p26,1); lcd_cmd(0x20,0,0);
lcd_cmd(0xb1,pb1,3); lcd_cmd(0xb2,pb2,3); lcd_cmd(0xb3,pb3,6); lcd_cmd(0xb4,pb4,1);
lcd_cmd(0xc0,pc0,3); lcd_cmd(0xc1,pc1,1); lcd_cmd(0xc2,pc2,2); lcd_cmd(0xc3,pc3,2);
lcd_cmd(0xc4,pc4,2); lcd_cmd(0xc5,pc5,1);
lcd_cmd(0xe0,pe0,16); lcd_cmd(0xe1,pe1,16);
lcd_cmd(0x35,p35,1);
lcd_cmd(0x29,0,0); MS(20); /* DISPON */
lcd_cmd(0x2a,pcas0,4); lcd_cmd(0x2b,pras0,4);
lcd_cmd(0x11,0,0); MS(150);
}
static u32 g_pwm_mctrl; /* 1.6.8 (test44, BL_MR3RST): MCTRL left at 0x400 for the dimmed light, see bl_apply */
HCOLD static void pwm2p(u32 mr1, u32 per, int first){
if(first) REG(CT2+0x34)=0;
REG(CT2+0x00)=0;
REG(CT2+0x18)=0; REG(CT2+0x1C)=0; REG(CT2+0x20)=0; REG(CT2+0x24)=0;
REG(CT2+0x14)=0;
REG(CT2+0x00)=2; REG(CT2+0x08)=0; REG(CT2+0x00)=0;
REG(CT2+0x14)=0x400u;
REG(CT2+0x24)=per;
REG(CT2+0x1C)=mr1;
REG(CT2+0x14)=g_pwm_mctrl;
REG(CT2+0x34)=0x00200002u;
REG(CT2+0x00)=2;
REG(CT2+0x3C)=0x1Fu;
REG(CT2+0x00)=1;
}
static void pwm2(u32 mr1, int first){ pwm2p(mr1, 0x17700u, first); }
#ifdef BL_PWM
/* 1.6.8 (test42): the light in percent, exactly as the Paradise firmware sets it. Traced in the Paradise
* emulator: its brightness setting (settings block byte 8, bits 0..2) only changes timer 2 MR1:
* 0x13EC0 / 0x10680 / 0xCE40 for 85 / 70 / 55 % of the period 0x17700, MR1 = period at the start (full).
* Same register sequence as pwm2. */
static u32 g_bl_pct = 100u, g_bl_on = 1u;
#ifdef BL_MR3RST
/* 1.6.8 (test44): test42 had no effect on the device. With MCTRL 0 after the setup (as the firmware writes it)
* the counter never restarts at MR3: one period lasts 2^32 cycles (60 s), the output is the same level all the
* time, whatever MR1 is (also why the 1.6.6 tests showed nothing). MR3RST kept: a real 750 Hz PWM. The output
* goes high at the MR1 match; high is light (MR1 = 0 was always bright), so MR1 = the dark part of the period. */
static void bl_apply(int first){ u32 p = g_bl_pct;
if(p >= 100u){ g_pwm_mctrl = 0u; pwm2(0x17700u, first); return; } /* full: exactly as before */
g_pwm_mctrl = 0x400u; pwm2(0x17700u - 0x17700u * p / 100u, first); g_pwm_mctrl = 0u; }
#else
static void bl_apply(int first){ u32 p = g_bl_pct; pwm2(p >= 100u ? 0x17700u : (0x17700u * p / 100u ? 0x17700u * p / 100u : 1u), first); }
#endif
void hw_bl_set(u32 pct){ if(pct > 100u) pct = 100u; if(pct == g_bl_pct) return; g_bl_pct = pct; if(g_bl_on) bl_apply(0); }
#endif
TC_INIT static void backlight_on(void){
REG(0x40007034u)=0;
pwm2(0x17700u,1);
REG(0x40009000u)=0x5AFA0000u; REG(0x40008000u)=0x5AFA0000u; /* like FU */
REG(0x40018034u)=0x15555155u; REG(0x40019034u)=0x55540140u;
#ifdef BL_PWM
bl_apply(0);
#else
pwm2(0,0);
#endif
REG(CLK+0x20)=0x42u;
}
/* ---------------- own additions ---------------- */
/* Buzzer on timer 7, started and stopped exactly like the firmware does:
* period in 72 MHz cycles, short pulse (quiet, as on the Paradise). */
#define CT7 0x40007000u
#ifdef TONE_FIX
/* v0.8.15: the counter runs periodically (MCTRL bit 10 = restart at MR3, like the backlight with 0x400).
* Before, MCTRL ended up at 0: only a single pulse per call, so a click instead of a tone.
* If only the pitch changes, only MR0/MR3 are updated (no restart, no click). */
#ifdef HW_OPTS
/* 1.6.8: volume and brightness set in the Studio (TamaEmu, T18Emu). Volume: pulse length (0 off, 1 quiet 1/128,
* 2 normal 1/32 as before, 3 loud 1/8 of the period). Brightness: the pixels darkened (0 = 100 %, 1 75, 2 50, 3 25 %). */
u32 g_hw_vol = 2u, g_hw_dim = 0u;
static const u8 VOL_SH[4] = { 5, 7, 5, 3 };
#endif
#ifdef HW_VOL5
/* 1.6.12 test3 (T7Emu): volume in 5 steps by the pulse length: 0 off, 1 1/32 of the period (as before), 2 1/8,
* 3 1/4, 4 1/2 (a square wave, the loudest the buzzer gets) */
u32 g_hw_vol5 = 1u;
static const u8 VOL5_SH[5] = { 5, 5, 3, 2, 1 };
#endif
#ifdef CLK_ECO
u32 g_hw_clk_sh; /* 1.6.9 test22: AHB clock divided by 2^sh (eco.h); the tone timer runs on the divided clock too */
u32 g_hw_tone_hz;
#define TONE_CLK (72000000u >> g_hw_clk_sh)
#else
#define TONE_CLK 72000000u
#endif
#ifdef HW_TONE_IRQSAFE
/* 1.6.12 test4 (T7Emu): the tone is also set from the SysTick (T7_TONE_ISR); a call from the main loop must not be
* cut in the middle of the register writes */
static void hw_tone_raw(u32 hz);
void hw_tone(u32 hz){ u32 pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); hw_tone_raw(hz); __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); }
HCOLD static void hw_tone_raw(u32 hz){
#else
HCOLD void hw_tone(u32 hz){
#endif
static u32 on;
#ifdef HW_OPTS
if(!g_hw_vol) hz = 0;
#endif
#ifdef HW_VOL5
if(!g_hw_vol5) hz = 0;
#endif
#ifdef CLK_ECO
g_hw_tone_hz = hz;
#endif
if(!hz){ REG(CT7+0x34)=0; REG(CT7+0x00)=0; on=0; return; }
#ifdef HW_OPTS
u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL_SH[g_hw_vol & 3u]);
#elif defined(HW_VOL5)
u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL5_SH[g_hw_vol5 > 4u ? 4u : g_hw_vol5]);
#else
u32 per = TONE_CLK / hz, mr0 = per - per/32u;
#endif
#ifndef HW_TONE_RESTART
/* 1.7.4 HW_TONE_RESTART: a new pitch written into the running timer left the buzzer silent on the device (GBEmu
* test39; users: the sound cuts off in the emulators). With it every new pitch starts the timer anew below. */
if(on){ REG(CT7+0x24)=per; REG(CT7+0x18)=mr0;
#ifdef TONE_SAFE /* 1.6.9 test38 (GBEmu): a shorter period below the running counter left the buzzer silent until the
* 32-bit counter wrapped (~60 s); then the counter starts again */
if(REG(CT7+0x08) >= per){ REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=1; }
#endif
return; }
#endif
REG(CT7+0x34)=0;
REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0;
REG(CT7+0x18)=mr0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0;
REG(CT7+0x24)=per;
REG(CT7+0x14)=0x400u;
REG(CT7+0x34)=0x00100001u;
REG(CT7+0x3C)=0x1Fu;
REG(CT7+0x00)=1;
on=1;
}
#else
void hw_tone(u32 hz){
if(!hz){ REG(CT7+0x34)=0; return; }
u32 per = 72000000u / hz, mr0 = per - per/32u;
REG(CT7+0x34)=0;
REG(CT7+0x00)=0;
REG(CT7+0x18)=0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0; REG(CT7+0x24)=0;
REG(CT7+0x14)=0;
REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0;
REG(CT7+0x14)=0x600u;
REG(CT7+0x24)=per;
REG(CT7+0x18)=mr0;
REG(CT7+0x14)=0;
REG(CT7+0x34)=0x00100001u;
REG(CT7+0x00)=2;
REG(CT7+0x3C)=0x1Fu;
REG(CT7+0x00)=1;
}
#endif
void hw_bl_pwm_off(void){ REG(CT2+0x00)=0; REG(CT2+0x34)=0; } /* backlight off only (when leaving) */
#ifdef HW_BL_LEVELS /* 1.6.6 tests (T7 dimming): the PWM had no visible effect on the device */
/* 1.6.6 test: backlight in percent through the PWM (MR1: 0 = full; near the period = dark), panel stays on */
void hw_bl_level(u32 pct){ if(pct>=100u) pwm2(0u,0); else pwm2(0x17700u - 0x17700u*pct/100u, 0); }
/* 1.6.6 test: which setting dims on the device? m bit 0: MR1 = pct of the period (else the rest of it),
* bit 1: 20 kHz (else 750 Hz like the Paradise firmware) */
void hw_bl_test(u32 m, u32 pct){
u32 per = (m & 2u) ? 3600u : 0x17700u;
u32 mr1 = (m & 1u) ? per*pct/100u : per - per*pct/100u;
pwm2p(mr1, per, 0);
}
#endif
#ifdef BL_SLEEP
/* v0.8.18: off = put the display to sleep (DISPOFF, SLPIN) and stop the backlight timer,
* PWM output off (like panel_down in the Flash Tool). On = SLPOUT, short wait, DISPON, backlight restart.
* MR1 values alone (v0.8.17) had no effect on the device. */
static int is_on=1;
#ifdef WAKE_ASYNC
/* test14: switching the panel on in steps from the main loop (SLPOUT, 125 ms later DISPON, 20 ms later the light),
* hw_backlight(1) waited 145 ms and the emulator fell behind (the ring of a call in standby ran slow).
* Returns 0 when the panel is on already. */
int hw_wake_step(int ph){
#ifdef HW_WAKE_ABORT
if(ph==0){ if(is_on) return 0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); return 1; } /* 1.7.2 test17: woken ahead, nobody came: asleep again */
#endif
if(ph==1){ if(is_on) return 0; lcd_cmd(0x11,0,0); return 1; }
if(ph==2){ lcd_cmd(0x29,0,0); return 1; }
#ifdef BL_PWM
g_bl_on=1u; bl_apply(1);
#else
pwm2(0u,1);
#endif
is_on=1; return 1;
}
#endif
HCOLD void hw_backlight(int on){
#ifndef WAKE_QUICK
/* 1.6.8: the panel needs 120 ms after SLPOUT; switched on earlier it showed white for a moment. Its picture is
* kept while it sleeps, so after the wait it shows the old picture, the light comes last. */
#ifdef BL_PWM
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); g_bl_on=1u; bl_apply(1); is_on=1; }
#else
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); pwm2(0u,1); is_on=1; }
#endif
#else
if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(10); lcd_cmd(0x29,0,0); pwm2(0u,1); is_on=1; }
#endif
else { if(!is_on) return; REG(CT2+0x00)=0; REG(CT2+0x34)=0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); is_on=0;
#ifdef BL_PWM
g_bl_on=0u;
#endif
}
}
#elif defined(BL_OFFFIX)
/* v0.8.17: duty 0 = full brightness. MR1 equal to the period (0x17700) never matches, so it stayed bright.
* One cycle before the end of the period is practically dark. */
void hw_backlight(int on){ pwm2(on ? 0u : 0x176FFu, 0); }
#else
void hw_backlight(int on){ pwm2(on ? 0u : 0x17700u, 0); }
#endif
void hw_wdt_feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; }
TC_INIT void hw_init(void){
wdt_off(); mailbox_clear(); clock_init(); periph_enable(); flashctl_init(); pin_mux();
display_power(); display_init(); backlight_on();
/* buttons: P0.8 wheel, P0.9 A, P0.10 C, P0.11 B as inputs (active low) */
REG(GPIO0+0x04) &= ~((1u<<8)|(1u<<9)|(1u<<10)|(1u<<11));
flashctl_init();
}
#ifdef GPLAY
#include "gplay.h"
uint32_t g_gp_secs, g_gp_last;
#endif
u32 hw_buttons(void){
u32 d = REG(GPIO0+0x00);
u32 b = 0;
if(!(d & (1u<<9))) b |= BTN_A;
if(!(d & (1u<<11))) b |= BTN_B;
if(!(d & (1u<<10))) b |= BTN_C;
if(!(d & (1u<<8))) b |= BTN_WHEEL;
#ifdef GPLAY
gp_key(b);
#endif
return b;
}
/* Send rectangle x0..x1-1, y0..y1-1 from a 128-wide framebuffer (RGB565) to the panel. */
void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1){
u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)};
u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)};
lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4);
LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); }
LCD_DC(1);
for(u32 y=y0;y<y1;y++){
const u16* r=fb+y*stride;
for(u32 x=x0;x<x1;x++){
u8 two[2]={(u8)(r[x]>>8),(u8)r[x]};
spi_tx(&two[0],1); spi_tx(&two[1],1); /* byte by byte like the FU (1.3.8) */
}
}
LCD_DC(0);
}
#ifdef FAST_LCD
/* v0.8.17: display output in one piece per rectangle and 16 bytes per SPI pass (like the gamma tables
* of the display setup, which run this way on the device). Before, per byte: wait, delay of 8, wait. */
void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1){
u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)};
u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)};
lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4);
LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); }
LCD_DC(1);
}
#ifdef HW_OPTS
__attribute__((noinline, minsize)) static u32 px_dim(u32 v, u32 d){ u32 q=(v>>2)&0x39E7u; return d==1u ? v-q : d==2u ? (v>>1)&0x7BEFu : q; }
#endif
void hw_px_row(const u16* r, u32 n){
u8 b[16]; u32 k=0;
#ifdef HW_OPTS
#ifdef BL_PWM
u32 d=0; /* the light is dimmed instead */
#else
u32 d=g_hw_dim;
#endif
#pragma clang loop unroll(disable)
for(u32 i=0;i<n;i++){ u32 v=r[i]; if(d) v=px_dim(v,d); b[k++]=(u8)(v>>8); b[k++]=(u8)v; if(k==16u){ spi_tx(b,16); k=0; } }
#else
for(u32 i=0;i<n;i++){ b[k++]=(u8)(r[i]>>8); b[k++]=(u8)r[i]; if(k==16u){ spi_tx(b,16); k=0; } }
#endif
if(k) spi_tx(b,k);
}
void hw_px_end(void){ LCD_DC(0); }
#endif
/* Back to the Paradise: firmware routine that reloads the encrypted PRAM image
and restarts (flash 0x110568, XIP 0x100FF569). */
#ifdef CLK_ECO
/* 1.6.9 test22: the AHB prescaler (SYS_AHBCP 0x45000010, Sonix TRM: SYSCLK / 2^sh for the core, the memory and, through
* APB, the peripherals). SysTick keeps its 1 ms, a playing tone keeps its pitch. Only while the screen is off. */
__attribute__((minsize)) void hw_clk_shift(u32 sh, u32 core_hz){
if(sh > 3u) sh = 3u;
if(sh == g_hw_clk_sh) return;
REG(0x45000010u) = sh; g_hw_clk_sh = sh;
__asm__ volatile("dsb\n isb");
REG(0xE000E014u) = (core_hz >> sh) / 1000u - 1u; REG(0xE000E018u) = 0;
if(g_hw_tone_hz) hw_tone(g_hw_tone_hz);
}
#endif
void hw_back_to_paradise(void){
__asm__ volatile("cpsid i");
#ifdef CLK_ECO
REG(0x45000010u) = 0; /* the Paradise runs at full speed again */
#endif
((void(*)(void))(PARADISE_REBOOT|1u))();
for(;;){}
}
+38 -38
View File
@@ -1,38 +1,38 @@
#ifndef HW_H
#define HW_H
#include "io.h"
#define BTN_A 1u
#define BTN_B 2u
#define BTN_C 4u
#define BTN_WHEEL 8u
#ifndef PARADISE_REBOOT
#define PARADISE_REBOOT 0x100FF568u
#endif
void hw_init(void);
void hw_wdt_feed(void);
u32 hw_buttons(void);
void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1);
void hw_back_to_paradise(void);
void hw_backlight(int on);
int hw_wake_step(int ph); /* WAKE_ASYNC: 1 SLPOUT, 2 DISPON, 3 light (HW_WAKE_ABORT: 0 asleep again) */
void hw_bl_pwm_off(void);
void hw_bl_level(u32 pct);
void hw_bl_test(u32 m, u32 pct);
void hw_tone(u32 hz); /* 0 = off */
#ifdef HW_VOL5
extern u32 g_hw_vol5; /* 1.6.12 test3: 0 off .. 4 loudest, 1 as before */
#endif
#ifdef HW_OPTS
extern u32 g_hw_vol, g_hw_dim; /* 1.6.8: volume 0..3 (2 = as before), brightness 0..3 (0 = full) */
#endif
void hw_bl_set(u32 pct);
#ifdef CLK_ECO
extern u32 g_hw_clk_sh, g_hw_tone_hz;
void hw_clk_shift(u32 sh, u32 core_hz); /* 1.6.9: AHB clock / 2^sh (0..3), SysTick stays 1 ms */
#endif /* 1.6.8 BL_PWM: light 0..100 % */
#ifdef FAST_LCD
void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1);
void hw_px_row(const u16* r, u32 n);
void hw_px_end(void);
#endif
#endif
#ifndef HW_H
#define HW_H
#include "io.h"
#define BTN_A 1u
#define BTN_B 2u
#define BTN_C 4u
#define BTN_WHEEL 8u
#ifndef PARADISE_REBOOT
#define PARADISE_REBOOT 0x100FF568u
#endif
void hw_init(void);
void hw_wdt_feed(void);
u32 hw_buttons(void);
void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1);
void hw_back_to_paradise(void);
void hw_backlight(int on);
int hw_wake_step(int ph); /* WAKE_ASYNC: 1 SLPOUT, 2 DISPON, 3 light (HW_WAKE_ABORT: 0 asleep again) */
void hw_bl_pwm_off(void);
void hw_bl_level(u32 pct);
void hw_bl_test(u32 m, u32 pct);
void hw_tone(u32 hz); /* 0 = off */
#ifdef HW_VOL5
extern u32 g_hw_vol5; /* 1.6.12 test3: 0 off .. 4 loudest, 1 as before */
#endif
#ifdef HW_OPTS
extern u32 g_hw_vol, g_hw_dim; /* 1.6.8: volume 0..3 (2 = as before), brightness 0..3 (0 = full) */
#endif
void hw_bl_set(u32 pct);
#ifdef CLK_ECO
extern u32 g_hw_clk_sh, g_hw_tone_hz;
void hw_clk_shift(u32 sh, u32 core_hz); /* 1.6.9: AHB clock / 2^sh (0..3), SysTick stays 1 ms */
#endif /* 1.6.8 BL_PWM: light 0..100 % */
#ifdef FAST_LCD
void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1);
void hw_px_row(const u16* r, u32 n);
void hw_px_end(void);
#endif
#endif
+23 -23
View File
@@ -1,23 +1,23 @@
#ifndef IO_H
#define IO_H
typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8;
#ifndef REG
#define REG(a) (*(volatile u32*)(a))
#endif
/* Paradise flash through the uncached XIP window (the host test maps it to an array) */
#ifndef XIP_PTR
#define XIP_PTR(a) ((const volatile u8*)(0x60000000u + (a)))
#endif
#define UART 0x4000B000u
#define FCTL 0x40022000u
#define CLK 0x45000000u
static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); }
#ifndef TC_INIT
#ifdef EMU_OVL
#define TC_INIT __attribute__((section(".initcode"), noinline, minsize))
#else
#define TC_INIT __attribute__((section(".initcode"), noinline))
#endif
#endif
#endif
#ifndef IO_H
#define IO_H
typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8;
#ifndef REG
#define REG(a) (*(volatile u32*)(a))
#endif
/* Paradise flash through the uncached XIP window (the host test maps it to an array) */
#ifndef XIP_PTR
#define XIP_PTR(a) ((const volatile u8*)(0x60000000u + (a)))
#endif
#define UART 0x4000B000u
#define FCTL 0x40022000u
#define CLK 0x45000000u
static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); }
#ifndef TC_INIT
#ifdef EMU_OVL
#define TC_INIT __attribute__((section(".initcode"), noinline, minsize))
#else
#define TC_INIT __attribute__((section(".initcode"), noinline))
#endif
#endif
#endif
+31 -31
View File
@@ -1,31 +1,31 @@
#include <stddef.h>
#ifdef LIBC_WORD
/* 1.7.3 test21: small (-Os) with a word loop when aligned, instead of the unrolled byte loops of -O2 (room in TamaEmu) */
void *memset(void *d, int c, size_t n){ unsigned char *p=d; unsigned w=(unsigned char)c*0x01010101u;
if(!((unsigned)p&3u)) for(;n>=4;n-=4,p+=4) *(volatile unsigned*)p=w;
while(n--) *p++=(unsigned char)c; return d; }
void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s;
if(!(((unsigned)p|(unsigned)q)&3u)) for(;n>=4;n-=4,p+=4,q+=4) *(volatile unsigned*)p=*(const unsigned*)q;
while(n--) *p++=*q++; return d; }
#else
void *memset(void *d, int c, size_t n){ unsigned char *p=d; while(n--) *p++=(unsigned char)c; return d; }
void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; while(n--) *p++=*q++; return d; }
#endif
void *memmove(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s;
if(p<q){ while(n--) *p++=*q++; } else { p+=n; q+=n; while(n--) *--p=*--q; } return d; }
int memcmp(const void *a, const void *b, size_t n){ const unsigned char *p=a,*q=b; for(;n;n--,p++,q++) if(*p!=*q) return *p-*q; return 0; }
#ifdef LIBC_ALIAS
/* test23: one copy routine instead of four (each wrapper had its own inlined copy loop) */
void __aeabi_memcpy(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
void __aeabi_memcpy4(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
void __aeabi_memcpy8(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
#else
void __aeabi_memcpy(void *d, const void *s, size_t n){ memcpy(d,s,n); }
void __aeabi_memcpy4(void *d, const void *s, size_t n){ memcpy(d,s,n); }
void __aeabi_memcpy8(void *d, const void *s, size_t n){ memcpy(d,s,n); }
#endif
void __aeabi_memset(void *d, size_t n, int c){ memset(d,c,n); }
void __aeabi_memset4(void *d, size_t n, int c){ memset(d,c,n); }
void __aeabi_memclr(void *d, size_t n){ memset(d,0,n); }
void __aeabi_memclr4(void *d, size_t n){ memset(d,0,n); }
void __aeabi_memclr8(void *d, size_t n){ memset(d,0,n); }
#include <stddef.h>
#ifdef LIBC_WORD
/* 1.7.3 test21: small (-Os) with a word loop when aligned, instead of the unrolled byte loops of -O2 (room in TamaEmu) */
void *memset(void *d, int c, size_t n){ unsigned char *p=d; unsigned w=(unsigned char)c*0x01010101u;
if(!((unsigned)p&3u)) for(;n>=4;n-=4,p+=4) *(volatile unsigned*)p=w;
while(n--) *p++=(unsigned char)c; return d; }
void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s;
if(!(((unsigned)p|(unsigned)q)&3u)) for(;n>=4;n-=4,p+=4,q+=4) *(volatile unsigned*)p=*(const unsigned*)q;
while(n--) *p++=*q++; return d; }
#else
void *memset(void *d, int c, size_t n){ unsigned char *p=d; while(n--) *p++=(unsigned char)c; return d; }
void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; while(n--) *p++=*q++; return d; }
#endif
void *memmove(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s;
if(p<q){ while(n--) *p++=*q++; } else { p+=n; q+=n; while(n--) *--p=*--q; } return d; }
int memcmp(const void *a, const void *b, size_t n){ const unsigned char *p=a,*q=b; for(;n;n--,p++,q++) if(*p!=*q) return *p-*q; return 0; }
#ifdef LIBC_ALIAS
/* test23: one copy routine instead of four (each wrapper had its own inlined copy loop) */
void __aeabi_memcpy(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
void __aeabi_memcpy4(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
void __aeabi_memcpy8(void *d, const void *s, size_t n) __attribute__((alias("memcpy")));
#else
void __aeabi_memcpy(void *d, const void *s, size_t n){ memcpy(d,s,n); }
void __aeabi_memcpy4(void *d, const void *s, size_t n){ memcpy(d,s,n); }
void __aeabi_memcpy8(void *d, const void *s, size_t n){ memcpy(d,s,n); }
#endif
void __aeabi_memset(void *d, size_t n, int c){ memset(d,c,n); }
void __aeabi_memset4(void *d, size_t n, int c){ memset(d,c,n); }
void __aeabi_memclr(void *d, size_t n){ memset(d,0,n); }
void __aeabi_memclr4(void *d, size_t n){ memset(d,0,n); }
void __aeabi_memclr8(void *d, size_t n){ memset(d,0,n); }
+36 -36
View File
@@ -1,36 +1,36 @@
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(.text*)
*(.rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
/* v0.8.16: mutable data lives in SRAM (initial values in PRAM, copied at startup). Writing to
* PRAM while code runs from PRAM corrupts the fetched instructions on the device. */
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
__ram_end = __data_end;
.init : {
. = ALIGN(4);
__initcode_start = .;
KEEP(*(.initcode))
KEEP(*(.initdata*))
__initlast = .;
KEEP(*(.initcode_z))
. = ALIGN(4);
} > PRAM
/* jit_init writes the fixed routines (just over 2 KB) from __initcode_start while
* it is running itself: it must be placed far enough behind them */
ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot")
.jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM
__jit_end = 0x10000;
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(.text*)
*(.rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
/* v0.8.16: mutable data lives in SRAM (initial values in PRAM, copied at startup). Writing to
* PRAM while code runs from PRAM corrupts the fetched instructions on the device. */
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
__ram_end = __data_end;
.init : {
. = ALIGN(4);
__initcode_start = .;
KEEP(*(.initcode))
KEEP(*(.initdata*))
__initlast = .;
KEEP(*(.initcode_z))
. = ALIGN(4);
} > PRAM
/* jit_init writes the fixed routines (just over 2 KB) from __initcode_start while
* it is running itself: it must be placed far enough behind them */
ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot")
.jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM
__jit_end = 0x10000;
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
+44 -44
View File
@@ -1,44 +1,44 @@
/* TamaEmu with EMU_OVL (1.6.13 test10): like link.ld, but the settings menus (ask.c) and the code that runs only when
* leaving or in the settings (.ovltext) sit at the end of the image, in the translator's room (the overlay). The app
* copies them back from its image in the flash when they are needed (ovl_load). */
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*ask.o(.text.keep*)
*(EXCLUDE_FILE(*ask.o) .text*)
*ask.o(.rodata.keep*)
*(EXCLUDE_FILE(*ask.o) .rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
__ram_end = __data_end;
.init : {
. = ALIGN(4);
__initcode_start = .;
KEEP(*(.initcode))
KEEP(*(.initdata*))
__initlast = .;
KEEP(*(.initcode_z))
. = ALIGN(4);
__ovl_start = .;
*(.ovltext*)
*(.ovlrodata*)
*ask.o(.text* .rodata*)
. = ALIGN(4);
__ovl_end = .;
} > PRAM
ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot")
ASSERT(__ovl_start - __initcode_start >= 0x1400, "the overlay must lie behind the translator's fixed routines")
.jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM
__jit_end = 0x10000;
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
/* TamaEmu with EMU_OVL (1.6.13 test10): like link.ld, but the settings menus (ask.c) and the code that runs only when
* leaving or in the settings (.ovltext) sit at the end of the image, in the translator's room (the overlay). The app
* copies them back from its image in the flash when they are needed (ovl_load). */
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*ask.o(.text.keep*)
*(EXCLUDE_FILE(*ask.o) .text*)
*ask.o(.rodata.keep*)
*(EXCLUDE_FILE(*ask.o) .rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
__ram_end = __data_end;
.init : {
. = ALIGN(4);
__initcode_start = .;
KEEP(*(.initcode))
KEEP(*(.initdata*))
__initlast = .;
KEEP(*(.initcode_z))
. = ALIGN(4);
__ovl_start = .;
*(.ovltext*)
*(.ovlrodata*)
*ask.o(.text* .rodata*)
. = ALIGN(4);
__ovl_end = .;
} > PRAM
ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot")
ASSERT(__ovl_start - __initcode_start >= 0x1400, "the overlay must lie behind the translator's fixed routines")
.jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM
__jit_end = 0x10000;
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
+1530 -1530
View File
File diff suppressed because it is too large. Load diff
+91 -91
View File
@@ -1,91 +1,91 @@
/* 1.6.8 (PARA_BACK): the Paradise does not live while a program runs.
* The Paradise keeps no time of its own while a program runs, but its seconds counter 0x45000304 does.
* Back in the Paradise, its firmware compares "now" (base plus counter) with the time it lived up to
* (the six date fields at +0x1C of the settings block 0xEFE000/0xEFF000, year .. second, u16 each) and
* lives the whole gap at once: hunger, mood, care misses, even death. Same as TamaParadise v83.
* So: when a program starts, it notes the counter and the Paradise's time in the clock mailbox of paraclock.h
* ("PCLK" at 0x20000FC0, kept over the restart; the menu fills it at its start, a program started
* straight from the Paradise fills it itself). When it goes back, the date fields move forward by the time
* spent outside (never past now), both copies, new CRC, and the mailbox is cleared.
* (A first try with its own words at 0x20000FE0 made the Paradise start the program again: those words
* are not free.)
* Header only; needs flash_read and flash_update4k, a 4 KB buffer from the caller. */
#ifndef PARABACK_H
#define PARABACK_H
#include <stdint.h>
#ifndef PB_ATTR
#define PB_ATTR
#endif
#ifndef PB_MARK_ATTR
#define PB_MARK_ATTR /* para_leave_mark runs first thing at the start, before the flash window is set up: never in the flash */
#endif
#ifndef PB_MB
#define PB_MB ((volatile uint32_t *)0x20000FC0u) /* same as PARA_MB: magic, time, counter, ~time */
#endif
#define PB_MAGIC 0x4B4C4350u /* "PCLK" */
#ifndef PB_CNT
#define PB_CNT (*(volatile uint32_t *)0x45000304u)
#endif
/* t: the Paradise's local time (seconds since 1970) when the program started, cnt: the counter then */
__attribute__((noinline, unused)) PB_MARK_ATTR static void para_leave_mark(uint32_t cnt, uint32_t t)
{
volatile uint32_t *m = PB_MB;
if (m[0] == PB_MAGIC && m[3] == ~m[1] && m[1] && cnt - m[2] <= 400u * 86400u) return; /* noted by the menu */
if (!t) { m[0] = 0; return; }
m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PB_MAGIC;
}
static inline uint32_t pb_days(int32_t y, int32_t mo, int32_t d) /* days since 1970-01-01 */
{
y -= mo <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400;
int32_t doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return (uint32_t)(era * 146097 + doe - 719468);
}
__attribute__((minsize, noinline)) PB_ATTR static uint32_t pb_crc(const uint8_t *b)
{
uint32_t c = 0;
for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; }
return c;
}
static inline uint32_t pb_u16(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8; }
static inline void pb_w16(uint8_t *b, uint32_t o, uint32_t v) { b[o] = (uint8_t)v; b[o + 1] = (uint8_t)(v >> 8); }
/* Before going back. Returns 1 when the fields were moved. */
__attribute__((noinline, unused, minsize)) PB_ATTR static int para_back_fix(uint8_t *b)
{
volatile uint32_t *m = PB_MB;
if (m[0] != PB_MAGIC || m[3] != ~m[1] || !m[1]) return 0;
uint32_t gap = PB_CNT - m[2], now = m[1] + gap;
#ifdef PARA_MB_KEEP
/* test29: the time stays in the mailbox, moved to now. A start device goes back to the menu, not to the
* Paradise: the SRAM then holds no Paradise clock, and the next program started without a time. */
m[1] = now; m[2] = PB_CNT; m[3] = ~now;
#else
m[0] = 0;
#endif
if (gap < 60u || gap > 400u * 86400u) return 0;
flash_read(0xEFE000u, b, 0x1000u);
uint32_t c = pb_crc(b);
if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0;
uint32_t y = pb_u16(b, 0x1C), mo = pb_u16(b, 0x1E), d = pb_u16(b, 0x20);
uint32_t hh = pb_u16(b, 0x22), mi = pb_u16(b, 0x24), se = pb_u16(b, 0x26);
if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) return 0;
uint32_t f = pb_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se;
if (f >= now) return 0;
uint32_t nf = f + gap; if (nf > now) nf = now;
/* back to a date (civil from days) */
int32_t z = (int32_t)(nf / 86400u) + 719468, era = (z >= 0 ? z : z - 146096) / 146097;
uint32_t doe = (uint32_t)(z - era * 146097), yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
int32_t yy = (int32_t)yoe + era * 400; uint32_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100), mp = (5 * doy + 2) / 153;
uint32_t dd = doy - (153 * mp + 2) / 5 + 1, mm = mp < 10 ? mp + 3 : mp - 9; yy += mm <= 2;
uint32_t s = nf % 86400u;
pb_w16(b, 0x1C, (uint32_t)yy); pb_w16(b, 0x1E, mm); pb_w16(b, 0x20, dd);
pb_w16(b, 0x22, s / 3600u); pb_w16(b, 0x24, s / 60u % 60u); pb_w16(b, 0x26, s % 60u);
c = pb_crc(b);
pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu);
flash_update4k(0xEFE000u, b);
flash_update4k(0xEFF000u, b);
return 1;
}
#endif
/* 1.6.8 (PARA_BACK): the Paradise does not live while a program runs.
* The Paradise keeps no time of its own while a program runs, but its seconds counter 0x45000304 does.
* Back in the Paradise, its firmware compares "now" (base plus counter) with the time it lived up to
* (the six date fields at +0x1C of the settings block 0xEFE000/0xEFF000, year .. second, u16 each) and
* lives the whole gap at once: hunger, mood, care misses, even death. Same as TamaParadise v83.
* So: when a program starts, it notes the counter and the Paradise's time in the clock mailbox of paraclock.h
* ("PCLK" at 0x20000FC0, kept over the restart; the menu fills it at its start, a program started
* straight from the Paradise fills it itself). When it goes back, the date fields move forward by the time
* spent outside (never past now), both copies, new CRC, and the mailbox is cleared.
* (A first try with its own words at 0x20000FE0 made the Paradise start the program again: those words
* are not free.)
* Header only; needs flash_read and flash_update4k, a 4 KB buffer from the caller. */
#ifndef PARABACK_H
#define PARABACK_H
#include <stdint.h>
#ifndef PB_ATTR
#define PB_ATTR
#endif
#ifndef PB_MARK_ATTR
#define PB_MARK_ATTR /* para_leave_mark runs first thing at the start, before the flash window is set up: never in the flash */
#endif
#ifndef PB_MB
#define PB_MB ((volatile uint32_t *)0x20000FC0u) /* same as PARA_MB: magic, time, counter, ~time */
#endif
#define PB_MAGIC 0x4B4C4350u /* "PCLK" */
#ifndef PB_CNT
#define PB_CNT (*(volatile uint32_t *)0x45000304u)
#endif
/* t: the Paradise's local time (seconds since 1970) when the program started, cnt: the counter then */
__attribute__((noinline, unused)) PB_MARK_ATTR static void para_leave_mark(uint32_t cnt, uint32_t t)
{
volatile uint32_t *m = PB_MB;
if (m[0] == PB_MAGIC && m[3] == ~m[1] && m[1] && cnt - m[2] <= 400u * 86400u) return; /* noted by the menu */
if (!t) { m[0] = 0; return; }
m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PB_MAGIC;
}
static inline uint32_t pb_days(int32_t y, int32_t mo, int32_t d) /* days since 1970-01-01 */
{
y -= mo <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400;
int32_t doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return (uint32_t)(era * 146097 + doe - 719468);
}
__attribute__((minsize, noinline)) PB_ATTR static uint32_t pb_crc(const uint8_t *b)
{
uint32_t c = 0;
for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; }
return c;
}
static inline uint32_t pb_u16(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8; }
static inline void pb_w16(uint8_t *b, uint32_t o, uint32_t v) { b[o] = (uint8_t)v; b[o + 1] = (uint8_t)(v >> 8); }
/* Before going back. Returns 1 when the fields were moved. */
__attribute__((noinline, unused, minsize)) PB_ATTR static int para_back_fix(uint8_t *b)
{
volatile uint32_t *m = PB_MB;
if (m[0] != PB_MAGIC || m[3] != ~m[1] || !m[1]) return 0;
uint32_t gap = PB_CNT - m[2], now = m[1] + gap;
#ifdef PARA_MB_KEEP
/* test29: the time stays in the mailbox, moved to now. A start device goes back to the menu, not to the
* Paradise: the SRAM then holds no Paradise clock, and the next program started without a time. */
m[1] = now; m[2] = PB_CNT; m[3] = ~now;
#else
m[0] = 0;
#endif
if (gap < 60u || gap > 400u * 86400u) return 0;
flash_read(0xEFE000u, b, 0x1000u);
uint32_t c = pb_crc(b);
if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0;
uint32_t y = pb_u16(b, 0x1C), mo = pb_u16(b, 0x1E), d = pb_u16(b, 0x20);
uint32_t hh = pb_u16(b, 0x22), mi = pb_u16(b, 0x24), se = pb_u16(b, 0x26);
if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) return 0;
uint32_t f = pb_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se;
if (f >= now) return 0;
uint32_t nf = f + gap; if (nf > now) nf = now;
/* back to a date (civil from days) */
int32_t z = (int32_t)(nf / 86400u) + 719468, era = (z >= 0 ? z : z - 146096) / 146097;
uint32_t doe = (uint32_t)(z - era * 146097), yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
int32_t yy = (int32_t)yoe + era * 400; uint32_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100), mp = (5 * doy + 2) / 153;
uint32_t dd = doy - (153 * mp + 2) / 5 + 1, mm = mp < 10 ? mp + 3 : mp - 9; yy += mm <= 2;
uint32_t s = nf % 86400u;
pb_w16(b, 0x1C, (uint32_t)yy); pb_w16(b, 0x1E, mm); pb_w16(b, 0x20, dd);
pb_w16(b, 0x22, s / 3600u); pb_w16(b, 0x24, s / 60u % 60u); pb_w16(b, 0x26, s % 60u);
c = pb_crc(b);
pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu);
flash_update4k(0xEFE000u, b);
flash_update4k(0xEFF000u, b);
return 1;
}
#endif
+118 -118
View File
@@ -1,118 +1,118 @@
/* The Paradise's own clock, read from its SRAM when an emulator starts (before the emulator uses
* the SRAM). The Paradise keeps the time as a base (days, seconds of the day) plus its seconds
* counter 0x45000304; next to it the six fields it shows (year, month, day, hour, minute, second,
* u16 each). Where this lies differs between the editions, so it is searched: a place counts only
* if base plus counter give the time of day the fields show (chance 1 in 86400). The fields may
* lag the counter by a few seconds; that is added. Same method as TamaParadise (uhrstellen).
* Only for the emulators' start; header only, shared by TamaEmu, T7Emu and T18Emu. */
#ifndef PARACLOCK_H
#define PARACLOCK_H
#include <stdint.h>
#ifndef PARA_ATTR
#define PARA_ATTR /* TamaEmu: start-up code only (its translator takes the space afterwards) */
#endif
/* days since 1970-01-01 */
static inline int32_t para_days(int32_t y, int32_t m, int32_t d)
{
y -= m <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400;
int32_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
/* Search [lo, hi) (byte offsets in the SRAM at 0x18000000) for the clock, skip [skip_lo, skip_hi).
* Returns local time as seconds since 1970 (0 = not found). cnt: the seconds counter now. Must not
* use anything but registers and the stack: it runs before the emulator sets up its memory. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_clock(uint32_t cnt, uint32_t lo, uint32_t hi, uint32_t skip_lo, uint32_t skip_hi)
{
const volatile uint16_t *h = (const volatile uint16_t *)0x18000000u;
uint32_t best = 0, best_lag = 600;
if (lo < 0x10) lo = 0x10;
for (uint32_t o = lo; o + 12 <= hi; o += 2) {
if (o + 12 > skip_lo && o - 0x10 < skip_hi) continue;
uint32_t y = h[o / 2];
if (y < 2000u || y > 2100u) continue;
uint32_t mo = h[o / 2 + 1], d = h[o / 2 + 2], hh = h[o / 2 + 3], mi = h[o / 2 + 4], se = h[o / 2 + 5];
if (mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue;
uint32_t days = h[(o - 0x10) / 2] | (uint32_t)h[(o - 0x10) / 2 + 1] << 16;
uint32_t sek = h[(o - 0x0C) / 2] | (uint32_t)h[(o - 0x0C) / 2 + 1] << 16;
if (sek >= 86400u || days >= 40000u) continue;
uint32_t tod = (sek + cnt % 86400u) % 86400u; /* days * 86400 drops out */
uint32_t shown = hh * 3600u + mi * 60u + se;
uint32_t lag = (tod + 86400u - shown) % 86400u; /* fields behind the clock by this much */
if (lag < best_lag) {
best_lag = lag;
best = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + shown + lag;
}
}
return best;
}
/* 1.6.8: the Paramix menu runs before a program and uses the SRAM itself, so it looks the clock up at
* its own start and leaves it in the mailbox (0x20000FC0: "PCLK", time, counter, ~time). A program
* started from the menu takes it from there when its own search finds nothing. One day at most. */
#define PARA_MB ((volatile uint32_t *)0x20000FC0u)
#define PARA_MB_MAGIC 0x4B4C4350u
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox(uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
#ifdef PARA_MB_KEEP
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 400u * 86400u) return 0; /* test29: kept, see paraback.h */
#else
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 86400u) return 0;
#endif
return m[1] + (cnt - m[2]);
}
/* 1.7.2 test17: the mailbox written in the last two minutes (the menu right before starting the program, or its clock in a
* start device without the Paradise): it comes first, before the search in the SRAM, which may find old leftovers there */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox_fresh(uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 120u) return 0;
return m[1] + (cnt - m[2]);
}
#ifdef PARA_FLASH
/* 1.6.9 test37 (PARA_FLASH): the Paradise keeps the base of its clock in its settings page 0xEFE000 (copy at 0xEFF000):
* days since 2025-01-01 at +0x0C and seconds at +0x10; now = base + the seconds counter 0x45000304, which runs on
* while programs run. Found in the TamaParadise runs: the same base as in the SRAM clock (block in the SRAM at
* 0x18000B9C is this page). Used when neither the SRAM nor the mailbox give the time (the Paradise restarted and the
* mailbox was gone: reported, the clock of V3Emu and Tama-Go was not set now and then). The page must have a good
* CRC and its date fields (+0x1C, the time the Paradise lived up to) must lie within a year before that time. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_flash(uint32_t cnt)
{
for (uint32_t pg = 0x60EFE000u; pg <= 0x60EFF000u; pg += 0x1000u) {
const volatile uint8_t *b = (const volatile uint8_t *)pg;
uint32_t c = 0;
for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; }
if ((b[0] | (uint32_t)b[1] << 8) != c || (b[2] | (uint32_t)b[3] << 8) != (~c & 0xFFFFu)) continue;
uint32_t days = b[0x0C] | (uint32_t)b[0x0D] << 8 | (uint32_t)b[0x0E] << 16 | (uint32_t)b[0x0F] << 24;
uint32_t sek = b[0x10] | (uint32_t)b[0x11] << 8 | (uint32_t)b[0x12] << 16 | (uint32_t)b[0x13] << 24;
if (days > 40000u || sek >= 86400u) continue;
uint32_t y = b[0x1C] | (uint32_t)b[0x1D] << 8, mo = b[0x1E] | (uint32_t)b[0x1F] << 8, d = b[0x20] | (uint32_t)b[0x21] << 8;
uint32_t hh = b[0x22] | (uint32_t)b[0x23] << 8, mi = b[0x24] | (uint32_t)b[0x25] << 8, se = b[0x26] | (uint32_t)b[0x27] << 8;
if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue;
uint32_t t = (20089u + days) * 86400u + sek + cnt; /* 20089: days from 1970 to 2025-01-01 */
uint32_t f = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se;
if (f > t + 600u || t - f > 366u * 86400u) continue;
return t;
}
return 0;
}
#endif
#ifdef PARA_CLEAN_CLK
/* 1.7.2 test17 (PARA_CLEAN_CLK): start device without the Paradise: nobody but the menu keeps the time, in its clock
* sector 0x0C0000 ("PMXK", time, counter then, idle, check = xor of the four). A program that starts first (autostart,
* the menu did not run) found no time before. Readable only after hw_init. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_cleanclk(uint32_t cnt)
{
const volatile uint32_t *p = (const volatile uint32_t *)0x600C0000u;
uint32_t m = p[0], t = p[1], c = p[2], i = p[3], k = p[4];
if (m != 0x4B584D50u || k != (m ^ t ^ c ^ i) || !t || cnt < c) return 0;
return t + (cnt - c);
}
#endif
__attribute__((noinline, unused)) static void para_mailbox_put(uint32_t t, uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
if (!t) return;
m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PARA_MB_MAGIC;
}
#endif
/* The Paradise's own clock, read from its SRAM when an emulator starts (before the emulator uses
* the SRAM). The Paradise keeps the time as a base (days, seconds of the day) plus its seconds
* counter 0x45000304; next to it the six fields it shows (year, month, day, hour, minute, second,
* u16 each). Where this lies differs between the editions, so it is searched: a place counts only
* if base plus counter give the time of day the fields show (chance 1 in 86400). The fields may
* lag the counter by a few seconds; that is added. Same method as TamaParadise (uhrstellen).
* Only for the emulators' start; header only, shared by TamaEmu, T7Emu and T18Emu. */
#ifndef PARACLOCK_H
#define PARACLOCK_H
#include <stdint.h>
#ifndef PARA_ATTR
#define PARA_ATTR /* TamaEmu: start-up code only (its translator takes the space afterwards) */
#endif
/* days since 1970-01-01 */
static inline int32_t para_days(int32_t y, int32_t m, int32_t d)
{
y -= m <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400;
int32_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
/* Search [lo, hi) (byte offsets in the SRAM at 0x18000000) for the clock, skip [skip_lo, skip_hi).
* Returns local time as seconds since 1970 (0 = not found). cnt: the seconds counter now. Must not
* use anything but registers and the stack: it runs before the emulator sets up its memory. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_clock(uint32_t cnt, uint32_t lo, uint32_t hi, uint32_t skip_lo, uint32_t skip_hi)
{
const volatile uint16_t *h = (const volatile uint16_t *)0x18000000u;
uint32_t best = 0, best_lag = 600;
if (lo < 0x10) lo = 0x10;
for (uint32_t o = lo; o + 12 <= hi; o += 2) {
if (o + 12 > skip_lo && o - 0x10 < skip_hi) continue;
uint32_t y = h[o / 2];
if (y < 2000u || y > 2100u) continue;
uint32_t mo = h[o / 2 + 1], d = h[o / 2 + 2], hh = h[o / 2 + 3], mi = h[o / 2 + 4], se = h[o / 2 + 5];
if (mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue;
uint32_t days = h[(o - 0x10) / 2] | (uint32_t)h[(o - 0x10) / 2 + 1] << 16;
uint32_t sek = h[(o - 0x0C) / 2] | (uint32_t)h[(o - 0x0C) / 2 + 1] << 16;
if (sek >= 86400u || days >= 40000u) continue;
uint32_t tod = (sek + cnt % 86400u) % 86400u; /* days * 86400 drops out */
uint32_t shown = hh * 3600u + mi * 60u + se;
uint32_t lag = (tod + 86400u - shown) % 86400u; /* fields behind the clock by this much */
if (lag < best_lag) {
best_lag = lag;
best = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + shown + lag;
}
}
return best;
}
/* 1.6.8: the Paramix menu runs before a program and uses the SRAM itself, so it looks the clock up at
* its own start and leaves it in the mailbox (0x20000FC0: "PCLK", time, counter, ~time). A program
* started from the menu takes it from there when its own search finds nothing. One day at most. */
#define PARA_MB ((volatile uint32_t *)0x20000FC0u)
#define PARA_MB_MAGIC 0x4B4C4350u
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox(uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
#ifdef PARA_MB_KEEP
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 400u * 86400u) return 0; /* test29: kept, see paraback.h */
#else
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 86400u) return 0;
#endif
return m[1] + (cnt - m[2]);
}
/* 1.7.2 test17: the mailbox written in the last two minutes (the menu right before starting the program, or its clock in a
* start device without the Paradise): it comes first, before the search in the SRAM, which may find old leftovers there */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox_fresh(uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 120u) return 0;
return m[1] + (cnt - m[2]);
}
#ifdef PARA_FLASH
/* 1.6.9 test37 (PARA_FLASH): the Paradise keeps the base of its clock in its settings page 0xEFE000 (copy at 0xEFF000):
* days since 2025-01-01 at +0x0C and seconds at +0x10; now = base + the seconds counter 0x45000304, which runs on
* while programs run. Found in the TamaParadise runs: the same base as in the SRAM clock (block in the SRAM at
* 0x18000B9C is this page). Used when neither the SRAM nor the mailbox give the time (the Paradise restarted and the
* mailbox was gone: reported, the clock of V3Emu and Tama-Go was not set now and then). The page must have a good
* CRC and its date fields (+0x1C, the time the Paradise lived up to) must lie within a year before that time. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_flash(uint32_t cnt)
{
for (uint32_t pg = 0x60EFE000u; pg <= 0x60EFF000u; pg += 0x1000u) {
const volatile uint8_t *b = (const volatile uint8_t *)pg;
uint32_t c = 0;
for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; }
if ((b[0] | (uint32_t)b[1] << 8) != c || (b[2] | (uint32_t)b[3] << 8) != (~c & 0xFFFFu)) continue;
uint32_t days = b[0x0C] | (uint32_t)b[0x0D] << 8 | (uint32_t)b[0x0E] << 16 | (uint32_t)b[0x0F] << 24;
uint32_t sek = b[0x10] | (uint32_t)b[0x11] << 8 | (uint32_t)b[0x12] << 16 | (uint32_t)b[0x13] << 24;
if (days > 40000u || sek >= 86400u) continue;
uint32_t y = b[0x1C] | (uint32_t)b[0x1D] << 8, mo = b[0x1E] | (uint32_t)b[0x1F] << 8, d = b[0x20] | (uint32_t)b[0x21] << 8;
uint32_t hh = b[0x22] | (uint32_t)b[0x23] << 8, mi = b[0x24] | (uint32_t)b[0x25] << 8, se = b[0x26] | (uint32_t)b[0x27] << 8;
if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue;
uint32_t t = (20089u + days) * 86400u + sek + cnt; /* 20089: days from 1970 to 2025-01-01 */
uint32_t f = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se;
if (f > t + 600u || t - f > 366u * 86400u) continue;
return t;
}
return 0;
}
#endif
#ifdef PARA_CLEAN_CLK
/* 1.7.2 test17 (PARA_CLEAN_CLK): start device without the Paradise: nobody but the menu keeps the time, in its clock
* sector 0x0C0000 ("PMXK", time, counter then, idle, check = xor of the four). A program that starts first (autostart,
* the menu did not run) found no time before. Readable only after hw_init. */
__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_cleanclk(uint32_t cnt)
{
const volatile uint32_t *p = (const volatile uint32_t *)0x600C0000u;
uint32_t m = p[0], t = p[1], c = p[2], i = p[3], k = p[4];
if (m != 0x4B584D50u || k != (m ^ t ^ c ^ i) || !t || cnt < c) return 0;
return t + (cnt - c);
}
#endif
__attribute__((noinline, unused)) static void para_mailbox_put(uint32_t t, uint32_t cnt)
{
volatile uint32_t *m = PARA_MB;
if (!t) return;
m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PARA_MB_MAGIC;
}
#endif
+80 -80
View File
@@ -1,80 +1,80 @@
/* plink.h - 1.6.9: link to another Paradise over the UART on the contacts (as T18Emu's T18_LINK).
* UART1 0x4000B000, IRQ 37, 460800 8N1 like the flash program. Frames: A5 type len data sum (sum = type + len + data,
* low byte), 5A as start byte is taken too (from the PC). Every second a hello 'H' (ignored by the other side).
* Two Paradise plugged together at the top (their connector crosses TX and RX).
* Header only: include once in the program's main.c, put plink_irq at vector 16 + 37, call plink_init once and
* plink_poll in the main loop. Author: mameise */
#ifndef PLINK_H
#define PLINK_H
#include "io.h"
#ifndef PL_ATTR
#define PL_ATTR __attribute__((noinline))
#endif
#ifndef PL_INIT_ATTR
#define PL_INIT_ATTR PL_ATTR
#endif
#define PL_U1 0x4000B000u
#define PL_DATA REG(PL_U1 + 0x00)
#define PL_IER REG(PL_U1 + 0x04)
#define PL_FCR REG(PL_U1 + 0x08)
#define PL_LCR REG(PL_U1 + 0x0C)
#define PL_LSR REG(PL_U1 + 0x14)
#define PL_FDR REG(PL_U1 + 0x28)
#define PL_CTRL REG(PL_U1 + 0x30)
typedef void (*plink_fn)(u8 ty, const u8 *d, int n);
static struct {
u8 rx[256]; volatile u8 rh, rt;
u8 st, ty, len, pos, sum, on;
u8 f[64];
u32 hello, last_rx;
} g_pl;
__attribute__((used)) static void plink_irq(void)
{
while (PL_LSR & 1u) { u8 b = (u8)PL_DATA; u8 nt = (u8)(g_pl.rt + 1u); if (nt != g_pl.rh) { g_pl.rx[g_pl.rt] = b; g_pl.rt = nt; } }
}
PL_INIT_ATTR static void plink_init(void)
{
g_pl.rh = g_pl.rt = 0; g_pl.st = 0; g_pl.hello = 0; g_pl.last_rx = 0;
PL_IER = 0;
PL_LCR = 0x83; PL_DATA = 0x1A; PL_IER = 0x00; PL_LCR = 0x03; PL_FDR = 0x100; PL_FCR = 0x07; PL_CTRL = 0xC1; /* 460800 8N1 */
while (PL_LSR & 1u) (void)PL_DATA;
PL_IER = 0x01; /* received data */
REG(0xE000E104u) = 1u << (37 - 32); /* NVIC: UART1 */
g_pl.on = 1;
}
PL_ATTR static void plink_send(u8 ty, const u8 *d, int n)
{
if (!g_pl.on) return;
u8 h[3] = { 0xA5, ty, (u8)n }, s = (u8)(ty + n);
for (int i = 0; i < n + 4; i++) {
u8 v = i < 3 ? h[i] : i < n + 3 ? d[i - 3] : s;
if (i >= 3 && i < n + 3) s = (u8)(s + v);
for (u32 w = 0; !(PL_LSR & 0x20u); w++) if (w > 20000u) { g_pl.on = 0; return; } /* no UART: off, the game runs on */
PL_DATA = v;
}
}
/* flags for the hello: bit 0 = in the connection screen (ready) */
PL_ATTR static void plink_poll(u32 now, u8 flags, plink_fn fn)
{
if (!g_pl.on) return;
while (g_pl.rh != g_pl.rt) {
u8 b = g_pl.rx[g_pl.rh]; g_pl.rh = (u8)(g_pl.rh + 1u);
switch (g_pl.st) {
case 0: if (b == 0xA5 || b == 0x5A) g_pl.st = 1; break;
case 1: g_pl.ty = b; g_pl.sum = b; g_pl.st = 2; break;
case 2: if (b > 64) { g_pl.st = 0; break; } g_pl.len = b; g_pl.pos = 0; g_pl.sum = (u8)(g_pl.sum + b); g_pl.st = b ? 3 : 4; break;
case 3: g_pl.f[g_pl.pos++] = b; g_pl.sum = (u8)(g_pl.sum + b); if (g_pl.pos >= g_pl.len) g_pl.st = 4; break;
default:
g_pl.st = 0;
if (b != g_pl.sum) break; /* noise on an open contact */
g_pl.last_rx = now ? now : 1u;
if (g_pl.ty != 'H' && g_pl.ty != 'P') fn(g_pl.ty, g_pl.f, g_pl.len);
break;
}
}
if (now - g_pl.hello >= 1000u) { g_pl.hello = now; plink_send('H', &flags, 1); }
}
#endif
/* plink.h - 1.6.9: link to another Paradise over the UART on the contacts (as T18Emu's T18_LINK).
* UART1 0x4000B000, IRQ 37, 460800 8N1 like the flash program. Frames: A5 type len data sum (sum = type + len + data,
* low byte), 5A as start byte is taken too (from the PC). Every second a hello 'H' (ignored by the other side).
* Two Paradise plugged together at the top (their connector crosses TX and RX).
* Header only: include once in the program's main.c, put plink_irq at vector 16 + 37, call plink_init once and
* plink_poll in the main loop. Author: mameise */
#ifndef PLINK_H
#define PLINK_H
#include "io.h"
#ifndef PL_ATTR
#define PL_ATTR __attribute__((noinline))
#endif
#ifndef PL_INIT_ATTR
#define PL_INIT_ATTR PL_ATTR
#endif
#define PL_U1 0x4000B000u
#define PL_DATA REG(PL_U1 + 0x00)
#define PL_IER REG(PL_U1 + 0x04)
#define PL_FCR REG(PL_U1 + 0x08)
#define PL_LCR REG(PL_U1 + 0x0C)
#define PL_LSR REG(PL_U1 + 0x14)
#define PL_FDR REG(PL_U1 + 0x28)
#define PL_CTRL REG(PL_U1 + 0x30)
typedef void (*plink_fn)(u8 ty, const u8 *d, int n);
static struct {
u8 rx[256]; volatile u8 rh, rt;
u8 st, ty, len, pos, sum, on;
u8 f[64];
u32 hello, last_rx;
} g_pl;
__attribute__((used)) static void plink_irq(void)
{
while (PL_LSR & 1u) { u8 b = (u8)PL_DATA; u8 nt = (u8)(g_pl.rt + 1u); if (nt != g_pl.rh) { g_pl.rx[g_pl.rt] = b; g_pl.rt = nt; } }
}
PL_INIT_ATTR static void plink_init(void)
{
g_pl.rh = g_pl.rt = 0; g_pl.st = 0; g_pl.hello = 0; g_pl.last_rx = 0;
PL_IER = 0;
PL_LCR = 0x83; PL_DATA = 0x1A; PL_IER = 0x00; PL_LCR = 0x03; PL_FDR = 0x100; PL_FCR = 0x07; PL_CTRL = 0xC1; /* 460800 8N1 */
while (PL_LSR & 1u) (void)PL_DATA;
PL_IER = 0x01; /* received data */
REG(0xE000E104u) = 1u << (37 - 32); /* NVIC: UART1 */
g_pl.on = 1;
}
PL_ATTR static void plink_send(u8 ty, const u8 *d, int n)
{
if (!g_pl.on) return;
u8 h[3] = { 0xA5, ty, (u8)n }, s = (u8)(ty + n);
for (int i = 0; i < n + 4; i++) {
u8 v = i < 3 ? h[i] : i < n + 3 ? d[i - 3] : s;
if (i >= 3 && i < n + 3) s = (u8)(s + v);
for (u32 w = 0; !(PL_LSR & 0x20u); w++) if (w > 20000u) { g_pl.on = 0; return; } /* no UART: off, the game runs on */
PL_DATA = v;
}
}
/* flags for the hello: bit 0 = in the connection screen (ready) */
PL_ATTR static void plink_poll(u32 now, u8 flags, plink_fn fn)
{
if (!g_pl.on) return;
while (g_pl.rh != g_pl.rt) {
u8 b = g_pl.rx[g_pl.rh]; g_pl.rh = (u8)(g_pl.rh + 1u);
switch (g_pl.st) {
case 0: if (b == 0xA5 || b == 0x5A) g_pl.st = 1; break;
case 1: g_pl.ty = b; g_pl.sum = b; g_pl.st = 2; break;
case 2: if (b > 64) { g_pl.st = 0; break; } g_pl.len = b; g_pl.pos = 0; g_pl.sum = (u8)(g_pl.sum + b); g_pl.st = b ? 3 : 4; break;
case 3: g_pl.f[g_pl.pos++] = b; g_pl.sum = (u8)(g_pl.sum + b); if (g_pl.pos >= g_pl.len) g_pl.st = 4; break;
default:
g_pl.st = 0;
if (b != g_pl.sum) break; /* noise on an open contact */
g_pl.last_rx = now ? now : 1u;
if (g_pl.ty != 'H' && g_pl.ty != 'P') fn(g_pl.ty, g_pl.f, g_pl.len);
break;
}
}
if (now - g_pl.hello >= 1000u) { g_pl.hello = now; plink_send('H', &flags, 1); }
}
#endif
+58 -58
View File
@@ -1,58 +1,58 @@
/* Paramix: an emulator's whole state in the flash (1.6.11 test2, GBEmu and SMSEmu). Stored on leaving, read once at the
* next start and dropped right after reading, so a power cut later starts from the game's own save as the real
* hardware would. Layout: header (magic "PMST", tag, length, sum) and the parts one after the other; the sectors behind
* the first are written first, the one with the header last (a cut while storing leaves no valid state).
* tag: anything that changes with the program build or the game (a state of another build is not taken).
* Header only. Author: mameise */
#ifndef PSTATE_H
#define PSTATE_H
typedef struct { void *p; u32 n; } StPart;
#define ST_MAGIC 0x54534D50u /* "PMST" */
#define ST_HEAD 16u
/* byte i of the parts behind the header */
static inline u8 st_byte(const StPart *pt, int np, u32 i)
{
for (int k = 0; k < np; k++) { if (i < pt[k].n) return ((const u8 *)pt[k].p)[i]; i -= pt[k].n; }
return 0xFF;
}
static u32 st_len(const StPart *pt, int np) { u32 n = 0; for (int k = 0; k < np; k++) n += pt[k].n; return n; }
/* sec: 4 KB buffer. Returns 1 when stored. */
static int st_store(u32 at, u32 max, u32 tag, const StPart *pt, int np, u8 *sec)
{
u32 len = st_len(pt, np), tot = ST_HEAD + len;
if (tot > max) return 0;
u32 sum = 0x5157u;
for (int k = 0; k < np; k++) { const u8 *p = (const u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) sum = sum * 31u + p[i]; }
u32 ns = (tot + 0xFFFu) >> 12;
for (u32 s = ns; s-- > 0; ) { /* the last sector first, the header sector at the end */
hw_wdt_feed();
for (u32 i = 0; i < 0x1000u; i++) {
u32 o = (s << 12) + i;
u8 v = 0xFF;
if (o < ST_HEAD) { u32 w = o < 4 ? ST_MAGIC : o < 8 ? tag : o < 12 ? len : sum; v = (u8)(w >> (8 * (o & 3u))); }
else if (o < tot) v = st_byte(pt, np, o - ST_HEAD);
sec[i] = v;
}
flash_update4k(at + (s << 12), sec);
}
return 1;
}
static u32 st_rd32(const volatile u8 *p) { return p[0] | (u32)p[1] << 8 | (u32)p[2] << 16 | (u32)p[3] << 24; }
/* Returns 1 when a state of this tag was read into the parts (sizes must match). */
static int st_load(u32 at, u32 max, u32 tag, const StPart *pt, int np)
{
const volatile u8 *f = XIP_PTR(at);
u32 len = st_len(pt, np);
if (st_rd32(f) != ST_MAGIC || st_rd32(f + 4) != tag || st_rd32(f + 8) != len || ST_HEAD + len > max) return 0;
u32 sum = 0x5157u;
for (u32 i = 0; i < len; i++) { sum = sum * 31u + f[ST_HEAD + i]; if ((i & 0xFFFu) == 0) hw_wdt_feed(); }
if (sum != st_rd32(f + 12)) return 0;
u32 o = ST_HEAD;
for (int k = 0; k < np; k++) { u8 *p = (u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) p[i] = f[o++]; }
return 1;
}
/* the header away: the state is used once */
static void st_drop(u32 at) { if (st_rd32(XIP_PTR(at)) != 0xFFFFFFFFu) flash_erase4k(at); }
#endif
/* Paramix: an emulator's whole state in the flash (1.6.11 test2, GBEmu and SMSEmu). Stored on leaving, read once at the
* next start and dropped right after reading, so a power cut later starts from the game's own save as the real
* hardware would. Layout: header (magic "PMST", tag, length, sum) and the parts one after the other; the sectors behind
* the first are written first, the one with the header last (a cut while storing leaves no valid state).
* tag: anything that changes with the program build or the game (a state of another build is not taken).
* Header only. Author: mameise */
#ifndef PSTATE_H
#define PSTATE_H
typedef struct { void *p; u32 n; } StPart;
#define ST_MAGIC 0x54534D50u /* "PMST" */
#define ST_HEAD 16u
/* byte i of the parts behind the header */
static inline u8 st_byte(const StPart *pt, int np, u32 i)
{
for (int k = 0; k < np; k++) { if (i < pt[k].n) return ((const u8 *)pt[k].p)[i]; i -= pt[k].n; }
return 0xFF;
}
static u32 st_len(const StPart *pt, int np) { u32 n = 0; for (int k = 0; k < np; k++) n += pt[k].n; return n; }
/* sec: 4 KB buffer. Returns 1 when stored. */
static int st_store(u32 at, u32 max, u32 tag, const StPart *pt, int np, u8 *sec)
{
u32 len = st_len(pt, np), tot = ST_HEAD + len;
if (tot > max) return 0;
u32 sum = 0x5157u;
for (int k = 0; k < np; k++) { const u8 *p = (const u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) sum = sum * 31u + p[i]; }
u32 ns = (tot + 0xFFFu) >> 12;
for (u32 s = ns; s-- > 0; ) { /* the last sector first, the header sector at the end */
hw_wdt_feed();
for (u32 i = 0; i < 0x1000u; i++) {
u32 o = (s << 12) + i;
u8 v = 0xFF;
if (o < ST_HEAD) { u32 w = o < 4 ? ST_MAGIC : o < 8 ? tag : o < 12 ? len : sum; v = (u8)(w >> (8 * (o & 3u))); }
else if (o < tot) v = st_byte(pt, np, o - ST_HEAD);
sec[i] = v;
}
flash_update4k(at + (s << 12), sec);
}
return 1;
}
static u32 st_rd32(const volatile u8 *p) { return p[0] | (u32)p[1] << 8 | (u32)p[2] << 16 | (u32)p[3] << 24; }
/* Returns 1 when a state of this tag was read into the parts (sizes must match). */
static int st_load(u32 at, u32 max, u32 tag, const StPart *pt, int np)
{
const volatile u8 *f = XIP_PTR(at);
u32 len = st_len(pt, np);
if (st_rd32(f) != ST_MAGIC || st_rd32(f + 4) != tag || st_rd32(f + 8) != len || ST_HEAD + len > max) return 0;
u32 sum = 0x5157u;
for (u32 i = 0; i < len; i++) { sum = sum * 31u + f[ST_HEAD + i]; if ((i & 0xFFFu) == 0) hw_wdt_feed(); }
if (sum != st_rd32(f + 12)) return 0;
u32 o = ST_HEAD;
for (int k = 0; k < np; k++) { u8 *p = (u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) p[i] = f[o++]; }
return 1;
}
/* the header away: the state is used once */
static void st_drop(u32 at) { if (st_rd32(XIP_PTR(at)) != 0xFFFFFFFFu) flash_erase4k(at); }
#endif
+269 -269
View File
@@ -1,269 +1,269 @@
/* Save and restore state.
* 1. Written flash sectors of the guest go back into its image in the
* Paradise flash (that is where the Tamagotchi's save lives).
* 2. The run state (CPU, RAM, peripherals, screen) is packed into the
* backup area; the next start resumes from there. */
#include "hw.h"
#include "flash.h"
#include "../core/tc.h"
#include "state.h"
#ifdef EMU_OVL
#define ST_OVL __attribute__((section(".ovltext"))) /* 1.6.13 test10: the save when leaving, from the overlay */
#else
#define ST_OVL
#endif
#define MAGIC 0x53584D50u /* "PMXS" */
#define SVER 3u /* 2: Emu fields rearranged for the translator (v0.7), 3: 64 KB sectors and spare pages (v0.9.2) */
static u8 *g_sec; /* 4 KB buffer: first overlay slot (empty when saving) */
/* ---- Spare pages (v0.9.2) ----
* The guest also writes 64 KB sectors that are empty in its firmware (item stores and others).
* The Studio does not store empty blocks, so these written 8 KB parts go into spare pages
* behind the packed firmware. A table in the first 4 KB says which page holds which part.
* Order when writing: page first, then table. A table that does not check out counts as empty. */
#define PG_MAX 64
#define PG_MAGIC 0x50584D50u /* "PMXP" */
#ifndef PT_PAD
#define PT_PAD 4 /* host test: 4096, so the 4 KB read stays inside the variable */
#endif
#if defined(LZ_GONE) && defined(TC_LZ)
/* 1.7.3 test21 LZ_GONE: packed blocks the guest erased, kept behind the table (own check word: older tables have
* whatever followed in RAM there). Before, they counted only until the next start: then the parts not written again
* read the old packed data, mixed with the new ones (items gone wrong, the game slow, odd pictures and sounds). */
#define GONE_W 5u
#define GONE_MAGIC 0x454E4F47u
#else
#define GONE_W 0u
#endif
static struct { u32 magic, n, chk, pad; u16 vp[PG_MAX]; u32 gone[GONE_W]; u8 tail[PT_PAD]; } g_pt;
#define PT_LEN (16u+2u*PG_MAX+4u*GONE_W)
static u32 g_pg_tab, g_pg_data, g_pg_n;
u32 st_n_pages, st_n_free;
__attribute__((noinline)) static u32 pt_chk(void){ u32 x=g_pt.magic ^ (g_pt.n*0x9E3779B1u); for(u32 i=0;i<PG_MAX;i++) x=(x<<5|x>>27) ^ g_pt.vp[i]; return x; }
__attribute__((noinline)) static void pt_save(void){
g_pt.magic=PG_MAGIC; g_pt.n=g_pg_n; g_pt.chk=pt_chk();
/* The DMA reads 4 KB from the table: what follows it in RAM is ignored when reading back. */
if(g_pg_n && !flash_same(g_pg_tab, &g_pt, PT_LEN)) flash_prog4k(g_pg_tab, &g_pt);
}
__attribute__((noinline)) static void pt_count(void){ u32 n=0; for(u32 i=0;i<g_pg_n;i++) if(g_pt.vp[i]!=0xFFFFu) n++; st_n_pages=n; st_n_free=g_pg_n-n; }
static int blk_mapped(const StCfg *c, u32 blk){ return c->map[blk & 127u] != 0xFFu; }
TC_INIT void st_pages(Emu *e, const StCfg *c)
{
u32 lo=(c->guest_off + c->guest_size + 0x1FFFu) & ~0x1FFFu, hi=c->spare_end & ~0x1FFFu;
g_pg_n=0;
if(hi >= lo + 0x4000u){ g_pg_tab=lo; g_pg_data=lo+0x2000u; g_pg_n=(hi-g_pg_data)>>13; if(g_pg_n>PG_MAX) g_pg_n=PG_MAX; }
flash_read(g_pg_tab, &g_pt, PT_LEN);
int bad=!g_pg_n || g_pt.magic!=PG_MAGIC || g_pt.n!=g_pg_n || g_pt.chk!=pt_chk();
if(bad)
for(u32 i=0;i<PG_MAX;i++) g_pt.vp[i]=0xFFFFu;
#if GONE_W
{ u32 x=GONE_MAGIC; for(u32 i=0;i<4;i++) x^=g_pt.gone[i];
if(bad || x!=g_pt.gone[4]){ for(u32 i=0;i<4;i++) g_pt.gone[i]=0; g_pt.gone[4]=GONE_MAGIC; } /* no table, or an older one */
for(u32 i=0;i<4;i++) tc_lz_gone[i]=g_pt.gone[i]; }
#endif
e->pg_base=(const uint8_t*)XIP_PTR(g_pg_data);
for(u32 i=0;i<4;i++) e->pg_blk[i]=0;
for(u32 i=0;i<1024;i++) e->pg_map[i]=0xFFu;
u32 nb=e->dev.rom_size>>16; if(nb>128) nb=128;
for(u32 b=0;b<nb;b++) if(!blk_mapped(c,b) && (b<<16)-e->par_base>=0x10000u) e->pg_blk[b>>5] |= 1u<<(b&31u);
for(u32 i=0;i<g_pg_n;i++){ u32 v=g_pt.vp[i];
if(v<1024u && ((e->pg_blk[v>>8]>>((v>>3)&31u))&1u) && e->pg_map[v]==0xFFu) e->pg_map[v]=(u8)i; else g_pt.vp[i]=0xFFFFu; }
pt_count();
}
/* Address in the Paradise flash of a stored block (0 = none). */
__attribute__((noinline)) static u32 blk_addr(const StCfg *c, u32 off)
{
u32 k=c->map[(off>>16)&127];
if(k==0xFE) k=off>>16;
if(k==0xFF) return 0;
return c->guest_off + (k<<16) + (off & 0xFFFFu);
}
__attribute__((noinline)) static int all_ff(const u8 *p){ const u32 *w=(const u32*)p; for(u32 i=0;i<OVL_SIZE/4u;i++) if(w[i]!=0xFFFFFFFFu) return 0; return 1; }
/* Write an 8 KB part back. step: at most one 4 KB write. Returns the number of flash writes. */
static int wb_part(Emu *e, const StCfg *c, u32 base, const u8 *mem, int step)
{
u32 a=blk_addr(c, base);
if(!a){
u32 v=(base>>13)&1023u, i=e->pg_map[v];
if(!((e->pg_blk[v>>8]>>((v>>3)&31u))&1u)) return 0;
#if defined(LZ_GONE) && defined(TC_LZ)
u32 lb=(base>>16)&127u; /* LZ_GONE: a part of a packed block keeps its page even when empty, else the old data comes back */
if(all_ff(mem) && !(tc_lz_tab && ((const u32*)tc_lz_tab)[lb] && !((tc_lz_gone[lb>>5]>>(lb&31u))&1u))){
#else
if(all_ff(mem)){ /* erased: release the page */
#endif
if(i==0xFFu) return 0;
g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; pt_save(); pt_count(); return 1;
}
if(i==0xFFu){ /* new page */
for(i=0;i<g_pg_n && g_pt.vp[i]!=0xFFFFu;i++){}
if(i>=g_pg_n){ e->flash_lost_writes++; return 0; }
a=g_pg_data + (i<<13);
flash_update4k(a, mem); flash_update4k(a+0x1000u, mem+0x1000u);
g_pt.vp[i]=(u16)v; e->pg_map[v]=(u8)i; pt_save(); pt_count();
return 3;
}
a=g_pg_data + (i<<13);
}
if(step){
for(u32 h=0;h<2;h++) if(!flash_same(a+h*0x1000u, mem+h*0x1000u, 0x1000u)){ flash_prog4k(a+h*0x1000u, mem+h*0x1000u); return 1; }
return 0;
}
return flash_update4k(a, mem) + flash_update4k(a+0x1000u, mem+0x1000u);
}
/* Erase a 64 KB sector of the guest (hook tc_big_erase). */
static const StCfg *g_evcfg;
int st_big_erase(Emu *e, uint32_t base)
{
const StCfg *c=g_evcfg; if(!c) return 0;
u32 a=blk_addr(c, base & ~0xFFFFu);
if(a){
for(u32 s=0;s<16u;s++) if(!flash_isff(a+s*0x1000u, 0x1000u)) flash_erase4k(a+s*0x1000u);
return 1;
}
#ifdef TC_LZ
{ u32 b=(base>>16)&127u; tc_lz_gone[b>>5] |= 1u<<(b&31u); } /* 1.7.3: an erased packed block reads empty */
#endif
u32 v0=((base>>16)&127u)*8u; int ch=0;
#if GONE_W
{ u32 b=(base>>16)&127u, m=1u<<(b&31u);
if(tc_lz_tab && ((const u32*)tc_lz_tab)[b] && !(g_pt.gone[b>>5]&m)){ g_pt.gone[b>>5]|=m; g_pt.gone[4]^=m; ch=1; } }
#endif
for(u32 v=v0; v<v0+8u; v++){ u32 i=e->pg_map[v]; if(i!=0xFFu){ g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; ch=1; } }
if(ch){ pt_save(); pt_count(); }
return 1;
}
/* ---- Writing back the guest flash ---- */
ST_OVL int st_flush_guest(Emu *e, const StCfg *c)
{
int n=0;
if(e->flash_busy || e->flash_state) return 0;
for(int i=0;i<e->ovl.n;i++){
if(e->ovl.base[i]==0xFFFFFFFFu) continue;
n+=wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 0);
tc_ovl_free(e, i); /* slot free, reads go to flash again */
}
e->ovl.n=0;
e->fw_len=0; e->fw_lo=0xFFFFFFFFu;
return n;
}
/* v0.8.22: write back step by step. At most one changed 4 KB part per call; the slots
* stay in use (no copying again). Returns 1 when everything in flash is already up to date. */
u32 st_n_step;
int st_flush_step(Emu *e, const StCfg *c)
{
static int cur;
if(e->flash_busy || e->flash_state) return 0;
int total=e->ovl.n;
for(int t=0;t<total;t++){
int i=(cur+t)%total;
if(e->ovl.base[i]==0xFFFFFFFFu) continue;
if(wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 1)){ st_n_step++; cur=i; return 0; }
}
return 1;
}
/* All slots in use: write one (round robin) to the image and free it.
* Costs one flash write; the guest only sees a short pause. */
void st_init(const StCfg *c, u8 *buf4k){ g_evcfg=c; g_sec=buf4k; }
u32 st_n_evict; /* counter for the speed display */
int st_evict(Emu *e)
{
static int next;
if(!g_evcfg) return 0;
for(int t=0;t<OVL_SLOTS;t++){
int i=(next+t)%OVL_SLOTS;
if(!e->ovl.mem[i] || e->ovl.base[i]==0xFFFFFFFFu) continue;
wb_part(e, g_evcfg, e->ovl.base[i], e->ovl.mem[i], 0);
st_n_evict++;
tc_ovl_free(e, i);
e->fw_len=0; e->fw_lo=0xFFFFFFFFu;
next=i+1;
return 1;
}
return 0;
}
/* ---- packed data stream (PackBits) ---- */
typedef struct { u32 addr, n, sec, total; } Wr;
ST_OVL static void w_flush(Wr *w){ if(!w->n) return; for(u32 i=w->n;i<0x1000u;i++) g_sec[i]=0xFF; flash_update4k(w->addr+w->sec*0x1000u, g_sec); w->sec++; w->n=0; }
ST_OVL static void w_byte(Wr *w, u8 b){ g_sec[w->n++]=b; w->total++; if(w->n==0x1000u) w_flush(w); }
ST_OVL static void w_block(Wr *w, const u8 *p, u32 len)
{
u32 i=0;
while(i<len){
u32 r=1; while(i+r<len && r<130 && p[i+r]==p[i]) r++;
if(r>=3){ w_byte(w,(u8)(0x80+r-3)); w_byte(w,p[i]); i+=r; continue; }
u32 s=i, l=0;
while(i<len && l<128){
u32 q=1; while(i+q<len && q<3 && p[i+q]==p[i]) q++;
if(q>=3) break;
i++; l++;
}
w_byte(w,(u8)(l-1)); for(u32 k=0;k<l;k++) w_byte(w,p[s+k]);
}
}
typedef struct { const volatile u8 *p, *end; int bad; } Rd;
static u8 r_byte(Rd *r){ if(r->p>=r->end){ r->bad=1; return 0; } return *r->p++; }
static void r_block(Rd *r, u8 *d, u32 len)
{
u32 i=0;
while(i<len && !r->bad){
u8 c=r_byte(r);
if(c&0x80){ u32 n=(u32)(c-0x80)+3; u8 v=r_byte(r); for(u32 k=0;k<n && i<len;k++) d[i++]=v; }
else { u32 n=(u32)c+1; for(u32 k=0;k<n && i<len;k++) d[i++]=r_byte(r); }
}
}
typedef struct { u32 magic, ver, key, rtc, bytes, sectors, chk; } Hdr;
static u32 st_key(const StCfg *c){ return (u32)sizeof(Emu) ^ (c->device<<24) ^ (c->guest_size<<4) ^ 0x5A17u; }
static u32 rtc_now(void){ return REG(0x45000304u); }
void st_drop(const StCfg *c){ if(!flash_isff(c->save_off, 0x1000u)) flash_erase4k(c->save_off); }
ST_OVL void st_save(Emu *e, const StCfg *c, u16 (*gram)[128])
{
st_flush_guest(e, c);
#ifdef SESS_FLAG
if(c->nosess) return; /* 1.7.3 test7 NOSESS: only the guest's own save (its flash), no run state */
#endif
/* invalidate the old header first */
for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF;
flash_update4k(c->save_off, g_sec);
Wr w={ c->save_off+0x1000u, 0, 0, 0 };
w_block(&w, (const u8*)e, sizeof(Emu));
w_block(&w, (const u8*)gram, 128u*128u*2u);
w_flush(&w);
Hdr h={ MAGIC, SVER, st_key(c), rtc_now(), w.total, w.sec, 0 };
h.chk = h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors;
for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF;
u8 *hp=(u8*)&h; for(u32 i=0;i<sizeof h;i++) g_sec[i]=hp[i];
flash_prog4k(c->save_off, g_sec);
}
/* Returns 1 if a state was loaded. The caller sets the pointers in Emu. */
TC_INIT int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s)
{
#ifdef SESS_FLAG
if(c->nosess){ st_drop(c); return 0; } /* 1.7.3 test7 NOSESS: an old session is thrown away, the guest boots from its own save */
#endif
Hdr h; flash_read(c->save_off, &h, sizeof h);
if(h.magic!=MAGIC || h.ver!=SVER || h.key!=st_key(c)) return 0;
if(h.chk != (h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors)) return 0;
if(h.sectors > 0x4F) return 0;
Rd r={ XIP_PTR(c->save_off + 0x1000u), 0, 0 };
r.end = r.p + h.bytes;
r_block(&r, (u8*)e, sizeof(Emu));
r_block(&r, (u8*)gram, 128u*128u*2u);
if(r.bad) return 0;
u32 now=rtc_now();
*pause_s = (now>=h.rtc) ? now-h.rtc : 0;
return 1;
}
/* Save and restore state.
* 1. Written flash sectors of the guest go back into its image in the
* Paradise flash (that is where the Tamagotchi's save lives).
* 2. The run state (CPU, RAM, peripherals, screen) is packed into the
* backup area; the next start resumes from there. */
#include "hw.h"
#include "flash.h"
#include "../core/tc.h"
#include "state.h"
#ifdef EMU_OVL
#define ST_OVL __attribute__((section(".ovltext"))) /* 1.6.13 test10: the save when leaving, from the overlay */
#else
#define ST_OVL
#endif
#define MAGIC 0x53584D50u /* "PMXS" */
#define SVER 3u /* 2: Emu fields rearranged for the translator (v0.7), 3: 64 KB sectors and spare pages (v0.9.2) */
static u8 *g_sec; /* 4 KB buffer: first overlay slot (empty when saving) */
/* ---- Spare pages (v0.9.2) ----
* The guest also writes 64 KB sectors that are empty in its firmware (item stores and others).
* The Studio does not store empty blocks, so these written 8 KB parts go into spare pages
* behind the packed firmware. A table in the first 4 KB says which page holds which part.
* Order when writing: page first, then table. A table that does not check out counts as empty. */
#define PG_MAX 64
#define PG_MAGIC 0x50584D50u /* "PMXP" */
#ifndef PT_PAD
#define PT_PAD 4 /* host test: 4096, so the 4 KB read stays inside the variable */
#endif
#if defined(LZ_GONE) && defined(TC_LZ)
/* 1.7.3 test21 LZ_GONE: packed blocks the guest erased, kept behind the table (own check word: older tables have
* whatever followed in RAM there). Before, they counted only until the next start: then the parts not written again
* read the old packed data, mixed with the new ones (items gone wrong, the game slow, odd pictures and sounds). */
#define GONE_W 5u
#define GONE_MAGIC 0x454E4F47u
#else
#define GONE_W 0u
#endif
static struct { u32 magic, n, chk, pad; u16 vp[PG_MAX]; u32 gone[GONE_W]; u8 tail[PT_PAD]; } g_pt;
#define PT_LEN (16u+2u*PG_MAX+4u*GONE_W)
static u32 g_pg_tab, g_pg_data, g_pg_n;
u32 st_n_pages, st_n_free;
__attribute__((noinline)) static u32 pt_chk(void){ u32 x=g_pt.magic ^ (g_pt.n*0x9E3779B1u); for(u32 i=0;i<PG_MAX;i++) x=(x<<5|x>>27) ^ g_pt.vp[i]; return x; }
__attribute__((noinline)) static void pt_save(void){
g_pt.magic=PG_MAGIC; g_pt.n=g_pg_n; g_pt.chk=pt_chk();
/* The DMA reads 4 KB from the table: what follows it in RAM is ignored when reading back. */
if(g_pg_n && !flash_same(g_pg_tab, &g_pt, PT_LEN)) flash_prog4k(g_pg_tab, &g_pt);
}
__attribute__((noinline)) static void pt_count(void){ u32 n=0; for(u32 i=0;i<g_pg_n;i++) if(g_pt.vp[i]!=0xFFFFu) n++; st_n_pages=n; st_n_free=g_pg_n-n; }
static int blk_mapped(const StCfg *c, u32 blk){ return c->map[blk & 127u] != 0xFFu; }
TC_INIT void st_pages(Emu *e, const StCfg *c)
{
u32 lo=(c->guest_off + c->guest_size + 0x1FFFu) & ~0x1FFFu, hi=c->spare_end & ~0x1FFFu;
g_pg_n=0;
if(hi >= lo + 0x4000u){ g_pg_tab=lo; g_pg_data=lo+0x2000u; g_pg_n=(hi-g_pg_data)>>13; if(g_pg_n>PG_MAX) g_pg_n=PG_MAX; }
flash_read(g_pg_tab, &g_pt, PT_LEN);
int bad=!g_pg_n || g_pt.magic!=PG_MAGIC || g_pt.n!=g_pg_n || g_pt.chk!=pt_chk();
if(bad)
for(u32 i=0;i<PG_MAX;i++) g_pt.vp[i]=0xFFFFu;
#if GONE_W
{ u32 x=GONE_MAGIC; for(u32 i=0;i<4;i++) x^=g_pt.gone[i];
if(bad || x!=g_pt.gone[4]){ for(u32 i=0;i<4;i++) g_pt.gone[i]=0; g_pt.gone[4]=GONE_MAGIC; } /* no table, or an older one */
for(u32 i=0;i<4;i++) tc_lz_gone[i]=g_pt.gone[i]; }
#endif
e->pg_base=(const uint8_t*)XIP_PTR(g_pg_data);
for(u32 i=0;i<4;i++) e->pg_blk[i]=0;
for(u32 i=0;i<1024;i++) e->pg_map[i]=0xFFu;
u32 nb=e->dev.rom_size>>16; if(nb>128) nb=128;
for(u32 b=0;b<nb;b++) if(!blk_mapped(c,b) && (b<<16)-e->par_base>=0x10000u) e->pg_blk[b>>5] |= 1u<<(b&31u);
for(u32 i=0;i<g_pg_n;i++){ u32 v=g_pt.vp[i];
if(v<1024u && ((e->pg_blk[v>>8]>>((v>>3)&31u))&1u) && e->pg_map[v]==0xFFu) e->pg_map[v]=(u8)i; else g_pt.vp[i]=0xFFFFu; }
pt_count();
}
/* Address in the Paradise flash of a stored block (0 = none). */
__attribute__((noinline)) static u32 blk_addr(const StCfg *c, u32 off)
{
u32 k=c->map[(off>>16)&127];
if(k==0xFE) k=off>>16;
if(k==0xFF) return 0;
return c->guest_off + (k<<16) + (off & 0xFFFFu);
}
__attribute__((noinline)) static int all_ff(const u8 *p){ const u32 *w=(const u32*)p; for(u32 i=0;i<OVL_SIZE/4u;i++) if(w[i]!=0xFFFFFFFFu) return 0; return 1; }
/* Write an 8 KB part back. step: at most one 4 KB write. Returns the number of flash writes. */
static int wb_part(Emu *e, const StCfg *c, u32 base, const u8 *mem, int step)
{
u32 a=blk_addr(c, base);
if(!a){
u32 v=(base>>13)&1023u, i=e->pg_map[v];
if(!((e->pg_blk[v>>8]>>((v>>3)&31u))&1u)) return 0;
#if defined(LZ_GONE) && defined(TC_LZ)
u32 lb=(base>>16)&127u; /* LZ_GONE: a part of a packed block keeps its page even when empty, else the old data comes back */
if(all_ff(mem) && !(tc_lz_tab && ((const u32*)tc_lz_tab)[lb] && !((tc_lz_gone[lb>>5]>>(lb&31u))&1u))){
#else
if(all_ff(mem)){ /* erased: release the page */
#endif
if(i==0xFFu) return 0;
g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; pt_save(); pt_count(); return 1;
}
if(i==0xFFu){ /* new page */
for(i=0;i<g_pg_n && g_pt.vp[i]!=0xFFFFu;i++){}
if(i>=g_pg_n){ e->flash_lost_writes++; return 0; }
a=g_pg_data + (i<<13);
flash_update4k(a, mem); flash_update4k(a+0x1000u, mem+0x1000u);
g_pt.vp[i]=(u16)v; e->pg_map[v]=(u8)i; pt_save(); pt_count();
return 3;
}
a=g_pg_data + (i<<13);
}
if(step){
for(u32 h=0;h<2;h++) if(!flash_same(a+h*0x1000u, mem+h*0x1000u, 0x1000u)){ flash_prog4k(a+h*0x1000u, mem+h*0x1000u); return 1; }
return 0;
}
return flash_update4k(a, mem) + flash_update4k(a+0x1000u, mem+0x1000u);
}
/* Erase a 64 KB sector of the guest (hook tc_big_erase). */
static const StCfg *g_evcfg;
int st_big_erase(Emu *e, uint32_t base)
{
const StCfg *c=g_evcfg; if(!c) return 0;
u32 a=blk_addr(c, base & ~0xFFFFu);
if(a){
for(u32 s=0;s<16u;s++) if(!flash_isff(a+s*0x1000u, 0x1000u)) flash_erase4k(a+s*0x1000u);
return 1;
}
#ifdef TC_LZ
{ u32 b=(base>>16)&127u; tc_lz_gone[b>>5] |= 1u<<(b&31u); } /* 1.7.3: an erased packed block reads empty */
#endif
u32 v0=((base>>16)&127u)*8u; int ch=0;
#if GONE_W
{ u32 b=(base>>16)&127u, m=1u<<(b&31u);
if(tc_lz_tab && ((const u32*)tc_lz_tab)[b] && !(g_pt.gone[b>>5]&m)){ g_pt.gone[b>>5]|=m; g_pt.gone[4]^=m; ch=1; } }
#endif
for(u32 v=v0; v<v0+8u; v++){ u32 i=e->pg_map[v]; if(i!=0xFFu){ g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; ch=1; } }
if(ch){ pt_save(); pt_count(); }
return 1;
}
/* ---- Writing back the guest flash ---- */
ST_OVL int st_flush_guest(Emu *e, const StCfg *c)
{
int n=0;
if(e->flash_busy || e->flash_state) return 0;
for(int i=0;i<e->ovl.n;i++){
if(e->ovl.base[i]==0xFFFFFFFFu) continue;
n+=wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 0);
tc_ovl_free(e, i); /* slot free, reads go to flash again */
}
e->ovl.n=0;
e->fw_len=0; e->fw_lo=0xFFFFFFFFu;
return n;
}
/* v0.8.22: write back step by step. At most one changed 4 KB part per call; the slots
* stay in use (no copying again). Returns 1 when everything in flash is already up to date. */
u32 st_n_step;
int st_flush_step(Emu *e, const StCfg *c)
{
static int cur;
if(e->flash_busy || e->flash_state) return 0;
int total=e->ovl.n;
for(int t=0;t<total;t++){
int i=(cur+t)%total;
if(e->ovl.base[i]==0xFFFFFFFFu) continue;
if(wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 1)){ st_n_step++; cur=i; return 0; }
}
return 1;
}
/* All slots in use: write one (round robin) to the image and free it.
* Costs one flash write; the guest only sees a short pause. */
void st_init(const StCfg *c, u8 *buf4k){ g_evcfg=c; g_sec=buf4k; }
u32 st_n_evict; /* counter for the speed display */
int st_evict(Emu *e)
{
static int next;
if(!g_evcfg) return 0;
for(int t=0;t<OVL_SLOTS;t++){
int i=(next+t)%OVL_SLOTS;
if(!e->ovl.mem[i] || e->ovl.base[i]==0xFFFFFFFFu) continue;
wb_part(e, g_evcfg, e->ovl.base[i], e->ovl.mem[i], 0);
st_n_evict++;
tc_ovl_free(e, i);
e->fw_len=0; e->fw_lo=0xFFFFFFFFu;
next=i+1;
return 1;
}
return 0;
}
/* ---- packed data stream (PackBits) ---- */
typedef struct { u32 addr, n, sec, total; } Wr;
ST_OVL static void w_flush(Wr *w){ if(!w->n) return; for(u32 i=w->n;i<0x1000u;i++) g_sec[i]=0xFF; flash_update4k(w->addr+w->sec*0x1000u, g_sec); w->sec++; w->n=0; }
ST_OVL static void w_byte(Wr *w, u8 b){ g_sec[w->n++]=b; w->total++; if(w->n==0x1000u) w_flush(w); }
ST_OVL static void w_block(Wr *w, const u8 *p, u32 len)
{
u32 i=0;
while(i<len){
u32 r=1; while(i+r<len && r<130 && p[i+r]==p[i]) r++;
if(r>=3){ w_byte(w,(u8)(0x80+r-3)); w_byte(w,p[i]); i+=r; continue; }
u32 s=i, l=0;
while(i<len && l<128){
u32 q=1; while(i+q<len && q<3 && p[i+q]==p[i]) q++;
if(q>=3) break;
i++; l++;
}
w_byte(w,(u8)(l-1)); for(u32 k=0;k<l;k++) w_byte(w,p[s+k]);
}
}
typedef struct { const volatile u8 *p, *end; int bad; } Rd;
static u8 r_byte(Rd *r){ if(r->p>=r->end){ r->bad=1; return 0; } return *r->p++; }
static void r_block(Rd *r, u8 *d, u32 len)
{
u32 i=0;
while(i<len && !r->bad){
u8 c=r_byte(r);
if(c&0x80){ u32 n=(u32)(c-0x80)+3; u8 v=r_byte(r); for(u32 k=0;k<n && i<len;k++) d[i++]=v; }
else { u32 n=(u32)c+1; for(u32 k=0;k<n && i<len;k++) d[i++]=r_byte(r); }
}
}
typedef struct { u32 magic, ver, key, rtc, bytes, sectors, chk; } Hdr;
static u32 st_key(const StCfg *c){ return (u32)sizeof(Emu) ^ (c->device<<24) ^ (c->guest_size<<4) ^ 0x5A17u; }
static u32 rtc_now(void){ return REG(0x45000304u); }
void st_drop(const StCfg *c){ if(!flash_isff(c->save_off, 0x1000u)) flash_erase4k(c->save_off); }
ST_OVL void st_save(Emu *e, const StCfg *c, u16 (*gram)[128])
{
st_flush_guest(e, c);
#ifdef SESS_FLAG
if(c->nosess) return; /* 1.7.3 test7 NOSESS: only the guest's own save (its flash), no run state */
#endif
/* invalidate the old header first */
for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF;
flash_update4k(c->save_off, g_sec);
Wr w={ c->save_off+0x1000u, 0, 0, 0 };
w_block(&w, (const u8*)e, sizeof(Emu));
w_block(&w, (const u8*)gram, 128u*128u*2u);
w_flush(&w);
Hdr h={ MAGIC, SVER, st_key(c), rtc_now(), w.total, w.sec, 0 };
h.chk = h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors;
for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF;
u8 *hp=(u8*)&h; for(u32 i=0;i<sizeof h;i++) g_sec[i]=hp[i];
flash_prog4k(c->save_off, g_sec);
}
/* Returns 1 if a state was loaded. The caller sets the pointers in Emu. */
TC_INIT int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s)
{
#ifdef SESS_FLAG
if(c->nosess){ st_drop(c); return 0; } /* 1.7.3 test7 NOSESS: an old session is thrown away, the guest boots from its own save */
#endif
Hdr h; flash_read(c->save_off, &h, sizeof h);
if(h.magic!=MAGIC || h.ver!=SVER || h.key!=st_key(c)) return 0;
if(h.chk != (h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors)) return 0;
if(h.sectors > 0x4F) return 0;
Rd r={ XIP_PTR(c->save_off + 0x1000u), 0, 0 };
r.end = r.p + h.bytes;
r_block(&r, (u8*)e, sizeof(Emu));
r_block(&r, (u8*)gram, 128u*128u*2u);
if(r.bad) return 0;
u32 now=rtc_now();
*pause_s = (now>=h.rtc) ? now-h.rtc : 0;
return 1;
}
+21 -21
View File
@@ -1,21 +1,21 @@
#ifndef STATE_H
#define STATE_H
#include "io.h"
#include "../core/tc.h"
#ifdef SESS_FLAG
typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end, nosess; } StCfg; /* 1.7.3 test7: nosess = flags bit 12 */
#else
typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end; } StCfg;
#endif
int st_flush_guest(Emu *e, const StCfg *c);
int st_evict(Emu *e);
int st_flush_step(Emu *e, const StCfg *c); /* one part per call, 1 = done */
extern u32 st_n_step;
void st_init(const StCfg *c, u8 *buf4k); /* buf4k: buffer for save/load */
void st_pages(Emu *e, const StCfg *c); /* spare pages: load the table, set the pointers */
int st_big_erase(Emu *e, uint32_t base); /* hook tc_big_erase */
void st_drop(const StCfg *c); /* throw the run state away */
extern u32 st_n_pages, st_n_free;
void st_save(Emu *e, const StCfg *c, u16 (*gram)[128]);
int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s);
#endif
#ifndef STATE_H
#define STATE_H
#include "io.h"
#include "../core/tc.h"
#ifdef SESS_FLAG
typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end, nosess; } StCfg; /* 1.7.3 test7: nosess = flags bit 12 */
#else
typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end; } StCfg;
#endif
int st_flush_guest(Emu *e, const StCfg *c);
int st_evict(Emu *e);
int st_flush_step(Emu *e, const StCfg *c); /* one part per call, 1 = done */
extern u32 st_n_step;
void st_init(const StCfg *c, u8 *buf4k); /* buf4k: buffer for save/load */
void st_pages(Emu *e, const StCfg *c); /* spare pages: load the table, set the pointers */
int st_big_erase(Emu *e, uint32_t base); /* hook tc_big_erase */
void st_drop(const StCfg *c); /* throw the run state away */
extern u32 st_n_pages, st_n_free;
void st_save(Emu *e, const StCfg *c, u16 (*gram)[128]);
int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s);
#endif
+346 -346
View File
@@ -1,346 +1,346 @@
@ Stub in XIP flash: copies the app image to PRAM 0 and restarts.
@ APP_SRC (XIP address of the image) is set at build time.
@ With HOOKS: four entry points for the home screen handlers. They count how
@ long A and C are held together, start the emulator after LIMIT calls and
@ otherwise call the original handler.
.syntax unified
.thumb
@ Autostart (v1.2.8): with AUTO set, the stub decides once per boot (first home screen call)
@ whether to start the emulator right away. Mailbox word 0x20000FFC (kept over a restart and
@ the reset button, lost in the Paradise's deep sleep):
@ "PMXL" written by the emulator when going back: stay in the Paradise
@ "PMXR" written here: any later restart with it (reset button) starts the emulator
@ other power-on or waking from deep sleep: the Paradise's seconds counter tells them
@ apart (it starts at 0 after power-on and when the clock is set)
@ Holding B skips the emulator. "Decided this boot" is kept in the UsageFault priority
@ (SHPR1 byte 2): it is cleared by every reset and the firmware does not use it.
@ AUTO is a placeholder the Studio sets to 0 or 1.
#ifndef AUTO
#define AUTO 0
#endif
.macro AUTOSTART
#if defined(HOOKS)
ldr r2, =AUTO
cbz r2, 7f
ldr r2, =0xE000ED18
ldrb r3, [r2, #2]
cbnz r3, 7f @ already decided in this boot
movs r3, #0xFF
strb r3, [r2, #2]
ldrb r3, [r2, #2]
cbz r3, 7f @ cannot keep the flag: never autostart
ldr r2, =0x20000FFC
ldr r3, [r2]
ldr r0, =0x4C584D50 @ "PMXL": back from the emulator
cmp r3, r0
beq 8f
ldr r0, =0x52584D50 @ "PMXR": restart while running
cmp r3, r0
beq 9f
ldr r0, =0x45000304 @ mailbox lost: deep sleep (clock ran) or power-on (clock new)
ldr r0, [r0]
cmp r0, #30
bhs 8f
9:
ldr r0, =0x52584D50
str r0, [r2]
tst r1, #0x800 @ B (P0.11) held: stay in the Paradise
beq 7f
b start
8:
ldr r0, =0x52584D50
str r0, [r2]
7:
ldr r0, =0x40018000
#endif
.endm
@ 1.7.2 test19 (BFALL): C held when the Paradise comes up after switching on (or after the reset button) starts
@ the flash app of the write protection (0xFF0000, its load table at 0xFFE000), a way back when a program or a
@ save leaves the screen black. Once per boot (BusFault priority byte as the flag, the firmware does not use it);
@ not when back from a program on purpose ("PMXL") and not after waking from deep sleep (mailbox lost, clock ran).
#ifndef NO_BFALL
.macro BFALL
ldr r2, =0xE000ED19
ldrb r3, [r2]
cbnz r3, 7f
movs r3, #0xFF
strb r3, [r2]
ldrb r3, [r2]
cbz r3, 7f
tst r1, #0x400 @ C (P0.10); B at switching on already skips the autostart
bne 7f
#ifndef BFALL_WITH_A
@ 1.7.3 test29 (BFALL_NOA): not with A held too. A and C is the program key on the home screen; the first home
@ handler call of a boot with A+C held (within 30 s of switching on, or after a reset) started the flash app instead.
tst r1, #0x200 @ A (P0.9) held: the menu key, no way back
beq 7f
#endif
ldr r2, =0x20000FFC
ldr r2, [r2]
ldr r0, =0x4C584D50
cmp r2, r0
beq 7f
ldr r0, =0x45000304
ldr r0, [r0]
cmp r0, #30
blo 6f
ldr r0, =0x52584D50 @ "PMXR" / "PMXM": a reset, the mailbox was kept
cmp r2, r0
beq 6f
ldr r0, =0x4D584D50
cmp r2, r0
bne 7f
6:ldr r0, =0x60FFE000 @ load table of the flash app, uncached flash
ldr r2, [r0]
ldr r3, =0x494E4F53 @ "SONI"
cmp r2, r3
bne 7f
ldr r2, [r0, #0x10]
ldr r3, =0x60FF0000
cmp r2, r3
bne 7f
cpsid i
mov r4, r3
b realstart
7:
ldr r0, =0x40018000
ldr r1, [r0]
.endm
#else
.macro BFALL
.endm
#endif
.global start
.thumb_func
start:
cpsid i
#ifdef FELD
ldr r4, app_src
b.w realstart
.align 2
app_src: .word APP_SRC
@ 1.6.0: start the program image at r0 (XIP address), fixed at +0x0C. The menu starts its
@ other programs (more emulators) through here.
.global start_src
.thumb_func
start_src:
cpsid i
mov r4, r0
@ 1.6.6: the cached window (0x10000000) shows only 1 MB from 0x11000; programs further up (more emulators
@ from 0xD40000 down) came out as garbage. Copy from the uncached flash (0x60000000 + offset) instead.
add r4, r4, #0x50000000
add r4, r4, #0x11000
b.w realstart
@ 1.6.8: launcher ROM ("only a start device for programs"): the Studio points the handlers of every
@ scene after the setup (home, events, care ...) here, so the menu starts instead of the Paradise game.
.org 0x20
.global launch
.thumb_func
launch:
cpsid i
ldr r4, feld_src
b.w realstart
.align 2
feld_src: .word FELD_SRC
@ 1.6.8: entry for the start device's trampolines (r12 = the scene's original handler): the menu starts
@ only once the Paradise has a save (settings block 0xEFE000 stamped, date set), otherwise the original
@ handler runs, so a setup after "reset" can finish in the Paradise itself.
.org 0x2C
.global lcheck_e
.thumb_func
lcheck_e:
b.w lcheck
#else
ldr r4, =APP_SRC
b.w realstart
.ltorg
#endif
#if defined(HOOKS) && !defined(FELD)
.org 0x40 @ hooks fixed at 0x40 (Studio: HOOK_OFF), original handlers at 0x94
.global hook0, hook1, hook2, hook3
.thumb_func
hook0: ldr.w r12, orig0
b check
.thumb_func
hook1: ldr.w r12, orig1
b check
.thumb_func
hook2: ldr.w r12, orig2
b check
.thumb_func
hook3: ldr.w r12, orig3
b check
.org 0x94
orig0: .word ORIG0
orig1: .word ORIG1
orig2: .word ORIG2
orig3: .word ORIG3
.thumb_func
check:
push {r0-r3, r12, lr}
ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0
ldr r1, [r0]
BFALL
AUTOSTART
ldr r2, =0x20000FF8 @ counter at the end of the mailbox
ldr r3, [r2]
tst r1, #0x600
bne 5f
lsrs r0, r3, #16
movw r1, #0xE7A1
cmp r0, r1
beq 4f
movw r3, #0
movt r3, #0xE7A1
4:
adds r3, #1
str r3, [r2]
uxth r0, r3
cmp r0, #LIMIT
bhs start
b 6f
5:
movs r3, #0
str r3, [r2]
6:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
#if defined(HOOKS) && defined(FELD)
@ With field switch: A+C starts the field switch (FELD_SRC), which in turn also
@ offers the program (APP_SRC). Return targets fixed at 0x94 as before.
.org 0x40
.global hook0, hook1, hook2, hook3
.thumb_func
hook0: ldr.w r12, orig0
b check
.thumb_func
hook1: ldr.w r12, orig1
b check
.thumb_func
hook2: ldr.w r12, orig2
b check
.thumb_func
hook3: ldr.w r12, orig3
b check
.org 0x94
orig0: .word ORIG0
orig1: .word ORIG1
orig2: .word ORIG2
orig3: .word ORIG3
.thumb_func
check:
push {r0-r3, r12, lr}
ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0
ldr r1, [r0]
BFALL
AUTOSTART
ldr r2, =0x20000FF8 @ counter at the end of the mailbox
ldr r3, [r2]
#ifndef HOOK_TEST
tst r1, #0x600
bne 5f
#endif
lsrs r0, r3, #16
movw r1, #0xE7A1
cmp r0, r1
beq 4f
movw r3, #0
movt r3, #0xE7A1
4:
adds r3, #1
str r3, [r2]
uxth r0, r3
cmp r0, #LIMIT
blo 6f
ldr.w r4, feld_src
cmp r4, #0
beq start
cpsid i
b realstart
5:
movs r3, #0
str r3, [r2]
6:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
#if defined(HOOKS) && defined(FELD)
.thumb_func
lcheck:
push {r0-r3, r12, lr}
ldr r0, =0x60EFE000 @ settings block, uncached flash
ldrh r1, [r0, #0]
ldrh r2, [r0, #2]
mvns r2, r2
uxth r2, r2
cmp r1, r2 @ stamp: CRC and its inverse
bne 1f
ldrh r1, [r0, #0x1C] @ year 2020..2099
movw r2, #2020
cmp r1, r2
blo 1f
movw r2, #2099
cmp r1, r2
bhi 1f
ldrh r1, [r0, #0x1E] @ month 1..12
subs r1, #1
cmp r1, #12
bhs 1f
cpsid i
ldr.w r4, feld_src
b realstart
1:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
@ Restart like the firmware itself (routine at flash 0x110568): first switch the
@ clock to source 4 (0x45000000 = 0x8041, 0x4500000C = 4, wait for 0x44), then
@ copy the image to PRAM 0, then SYSRESETREQ. v0.8 without this sequence froze
@ the real device after A+C (suspected: clock), the emulator did not show it.
.thumb_func
realstart:
cpsid i
ldr r3, =0x45000000
movw r2, #0x8041
str r2, [r3]
movs r2, #4
str r2, [r3, #0xC]
ldr r1, =0x400000
3:
ldr r2, [r3, #0xC]
cmp r2, #0x44
beq 4f
subs r1, #1
bne 3b
4:
mov r0, r4
movs r1, #0
ldr r2, =0x10000
1:
ldr r3, [r0], #4
str r3, [r1], #4
subs r2, #4
bne 1b
dsb
isb
ldr r0, =0xE000ED08 @ VTOR = 0, as after a real reset
movs r1, #0
str r1, [r0]
ldr r0, =0xE000ED0C @ AIRCR: keep priority grouping, SYSRESETREQ
ldr r1, [r0]
and r1, r1, #0x700
ldr r2, =0x05FA0004
orrs r1, r2
str r1, [r0]
dsb
2:
b 2b
.ltorg
@ Stub in XIP flash: copies the app image to PRAM 0 and restarts.
@ APP_SRC (XIP address of the image) is set at build time.
@ With HOOKS: four entry points for the home screen handlers. They count how
@ long A and C are held together, start the emulator after LIMIT calls and
@ otherwise call the original handler.
.syntax unified
.thumb
@ Autostart (v1.2.8): with AUTO set, the stub decides once per boot (first home screen call)
@ whether to start the emulator right away. Mailbox word 0x20000FFC (kept over a restart and
@ the reset button, lost in the Paradise's deep sleep):
@ "PMXL" written by the emulator when going back: stay in the Paradise
@ "PMXR" written here: any later restart with it (reset button) starts the emulator
@ other power-on or waking from deep sleep: the Paradise's seconds counter tells them
@ apart (it starts at 0 after power-on and when the clock is set)
@ Holding B skips the emulator. "Decided this boot" is kept in the UsageFault priority
@ (SHPR1 byte 2): it is cleared by every reset and the firmware does not use it.
@ AUTO is a placeholder the Studio sets to 0 or 1.
#ifndef AUTO
#define AUTO 0
#endif
.macro AUTOSTART
#if defined(HOOKS)
ldr r2, =AUTO
cbz r2, 7f
ldr r2, =0xE000ED18
ldrb r3, [r2, #2]
cbnz r3, 7f @ already decided in this boot
movs r3, #0xFF
strb r3, [r2, #2]
ldrb r3, [r2, #2]
cbz r3, 7f @ cannot keep the flag: never autostart
ldr r2, =0x20000FFC
ldr r3, [r2]
ldr r0, =0x4C584D50 @ "PMXL": back from the emulator
cmp r3, r0
beq 8f
ldr r0, =0x52584D50 @ "PMXR": restart while running
cmp r3, r0
beq 9f
ldr r0, =0x45000304 @ mailbox lost: deep sleep (clock ran) or power-on (clock new)
ldr r0, [r0]
cmp r0, #30
bhs 8f
9:
ldr r0, =0x52584D50
str r0, [r2]
tst r1, #0x800 @ B (P0.11) held: stay in the Paradise
beq 7f
b start
8:
ldr r0, =0x52584D50
str r0, [r2]
7:
ldr r0, =0x40018000
#endif
.endm
@ 1.7.2 test19 (BFALL): C held when the Paradise comes up after switching on (or after the reset button) starts
@ the flash app of the write protection (0xFF0000, its load table at 0xFFE000), a way back when a program or a
@ save leaves the screen black. Once per boot (BusFault priority byte as the flag, the firmware does not use it);
@ not when back from a program on purpose ("PMXL") and not after waking from deep sleep (mailbox lost, clock ran).
#ifndef NO_BFALL
.macro BFALL
ldr r2, =0xE000ED19
ldrb r3, [r2]
cbnz r3, 7f
movs r3, #0xFF
strb r3, [r2]
ldrb r3, [r2]
cbz r3, 7f
tst r1, #0x400 @ C (P0.10); B at switching on already skips the autostart
bne 7f
#ifndef BFALL_WITH_A
@ 1.7.3 test29 (BFALL_NOA): not with A held too. A and C is the program key on the home screen; the first home
@ handler call of a boot with A+C held (within 30 s of switching on, or after a reset) started the flash app instead.
tst r1, #0x200 @ A (P0.9) held: the menu key, no way back
beq 7f
#endif
ldr r2, =0x20000FFC
ldr r2, [r2]
ldr r0, =0x4C584D50
cmp r2, r0
beq 7f
ldr r0, =0x45000304
ldr r0, [r0]
cmp r0, #30
blo 6f
ldr r0, =0x52584D50 @ "PMXR" / "PMXM": a reset, the mailbox was kept
cmp r2, r0
beq 6f
ldr r0, =0x4D584D50
cmp r2, r0
bne 7f
6:ldr r0, =0x60FFE000 @ load table of the flash app, uncached flash
ldr r2, [r0]
ldr r3, =0x494E4F53 @ "SONI"
cmp r2, r3
bne 7f
ldr r2, [r0, #0x10]
ldr r3, =0x60FF0000
cmp r2, r3
bne 7f
cpsid i
mov r4, r3
b realstart
7:
ldr r0, =0x40018000
ldr r1, [r0]
.endm
#else
.macro BFALL
.endm
#endif
.global start
.thumb_func
start:
cpsid i
#ifdef FELD
ldr r4, app_src
b.w realstart
.align 2
app_src: .word APP_SRC
@ 1.6.0: start the program image at r0 (XIP address), fixed at +0x0C. The menu starts its
@ other programs (more emulators) through here.
.global start_src
.thumb_func
start_src:
cpsid i
mov r4, r0
@ 1.6.6: the cached window (0x10000000) shows only 1 MB from 0x11000; programs further up (more emulators
@ from 0xD40000 down) came out as garbage. Copy from the uncached flash (0x60000000 + offset) instead.
add r4, r4, #0x50000000
add r4, r4, #0x11000
b.w realstart
@ 1.6.8: launcher ROM ("only a start device for programs"): the Studio points the handlers of every
@ scene after the setup (home, events, care ...) here, so the menu starts instead of the Paradise game.
.org 0x20
.global launch
.thumb_func
launch:
cpsid i
ldr r4, feld_src
b.w realstart
.align 2
feld_src: .word FELD_SRC
@ 1.6.8: entry for the start device's trampolines (r12 = the scene's original handler): the menu starts
@ only once the Paradise has a save (settings block 0xEFE000 stamped, date set), otherwise the original
@ handler runs, so a setup after "reset" can finish in the Paradise itself.
.org 0x2C
.global lcheck_e
.thumb_func
lcheck_e:
b.w lcheck
#else
ldr r4, =APP_SRC
b.w realstart
.ltorg
#endif
#if defined(HOOKS) && !defined(FELD)
.org 0x40 @ hooks fixed at 0x40 (Studio: HOOK_OFF), original handlers at 0x94
.global hook0, hook1, hook2, hook3
.thumb_func
hook0: ldr.w r12, orig0
b check
.thumb_func
hook1: ldr.w r12, orig1
b check
.thumb_func
hook2: ldr.w r12, orig2
b check
.thumb_func
hook3: ldr.w r12, orig3
b check
.org 0x94
orig0: .word ORIG0
orig1: .word ORIG1
orig2: .word ORIG2
orig3: .word ORIG3
.thumb_func
check:
push {r0-r3, r12, lr}
ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0
ldr r1, [r0]
BFALL
AUTOSTART
ldr r2, =0x20000FF8 @ counter at the end of the mailbox
ldr r3, [r2]
tst r1, #0x600
bne 5f
lsrs r0, r3, #16
movw r1, #0xE7A1
cmp r0, r1
beq 4f
movw r3, #0
movt r3, #0xE7A1
4:
adds r3, #1
str r3, [r2]
uxth r0, r3
cmp r0, #LIMIT
bhs start
b 6f
5:
movs r3, #0
str r3, [r2]
6:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
#if defined(HOOKS) && defined(FELD)
@ With field switch: A+C starts the field switch (FELD_SRC), which in turn also
@ offers the program (APP_SRC). Return targets fixed at 0x94 as before.
.org 0x40
.global hook0, hook1, hook2, hook3
.thumb_func
hook0: ldr.w r12, orig0
b check
.thumb_func
hook1: ldr.w r12, orig1
b check
.thumb_func
hook2: ldr.w r12, orig2
b check
.thumb_func
hook3: ldr.w r12, orig3
b check
.org 0x94
orig0: .word ORIG0
orig1: .word ORIG1
orig2: .word ORIG2
orig3: .word ORIG3
.thumb_func
check:
push {r0-r3, r12, lr}
ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0
ldr r1, [r0]
BFALL
AUTOSTART
ldr r2, =0x20000FF8 @ counter at the end of the mailbox
ldr r3, [r2]
#ifndef HOOK_TEST
tst r1, #0x600
bne 5f
#endif
lsrs r0, r3, #16
movw r1, #0xE7A1
cmp r0, r1
beq 4f
movw r3, #0
movt r3, #0xE7A1
4:
adds r3, #1
str r3, [r2]
uxth r0, r3
cmp r0, #LIMIT
blo 6f
ldr.w r4, feld_src
cmp r4, #0
beq start
cpsid i
b realstart
5:
movs r3, #0
str r3, [r2]
6:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
#if defined(HOOKS) && defined(FELD)
.thumb_func
lcheck:
push {r0-r3, r12, lr}
ldr r0, =0x60EFE000 @ settings block, uncached flash
ldrh r1, [r0, #0]
ldrh r2, [r0, #2]
mvns r2, r2
uxth r2, r2
cmp r1, r2 @ stamp: CRC and its inverse
bne 1f
ldrh r1, [r0, #0x1C] @ year 2020..2099
movw r2, #2020
cmp r1, r2
blo 1f
movw r2, #2099
cmp r1, r2
bhi 1f
ldrh r1, [r0, #0x1E] @ month 1..12
subs r1, #1
cmp r1, #12
bhs 1f
cpsid i
ldr.w r4, feld_src
b realstart
1:
pop {r0-r3, r12, lr}
bx r12
.ltorg
#endif
@ Restart like the firmware itself (routine at flash 0x110568): first switch the
@ clock to source 4 (0x45000000 = 0x8041, 0x4500000C = 4, wait for 0x44), then
@ copy the image to PRAM 0, then SYSRESETREQ. v0.8 without this sequence froze
@ the real device after A+C (suspected: clock), the emulator did not show it.
.thumb_func
realstart:
cpsid i
ldr r3, =0x45000000
movw r2, #0x8041
str r2, [r3]
movs r2, #4
str r2, [r3, #0xC]
ldr r1, =0x400000
3:
ldr r2, [r3, #0xC]
cmp r2, #0x44
beq 4f
subs r1, #1
bne 3b
4:
mov r0, r4
movs r1, #0
ldr r2, =0x10000
1:
ldr r3, [r0], #4
str r3, [r1], #4
subs r2, #4
bne 1b
dsb
isb
ldr r0, =0xE000ED08 @ VTOR = 0, as after a real reset
movs r1, #0
str r1, [r0]
ldr r0, =0xE000ED0C @ AIRCR: keep priority grouping, SYSRESETREQ
ldr r1, [r0]
and r1, r1, #0x700
ldr r2, =0x05FA0004
orrs r1, r2
str r1, [r0]
dsb
2:
b 2b
.ltorg
+47 -47
View File
@@ -1,47 +1,47 @@
#!/usr/bin/env python3
"""Install download content (TAMAGO records from .jpg) into an 8 MB image.
dlc.py <image_in> <file.jpg> <image_out> [--fach N] (games: slot 0 or 1)
dlc.py <image> --liste"""
import sys
GAMES = (0x7A0000, 0x8000, 2)
KINDS = [('Essen', 0x590000, 0x800, 20), ('Snacks', 0x5A0000, 0x800, 20), ('Kleidung', 0x600000, 0x4000, 5),
('Zubehoer', 0x650000, 0x2000, 10), ('Sachen', 0x6A0000, 0x2000, 10), ('Alltag', 0x740000, 0x8000, 5),
('Tapeten', 0x780000, 0x2000, 10), ('Spiele', 0x7A0000, 0x8000, 2), ('Reiseziele', 0x7B0000, 0x8000, 2)]
def payload(data):
if data[:6] == b'TAMAGO': blob = data
else:
e = data.find(b'\xff\xd9'); m = data.find(b'TAMAGO', e + 2 if e >= 0 else 0)
if m < 0: raise SystemExit('no TAMAGO record in the file')
blob = data[m:]
def ok(n): return n >= 3 and (sum(blob[:n - 2]) & 0xFFFF) == int.from_bytes(blob[n - 2:n], 'big')
ln = int.from_bytes(blob[0x48:0x4C], 'big') if len(blob) >= 0x4C else 0
if 0x60 <= ln <= len(blob) and ok(ln): return blob[:ln]
for s in range(17):
n = len(blob) - s
if n >= max(0x60, ln) and ok(n): return blob[:n]
raise SystemExit('record checksum does not match')
def info(rec):
name = rec[6:0x34].decode('utf-16-be', 'replace').rstrip('\0').strip()
return rec[0x34:0x48].split(b'\0')[0].decode('latin1'), name
def liste(img):
for l, b, sz, n in KINDS:
for s in range(n):
o = b + s * sz
if img[o:o + 6] == b'TAMAGO': print('%-10s Fach %d %s %s' % (l, s, *info(img[o:o + sz])))
def main():
img = bytearray(open(sys.argv[1], 'rb').read()); img += b'\xff' * (0x800000 - len(img))
if '--liste' in sys.argv: liste(img); return
rec = payload(open(sys.argv[2], 'rb').read())
if rec[0x4E] != 0x94 or rec[0x50] != 0x5B: raise SystemExit('not a game (type %02x cat %02x)' % (rec[0x4E], rec[0x50]))
base, sz, n = GAMES
fach = int(sys.argv[sys.argv.index('--fach') + 1]) if '--fach' in sys.argv else n - 1
o = base + fach * sz
print('ersetze', info(img[o:o + sz]) if img[o:o + 6] == b'TAMAGO' else 'leer', '->', info(rec))
img[o:o + sz] = rec + b'\xff' * (sz - len(rec))
open(sys.argv[3], 'wb').write(img)
if __name__ == '__main__': main()
#!/usr/bin/env python3
"""Install download content (TAMAGO records from .jpg) into an 8 MB image.
dlc.py <image_in> <file.jpg> <image_out> [--fach N] (games: slot 0 or 1)
dlc.py <image> --liste"""
import sys
GAMES = (0x7A0000, 0x8000, 2)
KINDS = [('Essen', 0x590000, 0x800, 20), ('Snacks', 0x5A0000, 0x800, 20), ('Kleidung', 0x600000, 0x4000, 5),
('Zubehoer', 0x650000, 0x2000, 10), ('Sachen', 0x6A0000, 0x2000, 10), ('Alltag', 0x740000, 0x8000, 5),
('Tapeten', 0x780000, 0x2000, 10), ('Spiele', 0x7A0000, 0x8000, 2), ('Reiseziele', 0x7B0000, 0x8000, 2)]
def payload(data):
if data[:6] == b'TAMAGO': blob = data
else:
e = data.find(b'\xff\xd9'); m = data.find(b'TAMAGO', e + 2 if e >= 0 else 0)
if m < 0: raise SystemExit('no TAMAGO record in the file')
blob = data[m:]
def ok(n): return n >= 3 and (sum(blob[:n - 2]) & 0xFFFF) == int.from_bytes(blob[n - 2:n], 'big')
ln = int.from_bytes(blob[0x48:0x4C], 'big') if len(blob) >= 0x4C else 0
if 0x60 <= ln <= len(blob) and ok(ln): return blob[:ln]
for s in range(17):
n = len(blob) - s
if n >= max(0x60, ln) and ok(n): return blob[:n]
raise SystemExit('record checksum does not match')
def info(rec):
name = rec[6:0x34].decode('utf-16-be', 'replace').rstrip('\0').strip()
return rec[0x34:0x48].split(b'\0')[0].decode('latin1'), name
def liste(img):
for l, b, sz, n in KINDS:
for s in range(n):
o = b + s * sz
if img[o:o + 6] == b'TAMAGO': print('%-10s Fach %d %s %s' % (l, s, *info(img[o:o + sz])))
def main():
img = bytearray(open(sys.argv[1], 'rb').read()); img += b'\xff' * (0x800000 - len(img))
if '--liste' in sys.argv: liste(img); return
rec = payload(open(sys.argv[2], 'rb').read())
if rec[0x4E] != 0x94 or rec[0x50] != 0x5B: raise SystemExit('not a game (type %02x cat %02x)' % (rec[0x4E], rec[0x50]))
base, sz, n = GAMES
fach = int(sys.argv[sys.argv.index('--fach') + 1]) if '--fach' in sys.argv else n - 1
o = base + fach * sz
print('ersetze', info(img[o:o + sz]) if img[o:o + 6] == b'TAMAGO' else 'leer', '->', info(rec))
img[o:o + sz] = rec + b'\xff' * (sz - len(rec))
open(sys.argv[3], 'wb').write(img)
if __name__ == '__main__': main()
+65 -65
View File
@@ -1,65 +1,65 @@
#!/usr/bin/env python3
"""Install the field switch into the Paradise ROM (Land/Water/Sky, firmware v1).
feld_rom.py <rom_in> <rom_out> [--app app.bin] [--feld feld.bin]
Holding B+C on the home screen starts the field switch, A+C (if --app)
starts the program as before. The three save slots sit after the characters."""
import sys, struct, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from patch_rom import scene_table, xip, APP_OFF, STUB_OFF
import subprocess, tempfile
FELD_OFF = 0xB1000
SLOT_SIZE = 0x58000
FELD_MAGIC = 0x444C4546
def build_stub(app_src, feld_src, origs, limit=90):
here = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(here, '..', 'stub', 'stub.S')
t = tempfile.mkdtemp()
defs = ['-DAPP_SRC=%d' % app_src, '-DFELD=1', '-DFELD_SRC=%d' % feld_src, '-DHOOKS=1', '-DLIMIT=%d' % limit]
defs += ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)]
if os.environ.get('HOOK_TEST'): defs.append('-DHOOK_TEST=1')
subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs)
subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf'])
subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin'])
return open(t + '/s.bin', 'rb').read()
def slot_off(d):
asset_end = (0x111000 + 16 + struct.unpack_from('<I', d, 0x111000 + 8)[0] + 0xFFF) & ~0xFFF
return max(0x830000, asset_end)
def main():
rin, rout = sys.argv[1:3]
d = bytearray(open(rin, 'rb').read())
assert len(d) == 0x1000000
fid = struct.unpack_from('<I', d, 0xD49000)[0]
assert fid in (1, 2, 3), 'nur Land, Water oder Sky (Kennung %d)' % fid
here = os.path.dirname(os.path.abspath(__file__))
fb = sys.argv[sys.argv.index('--feld') + 1] if '--feld' in sys.argv else os.path.join(here, '..', 'feld', 'feld.bin')
f = bytearray(open(fb, 'rb').read())
i = f.find(struct.pack('<I', FELD_MAGIC))
assert i >= 0
so = slot_off(d)
assert so + 3 * SLOT_SIZE <= 0x940000, 'no room for the slots'
struct.pack_into('<II', f, i + 8, so, SLOT_SIZE)
assert len(f) <= 0xC0000 - FELD_OFF
tab = scene_table(bytes(d))
o = tab['PSID_HOME']
origs = list(struct.unpack_from('<4I', d, o + 12))
if any(xip(STUB_OFF) <= v < xip(STUB_OFF) + 0x1000 for v in origs):
raise SystemExit('ROM ist schon gepatcht')
app_src = 0
if '--app' in sys.argv:
a = open(sys.argv[sys.argv.index('--app') + 1], 'rb').read()
assert len(a) <= 0x10000
d[APP_OFF:APP_OFF + 0x10000] = a + b'\x00' * (0x10000 - len(a))
app_src = xip(APP_OFF)
st = build_stub(app_src, xip(FELD_OFF), origs)
d[STUB_OFF:STUB_OFF + 0x1000] = st + b'\xff' * (0x1000 - len(st))
d[FELD_OFF:FELD_OFF + len(f)] = f
for k in range(4):
struct.pack_into('<I', d, o + 12 + 4 * k, (xip(STUB_OFF) + 0x40 + 6 * k) | 1)
open(rout, 'wb').write(d)
print('field switch added: slots from %#x, %#x each' % (so, SLOT_SIZE))
if __name__ == '__main__': main()
#!/usr/bin/env python3
"""Install the field switch into the Paradise ROM (Land/Water/Sky, firmware v1).
feld_rom.py <rom_in> <rom_out> [--app app.bin] [--feld feld.bin]
Holding B+C on the home screen starts the field switch, A+C (if --app)
starts the program as before. The three save slots sit after the characters."""
import sys, struct, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from patch_rom import scene_table, xip, APP_OFF, STUB_OFF
import subprocess, tempfile
FELD_OFF = 0xB1000
SLOT_SIZE = 0x58000
FELD_MAGIC = 0x444C4546
def build_stub(app_src, feld_src, origs, limit=90):
here = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(here, '..', 'stub', 'stub.S')
t = tempfile.mkdtemp()
defs = ['-DAPP_SRC=%d' % app_src, '-DFELD=1', '-DFELD_SRC=%d' % feld_src, '-DHOOKS=1', '-DLIMIT=%d' % limit]
defs += ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)]
if os.environ.get('HOOK_TEST'): defs.append('-DHOOK_TEST=1')
subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs)
subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf'])
subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin'])
return open(t + '/s.bin', 'rb').read()
def slot_off(d):
asset_end = (0x111000 + 16 + struct.unpack_from('<I', d, 0x111000 + 8)[0] + 0xFFF) & ~0xFFF
return max(0x830000, asset_end)
def main():
rin, rout = sys.argv[1:3]
d = bytearray(open(rin, 'rb').read())
assert len(d) == 0x1000000
fid = struct.unpack_from('<I', d, 0xD49000)[0]
assert fid in (1, 2, 3), 'nur Land, Water oder Sky (Kennung %d)' % fid
here = os.path.dirname(os.path.abspath(__file__))
fb = sys.argv[sys.argv.index('--feld') + 1] if '--feld' in sys.argv else os.path.join(here, '..', 'feld', 'feld.bin')
f = bytearray(open(fb, 'rb').read())
i = f.find(struct.pack('<I', FELD_MAGIC))
assert i >= 0
so = slot_off(d)
assert so + 3 * SLOT_SIZE <= 0x940000, 'no room for the slots'
struct.pack_into('<II', f, i + 8, so, SLOT_SIZE)
assert len(f) <= 0xC0000 - FELD_OFF
tab = scene_table(bytes(d))
o = tab['PSID_HOME']
origs = list(struct.unpack_from('<4I', d, o + 12))
if any(xip(STUB_OFF) <= v < xip(STUB_OFF) + 0x1000 for v in origs):
raise SystemExit('ROM ist schon gepatcht')
app_src = 0
if '--app' in sys.argv:
a = open(sys.argv[sys.argv.index('--app') + 1], 'rb').read()
assert len(a) <= 0x10000
d[APP_OFF:APP_OFF + 0x10000] = a + b'\x00' * (0x10000 - len(a))
app_src = xip(APP_OFF)
st = build_stub(app_src, xip(FELD_OFF), origs)
d[STUB_OFF:STUB_OFF + 0x1000] = st + b'\xff' * (0x1000 - len(st))
d[FELD_OFF:FELD_OFF + len(f)] = f
for k in range(4):
struct.pack_into('<I', d, o + 12 + 4 * k, (xip(STUB_OFF) + 0x40 + 6 * k) | 1)
open(rout, 'wb').write(d)
print('field switch added: slots from %#x, %#x each' % (so, SLOT_SIZE))
if __name__ == '__main__': main()
+87 -87
View File
@@ -1,87 +1,87 @@
#!/usr/bin/env python3
"""Item catalog from a Paradise image (ID, English name, fixed).
Based on werkzeuge/gegenstaende-lesen.py and Bilder.kt from the TamaParadise app."""
import struct, sys
u16=lambda d,o: struct.unpack_from('<H',d,o)[0]
u32=lambda d,o: struct.unpack_from('<I',d,o)[0]
SATZ=46; A=318
SONDER={305:' ',317:' ',375:'&',376:"'",381:'.'}
def bildtab(d):
o=0
while o+4<len(d):
e0=u32(d,o)
if 0x1000<=e0<=0x8000 and e0%4==0:
prev=e0; ok=True
for i in range(1,60):
w=u32(d,o+4*i)
if w<=prev or w>0x1000000: ok=False;break
prev=w
if ok:
k=o+e0
if k+24<len(d):
g=u32(d,k); p=u32(d,k+20)
if 24<p<g and 1<=g<=0x20000 and p%8==0 and d[k+8]>0 and d[k+9]>0: return o
o+=4
return -1
def itemtab(d,nb):
best,bn=-1,0; o=0
while o+SATZ<len(d):
if 5001<=u16(d,o)<=9999:
seen=set(); n=0
while n<400 and o+n*SATZ+5<len(d):
k=u16(d,o+n*SATZ); b=u16(d,o+n*SATZ+4)
if not (5001<=k<=9999) or b>=nb or k in seen: break
seen.add(k); n+=1
if n>bn: bn,best=n,o
if n>8: o+=n*SATZ-2
o+=2
return best,bn
def s_at(d,t,n):
ab=u16(d,t+2*n)
if ab<=0 or ab>0x8000: return ''
o=t+2*ab; s=''
while len(s)<40:
c=u16(d,o)
if c==0: break
if A<=c<A+26: s+=chr(65+c-A)
elif c in SONDER: s+=SONDER[c]
else: return ''
o+=2
return s.strip()
def word3(d,t,n):
ab=u16(d,t+2*n)
if ab<=0 or ab>0x8000: return False
return all(A<=u16(d,t+2*ab+2*k)<A+26 for k in range(3))
WORDS=["FOOD","SNACKS","OUTSIDE TOY","LAB LOG","MILK"]
def langtab(d):
best=None;bp=0;o=0
while o<len(d)-8:
n=u16(d,o)
if 100<=n<=4000 and u16(d,o+2)>n and u16(d,o+4)>u16(d,o+2) and u16(d,o+6)>u16(d,o+4) and word3(d,o,1):
prev=n;ok=True
for i in range(1,min(n,200)):
w=u16(d,o+2*i)
if w<prev or w>0x8000: ok=False;break
prev=w
if ok:
p=sum(1 for k in range(1,120) if s_at(d,o,k) in WORDS)
if p>bp: bp,best=p,o
o+=2
return best if bp>=2 else None
def catalog(d):
bt=bildtab(d); nb=u32(d,bt)//4
it,n=itemtab(d,nb)
lt=langtab(d)
out=[]
for i in range(n):
o=it+i*SATZ; k=u16(d,o); nm=u16(d,o+2)+1; price=u16(d,o+24)
if not (5001<=k<=8999): continue
name=s_at(d,lt,nm) if lt is not None else ''
out.append((k,price==0xFFFF,name))
return sorted(out),hex(bt),hex(it),n,lt
if __name__=='__main__':
for f in sys.argv[1:]:
d=open(f,'rb').read()
c,bt,it,n,lt=catalog(d)
print(f.split('/')[-1],bt,it,n,hex(lt) if lt else None,len(c),'fixed',[x[0] for x in c if x[1]],'without name',sum(1 for x in c if not x[2]))
print(' ',c[:3],c[-3:], max(len(x[2]) for x in c))
#!/usr/bin/env python3
"""Item catalog from a Paradise image (ID, English name, fixed).
Based on werkzeuge/gegenstaende-lesen.py and Bilder.kt from the TamaParadise app."""
import struct, sys
u16=lambda d,o: struct.unpack_from('<H',d,o)[0]
u32=lambda d,o: struct.unpack_from('<I',d,o)[0]
SATZ=46; A=318
SONDER={305:' ',317:' ',375:'&',376:"'",381:'.'}
def bildtab(d):
o=0
while o+4<len(d):
e0=u32(d,o)
if 0x1000<=e0<=0x8000 and e0%4==0:
prev=e0; ok=True
for i in range(1,60):
w=u32(d,o+4*i)
if w<=prev or w>0x1000000: ok=False;break
prev=w
if ok:
k=o+e0
if k+24<len(d):
g=u32(d,k); p=u32(d,k+20)
if 24<p<g and 1<=g<=0x20000 and p%8==0 and d[k+8]>0 and d[k+9]>0: return o
o+=4
return -1
def itemtab(d,nb):
best,bn=-1,0; o=0
while o+SATZ<len(d):
if 5001<=u16(d,o)<=9999:
seen=set(); n=0
while n<400 and o+n*SATZ+5<len(d):
k=u16(d,o+n*SATZ); b=u16(d,o+n*SATZ+4)
if not (5001<=k<=9999) or b>=nb or k in seen: break
seen.add(k); n+=1
if n>bn: bn,best=n,o
if n>8: o+=n*SATZ-2
o+=2
return best,bn
def s_at(d,t,n):
ab=u16(d,t+2*n)
if ab<=0 or ab>0x8000: return ''
o=t+2*ab; s=''
while len(s)<40:
c=u16(d,o)
if c==0: break
if A<=c<A+26: s+=chr(65+c-A)
elif c in SONDER: s+=SONDER[c]
else: return ''
o+=2
return s.strip()
def word3(d,t,n):
ab=u16(d,t+2*n)
if ab<=0 or ab>0x8000: return False
return all(A<=u16(d,t+2*ab+2*k)<A+26 for k in range(3))
WORDS=["FOOD","SNACKS","OUTSIDE TOY","LAB LOG","MILK"]
def langtab(d):
best=None;bp=0;o=0
while o<len(d)-8:
n=u16(d,o)
if 100<=n<=4000 and u16(d,o+2)>n and u16(d,o+4)>u16(d,o+2) and u16(d,o+6)>u16(d,o+4) and word3(d,o,1):
prev=n;ok=True
for i in range(1,min(n,200)):
w=u16(d,o+2*i)
if w<prev or w>0x8000: ok=False;break
prev=w
if ok:
p=sum(1 for k in range(1,120) if s_at(d,o,k) in WORDS)
if p>bp: bp,best=p,o
o+=2
return best if bp>=2 else None
def catalog(d):
bt=bildtab(d); nb=u32(d,bt)//4
it,n=itemtab(d,nb)
lt=langtab(d)
out=[]
for i in range(n):
o=it+i*SATZ; k=u16(d,o); nm=u16(d,o+2)+1; price=u16(d,o+24)
if not (5001<=k<=8999): continue
name=s_at(d,lt,nm) if lt is not None else ''
out.append((k,price==0xFFFF,name))
return sorted(out),hex(bt),hex(it),n,lt
if __name__=='__main__':
for f in sys.argv[1:]:
d=open(f,'rb').read()
c,bt,it,n,lt=catalog(d)
print(f.split('/')[-1],bt,it,n,hex(lt) if lt else None,len(c),'fixed',[x[0] for x in c if x[1]],'without name',sum(1 for x in c if not x[2]))
print(' ',c[:3],c[-3:], max(len(x[2]) for x in c))
+105 -105
View File
@@ -1,105 +1,105 @@
#!/usr/bin/env python3
"""Installs the stub into the Paradise ROM.
patch_rom.py <rom_in> <app.bin> <rom_out> [--scene PSID_NAME] [--guest fw.bin --device pc|idl]
Places the app image (max 64 KB) at APP_OFF and the stub at STUB_OFF and
redirects all four handlers of the chosen scene to the stub."""
import sys, struct, re, subprocess, os, tempfile
XIP_DEC = 0x11000
def xip(off): return 0x10000000 + off - XIP_DEC
APP_OFF, STUB_OFF = 0xA0000, 0xB0000
def scene_table(d):
names = {xip(m.start()): m.group()[:-1].decode() for m in re.finditer(rb'PSID_[A-Z0-9_]+\x00', d)}
ptrs = [(o, w) for o in range(0, len(d) - 4, 4) for w in [struct.unpack_from('<I', d, o)[0]] if w in names]
best, run = [], [ptrs[0]]
for a, b in zip(ptrs, ptrs[1:]):
if b[0] - a[0] == 28: run.append(b)
else:
if len(run) > len(best): best = run
run = [b]
if len(run) > len(best): best = run
base = best[0][0] - 4
return {names[w]: base + i * 28 for i, (o, w) in enumerate(best)}
def build_stub(app_src, origs=None, limit=90):
here = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(here, '..', 'stub', 'stub.S')
t = tempfile.mkdtemp()
defs = ['-DAPP_SRC=%d' % app_src]
if origs:
defs += ['-DHOOKS=1', '-DLIMIT=%d' % limit] + ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)]
subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs)
subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf'])
subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin'])
syms = {}
for l in subprocess.run(['llvm-nm', t + '/s.elf'], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
return open(t + '/s.bin', 'rb').read(), syms
GUEST_OFF, GUEST_END = 0x940000, 0xD40000
DEVICES = {'pc': (0, 0x400000), 'idl': (1, 0x800000)}
# Blocks with many data accesses first: they end up in the cached 1 MB window
HOT = {'pc': [0x25, 0x21, 0x04, 0x02, 0x01, 0x03, 0x05, 0x20, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2a],
'idl': [0x0e, 0x0b, 0x19, 0x16, 0x0d, 0x18, 0x0c, 0x4f, 0x50, 0x15, 0x40, 0x4c, 0x4d, 0x0f, 0x17, 0x1a]}
def pack_guest(fw, dev):
kind, size = DEVICES[dev]
fw = fw[:size] + b'\xff' * (size - min(len(fw), size))
nblk = size >> 16
par = nblk - 1 if dev == 'pc' else 0 # always include the parameter block (save)
used = [i for i in range(nblk) if i == par or fw[i << 16:(i + 1) << 16] != b'\xff' * 0x10000]
order = [b for b in HOT[dev] if b in used] + [b for b in used if b not in HOT[dev]]
m = bytearray(b'\xff' * 128)
blob = bytearray()
for idx, b in enumerate(order):
m[b] = idx
blob += fw[b << 16:(b + 1) << 16]
assert GUEST_OFF + len(blob) <= GUEST_END, 'guest ROM too big: %d blocks' % len(order)
return kind, bytes(m), bytes(blob)
def set_cfg(app, kind, guest_size, m):
i = app.find(struct.pack('<I', 0x43584D50))
assert i >= 0, 'PMXC not found'
a = bytearray(app)
struct.pack_into('<6I', a, i, 0x43584D50, 2, GUEST_OFF, guest_size, 0xC0000, kind)
a[i + 24:i + 24 + 128] = m
return bytes(a)
def main():
rin, app, rout = sys.argv[1:4]
scene = None # default: hold A+C on the home screen
if '--scene' in sys.argv: scene = sys.argv[sys.argv.index('--scene') + 1]
d = bytearray(open(rin, 'rb').read())
a = open(app, 'rb').read()
if '--guest' in sys.argv:
dev = sys.argv[sys.argv.index('--device') + 1] if '--device' in sys.argv else 'pc'
kind, m, blob = pack_guest(open(sys.argv[sys.argv.index('--guest') + 1], 'rb').read(), dev)
d[GUEST_OFF:GUEST_OFF + len(blob)] = blob
a = set_cfg(a, kind, len(blob), m)
print('Gast', dev, len(blob) >> 16, 'Bloecke ab', hex(GUEST_OFF))
assert len(a) <= 0x10000, 'App groesser als 64 KB'
for off, n in ((APP_OFF, 0x10000), (STUB_OFF, 0x1000)):
assert d[off:off + n] == b'\xff' * n or True
d[APP_OFF:APP_OFF + 0x10000] = a + b'\x00' * (0x10000 - len(a))
tab = scene_table(bytes(d))
if scene:
st, _ = build_stub(xip(APP_OFF))
d[STUB_OFF:STUB_OFF + len(st)] = st
o = tab[scene]
for k in range(3, 7):
struct.pack_into('<I', d, o + 4 * k, xip(STUB_OFF) | 1)
print('Szene', scene, 'bei', hex(o), '-> Starter', hex(xip(STUB_OFF) | 1), 'Stub', len(st), 'Byte')
else:
o = tab['PSID_HOME']
origs = list(struct.unpack_from('<4I', d, o + 12))
if any(xip(STUB_OFF) <= v < xip(STUB_OFF) + 0x1000 for v in origs):
raise SystemExit('ROM ist schon gepatcht (Heimbildschirm zeigt auf den Starter)')
st, sy = build_stub(xip(APP_OFF), origs)
d[STUB_OFF:STUB_OFF + len(st)] = st
for k in range(4):
struct.pack_into('<I', d, o + 12 + 4 * k, sy['hook%d' % k] | 1)
print('Heimbildschirm: A+C halten startet den Emulator; Stub', len(st), 'Byte')
open(rout, 'wb').write(d)
if __name__ == '__main__': main()
#!/usr/bin/env python3
"""Installs the stub into the Paradise ROM.
patch_rom.py <rom_in> <app.bin> <rom_out> [--scene PSID_NAME] [--guest fw.bin --device pc|idl]
Places the app image (max 64 KB) at APP_OFF and the stub at STUB_OFF and
redirects all four handlers of the chosen scene to the stub."""
import sys, struct, re, subprocess, os, tempfile
XIP_DEC = 0x11000
def xip(off): return 0x10000000 + off - XIP_DEC
APP_OFF, STUB_OFF = 0xA0000, 0xB0000
def scene_table(d):
names = {xip(m.start()): m.group()[:-1].decode() for m in re.finditer(rb'PSID_[A-Z0-9_]+\x00', d)}
ptrs = [(o, w) for o in range(0, len(d) - 4, 4) for w in [struct.unpack_from('<I', d, o)[0]] if w in names]
best, run = [], [ptrs[0]]
for a, b in zip(ptrs, ptrs[1:]):
if b[0] - a[0] == 28: run.append(b)
else:
if len(run) > len(best): best = run
run = [b]
if len(run) > len(best): best = run
base = best[0][0] - 4
return {names[w]: base + i * 28 for i, (o, w) in enumerate(best)}
def build_stub(app_src, origs=None, limit=90):
here = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(here, '..', 'stub', 'stub.S')
t = tempfile.mkdtemp()
defs = ['-DAPP_SRC=%d' % app_src]
if origs:
defs += ['-DHOOKS=1', '-DLIMIT=%d' % limit] + ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)]
subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs)
subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf'])
subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin'])
syms = {}
for l in subprocess.run(['llvm-nm', t + '/s.elf'], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
return open(t + '/s.bin', 'rb').read(), syms
GUEST_OFF, GUEST_END = 0x940000, 0xD40000
DEVICES = {'pc': (0, 0x400000), 'idl': (1, 0x800000)}
# Blocks with many data accesses first: they end up in the cached 1 MB window
HOT = {'pc': [0x25, 0x21, 0x04, 0x02, 0x01, 0x03, 0x05, 0x20, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2a],
'idl': [0x0e, 0x0b, 0x19, 0x16, 0x0d, 0x18, 0x0c, 0x4f, 0x50, 0x15, 0x40, 0x4c, 0x4d, 0x0f, 0x17, 0x1a]}
def pack_guest(fw, dev):
kind, size = DEVICES[dev]
fw = fw[:size] + b'\xff' * (size - min(len(fw), size))
nblk = size >> 16
par = nblk - 1 if dev == 'pc' else 0 # always include the parameter block (save)
used = [i for i in range(nblk) if i == par or fw[i << 16:(i + 1) << 16] != b'\xff' * 0x10000]
order = [b for b in HOT[dev] if b in used] + [b for b in used if b not in HOT[dev]]
m = bytearray(b'\xff' * 128)
blob = bytearray()
for idx, b in enumerate(order):
m[b] = idx
blob += fw[b << 16:(b + 1) << 16]
assert GUEST_OFF + len(blob) <= GUEST_END, 'guest ROM too big: %d blocks' % len(order)
return kind, bytes(m), bytes(blob)
def set_cfg(app, kind, guest_size, m):
i = app.find(struct.pack('<I', 0x43584D50))
assert i >= 0, 'PMXC not found'
a = bytearray(app)
struct.pack_into('<6I', a, i, 0x43584D50, 2, GUEST_OFF, guest_size, 0xC0000, kind)
a[i + 24:i + 24 + 128] = m
return bytes(a)
def main():
rin, app, rout = sys.argv[1:4]
scene = None # default: hold A+C on the home screen
if '--scene' in sys.argv: scene = sys.argv[sys.argv.index('--scene') + 1]
d = bytearray(open(rin, 'rb').read())
a = open(app, 'rb').read()
if '--guest' in sys.argv:
dev = sys.argv[sys.argv.index('--device') + 1] if '--device' in sys.argv else 'pc'
kind, m, blob = pack_guest(open(sys.argv[sys.argv.index('--guest') + 1], 'rb').read(), dev)
d[GUEST_OFF:GUEST_OFF + len(blob)] = blob
a = set_cfg(a, kind, len(blob), m)
print('Gast', dev, len(blob) >> 16, 'Bloecke ab', hex(GUEST_OFF))
assert len(a) <= 0x10000, 'App groesser als 64 KB'
for off, n in ((APP_OFF, 0x10000), (STUB_OFF, 0x1000)):
assert d[off:off + n] == b'\xff' * n or True
d[APP_OFF:APP_OFF + 0x10000] = a + b'\x00' * (0x10000 - len(a))
tab = scene_table(bytes(d))
if scene:
st, _ = build_stub(xip(APP_OFF))
d[STUB_OFF:STUB_OFF + len(st)] = st
o = tab[scene]
for k in range(3, 7):
struct.pack_into('<I', d, o + 4 * k, xip(STUB_OFF) | 1)
print('Szene', scene, 'bei', hex(o), '-> Starter', hex(xip(STUB_OFF) | 1), 'Stub', len(st), 'Byte')
else:
o = tab['PSID_HOME']
origs = list(struct.unpack_from('<4I', d, o + 12))
if any(xip(STUB_OFF) <= v < xip(STUB_OFF) + 0x1000 for v in origs):
raise SystemExit('ROM ist schon gepatcht (Heimbildschirm zeigt auf den Starter)')
st, sy = build_stub(xip(APP_OFF), origs)
d[STUB_OFF:STUB_OFF + len(st)] = st
for k in range(4):
struct.pack_into('<I', d, o + 12 + 4 * k, sy['hook%d' % k] | 1)
print('Heimbildschirm: A+C halten startet den Emulator; Stub', len(st), 'Byte')
open(rout, 'wb').write(d)
if __name__ == '__main__': main()
+249 -249
View File
@@ -1,249 +1,249 @@
# TamaEmu (emu.bin, device program) in Unicorn, like t7/test/devt7.py: hardware calls are caught, the screen is
# drawn into a picture, the SysTick advances every RT instructions (96 MHz Cortex-M3 ~ RT per ms). Measures the
# speed (emulated ms against real ms, dropped ms) and the power states (full clock, 12 MHz, deep sleep).
# python3 devemu.py <emu.elf> <paradise image with TamaEmu (mkimg.js)> <ms> [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir]
# load: the code run per ms until the main loop waits (wfi), against RT instructions
# LAGLOG=n: every n ms the emulated and dropped ms in that time
import sys, struct, subprocess, os
from unicorn import *
from unicorn.arm_const import *
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
RT = int(os.environ.get('RT', '64000'))
out = os.environ.get('OUT', '.')
syms = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
fl = bytearray(open(img, 'rb').read())
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # UART1 LSR: sender empty, nothing received
WIN = [0]
def win_load(base):
WIN[0] = base; o = base & 0xFFFFFF
u.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff'))
win_load(0x60011000)
def _xipw(uc, acc, addr, size, val, ud):
if addr == 0x4002F004 and val != WIN[0]: win_load(val); state["pw_dirty"] = (0x10000000, 0x100000)
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007)
fb = [[0] * 128 for _ in range(128)]
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
KS = []
for p in os.environ.get('KEYS', '').split(','):
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
state = {'ms': 0, 'tone': [], 'flashw': 0, 'bl': [], 'blpct': [], 'busy': 0, 'busyn': 0, 'ins': 0}
def keys():
m = 0
for t, v in KS:
if state['ms'] / 1000.0 >= t: m = v
return m
def ret(uc, v=None):
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
def h_begin(uc):
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
def h_row(uc):
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
for v in d:
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
rect['x'] += 1
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
state['rows'] = state.get('rows', 0) + 1; ret(uc)
def h_push(uc):
p = uc.reg_read(UC_ARM_REG_R0); x0, y0, x1, y1 = uc.reg_read(UC_ARM_REG_R2), uc.reg_read(UC_ARM_REG_R3), *struct.unpack('<II', uc.mem_read(uc.reg_read(UC_ARM_REG_SP), 8))
for y in range(y0, min(y1, 128)):
d = struct.unpack('<%dH' % (x1 - x0), uc.mem_read(p + 2 * x0, 2 * (x1 - x0)))
for i, v in enumerate(d):
if x0 + i < 128: fb[y][x0 + i] = v
ret(uc)
def h_tone(uc): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc): ret(uc, keys())
def h_prog(uc):
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = bytes(uc.mem_read(src & ~3, 0x1000)); a = ad & 0xFFFFFF
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1
o = a - (WIN[0] & 0xFFFFFF)
if 0 <= o < 0x100000: uc.mem_write(0x10000000 + o, d)
ret(uc)
def h_erase(uc):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000
o = a - (WIN[0] & 0xFFFFFF)
if 0 <= o < 0x100000: uc.mem_write(0x10000000 + o, b'\xff' * 0x1000)
ret(uc)
def h_back(uc): state['back'] = 1; uc.emu_stop()
def h_nop(uc): ret(uc)
def h_bl(uc): state['bl'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_blset(uc): state['blpct'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_push': h_push, 'hw_tone': h_tone,
'hw_buttons': h_btn, 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back,
'hw_init': h_nop, 'hw_backlight': h_bl, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop, 'hw_bl_set': h_blset,
'hw_wake_step': h_nop}
for n, f in H.items():
if n not in syms: continue
a = syms[n] & ~1
if a >= syms.get('__initcode_start', 0x10000): # start code: its room becomes the translator's afterwards
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: not state.get('jit') and f(uc))(f), begin=a, end=a)
else: u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
def bad(uc, access, addr, size, value, ud):
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
if os.environ.get('ROMHIST'): # reads of the guest firmware per flash block: cached window and direct (uncached)
_cfg = APPOFF + 0x140; _go = struct.unpack_from('<I', fl, _cfg + 8)[0]; _gl = struct.unpack_from('<I', fl, _cfg + 12)[0]
RH = {}
def _rh(uc, acc, a, sz, v, ud):
if a >= 0x60000000: k = ((a & 0xFFFFFF) - _go) >> 16; RH[('u', k)] = RH.get(('u', k), 0) + 1
else: k = ((WIN[0] & 0xFFFFFF) + (a - 0x10000000) - _go) >> 16; RH[('c', k)] = RH.get(('c', k), 0) + 1
u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x60000000 + _go, end=0x60000000 + _go + _gl - 1)
u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x10000000, end=0x100FFFFF)
import atexit
def _rhp():
_map = bytes(fl[_cfg + 24:_cfg + 152]); inv = {m: b for b, m in enumerate(_map) if m != 0xFF}
tot = {}
for (w, k), n in RH.items(): tot[k] = tot.get(k, 0) + n
print('romhist (flash slot: guest block, reads, uncached reads):')
print(' '.join('%d:%02x:%d:%d' % (k, inv.get(k, 0xFF), n, RH.get(('u', k), 0)) for k, n in sorted(tot.items(), key=lambda kv: -kv[1])[:40]))
atexit.register(_rhp)
if os.environ.get('INSTRACE'): # INSTRACE=ms: every instruction from that ms on, the last 300 (pc, sp)
import collections, atexit
TI = collections.deque(maxlen=300); _it = int(os.environ['INSTRACE'])
def _ih(uc, a, sz, ud):
if state['ms'] >= _it: TI.append((a, uc.reg_read(UC_ARM_REG_SP), uc.reg_read(UC_ARM_REG_LR)))
u.hook_add(UC_HOOK_CODE, _ih)
atexit.register(lambda: print('\n'.join('I %x sp %x lr %x' % t for t in TI)))
if os.environ.get('PWLOG'): # writes into the PRAM from elsewhere than the copy loop
_jcc = syms.get('J_cpcode', 0) & ~1
def _pwl(uc, acc, a, sz, v, ud):
p = uc.reg_read(UC_ARM_REG_PC)
if not (_jcc <= p < _jcc + 24): print('PRAM write %x = %x size %d by pc %x at ms %d' % (a, v, sz, p, state['ms']))
u.hook_add(UC_HOOK_MEM_WRITE, _pwl, begin=0, end=0xFFFF)
if os.environ.get('BLKTRACE'):
import collections
TR = collections.deque(maxlen=int(os.environ['BLKTRACE']))
u.hook_add(UC_HOOK_BLOCK, lambda uc, a, sz, ud: TR.append((a, sz)))
import atexit; atexit.register(lambda: print('last blocks', ' '.join('%x/%d' % t for t in TR)))
atexit.register(lambda: open(os.path.join(out, 'pram.bin'), 'wb').write(bytes(u.mem_read(0, 0x10000))))
atexit.register(lambda: open(os.path.join(out, 'sram.bin'), 'wb').write(bytes(u.mem_read(0x18000000, 0x20000))))
atexit.register(lambda: print('regs', ' '.join('%x' % u.reg_read(r) for r in [UC_ARM_REG_R0 + i for i in range(13)] + [UC_ARM_REG_SP, UC_ARM_REG_LR])))
# AHB prescaler (CLK_ECO) and the clock source (PW): RT >> sh instructions per ms
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
def _ahb(uc, acc, a, sz, v, ud): state['sh'] = v & 7
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
u.mem_write(0x4500000C, struct.pack('<I', 0x44)); u.mem_write(0x45000008, struct.pack('<I', 0x55)); u.mem_write(0x45000200, struct.pack('<I', 0x80))
state['ihrc'] = 0; state['pw'] = {'full': 0, 'ihrc': 0, 'sleep': 0}
def _clk(uc, acc, a, sz, v, ud):
state['ihrc'] = (v & 7) == 0; state['clkv'] = v & 7
u.hook_add(UC_HOOK_MEM_WRITE, _clk, begin=0x4500000C, end=0x4500000F)
def _clkrd(uc, acc, a, sz, v, ud): # the status (bits 6:4) follows the source at once (the hook runs before the store)
if 'clkv' in state: c = state['clkv']; uc.mem_write(0x4500000C, struct.pack('<I', c | (c << 4)))
u.hook_add(UC_HOOK_MEM_READ, _clkrd, begin=0x4500000C, end=0x4500000F)
rtc0 = int(os.environ.get('RTC0', '5000'))
def _pmu(uc, acc, a, sz, v, ud):
if v & 2 and not state.get('dsleep'):
t = state['ms']
while True:
t += 1
if t % 1000 == 0 or t >= total_ms or any(t / 1000.0 >= kt > state['ms'] / 1000.0 for kt, _ in KS): break
state['dsleep'] = t
if t % 1000 == 0 and 'g_pw_rtcw' in syms: uc.mem_write(syms['g_pw_rtcw'], b'\x01')
uc.mem_write(0x45000304, struct.pack('<I', rtc0 + t // 1000))
u.hook_add(UC_HOOK_MEM_WRITE, _pmu, begin=0x45000300, end=0x45000303)
# The load: the ms is run in NCH parts; the part in which the main loop waits (wfi) tells how busy it was.
NCH = int(os.environ.get('NCH', '8'))
state['pw_dirty'] = 0
# The translator copies new code into the PRAM with a small loop in the SRAM (J_cpcode: r0 target, r2 bytes). At
# its end (bx lr) the run stops and what Unicorn had translated from there is dropped.
if 'J_cpcode' in syms:
_jc = syms['J_cpcode'] & ~1
def _jc_in(uc, a, sz, ud): state['jcr'] = (uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R2)); state['jit'] = 1
def _jc_out(uc, a, sz, ud):
if state.pop('jc_go', 0): return # resumed right here after the stop
state['pw_dirty'] = state.get('jcr', (0, 0x10000)); state['jc_go'] = 1; uc.emu_stop()
u.hook_add(UC_HOOK_CODE, _jc_in, begin=_jc, end=_jc)
u.hook_add(UC_HOOK_CODE, _jc_out, begin=_jc + 20, end=_jc + 20)
for _v in os.environ.get('SETDATA', '').split(','): # SETDATA=sym:value,...: an initialised variable changed in the image
if ':' in _v:
_n, _x = _v.split(':'); _d = syms[_n] - syms['__data_start'] + syms['__data_load']; u.mem_write(_d, struct.pack('<I', int(_x, 0)))
if os.environ.get('NOJIT'): # the interpreter only: jit_enabled (data, initial value in the image) = 0
_d = syms['jit_enabled'] - syms['__data_start'] + syms['__data_load']; u.mem_write(_d, b'\0\0\0\0')
# the main loop waits (wfi): the rest of the ms is idle
_code = bytes(fl[APPOFF:APPOFF + 0x10000]); _end = syms.get('__initcode_start', 0x10000)
def _wfi(uc, a, sz, ud): state['waited'] = 1; uc.emu_stop()
_wfa = [i for i in range(0, _end, 2) if _code[i:i + 2] == b'\x30\xbf']
if not os.environ.get('NOWFI'):
for _a in _wfa: u.hook_add(UC_HOOK_CODE, _wfi, begin=_a, end=_a)
def shot(name):
from PIL import Image
im = Image.new('RGB', (128, 128))
for y in range(128):
for x in range(128):
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
im.save(os.path.join(out, name))
def st(i): return struct.unpack('<I', u.mem_read(0x18000000 + 4 * i, 4))[0]
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
u.reg_write(UC_ARM_REG_SP, sp)
pc = rst; gms = syms['g_ms']
si = 0; LL = int(os.environ.get('LAGLOG', '0')); llp = None
CL = int(os.environ.get('CLOCKLOG', '0')); IOOFF = int(os.environ.get('IOOFF', '0xd98c'), 16) # Emu.ioram (ARM layout)
PROF = {} if os.environ.get('PROF') else None; PROFFROM = int(os.environ.get('PROFFROM', '0')) # pc samples (8 per ms) by function
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
state['waited'] = 0
_sh = 3 if state['ihrc'] else state['sh']; n = max(1, RT >> _sh); ch = max(1, n // NCH)
err = 0; k = 0
while k < NCH and not state['waited'] and 'back' not in state and not state.get('dsleep'):
if state['pw_dirty']:
_a, _n = state["pw_dirty"]; (u.ctl_flush_tb() if os.environ.get("FULLFLUSH") else u.ctl_remove_cache(_a & ~1, _a + _n + 2)); state['pw_dirty'] = 0; state['jcopies'] = state.get('jcopies', 0) + 1
try: u.emu_start(pc | 1, 0xFFFFFFF0, count=ch)
except UcError as ex:
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); err = 1; break
pc = u.reg_read(UC_ARM_REG_PC)
if PROF is not None and not state['waited'] and (not PROFFROM or state['ms'] >= PROFFROM): PROF[pc] = PROF.get(pc, 0) + 1
if not state['pw_dirty']: k += 1
if err: break
state['shms'][min(_sh, 3)] += 1; state['pw']['ihrc' if state['ihrc'] else 'full'] += 1
state['busy'] += k; state['busyn'] += 1
if state['waited']: pc = (pc + 2) & ~1 # past the wfi: the tick comes
_ds = state.pop('dsleep', 0)
if _ds:
n = _ds - state['ms']; state['ms'] = _ds; state['pw']['sleep'] += n
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
continue
state['ms'] += 1
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
if CL and state['ms'] % CL == 0:
_io = bytes(u.mem_read(syms['g_emu'] + IOOFF + 0x1910, 0x10)); b = lambda x: (x >> 4) * 10 + (x & 15)
print('clock', state['ms'], 'guest %02d:%02d:%02d' % (b(_io[8]), b(_io[4]), b(_io[0])), flush=True)
if LL and state['ms'] % LL == 0:
cur = (st(9), st(10)); p0 = llp or cur
print('lag', state['ms'], cur[0] - p0[0], cur[1] - p0[1], 'pw', dict(state['pw']), flush=True); llp = cur
print('emulated ms', st(9), 'dropped ms', st(10), 'busy loop ms', st(12), 'guest pc %x' % st(6), 'mclk', st(4))
print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
print('power ms: full', state['pw']['full'], 'ihrc', state['pw']['ihrc'], 'deep sleep', state['pw']['sleep'])
print('backlight', state['bl'][-6:], 'light %', state['blpct'][-4:])
print('translator copies', state.get('jcopies', 0), ' '.join('%s %d' % (n, struct.unpack('<I', u.mem_read(syms[n], 4))[0]) for n in ('jit_st_flush', 'jit_st_blocks', 'jit_st_idle', 'st_n_evict') if n in syms)); print('load %.1f %% of the CPU (awake ms, in steps of %d %%)' % (100.0 * state['busy'] / max(1, state['busyn'] * NCH), 100 // NCH))
if PROF:
fs = sorted(((v, k) for k, v in syms.items() if v < 0x20000000), key=lambda t: t[0]); import bisect
fa = [a for a, _ in fs]; agg = {}
for a, n in PROF.items():
i = bisect.bisect_right(fa, a & ~1) - 1; nm = fs[i][1] if i >= 0 else '?'
if a >= syms.get('__initcode_start', 0x10000) and a < 0x10000: nm = 'JIT code'
if a >= 0x18000000: nm = 'SRAM code'
agg[nm] = agg.get(nm, 0) + n
tot = sum(agg.values())
if os.environ.get('PROFPC'): print('top pcs', ' '.join('%x:%d' % kv for kv in sorted(PROF.items(), key=lambda kv: -kv[1])[:12]))
print('profile (%d samples):' % tot, ', '.join('%s %.1f%%' % (k, 100.0 * v / tot) for k, v in sorted(agg.items(), key=lambda kv: -kv[1])[:16]))
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
shot('shot_end.png')
# TamaEmu (emu.bin, device program) in Unicorn, like t7/test/devt7.py: hardware calls are caught, the screen is
# drawn into a picture, the SysTick advances every RT instructions (96 MHz Cortex-M3 ~ RT per ms). Measures the
# speed (emulated ms against real ms, dropped ms) and the power states (full clock, 12 MHz, deep sleep).
# python3 devemu.py <emu.elf> <paradise image with TamaEmu (mkimg.js)> <ms> [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir]
# load: the code run per ms until the main loop waits (wfi), against RT instructions
# LAGLOG=n: every n ms the emulated and dropped ms in that time
import sys, struct, subprocess, os
from unicorn import *
from unicorn.arm_const import *
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
RT = int(os.environ.get('RT', '64000'))
out = os.environ.get('OUT', '.')
syms = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
fl = bytearray(open(img, 'rb').read())
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # UART1 LSR: sender empty, nothing received
WIN = [0]
def win_load(base):
WIN[0] = base; o = base & 0xFFFFFF
u.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff'))
win_load(0x60011000)
def _xipw(uc, acc, addr, size, val, ud):
if addr == 0x4002F004 and val != WIN[0]: win_load(val); state["pw_dirty"] = (0x10000000, 0x100000)
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007)
fb = [[0] * 128 for _ in range(128)]
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
KS = []
for p in os.environ.get('KEYS', '').split(','):
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
state = {'ms': 0, 'tone': [], 'flashw': 0, 'bl': [], 'blpct': [], 'busy': 0, 'busyn': 0, 'ins': 0}
def keys():
m = 0
for t, v in KS:
if state['ms'] / 1000.0 >= t: m = v
return m
def ret(uc, v=None):
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
def h_begin(uc):
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
def h_row(uc):
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
for v in d:
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
rect['x'] += 1
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
state['rows'] = state.get('rows', 0) + 1; ret(uc)
def h_push(uc):
p = uc.reg_read(UC_ARM_REG_R0); x0, y0, x1, y1 = uc.reg_read(UC_ARM_REG_R2), uc.reg_read(UC_ARM_REG_R3), *struct.unpack('<II', uc.mem_read(uc.reg_read(UC_ARM_REG_SP), 8))
for y in range(y0, min(y1, 128)):
d = struct.unpack('<%dH' % (x1 - x0), uc.mem_read(p + 2 * x0, 2 * (x1 - x0)))
for i, v in enumerate(d):
if x0 + i < 128: fb[y][x0 + i] = v
ret(uc)
def h_tone(uc): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc): ret(uc, keys())
def h_prog(uc):
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = bytes(uc.mem_read(src & ~3, 0x1000)); a = ad & 0xFFFFFF
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1
o = a - (WIN[0] & 0xFFFFFF)
if 0 <= o < 0x100000: uc.mem_write(0x10000000 + o, d)
ret(uc)
def h_erase(uc):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000
o = a - (WIN[0] & 0xFFFFFF)
if 0 <= o < 0x100000: uc.mem_write(0x10000000 + o, b'\xff' * 0x1000)
ret(uc)
def h_back(uc): state['back'] = 1; uc.emu_stop()
def h_nop(uc): ret(uc)
def h_bl(uc): state['bl'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_blset(uc): state['blpct'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_push': h_push, 'hw_tone': h_tone,
'hw_buttons': h_btn, 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back,
'hw_init': h_nop, 'hw_backlight': h_bl, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop, 'hw_bl_set': h_blset,
'hw_wake_step': h_nop}
for n, f in H.items():
if n not in syms: continue
a = syms[n] & ~1
if a >= syms.get('__initcode_start', 0x10000): # start code: its room becomes the translator's afterwards
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: not state.get('jit') and f(uc))(f), begin=a, end=a)
else: u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
def bad(uc, access, addr, size, value, ud):
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
if os.environ.get('ROMHIST'): # reads of the guest firmware per flash block: cached window and direct (uncached)
_cfg = APPOFF + 0x140; _go = struct.unpack_from('<I', fl, _cfg + 8)[0]; _gl = struct.unpack_from('<I', fl, _cfg + 12)[0]
RH = {}
def _rh(uc, acc, a, sz, v, ud):
if a >= 0x60000000: k = ((a & 0xFFFFFF) - _go) >> 16; RH[('u', k)] = RH.get(('u', k), 0) + 1
else: k = ((WIN[0] & 0xFFFFFF) + (a - 0x10000000) - _go) >> 16; RH[('c', k)] = RH.get(('c', k), 0) + 1
u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x60000000 + _go, end=0x60000000 + _go + _gl - 1)
u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x10000000, end=0x100FFFFF)
import atexit
def _rhp():
_map = bytes(fl[_cfg + 24:_cfg + 152]); inv = {m: b for b, m in enumerate(_map) if m != 0xFF}
tot = {}
for (w, k), n in RH.items(): tot[k] = tot.get(k, 0) + n
print('romhist (flash slot: guest block, reads, uncached reads):')
print(' '.join('%d:%02x:%d:%d' % (k, inv.get(k, 0xFF), n, RH.get(('u', k), 0)) for k, n in sorted(tot.items(), key=lambda kv: -kv[1])[:40]))
atexit.register(_rhp)
if os.environ.get('INSTRACE'): # INSTRACE=ms: every instruction from that ms on, the last 300 (pc, sp)
import collections, atexit
TI = collections.deque(maxlen=300); _it = int(os.environ['INSTRACE'])
def _ih(uc, a, sz, ud):
if state['ms'] >= _it: TI.append((a, uc.reg_read(UC_ARM_REG_SP), uc.reg_read(UC_ARM_REG_LR)))
u.hook_add(UC_HOOK_CODE, _ih)
atexit.register(lambda: print('\n'.join('I %x sp %x lr %x' % t for t in TI)))
if os.environ.get('PWLOG'): # writes into the PRAM from elsewhere than the copy loop
_jcc = syms.get('J_cpcode', 0) & ~1
def _pwl(uc, acc, a, sz, v, ud):
p = uc.reg_read(UC_ARM_REG_PC)
if not (_jcc <= p < _jcc + 24): print('PRAM write %x = %x size %d by pc %x at ms %d' % (a, v, sz, p, state['ms']))
u.hook_add(UC_HOOK_MEM_WRITE, _pwl, begin=0, end=0xFFFF)
if os.environ.get('BLKTRACE'):
import collections
TR = collections.deque(maxlen=int(os.environ['BLKTRACE']))
u.hook_add(UC_HOOK_BLOCK, lambda uc, a, sz, ud: TR.append((a, sz)))
import atexit; atexit.register(lambda: print('last blocks', ' '.join('%x/%d' % t for t in TR)))
atexit.register(lambda: open(os.path.join(out, 'pram.bin'), 'wb').write(bytes(u.mem_read(0, 0x10000))))
atexit.register(lambda: open(os.path.join(out, 'sram.bin'), 'wb').write(bytes(u.mem_read(0x18000000, 0x20000))))
atexit.register(lambda: print('regs', ' '.join('%x' % u.reg_read(r) for r in [UC_ARM_REG_R0 + i for i in range(13)] + [UC_ARM_REG_SP, UC_ARM_REG_LR])))
# AHB prescaler (CLK_ECO) and the clock source (PW): RT >> sh instructions per ms
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
def _ahb(uc, acc, a, sz, v, ud): state['sh'] = v & 7
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
u.mem_write(0x4500000C, struct.pack('<I', 0x44)); u.mem_write(0x45000008, struct.pack('<I', 0x55)); u.mem_write(0x45000200, struct.pack('<I', 0x80))
state['ihrc'] = 0; state['pw'] = {'full': 0, 'ihrc': 0, 'sleep': 0}
def _clk(uc, acc, a, sz, v, ud):
state['ihrc'] = (v & 7) == 0; state['clkv'] = v & 7
u.hook_add(UC_HOOK_MEM_WRITE, _clk, begin=0x4500000C, end=0x4500000F)
def _clkrd(uc, acc, a, sz, v, ud): # the status (bits 6:4) follows the source at once (the hook runs before the store)
if 'clkv' in state: c = state['clkv']; uc.mem_write(0x4500000C, struct.pack('<I', c | (c << 4)))
u.hook_add(UC_HOOK_MEM_READ, _clkrd, begin=0x4500000C, end=0x4500000F)
rtc0 = int(os.environ.get('RTC0', '5000'))
def _pmu(uc, acc, a, sz, v, ud):
if v & 2 and not state.get('dsleep'):
t = state['ms']
while True:
t += 1
if t % 1000 == 0 or t >= total_ms or any(t / 1000.0 >= kt > state['ms'] / 1000.0 for kt, _ in KS): break
state['dsleep'] = t
if t % 1000 == 0 and 'g_pw_rtcw' in syms: uc.mem_write(syms['g_pw_rtcw'], b'\x01')
uc.mem_write(0x45000304, struct.pack('<I', rtc0 + t // 1000))
u.hook_add(UC_HOOK_MEM_WRITE, _pmu, begin=0x45000300, end=0x45000303)
# The load: the ms is run in NCH parts; the part in which the main loop waits (wfi) tells how busy it was.
NCH = int(os.environ.get('NCH', '8'))
state['pw_dirty'] = 0
# The translator copies new code into the PRAM with a small loop in the SRAM (J_cpcode: r0 target, r2 bytes). At
# its end (bx lr) the run stops and what Unicorn had translated from there is dropped.
if 'J_cpcode' in syms:
_jc = syms['J_cpcode'] & ~1
def _jc_in(uc, a, sz, ud): state['jcr'] = (uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R2)); state['jit'] = 1
def _jc_out(uc, a, sz, ud):
if state.pop('jc_go', 0): return # resumed right here after the stop
state['pw_dirty'] = state.get('jcr', (0, 0x10000)); state['jc_go'] = 1; uc.emu_stop()
u.hook_add(UC_HOOK_CODE, _jc_in, begin=_jc, end=_jc)
u.hook_add(UC_HOOK_CODE, _jc_out, begin=_jc + 20, end=_jc + 20)
for _v in os.environ.get('SETDATA', '').split(','): # SETDATA=sym:value,...: an initialised variable changed in the image
if ':' in _v:
_n, _x = _v.split(':'); _d = syms[_n] - syms['__data_start'] + syms['__data_load']; u.mem_write(_d, struct.pack('<I', int(_x, 0)))
if os.environ.get('NOJIT'): # the interpreter only: jit_enabled (data, initial value in the image) = 0
_d = syms['jit_enabled'] - syms['__data_start'] + syms['__data_load']; u.mem_write(_d, b'\0\0\0\0')
# the main loop waits (wfi): the rest of the ms is idle
_code = bytes(fl[APPOFF:APPOFF + 0x10000]); _end = syms.get('__initcode_start', 0x10000)
def _wfi(uc, a, sz, ud): state['waited'] = 1; uc.emu_stop()
_wfa = [i for i in range(0, _end, 2) if _code[i:i + 2] == b'\x30\xbf']
if not os.environ.get('NOWFI'):
for _a in _wfa: u.hook_add(UC_HOOK_CODE, _wfi, begin=_a, end=_a)
def shot(name):
from PIL import Image
im = Image.new('RGB', (128, 128))
for y in range(128):
for x in range(128):
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
im.save(os.path.join(out, name))
def st(i): return struct.unpack('<I', u.mem_read(0x18000000 + 4 * i, 4))[0]
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
u.reg_write(UC_ARM_REG_SP, sp)
pc = rst; gms = syms['g_ms']
si = 0; LL = int(os.environ.get('LAGLOG', '0')); llp = None
CL = int(os.environ.get('CLOCKLOG', '0')); IOOFF = int(os.environ.get('IOOFF', '0xd98c'), 16) # Emu.ioram (ARM layout)
PROF = {} if os.environ.get('PROF') else None; PROFFROM = int(os.environ.get('PROFFROM', '0')) # pc samples (8 per ms) by function
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
state['waited'] = 0
_sh = 3 if state['ihrc'] else state['sh']; n = max(1, RT >> _sh); ch = max(1, n // NCH)
err = 0; k = 0
while k < NCH and not state['waited'] and 'back' not in state and not state.get('dsleep'):
if state['pw_dirty']:
_a, _n = state["pw_dirty"]; (u.ctl_flush_tb() if os.environ.get("FULLFLUSH") else u.ctl_remove_cache(_a & ~1, _a + _n + 2)); state['pw_dirty'] = 0; state['jcopies'] = state.get('jcopies', 0) + 1
try: u.emu_start(pc | 1, 0xFFFFFFF0, count=ch)
except UcError as ex:
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); err = 1; break
pc = u.reg_read(UC_ARM_REG_PC)
if PROF is not None and not state['waited'] and (not PROFFROM or state['ms'] >= PROFFROM): PROF[pc] = PROF.get(pc, 0) + 1
if not state['pw_dirty']: k += 1
if err: break
state['shms'][min(_sh, 3)] += 1; state['pw']['ihrc' if state['ihrc'] else 'full'] += 1
state['busy'] += k; state['busyn'] += 1
if state['waited']: pc = (pc + 2) & ~1 # past the wfi: the tick comes
_ds = state.pop('dsleep', 0)
if _ds:
n = _ds - state['ms']; state['ms'] = _ds; state['pw']['sleep'] += n
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
continue
state['ms'] += 1
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
if CL and state['ms'] % CL == 0:
_io = bytes(u.mem_read(syms['g_emu'] + IOOFF + 0x1910, 0x10)); b = lambda x: (x >> 4) * 10 + (x & 15)
print('clock', state['ms'], 'guest %02d:%02d:%02d' % (b(_io[8]), b(_io[4]), b(_io[0])), flush=True)
if LL and state['ms'] % LL == 0:
cur = (st(9), st(10)); p0 = llp or cur
print('lag', state['ms'], cur[0] - p0[0], cur[1] - p0[1], 'pw', dict(state['pw']), flush=True); llp = cur
print('emulated ms', st(9), 'dropped ms', st(10), 'busy loop ms', st(12), 'guest pc %x' % st(6), 'mclk', st(4))
print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
print('power ms: full', state['pw']['full'], 'ihrc', state['pw']['ihrc'], 'deep sleep', state['pw']['sleep'])
print('backlight', state['bl'][-6:], 'light %', state['blpct'][-4:])
print('translator copies', state.get('jcopies', 0), ' '.join('%s %d' % (n, struct.unpack('<I', u.mem_read(syms[n], 4))[0]) for n in ('jit_st_flush', 'jit_st_blocks', 'jit_st_idle', 'st_n_evict') if n in syms)); print('load %.1f %% of the CPU (awake ms, in steps of %d %%)' % (100.0 * state['busy'] / max(1, state['busyn'] * NCH), 100 // NCH))
if PROF:
fs = sorted(((v, k) for k, v in syms.items() if v < 0x20000000), key=lambda t: t[0]); import bisect
fa = [a for a, _ in fs]; agg = {}
for a, n in PROF.items():
i = bisect.bisect_right(fa, a & ~1) - 1; nm = fs[i][1] if i >= 0 else '?'
if a >= syms.get('__initcode_start', 0x10000) and a < 0x10000: nm = 'JIT code'
if a >= 0x18000000: nm = 'SRAM code'
agg[nm] = agg.get(nm, 0) + n
tot = sum(agg.values())
if os.environ.get('PROFPC'): print('top pcs', ' '.join('%x:%d' % kv for kv in sorted(PROF.items(), key=lambda kv: -kv[1])[:12]))
print('profile (%d samples):' % tot, ', '.join('%s %.1f%%' % (k, 100.0 * v / tot) for k, v in sorted(agg.items(), key=lambda kv: -kv[1])[:16]))
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
shot('shot_end.png')
+15 -15
View File
@@ -1,15 +1,15 @@
# keys.py "5:B 1.5:B*10 5:A 1:B 360: 0:W2000" -> KEYS for devemu.py: each item <wait s>:<key>[*n], key A B C W (wheel),
# W<ms> holds the wheel that long; a press lasts 150 ms. Prints KEYS and the total seconds.
import sys
M = {'A': 1, 'B': 2, 'C': 4, 'W': 8}
t = 0.0; out = []
for it in sys.argv[1].split():
w, k = it.split(':'); n = 1
if '*' in k: k, n = k.split('*'); n = int(n)
for _ in range(n):
t += float(w)
if not k: continue
hold = 0.15
if len(k) > 1: hold = int(k[1:]) / 1000.0
out.append('%.3f:%d' % (t, M[k[0]])); out.append('%.3f:0' % (t + hold)); t += hold
print(','.join(out)); print(int(t * 1000) + 3000, file=sys.stderr)
# keys.py "5:B 1.5:B*10 5:A 1:B 360: 0:W2000" -> KEYS for devemu.py: each item <wait s>:<key>[*n], key A B C W (wheel),
# W<ms> holds the wheel that long; a press lasts 150 ms. Prints KEYS and the total seconds.
import sys
M = {'A': 1, 'B': 2, 'C': 4, 'W': 8}
t = 0.0; out = []
for it in sys.argv[1].split():
w, k = it.split(':'); n = 1
if '*' in k: k, n = k.split('*'); n = int(n)
for _ in range(n):
t += float(w)
if not k: continue
hold = 0.15
if len(k) > 1: hold = int(k[1:]) / 1000.0
out.append('%.3f:%d' % (t, M[k[0]])); out.append('%.3f:0' % (t + hold)); t += hold
print(','.join(out)); print(int(t * 1000) + 3000, file=sys.stderr)
+9 -9
View File
@@ -1,9 +1,9 @@
// node mkimg.js <paradise.bin> <guest firmware> <emu.bin> <out.bin> [lang en|de]
// The Paradise image with TamaEmu as the main program (as the Studio builds it), for devemu.py
const fs = require('fs');
const E = require('../../src/emu.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [rom, fw, app, out, lang] = process.argv.slice(2);
const r = E.emuPatch(rd(rom), rd(fw), rd(app), rd(__dirname + '/../stub_tpl.bin'), { lang: lang || 'de' });
fs.writeFileSync(out, r.rom);
console.log('device', r.device, 'blocks', r.blocks, 'big', r.big);
// node mkimg.js <paradise.bin> <guest firmware> <emu.bin> <out.bin> [lang en|de]
// The Paradise image with TamaEmu as the main program (as the Studio builds it), for devemu.py
const fs = require('fs');
const E = require('../../src/emu.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [rom, fw, app, out, lang] = process.argv.slice(2);
const r = E.emuPatch(rd(rom), rd(fw), rd(app), rd(__dirname + '/../stub_tpl.bin'), { lang: lang || 'de' });
fs.writeFileSync(out, r.rom);
console.log('device', r.device, 'blocks', r.blocks, 'big', r.big);
+6 -6
View File
@@ -1,6 +1,6 @@
// node upg.js <image with TamaEmu> <emu.bin> <out>: the program replaced as the Studio does (emuUpgrade), session kept
const fs = require('fs');
const E = require('../../src/emu.js');
const [img, app, out] = process.argv.slice(2);
const r = E.emuUpgrade(new Uint8Array(fs.readFileSync(img)), new Uint8Array(fs.readFileSync(app)));
fs.writeFileSync(out, r || fs.readFileSync(img)); console.log(r ? 'upgraded' : 'same');
// node upg.js <image with TamaEmu> <emu.bin> <out>: the program replaced as the Studio does (emuUpgrade), session kept
const fs = require('fs');
const E = require('../../src/emu.js');
const [img, app, out] = process.argv.slice(2);
const r = E.emuUpgrade(new Uint8Array(fs.readFileSync(img)), new Uint8Array(fs.readFileSync(app)));
fs.writeFileSync(out, r || fs.readFileSync(img)); console.log(r ? 'upgraded' : 'same');