Building z86: Lessons from Implementing an Out-of-Order x86 CPU on FPGA

(nand2mario.github.io)

45 points | by zdw 2 days ago ago

19 comments

  • mercnz 2 days ago

    i've been trying to play with cpu design on sipeed fpga's and i'm really struggling with none of the gw5a parts having working ssram but running out of space on gw2a. managed to dual core rv32 on gw2a, then struggle on tang console 60k with the balance between luts and hitting routing limits vs bram. i'm curious if you tried pushing any of this far on sipeed parts or basically gave up with the lack of sram.

    i have tang primer 25k, tang mega 138k, tang console 60k, and tang console 138k. none have working ssram. apparently some of them may have had post-release ones but it seems that the tang console 138k shipped with the old revision still.

    so my attention has moved towards the idea of jit/dbt and doing pipeline decode and so forth hoping that can process stuff quicker with the inability to have large caches due to routing pressure from larger caches impeding both clock rates and ability to fit. i realise it's kind of nice being predictable with times though for compatability and so forth, but the idea of doing full x86 on a cpu core is scary with all the edge cases. i've got basic x86 and rv32imac translation working with preprocessing, and managed to do well on coremark hitting sram, but scaling that to wider workloads with slower memory etc is pretty non-linear i suspect.

    i'm curious what is good for benchmarking in between super complex workloads and super simple; atm i've only gone as far as simple checks/tests, coremark, zstd, and starting to look at parts of my compiler, but i have my own dos emulator with built in x86 cpu emulation, it's like my 3rd or 4th dos project, before that i tried v86 mode etc, but cpu emulation really is easier to debug, with interpreter or x86_64 jit (much easier to do x86 on x86_64 than other systems) so i can cluster out simple functions or such to test (my dos emulator actually is inspecting executables and running them and and can for instance replace turbo pascal overlay system, and it's easy to do turbo pascal programs to do a specific functional benchmark and test that component.

    i both hate x86 and really want to do better on x86 at the same time, and was fascinated by the idea of the likes of z486/486tang, but it seemed kind of sluggish, and i kind of made my own x11 based remote keyboard/mouse app for it, but the mouse wasn't quite working well and i had no working netowrk and quickly moved on. i can't even remember if it had network, but i was in straight dos, i've got working network over usb2 on tang console i suppose potentially do some coexist thing, but i didn't manage to get linux to work on the ae350 cpu core even though it works on my network boot sbi system. but like every time i go down the path of all of this stuff i'm like i want network storage, network upload/download of files, restart, remote control etc.

    the idea of using lockstep to do cpu development is how i managed my 68k cpu core originially but i did rv32 without, and i only did rv32 as a distraction after 68k being complex was getting frustrating. and 68k is easier than x86 :) even after using test386.asm on my x86 interpreter i kept hitting bugs and things not quite working right, and windows 98 was kind of fiddly, and then os/2 had it's own issues. i've been doing virtio-blk and virtio-net with os/2 and windows 98 to expose disk/network and replaced the tcp/ip stack on both of them to get better offload for running in virtual machine or my dos emulator, and did linux on the sipeed fgpa's with virtio-blk/virto-net from my custom smbi supervisor so that i didn't need linux to see microsd/my weird ethernet. but potentially doing similar for x86 type os could work well, i suspect they'd struggle with normal speeds too, i'm at 100 megabit on tang primer 20k, and up to like 120 to 170 megabit/sec on console 60k depending on cpu for the netboot part.

    • nand2mario a day ago

      I've had similar experiences with the Gowin parts. The original z386 actually ran on the Tang 138K before I moved development to the DE10-Nano. Missing SSRAM, routing congestion and achievable clock speeds were all challenges. Also for larger designs, Xilinx toolchains and parts are still somewhat superior.

      For benchmarking, I find DOS games quite useful as intermediate workloads. 3DBench, Doom, and Quake exercise different aspects of the CPU and memory subsystem, and simulating these with Verilator is still feasible. After that I go to Windows and Linux as system/protected mode workloads. Dhrystone is also useful for measuring integer IPC, although it's a much simpler workload.

      I can definitely relate to the love-hate relationship with x86. The sheer complexity makes it frustrating, but getting decades-old software to run correctly on a CPU you designed yourself is satisfying.

  • nand2mario 2 days ago

    Author here. Happy to discuss FPGA development and retro CPU design.

    • peterfirefly 9 hours ago

      Did you use the same REP STOS/MOVS/etc trick that the P6 does?

      (I don't know if it actually does but Intel has a patent on it -- I forgot to write down the patent number, sorry.)

      It emits a short fixed-length burst of STOS/MOVS/etc µops first before (optionally) going into a loop. The µops from the burst are special: they are predicated on the value of (E)CX so if it's a short enough string operation, the extra µops don't do anything. They use a small immediate field to say something like "execute me if (E)CX < 2", "execute me if (E)CX < 3", etc.

      It's a small performance optimization.

      • nand2mario 8 hours ago

        I think the patent you're referring to is US 5,404,473 ("Apparatus and method for handling string operations in a pipelined processor").

        Yes, the real P6 implements it. The microcode unrolls 8 elements that decrement (E)CX at every element (saturating at 0 via SUB.NZ) and gate each load/store on (E)CX != 0 (LOAD.NZ / STA.NZ). That lets the core get higher OOO throughput without microbranches on every element (e.g., for 4-byte MOVSD/STOSD, one 8-element body covers 32 bytes).

        One more thing: P6 actually has a separate 4×64-bit cache-line fast-string loop for even larger, aligned copies.

        z86 implements this hardware mechanism in RTL as well (LOAD.NZ / STA.NZ / SUB.NZ plus the US5404473 MS loop counter), while in microcode/src/strings.asm we currently use the MS loop counter for 4×64-bit 32-byte fast strings + a 1-element scalar loop rather than the 8-way .NZ unroll.

        • peterfirefly 8 hours ago

          (Hacker News keeps auto-killing your comments. I have no idea why.)

          So there's room for some (fairly easy) optimization then. Do you know vaguely how much/little performance you are leaving on the table?

          • nand2mario 5 hours ago

            There are now some measurements. For example:

            Benchmark Kind z86 uops PPro uops | z86 cyc PPro cyc Ratio Status / Notes ------------------------------------------------------------------------------------------------ haz_rep_movsd_256 kernel 2.78 2.86 | 1.70 1.33 1.28x [WARN ] REP MOVSD 256 dwords (1 KB) cycles/dword (PPro fast strings) haz_rep_stosd_256 kernel 1.88 2.24 | 1.30 1.20 1.09x [OK ] REP STOSD 256 dwords (1 KB) cycles/dword (PPro fast strings)

            So for rep movsd, z86 is 1.70 cycles per dword and ppro is 1.33 cycles per dword. So it seems z86 is slower but not terribly slower.

            This is part of a large suite of instruction timings, the result I've just uploaded, if you are interested: https://github.com/nand2mario/z86_pc/releases/download/v0.2/...

    • peterfirefly a day ago

      The P6 does something quirky with its instruction cache, at least according to the patents. There's a 2-way L1 cache + a victim cache, and all prefetched instructions + all µops in the system have to come from bytes that are still in that L1 + victim cache. That allows the P6 to correctly refetch the exact same bytes and decode them to the exact same µops if it ever needs to -- which it sometimes does, for some reason I don't quite understand yet. The early NexGen/AMD patents also talk about refetching and redecoding but without documenting a system that would ensure the refetching would be exact.

      That system is also used to detect self-modifying code -- all writes are checked against the L1 + victim cache and if there is a match, then the whole reordering machine gets flushed. It's really just a way to get to use fewer, narrower comparators.

      The victim cache and the µop system cooperate in order to free up place in the victim cache once the µops that correspond to a line are gone from the system. That is done by sending a special µop through the system (that's what the relevant patent implies). Once that µop retires (or that group of µops? the mechanism isn't spelled out in detail), the corresponding victim cache line is freed.

      How much of that is simulated by your system?

      ---

      The µop width is implied to be somewhere around 116 bits (from memory) in one or two of the patents, but what the reverse engineers found was something a lot narrower. Do you have a theory that explains it?

      ---

      Do you know why they bothered to have TRANSPORTUIP when they could have used a move-immediate µop instead?

      • nand2mario a day ago

        1. Victim cache & SMC. z86 does not implement the L1I victim cache or retirement-marker uops. On real P6, the victim cache guarantees the original macro-instruction bytes are still around if the core has to refetch and re-decode them (for example on microbranch mispredictions - yes, P6 speculatively executes past uop-branches and restarts on mispredict - or faults/assists inside multi-uop flows). z86 avoids refetching by retaining the active macro's decode/alias context in the decoder/MS until retirement, and handles SMC by probing L1I tags and in-flight fetch lines on stores (plus stalling fetches that overlap buffered stores) and flushing at the store's senior boundary.

        2. ~118-bit vs. narrower uops. It's Cuop vs. Auop (as I wrote up in https://nand2mario.github.io/posts/2026/p6_basics/). What reverse engineers dumped from the MSROM are compact Cuops (72 bits per uop inside a triad + sequence word), where registers are still unexpanded alias placeholders (MAR/UAR) and immediates are compact/indexed. Downstream in the decoder, alias muxes merge the Cuop with the x86 instruction's architectural registers, immediates/displacements, and decoded execution/routing controls into the wider Auop (~118 bits in P6 patents/textbooks, still not sure in actual hardware).

        3. Why TRANSPORTUIP instead of a move-immediate uop. The uIP target isn't carried in the normal immediate field - TRANSPORTUIP reuses the microbranch target encoding (U_JMP/U_JCC) so it can encode the full 14-bit uIP directly.

        • peterfirefly a day ago

          > handles SMC by probing L1I tags and in-flight fetch lines on stores (plus stalling fetches that overlap buffered stores) and flushing at the store's senior boundary.

          Is that enough? Don't you risk some of the L1I lines getting pushed out while their µops are still somewhere in the reordering machinery? Unless you are adding an address tag for every µop, somehow... maybe that's what you are saying you do?

          > The uIP target isn't carried in the normal immediate field

          And that's my point. Why not? Why add a special µop for this when it seems a normal move with an immediate source would do the job? I mean, the µcode assembler would know the address, right?

          I accept that it exists and that they chose that path, I just don't understand why and I would really like to understand why. I was hoping you had figured out why.

          • nand2mario 21 hours ago

            I think you are probably right about the victim cache and SMC. In theory the L1I could go away. SMC is a reason for the victim cache.

            For TRANSPORTUIP, the in-cuop immediate field is only 9 bits. So it's not enough for UIP. Larger immediates go to the CROM (constant ROM). So one reason to reuse the micro-branch-like encoding is to save CROM space.

            • peterfirefly 9 hours ago

              Ah, that's why. I thought it would have been easier to combine the 9-bit field with one of the other fields -- for example L2src, which they already do in some cases.

    • peterfirefly a day ago

      Wait a minute... I just noticed something.

      Did you manage to drastically code golf the size of your new µcode?

      Yours:

      > 1,526 three-µop lines

      Theirs:

      > MSROM holds 4,096 triad rows

      • nand2mario 21 hours ago

        Yes! The z86 microcode is considerably shorter than the actual P6 microcode. The Pentium Pro 0619h's MSROM actually uses a little over 3,000 triad rows.

        There are a couple of reasons for this:

        1. The P6 MSROM contains built-in self-test (BIST), microcode patching, and other maintenance routines that z86 doesn't need.

        2. z86 currently lacks some performance optimization mechanisms, such as micro-aliasing (macro-aliasing is already implemented). As a result, some system instructions are slower and use simpler microcode sequences. However, these mechanisms are rarely needed by user-mode code, where z86 actually achieves higher IPC.

        • peterfirefly 9 hours ago

          How does your decoder(s) handle instructions with two immediate fields (disp32 + imm32)? If I remember the patents correctly, the p6 decoder block emits 4 µops for them, mostly as a way to store the 64 immediate bits: 2-3 µops whose only job is to carry immediate bits 1-2 µops that actually do something (and which reference the others).

          If you can afford to have wider µops, then it becomes much easier, plus you no longer need to create a "sideways" reference mechanism to get at the immediate bits later.

    • RetroTechie 2 days ago

      Great stuff, very impressive!

      The specific projects on your site (including this one), what made you decide to pursue those? I guess I'm asking to shed some light on the journey that got you into this stuff?

      • nand2mario a day ago

        It started with NESTang (NES for Sipeed Tang FPGAs), which was mostly driven by curiosity about how the Nintendo NES worked. I gradually moved on to more sophisticated game consoles. The GBA project was particularly fun, as I had to adapt a new CPU core to make it work on the Tang FPGA. Since then, CPU design itself became the main focus, and that's what led to the x86 projects.

    • dmitrygr 8 hours ago

      Brilliant! Thank you for this thrill

    • tucnak 2 days ago

      No questions just came here to say nand2mario you're a legend! I don't care about retro gaming whatsoever, but I did enjoy your writing, it's very instructive, and learned lots about SV design from your blog. I've been slowly trying to wrap my head around NIC designs on VCU1525 board, or rather banging my head against Vivado. It would help LOTS if you went into how you're dealing with Vivado yourself. So very little resources on it, and LLM's are not too much help unfortunately.