// mem.c - ESP32-S3 memory map (TRM ch. "System and Memory").
#include <stdio.h>//
// Internal SRAM is one physical block seen through several bus windows; SRAM1 in
// particular is aliased between the data bus (0x3FC8_8000) and the instruction bus
// (0x4037_8000) - the same bytes - which the ESP-IDF startup relies on when it
// copies .iram code in through the data bus and then executes it. We back each
// SRAM block with one array and expose all its windows onto it.
//
// External flash is memory-mapped by the MMU: instructions at 0x4200_0000 (IROM)
// and read-only data at 0x3C00_0000 (DROM). The app image segments already carry
// those virtual addresses, so the loader drops them straight in.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "mem.h"

// --- backing stores ---
#define SRAM0_BASE 0x40370000u
#define SRAM0_SIZE 0x8000u                  // 32 KB, instruction bus
static uint8_t sram0[SRAM0_SIZE];

#define SRAM1_SIZE 0x68000u                 // 416 KB, data+instr aliased
static uint8_t sram1[SRAM1_SIZE];
#define SRAM1_D_BASE 0x3FC88000u            // data-bus window
#define SRAM1_I_BASE 0x40378000u            // instruction-bus window (same bytes)

#define SRAM2_BASE 0x3FCF0000u
#define SRAM2_SIZE 0x10000u                 // 64 KB, data bus
static uint8_t sram2[SRAM2_SIZE];

#define RTCRAM_BASE 0x50000000u
#define RTCRAM_SIZE 0x2000u                 // 8 KB RTC fast RAM
static uint8_t rtcram[RTCRAM_SIZE];

// External flash, memory-mapped (32 MB on the 1.75C). We keep one buffer and
// expose both the IROM and DROM windows onto it (the loader fills the parts the
// image uses). The MMU page math below already addresses the full 32 MB space.
#define FLASH_SIZE 0x2000000u               // 32 MB
static uint8_t *flash;                      // heap
#define IROM_BASE 0x42000000u               // instruction window
#define DROM_BASE 0x3C000000u               // data window

// PSRAM (8 MB), mapped by the MMU into the same 0x3C.. / 0x42.. space above the
// flash mapping. Kept simple: a flat buffer the firmware can map/use.
#define PSRAM_SIZE 0x800000u
static uint8_t *psram;

// Mask boot ROM: code at 0x4000_0000 and a read-only ROM-data window at
// 0x3FF0_0000 (the ROM's RW data lives in SRAM1 at 0x3FCD_xxxx, already covered).
#define ROMCODE_BASE 0x40000000u
#define ROMCODE_SIZE 0x70000u
static uint8_t romcode[ROMCODE_SIZE];
#define ROMDATA_BASE 0x3FF00000u
#define ROMDATA_SIZE 0x20000u
static uint8_t romdata[ROMDATA_SIZE];

void mem_init(void) {
    flash = calloc(1, FLASH_SIZE);
    psram = calloc(1, PSRAM_SIZE);
    memset(sram0, 0, sizeof sram0);
    memset(sram1, 0, sizeof sram1);
    memset(sram2, 0, sizeof sram2);
    memset(rtcram, 0, sizeof rtcram);
}

uint8_t *mem_psram(uint32_t off) { return off < PSRAM_SIZE ? &psram[off] : NULL; }
uint32_t mem_psram_size(void)     { return PSRAM_SIZE; }

// Flash/PSRAM MMU translation. The cacheable data window (0x3C00_0000) and
// instruction window (0x4200_0000) are paged (64 KB) by the MMU table the 2nd-stage
// bootloader programs at 0x600C_5000. An entry maps a virtual page to a physical
// page in flash (bit15=0) or PSRAM (bit15=1); bit14=1 means invalid. This is the
// ONLY path from the cacheable windows to the chips — flash[] holds the raw flash
// image (bootloader@0, parttable@0x8000, app@0x10000), so the mapping is authoritative.
static uint8_t *mmu_xlate(uint32_t a) {
    uint32_t idx = (a & 0x1FFFFFFu) >> 16;         // 64 KB page within the 32 MB space
    uint32_t e = mmu_entry(idx);
    if (e & 0x4000u) return NULL;                  // invalid entry
    uint32_t off = ((e & 0x3fffu) << 16) | (a & 0xFFFFu);
    if (e & 0x8000u) return off < PSRAM_SIZE ? &psram[off] : NULL;   // SPIRAM page
    return off < FLASH_SIZE ? &flash[off] : NULL;                     // flash page
}

// Resolve an address to a host pointer inside a backing store (or NULL). The
// cacheable flash/PSRAM windows resolve ONLY through the MMU (no vaddr shortcut) —
// exactly as on silicon, where an unmapped page is simply not accessible.
uint8_t *mem_host(uint32_t a) {
    if ((a >= DROM_BASE && a < DROM_BASE + 0x2000000u) ||
        (a >= IROM_BASE && a < IROM_BASE + 0x2000000u)) {
        return mmu_xlate(a);
    }
    if (a >= SRAM0_BASE   && a < SRAM0_BASE + SRAM0_SIZE)   return &sram0[a - SRAM0_BASE];
    if (a >= SRAM1_D_BASE && a < SRAM1_D_BASE + SRAM1_SIZE) return &sram1[a - SRAM1_D_BASE];
    if (a >= SRAM1_I_BASE && a < SRAM1_I_BASE + SRAM1_SIZE) return &sram1[a - SRAM1_I_BASE];
    if (a >= SRAM2_BASE   && a < SRAM2_BASE + SRAM2_SIZE)   return &sram2[a - SRAM2_BASE];
    if (a >= RTCRAM_BASE  && a < RTCRAM_BASE + RTCRAM_SIZE) return &rtcram[a - RTCRAM_BASE];
    if (a >= ROMCODE_BASE && a < ROMCODE_BASE + ROMCODE_SIZE) return &romcode[a - ROMCODE_BASE];
    if (a >= ROMDATA_BASE && a < ROMDATA_BASE + ROMDATA_SIZE) return &romdata[a - ROMDATA_BASE];
    return NULL;
}

bool mem_is_ram(uint32_t a) { return mem_host(a) != NULL; }

static bool is_mmio(uint32_t a) { return a >= 0x60000000u && a < 0x60100000u; }

uint8_t mem_r8(uint32_t a) {
    uint8_t *p = mem_host(a); if (p) return *p;
    if (is_mmio(a)) { uint32_t w = mmio_read(a & ~3u); return (w >> ((a & 3) * 8)) & 0xFF; }
    return 0;
}
uint16_t mem_r16(uint32_t a) { return mem_r8(a) | (mem_r8(a + 1) << 8); }
uint32_t mem_r32(uint32_t a) {
    uint8_t *p = mem_host(a); if (p) return p[0] | (p[1]<<8) | (p[2]<<16) | ((uint32_t)p[3]<<24);
    if (is_mmio(a)) return mmio_read(a);
    return 0;
}
void mem_w8(uint32_t a, uint8_t v) {
    uint8_t *p = mem_host(a); if (p) { *p = v; return; }
    if (is_mmio(a)) { uint32_t w = mmio_read(a & ~3u); int s = (a & 3) * 8;
        w = (w & ~(0xFFu << s)) | ((uint32_t)v << s); mmio_write(a & ~3u, w); }
}
void mem_w16(uint32_t a, uint16_t v) { mem_w8(a, v & 0xFF); mem_w8(a + 1, v >> 8); }
void mem_w32(uint32_t a, uint32_t v) {
    uint8_t *p = mem_host(a);
    if (p) { p[0]=v; p[1]=v>>8; p[2]=v>>16; p[3]=v>>24; return; }
    if (is_mmio(a)) mmio_write(a, v);
}

uint8_t *mem_flash(uint32_t off) { return off < FLASH_SIZE ? &flash[off] : NULL; }
uint32_t mem_flash_size(void)     { return FLASH_SIZE; }

void mem_load(uint32_t a, const uint8_t *data, uint32_t len) {
    for (uint32_t i = 0; i < len; i++) {
        uint8_t *p = mem_host(a + i);
        if (p) *p = data[i];
        else { fprintf(stderr, "mem_load: unmapped %08X\n", a + i); return; }
    }
}
