# Windows 95 on an ESP32-P4 — tiny386 port to the Guition JC8012P4A1C

A port of [tiny386](https://github.com/hchunhui/tiny386) (Chunhui He's x86 PC
emulator) to the **Guition JC8012P4A1C**, a 10.1" ESP32-P4 development board.
It boots **Windows 95 OSR2** from a microSD card onto the board's 1280×800
MIPI-DSI panel, with USB keyboard and mouse.

This is a study project. Nobody needs Windows 95 in 2026 — the interesting part
is what it takes to make a 1995 operating system usable on a €20 microcontroller,
and the measurements that show where the time actually goes.

![Windows 95 desktop running on the board](docs/10-desktop.jpg)

*Not a screenshot — that is the board's own 10.1" panel. Calculator and Control
Panel open, Start menu cascaded three deep, driven by a USB mouse. The fine
vertical striping is real: Windows is running in 16-colour VGA and dithering the
desktop colour, which is [the next thing to fix](#still-open).*

![where the wall clock went](docs/01-wall-clock.png)

---

## Table of contents

- [What works](#what-works)
- [The board](#the-board)
- [Quick start](#quick-start)
- [What had to change, and why](#what-had-to-change-and-why) ← the point of this repo
- [Measurements](#measurements)
- [Things that did not work](#things-that-did-not-work)
- [Still open](#still-open)
- [Credits and licence](#credits-and-licence)

---

## What works

| | |
|---|---|
| Windows 95 OSR2 | boots to the desktop, ~155 s from reset |
| Display | 1280×800 panel, hardware-rotated and scaled by the PPA, zero CPU per pixel |
| Keyboard + mouse | USB HID through the OTG port (a powered hub works for both at once) |
| Disk | two IDE disks from files on the microSD card |
| Sound | Adlib OPL2 and SoundBlaster 16 through the on-board ES8311 codec |
| FreeDOS / MS-DOS | boots too, as a floppy or hard disk image |

Guest RAM is 16 MB, which is what keeps Windows from paging to the SD card.

> **Note on speed.** This is roughly a 386SX-class machine: usable, not fast.
> The desktop, Explorer, Control Panel, Paint, Calculator and DOS programs all
> work; you will not be running Office. See [Measurements](#measurements) for
> honest numbers.

---

## The board

**Guition JC8012P4A1C** — sold as a "10.1 inch ESP32-P4 development board",
also listed as JC8012P4A1 / ESP32-P4 10.1" HMI display.

| | |
|---|---|
| SoC | ESP32-P4 (dual-core RISC-V, 360 MHz) |
| PSRAM | 32 MB hex, 200 MHz |
| Flash | 16 MB, QIO 80 MHz |
| L2 cache | 512 KB (128 B lines) |
| Display | 10.1" 800×1280 IPS, MIPI-DSI 2-lane, **JD9365** driver IC |
| Touch | GSL3680 capacitive (not used by this project) |
| Audio | ES8311 codec + NS4150 amplifier |
| microSD | SDMMC slot 0, 4-bit — CLK 43, CMD 44, D0-D3 39/40/41/42, powered from **internal LDO channel 4** |
| USB | OTG host, on by default in this firmware |
| Wi-Fi | via a companion ESP32-C6 over SDIO — **deliberately not used**, see below |
| Backlight / LCD reset | GPIO 23 / GPIO 27 |
| Audio pins | MCLK 13, BCLK 12, WS 10, DOUT 9, I²C SDA 7 SCL 8, **PA enable GPIO 20** |

Board-specific definitions live in one place:
[`esp/main/board_jc8012p4a1c.h`](esp/main/board_jc8012p4a1c.h).

**Two board quirks worth knowing if you are bringing up anything else on it:**

1. The SD card is on **SDMMC slot 0**, not the slot-1 default, and the board has
   **no external pull-ups** on the SD lines — without `SDMMC_SLOT_FLAG_INTERNAL_PULLUP`
   the card never answers and you get error `0x107`.
2. The PA (amplifier enable) is **GPIO 20** on the 10.1" board. Other Guition
   boards in the same family use GPIO 11. Driving the wrong one leaves the
   amplifier permanently on, which makes the speaker hot.

---

## Quick start

### 1. Flash the firmware

Pre-built, single file, flashes to offset 0:

```bash
python -m esptool --chip esp32p4 -b 460800 -p COM1 write_flash 0x0 firmware/tiny386-jc8012p4a1c-merged.bin
```

Or build it yourself (ESP-IDF v5.4.x):

```bash
cd esp && idf.py -DBOARD=jc8012p4a1c build flash
```

### 2. Prepare the microSD card

Format it FAT32 and copy:

```
/bios.bin          (from sdcard/, SeaBIOS — included)
/vgabios.bin       (from sdcard/, SeaVGABIOS — included)
/tiny386.ini       (from sdcard/, edit to taste)
/hd.img            ← you provide this, see below
```

### 3. Provide a disk image

**No operating system is included in this repository**, and none will be. You
need a `hd.img` with a bootable x86 OS installed. Two ways:

**FreeDOS (free, five minutes).** Grab a FreeDOS install floppy image, set
`fda = /sdcard/fdboot.img` in the ini, boot it, and `FDISK` + `FORMAT` the
blank `hd.img`.

**Windows 95 (needs your own licensed copy).** Install it *on a PC* first —
`tiny386` builds for Linux and Windows, and installing on a desktop takes
minutes instead of hours:

```bash
make                                  # builds the host tiny386
truncate -s 512M hd.img
./tiny386 tiny386.ini                 # with fda=boot floppy, cdc=win95.iso
```

Then copy the finished `hd.img` to the SD card. Notes from doing exactly that:

- Put the CD on **`cdc`** (secondary master), not `cda` — `cda` and `hda` share
  a slot in the config parser and the CD will hide your hard disk
  (`No fixed disks present`).
- Partition the image with LCHS 1024/16/63 geometry and partition type `0x0E`,
  or Windows' ScanDisk will complain about the last cluster.
- Set the BPB heads field to 16, not 32, or you get `Disk I/O error` at boot.
- Remove `DOS=HIGH` from the boot floppy's config — Windows 95 Setup needs the
  HMA free, otherwise it stops with *"Cannot start Windows in standard mode"*.
- If Windows 95 Setup dies at **`While initializing device IOS: Windows
  protection error`** on your PC, that is a genuine Windows 95 bug, not the
  emulator: its CPU speed calibration loop divides by a value that overflows on
  fast machines. It does not happen on the ESP32-P4 because the board is slow
  enough. On a PC, throttle the emulator to ~15 MIPS and it disappears.

### 4. Boot

Plug the card in, power up. The SD card is read at ~150 ms into boot, so it must
be inserted before power-on. Same for USB input devices.

Give it around 155 seconds to reach the desktop, and expect a long stretch of
black screen on the way — it is working, not hung. If the board lost power while
Windows was running, the first boot back runs ScanDisk and waits for a keypress:

![ScanDisk on first boot](docs/12-first-boot-scandisk.jpg)

`Fix It` on everything and `Skip Undo` when it offers an undo disk. Shut down
through *Start → Shut Down* to avoid it next time.

![Start menu](docs/11-start-menu.jpg)

---

## What had to change, and why

Upstream tiny386 already runs on ESP32-S3. Everything below is what the P4 port
needed on top of that, or what the profiling turned up. Each item says what the
symptom was, because the symptom is usually the interesting part.

### Display

**The panel is portrait, the guest is landscape.** The JD9365 is physically
800×1280; the PC console is 1280×800. The ESP32-P4's **PPA** (Pixel Processing
Accelerator) does the 90° rotation *and* the scale to fill the panel in
hardware, straight into the DPI frame buffer — no CPU per pixel, and no
intermediate copy. The active video mode is scaled to fill the screen the way a
CRT stretches whatever it is fed, so 720×400 text and 640×480 graphics both fill
the panel.

**Bright white flashes.** The DPI FIFO was underrunning because the emulator,
the PPA and the panel all share the PSRAM bus. Dropping the pixel clock from
60 MHz to 30 MHz keeps the panel fed. (The Wireless-Tag P4 fork landed on the
same conclusion independently.)

**Colour speckle.** Handing the PPA a pointer into the middle of the framebuffer
broke its cache synchronisation. Fixed by passing a cache-aligned base pointer
plus a block offset (`ppa_rotate_90cw_scaled_off`).

**Graphics modes appeared in the wrong place.** `vga.c` centres non-full-width
modes in the framebuffer through an `i0` byte offset, but the code that tells
the presenter which rectangle to show was hard-coded to `(0,0)`. A 640×480 DOS
mode therefore presented the wrong region. The rectangle is now derived from
`i0`.

**Two out of every three frames were computed and thrown away.** The VGA raster
fires a refresh ~33×/s, the panel is presented ~10-20×/s, and `vga_refresh()`
converts the whole 1280×800 frame — about 4 MB of PSRAM traffic — every time it
is called. The conversion is now gated to the present rate (`pc_vga_refresh_gate`
in `pc.c`). `vga_step()` still runs at full rate: guests poll the vertical
retrace bit at port 0x3DA and hang if the raster stops advancing.

**...and then most of the surviving frames were dropped anyway.** The gate was
closed on the same poll that opened it, but a refresh only happens on the VGA
raster's own retrace tick, which does not line up with the 5 ms poll. It now
closes on a frame that actually reached the panel. This one was invisible until
the firmware started reporting its own frame rate.

**Frames with nothing new in them.** Every present costs a whole-panel PPA write
(2 MB) plus the conversion, and it was happening 15×/s on a desktop that was not
changing. Every write that can change the screen — video memory through any of
the four `vga_mem_write*` entry points, or a VGA register — now sets a dirty
flag, and an undirty frame is skipped entirely. Only valid while the classic VGA
apertures are in use: with VBE the guest writes the linear framebuffer directly
and the flag cannot see it.

**Per-pixel divide in the inner loop.** The graphics converter divided by `xdiv`
once per pixel — a real RV32 hardware divide, roughly a million of them per
frame. `xdiv` is only ever 1 or 2, so it is a shift now. The paired byte stores
were merged into one 16-bit store while there.

**Present rate scales with the mode.** The fixed cost is the whole-panel PPA
write, so 640×480 and 1024×768 come within ~15% of each other and both run at
20 fps, where a moving mouse pointer stops looking broken. Only a native
1280×800 desktop doubles the total and has to stay near 10 fps.

### Disk — this was the whole ball game

**Windows was spending 97% of its wall clock waiting for the disk.** Not
inferred; measured. The firmware prints a `[perf]` line every 10 s splitting the
wall clock into *executing*, *halted*, and *blocked on disk*:

```
[perf] t=174s 0.02 MIPS 15.3 fps | halt 0% | disk 97% 1038 rd 1038 sec
```

1038 single-sector reads in 10 seconds, at ~9 ms each.

**The card was innocent.** Same driver, four paths above it:

![cost of one sector](docs/02-sector-cost.png)

Raw `sdmmc_read_sectors()` took 0.36 ms — and the same 0.36 ms with an
unaligned destination, and with a destination in PSRAM, so buffer placement was
not it either. The card negotiated 40 MHz 4-bit. The 25× was somewhere in the
filesystem stack.

**The clue that identified it** was that the cost scaled per *byte*, not per
call:

![read size](docs/03-read-size.png)

512 B, 4 KB, 32 KB and 64 KB reads all came out at 55 KB/s. That is the
signature of newlib's **unbuffered** refill path, which reads one byte at a
time: a 512-byte sector became 512 round trips through VFS and FatFs.

The `setvbuf(_IONBF)` responsible was added *earlier in the same session*, as an
optimisation, on the reasoning that stdio's buffer could never be reused because
every read seeks first. The reasoning was correct. The conclusion was wrong.

**The fix is a real block cache** ([`ide.c`](ide.c)): 4 KB lines, 2 MB,
direct-mapped, write-through, with stdio's buffer sized to exactly one line. A
buffer much *larger* than the line is bad in the other direction — a 32 KB
buffer turns a random 512-byte read into a 45 ms refill. Windows re-reads the
same registry, VMM and font sectors constantly, so the cache runs at **78-87%
hits** and disk time fell from 97% to 0-36%.

![boot time](docs/04-boot-time.png)

**A dead end worth recording:** `CONFIG_FATFS_USE_FASTSEEK` does nothing here.
ESP-IDF only builds the cluster link map for files opened **read-only**
(`vfs_fat.c`: *"fast-seek is only allowed in read mode, since file cannot be
expanded to use it"*), and the emulator needs write access.

### CPU and scheduling

**`HLT` does not mean the guest is idle.** The first version of the idle path
yielded a full FreeRTOS tick whenever the guest halted, on the theory that a
halted guest needs nothing. Most halts are microsecond waits for a disk or
keyboard IRQ, and a Windows boot does tens of thousands of them — the tick was
adding minutes to the boot. It now spins first (the device poll runs each time
round and delivers the interrupt as soon as it exists) and only sleeps if the
guest is *still* halted.

**The compiler was crippling the interpreter.** ESP-IDF builds everything with
`-fno-jump-tables -fno-tree-switch-conversion`. For a 256-way opcode switch that
is the single most expensive default in the build — it degrades into a chain of
compares. The emulator's hot files are compiled with
`-O3 -fjump-tables -ftree-switch-conversion` instead
([`esp/main/CMakeLists.txt`](esp/main/CMakeLists.txt)).

**Device polling was four times more frequent than it needed to be.**
`PC_STEP_COUNT` was 512 instructions, inherited from the smaller boards. The
poll block it guards — PIT, CMOS, keyboard, NE2000 and two DMA controllers —
costs about as much as a few hundred emulated instructions. At 2048 the guest
still sees every device within ~0.2 ms.

**The OPL was written from one core while the other rendered it.** The emulation
core writes OPL registers; the audio task renders samples from the other core,
with no synchronisation. That corrupts FM state rather than just tearing a
sample. Both sides take a spinlock now.

**Guest RAM 12 MB → 16 MB.** The PSRAM pool is a bump allocator covering guest
RAM + guest VGA RAM + the 2 MB console framebuffer; the rest of the 32 MB goes
to the two DPI frame buffers, USB, FatFs and stacks. Raising the pool to 22 MB
buys the guest 16 MB, which is the difference between Windows paging to the SD
card on every window it opens and not paging at all.

### Bring-up

**No Wi-Fi, on purpose.** `esp_hosted`'s auto-init grabs the SDMMC host for its
SDIO link to the companion ESP32-C6 and breaks the SD card. The dependency is
excluded entirely (`BOARD_NO_WIFI`), which also keeps the project on ESP-IDF
5.4.x and leaves all the PSRAM bandwidth to the emulator. NE2000 still links
against the packet hook, which is set to NULL.

**The SD card needed a cold power cycle** after the slot fix — a soft reset was
not enough for the card to re-run its init sequence.

**IRAM budget.** `cpu_exec1()` is the hottest code in the system but measures
135 KB and does not fit the IRAM segment, so it runs from cached flash. The hot
*helpers* (TLB, translate, segment checks, flags) are `IRAM_ATTR` and do fit,
which is where most of the win is. The TLB itself is explicitly allocated with
`MALLOC_CAP_INTERNAL` — it sits at exactly ESP-IDF's "always internal"
threshold, close enough to the edge to be worth asking rather than hoping, and
the boot log now prints where it landed.

---

## Measurements

All numbers from the board's own serial console. Enable them by watching the
UART at 115200 — the firmware prints a line every 10 seconds:

```
[perf] t=208s 1.48 MIPS 8.5 fps | halt 0% | disk 0% 0 rd 0 sec | cache 84% (512/608) | heap 5366072
```

| | before | after |
|---|---|---|
| Wall clock blocked on disk | 97% | 0-36% |
| One 512-byte sector read | 9.0 ms | 0.21 ms amortised |
| Disk cache hit rate | — | 78-87% |
| Reset → Windows 95 desktop | ~245 s | ~155 s |
| Emulated CPU, not disk-bound | | ~1.5 MIPS |
| Free heap with everything running | | ~5.3 MB |

**Reading the MIPS number:** it is low while the guest is idle, because the halt
path spins before sleeping — those spins burn wall clock without executing guest
instructions. ~1.5 MIPS is the figure to compare against; it puts the machine
around a 386SX.

`tools/make_charts.py` regenerates the figures.

The photos on this page are of the board's own panel, taken during the session
these numbers came from.

---

## Things that did not work

Recorded so nobody repeats them.

- **`CONFIG_FATFS_USE_FASTSEEK`** — no effect. ESP-IDF only builds the cluster
  link map for read-only files.
- **Shrinking the L2 cache to buy IRAM for `cpu_exec1()`** — the P4 splits one
  768 KB L2MEM between cache and RAM, so 256 KB of cache should free 512 KB of
  SRAM. The IRAM segment the linker places code into does not grow with it. The
  link fails at both 256 KB and 128 KB with `--enable-non-contiguous-regions
  discards section`.
- **`setvbuf(_IONBF)` on the disk image** — see above. Made it 12× slower.
- **Sleeping a FreeRTOS tick on `HLT`** — see above. Added minutes to the boot.

---

## Still open

- **Windows is running in 640×480 with 16 colours**, which is the worst possible
  mode for an emulator: VGA planar mode spreads one pixel across four bit
  planes, so every pixel the GUI draws goes through emulated latch and
  plane-mask logic instead of a memory write. It also dithers, which shows up as
  vertical stripes on the panel. A VESA/VBE driver would give Windows a linear
  framebuffer — tiny386 emulates Bochs VBE with no resolution limit, and the
  emulated adapter reports PCI ID `1234:1111`, which
  [vmdisp9x](https://github.com/JHRobotics/vmdisp9x)'s `qemumini.drv` matches
  exactly. Not done here because the driver is third-party; the ingredients are
  all in place.
- **Whether Windows is using 32-bit disk access** or has fallen back to MS-DOS
  compatibility mode — the latter would route every disk access through
  real-mode BIOS calls, which are expensive under emulation. Check
  *My Computer → Properties → Performance*.
- **`-O2`/`-Os` for `i386.c` instead of `-O3`.** `-O3` inlines aggressively and
  grows the code, which can lose to a smaller build when the problem is cache
  residency. Untested — the harness to measure it is in place.
- The interpreter costs roughly 240 host cycles per guest instruction, which is
  high. Where they go has not been established.
- Touch (GSL3680) is not wired up. Upstream has asked for touch support.

---

## Credits and licence

- **[tiny386](https://github.com/hchunhui/tiny386)** by Chunhui He — the
  emulator this is a port of. BSD 2-clause, see [LICENSE](LICENSE). Upstream's
  own README is kept as [README.upstream.md](README.upstream.md).
- **SeaBIOS / SeaVGABIOS** — LGPL, included in `sdcard/`.
- Peripheral models ported from **TinyEMU** and **QEMU**.
- The display path reuses the JD9365 bring-up and PPA present pipeline from my
  [Doom on ESP32-P4](https://github.com/winitboonkliang) projects on the same
  board.
- The [Wireless-Tag ESP32-P4 fork](https://github.com/Wireless-Tag) was useful
  for confirming the DPI clock behaviour.

No Microsoft software is included in this repository, and none will be
accepted. Bring your own licensed copy.
