antegre.com
Work:Docs/NativeCall.guide

NativeCall

nativecall.library 1.8 · hypervisor 8 · A1200 + PiStorm32-lite + Raspberry Pi 4 · Emu68 1.1 · WinUAE x64 · MIT license

NativeCall runs the number-crunching parts of 68k Amiga programs on the ARM CPU (Cortex-A72, NEON) of the Raspberry Pi in a PiStorm running Emu68. Since version 1.8 the same kernels also run on the PC's x64 cores when the program runs in WinUAE. The program runs on every Amiga: without native calls the same code runs as 68k.

New in 1.8: kernels on the PC under WinUAE Without a Pi and hypervisor, nativecall.library 1.8 runs the kernels on the PC's x64 processor through WinUAE's uaenative.library. One program, unchanged, runs on the Pi (ARM), in WinUAE (x64) and on every Amiga (68k): one SDK, one kernel source, one 68k binary. Details and benchmarks.

Download: NativeCall-1.8.0.zip (1.9 MB: sources, SDK and ready-made binaries) and the NativeCall.pdf manual, from the v1.8.0 release. Source code: github.com/Sdursun/NativeCall.

ncdemo torus demo, 68k version
ncdemo, 68k path (Emu68 JIT, GCC): 640×480, 4096 triangles. The N key switches between the two paths.
ncdemo torus demo, native ARM version
ncdemo, native path (Cortex-A72): same scene, same program. 3.3× in this early measurement; 4.1× with three cores in 1.8.

What is it?

PiStorm is a board that plugs into the Amiga's 68000 socket and replaces the 68k CPU with a Raspberry Pi. Emu68, running on the Pi, translates 68k code into AArch64 code on the fly (JIT), and does it quite fast. But the 68k instruction set has no NEON vector instructions, no hardware CRC32 and no extra cores: one of the Pi 4's four cores runs Emu68, and most of the power sits idle.

NativeCall opens that power to 68k programs: the program stays a normal AmigaOS program, only the heavy computing functions (kernels) run as ARM code.

Hardware
Amiga 1200 + PiStorm32-lite + Raspberry Pi 4 Model B (Cortex-A72 1.5 GHz)
Emulator
Emu68 1.1.0-beta.1, unmodified
Pi side
A small hypervisor that stays resident at EL2 (armstub)
Amiga side
nativecall.library + SDK (VBCC and GCC)
PC side (1.8)
WinUAE 6.1 beta with native code allowed + nativecall-windows-x86-64.dll
Native compiler
gcc 14, -mcpu=cortex-a72 -mbig-endian -mcmodel=tiny
Build
Entirely in Docker (nativecall-sdk:1)

Architecture

The obvious route was adding a new 68k instruction to Emu68. Instead, Emu68 is left alone: the armstub that the Pi firmware loads at boot is replaced by a custom one. The stub drops from EL3 to EL2, leaves a small hypervisor there and starts Emu68 at EL1. Emu68 believes it runs as usual.

  EL3   Pi firmware ──► nativecall-armstub.bin
                              │
  EL2   ┌─────────────────────┴───────────────────────┐
        │  hypervisor (top of RAM, 2 MB)              │
        │  · doorbell trap      (HCR_EL2.TPC)         │
        │  · .narm modules, own page tables           │
        │  · idle cores (core 1 and 3)                │
        └─────────────────────┬───────────────────────┘
  EL1   Emu68 (core 0)  ──►  68k JIT  ──►  AmigaOS 3.2
                                              └─ your program + nativecall.library

The trap: dc civac

With the HCR_EL2.TPC bit the hypervisor traps Emu68's cache clean instructions (dc civac). The 68k CPUSHL instruction becomes exactly that instruction in Emu68, which gives a 68k program a door to EL2. The door only opens when the right doorbell is in the registers:

  • D0 = 'NCAL' and D1 = ~'NCAL',
  • A0: a 64-byte call block (starting with 'NCAL'),
  • CPUSHL DC,(A0) in supervisor mode.
Why a doorbell? The first version only looked for the 'NCAL' signature in memory. Random data in network buffers sometimes carried it, was handled as a bogus request and corrupted the buffers. Complementary values in two registers removed that possibility.

Big-endian

Emu68 runs AArch64 in big-endian mode (SCTLR_EL1.EE). So native kernels are compiled with -mbig-endian too and read 68k memory at the same addresses without any conversion. Pointers are 32-bit 68k addresses (converted with NC_PTR()). The PC under WinUAE is little-endian: see WinUAE x64.

Fault handling

Native code runs at EL2 with its own page tables: the low 16 MB (Chip RAM and the hardware area) is not mapped, so native code cannot write to Amiga hardware by accident. If native code faults, the hypervisor catches it and the call returns NC_ST_FAULT; NC_LastFault() gives ESR/FAR/ELR. The Amiga keeps running.

Anatomy of a call

  1. The program calls nc_call(k, NCK_scale, p).
  2. nativecall.library fills in the call block (operation, kernel number, params address) and rings the doorbell under Supervisor() and Forbid().
  3. Emu68 translates CPUSHL into dc civac, and the CPU traps to EL2.
  4. The hypervisor checks the registers and the block, saves the FP/NEON registers and calls the kernel.
  5. Result and status are written to the block, registers are restored, and Emu68 continues with the next 68k instruction.

The fixed cost of this round trip is about 10 µs. While native code runs, 68k interrupts and multitasking stop, so a single call should stay under ~1 ms. nc_run() splits big jobs into ~0.5 ms chunks; it learns the chunk size per kernel by measuring.

Multiple cores

Emu68 runs 68k on core 0 only. Since hypervisor 3, the idle cores 1 and 3 are captured through Emu68's own PMU access (MDCR_EL2.TPM) and the WFE trap (HCR_EL2.TWE), again without changing Emu68. nc_run_mp() spreads the job over these cores; with nc_start_mp() / nc_wait() the 68k program keeps running while the job runs in the background.

Writing a program

The rule is simple: everything that talks to AmigaOS stays in 68k, the computing goes into kernels. Kernels are written once; the SDK compiles them both for the Pi (a .narm module) and for 68k (the fallback). By default the .narm is embedded in the program, so the program is a single file. With NC_X64 := 1 in the Makefile the kernels are also compiled for the PC (no C library, 8–12 KB) and embedded as well.

sdk/nc image                # once: Docker image
sdk/nc new myprog           # main.c, myprog_kernels.h/.c, Makefile
cd myprog
../sdk/nc make              # VBCC -> build/vbcc/myprog
../sdk/nc make CC68=gcc     # GCC  -> build/gcc/myprog

1. Kernel header

The parameter struct must have the same layout with both compilers. NC_CHECK_SIZE and NC_CHECK_OFFSET check this at compile time: a mismatch becomes a build error, not silent data corruption.

#include <nativecall/kernel.h>

struct ScaleParams {
    struct NCRange range;   /* for nc_run(): [from, to) */
    NC_U32 samples;         /* NC_S16 * (68k address) */
    NC_S32 factor;
};

#define MYPROG_KERNELS(K) K(scale) K(peak)

NC_CHECK_SIZE(struct ScaleParams, 16)
NC_CHECK_OFFSET(struct ScaleParams, factor, 12)
NC_DECLARE(myprog, MYPROG_KERNELS)   /* NCK_scale = 0, NCK_peak = 1 */

2. Kernels

NC_KERNEL(scale)
{
    struct ScaleParams *p = params;
    NC_S16 *s = NC_PTR(NC_S16, p->samples);
    NC_U32 i;

    for (i = p->range.from; i < p->range.to; i++)
        s[i] = (NC_S16)((s[i] * p->factor) >> 8);
    return 0;
}

NC_KERNEL(peak)
{
#if NC_NATIVE
    /* NEON version */
#else
    /* 68k version */
#endif
}

NC_MODULE(myprog, MYPROG_KERNELS)

3. The 68k program

struct NCKernels *k = nc_open(&myprog_kernels);  /* falls back to 68k */
struct ScaleParams *p = nc_alloc(sizeof(*p));
NC_S16 *samples = nc_alloc(count * 2);

p->samples = (NC_U32)samples;
p->factor  = 300;
nc_run(k, NCK_scale, p, 0, count);                 /* in chunks */
nc_run_mp(k, NCK_scale, p, sizeof(*p), 0, count);  /* also on the idle ARM cores */
peak = nc_call(k, NCK_peak, p);                    /* single call */

nc_free(samples, count * 2);
nc_free(p, sizeof(*p));
nc_close(k);

API

FunctionWhat it does
nc_open(&set)Opens the library, loads the module (order: ENV → embedded → PROGDIR). Falls back to 68k if that fails.
nc_call(k, i, p)Runs a kernel once.
nc_run(k, i, p, from, to)Runs the range [from, to) in ~0.5 ms chunks.
nc_run_mp(...)Like nc_run, also on the idle ARM cores (3 in total). In WinUAE on a thread pool (logical processors minus one).
nc_start_mp / nc_done / nc_waitAsynchronous nc_run_mp: 68k continues while the job runs.
nc_is_native(k), nc_status(k)Whether it runs native; status of the last call (NC_ST_OK, NC_ST_FAULT, ...).
nc_stats(k, i, &s, reset)A kernel's native time: call count, total / longest / last (µs).
nc_alloc / nc_freeMemory the kernel can see (Fast RAM above 16 MB, cleared).
nc_addr_ok(p, size)Is this memory visible to native code? (~0.1 µs; in WinUAE all RAM is accepted)
nc_now_us()Cheap clock: reads the ARM counter (~2 µs; timer.device ~20 µs). In WinUAE it reads the PC clock, because the emulated clock misses the time spent in kernels.
NC_GET32 / NC_PUT32 ...Accessors for plain arrays in 68k memory: byte-swapped on the little-endian PC, free on the Pi.

Benchmarks

A1200 + PiStorm32-lite + Pi 4, AmigaOS 3.2. 4 MB of random data (Adler32, CRC32), 10,000 vertices × 4 floats (matrix). 68k: VBCC 0.9h -O2 -cpu=68040 -fpu=68040. Best of 5 runs.

TestImplementationTime (ms)Throughputvs 68k
Adler3268k19.86201 MB/s1.0×
Adler32native8.64463 MB/s2.3×
Adler32native + NEON2.771443 MB/s7.2×
CRC3268k (table)52.1177 MB/s1.0×
CRC32native (table)24.40164 MB/s2.1×
CRC32native + crc32x2.381679 MB/s21.9×
Matrix 4×468k FPU1.01151 MB/s1.0×
Matrix 4×4native0.23677 MB/s4.5×
Matrix 4×4native + NEON0.111388 MB/s9.2×

Demos

Library 1.7/1.8, hypervisor 8, 640×480 16-bit RTG. 68k: GCC -m68040 -mtune=68060 -mhard-float. “MP” is the three ARM cores; ratios are based on the frame's compute time.

Program68kNativeNative MPMP vs 68k
raydemo (ray tracing)1.9 fps11.4 fps33.6 fps18.4×
filterdemo (rotate + 3×3 filter)9.7 fps52.4 fps125.3 fps15.5×
nbodydemo (1500 bodies)6.0 fps24.4 fps61.0 fps10.9×
voxeldemo (terrain flight)40.7 fps98.1 fps198.3 fps6.0×
ncdemo (software 3D)50.4 fps159.1 fps204.6 fps4.1×
mandeldemo (NEON)71.6 Miter/s–592.8 Miter/s8.3×

Takeaway: Emu68's JIT already runs plain 68k code fast; in simple loops plain C gains only 2–2.5×. The real difference is in ARM-specific instructions: NEON and hardware CRC32 bring 7 to 22 times the speed.

WinUAE x64 (new in 1.8)

When there is no Pi and no hypervisor, nativecall.library 1.8 looks for WinUAE's uaenative.library. If it finds it, the kernels run on the PC's x64 processor through nativecall-windows-x86-64.dll in WinUAE's plugins folder. The program does not change: the same 68k binary uses the ARM cores on a PiStorm, the PC in WinUAE, and its own 68k code everywhere else.

  • SDK: NC_X64 := 1 in the Makefile compiles the kernels for the PC as well (no C library, 8–12 KB) and embeds them in the program; no extra file. v1.7.0 binaries also run, with a .nx64 file next to them.
  • Multiple cores: nc_run_mp / nc_start_mp run on a thread pool on the PC (logical processors minus one).
  • Faults: crashes, stack overflows and endless loops are caught (NC_ST_FAULT / NC_ST_TIMEOUT) and WinUAE keeps running. Logging (nc_printf), fault details with a backtrace (from the unwind tables), and NCLog/NCStatus work as on the Pi; NCLog STATS reports “WinUAE x64”.
  • Byte order: the PC is little-endian. Parameter structs are converted by the compiler; plain arrays use the NC_GET32/NC_PUT32 accessors, which cost nothing on the Pi (the examples' .narm modules are byte-for-byte the same as in 1.7.0). NEON paths are ARM only; the PC runs the plain C path.

Benchmarks on the PC

WinUAE 6.1 beta, 68060 with JIT, a PC with 24 logical processors (pool of 23 threads). 1280×720, release binaries (GCC); ratios are based on compute time. The PC computes a frame tens of times faster than WinUAE's 68k, so the emulation (the copy to the screen, the 68k part of the frame) becomes the limit.

Program68k (JIT)x64, one threadx64 poolPool vs 68k
raydemo1.9 fps16.7 fps147.0 fps96.5×
filterdemo4.9 fps59.7 fps420.7 fps129.6×
nbodydemo13.7 fps147.2 fps693.2 fps103.9×
voxeldemo21.7 fps314.0 fps344.1 fps24.9×
ncdemo95.6 fps499.6 fps946.5 fps9.9× (whole frame)

mandeldemo, the v1.7.0 binary unchanged, 640×480: from 58.5 Miter/s (68k) to 6044 Miter/s on the pool (103×). The 1.8 release binary at 1280×720: 8146 Miter/s (142×). mp3demo BENCH (20 s): x64 is 14.4× (GCC) and 26.1× (VBCC) faster than 68k; samples differ by at most 1.

Installation in WinUAE

  1. Copy nativecall-windows-x86-64.dll to WinUAE's plugins folder.
  2. Settings › Host › Miscellaneous › Allow native code (native_code=true).
  3. Copy nativecall.library 1.8 to LIBS:.
  4. NCLog STATS should say “WinUAE x64”.
Limits While a kernel runs, the emulation stands still: keep calls short. WinUAE 6.1 beta sometimes resets on a 640×480 AGA screen with WriteChunkyPixels, with or without NativeCall; run the demos on an RTG screen. Tested with WinUAE 6.1 beta 22/23 on one PC.

Rules and lessons

  • Batch your work. Each call has a fixed cost of ~10 µs; put at least a few hundred µs of work into a call.
  • One call ≲ 1 ms. Interrupts wait while native code runs.
  • Kernels must be idempotent. With nc_run_mp every core works on its own copy of params; a kernel must not write to params, and each chunk writes only its own output.
  • FPU = double. Emu68's FPU works in 64 bits, not 80.
  • GCC 68k: -m68040 does not enable the FPU, -mhard-float is required (otherwise 100 times slower).
  • No ADRP in native modules: -mcmodel=tiny and a check for PIC that is not 4 KB aligned.
  • QEMU first. Hypervisor changes are tried in a patched QEMU (raspi3b + unmodified Emu68) first, then on the real A1200.

Installation

The archive NativeCall-1.8.0.zip is on the GitHub release page; the ready-made files are in its binaries/ folder. For WinUAE, see Installation in WinUAE. On the PiStorm:

  1. Back up: copy config.txt from the SD card's FAT partition. From the Amiga: Mount SYS:Storage/DOSDrivers/MountFAT → EMU68BOOT:.
  2. Copy nativecall-armstub.bin to the root of the FAT partition.
  3. Add this below the arm_64bit=1 line in config.txt:
# nativecall: EL2 hypervisor armstub
armstub=nativecall-armstub.bin
  1. Power the Amiga off and on: the armstub is loaded only when the Pi boots; an Emu68 soft reset is not enough.
  2. Copy nativecall.library to LIBS:.

The hypervisor finds its place from the device tree at boot (2 MB from the top of the last RAM block); no setting is needed. If it sees a problem in the tree, it boots without the hypervisor.

Going back Putting a # in front of the armstub= line in config.txt is enough. Without the armstub, NativeCall programs keep working on the 68k path.

License

NativeCall is released under the MIT License. hypervisor/boot.S is under the BSD 3-Clause License, and minimp3 (used by mp3demo) is CC0. See LICENSE in the repository.