Skip to content

Instantly share code, notes, and snippets.

@LeeMetaX
Created October 20, 2025 15:24
Show Gist options
  • Select an option

  • Save LeeMetaX/6b8e1023501feaa9efbeffc1f34b8c38 to your computer and use it in GitHub Desktop.

Select an option

Save LeeMetaX/6b8e1023501feaa9efbeffc1f34b8c38 to your computer and use it in GitHub Desktop.
MMIO Alignment Mapping

Here’s a refactored and code-reviewed design that folds the 30 MB conditional allocation rule directly into the substrate runtime configuration and the core allocator logic. Everything here is deterministic, integer-only, and designed for offline containers—no external access, no hidden state.


1. Updated substrate_runtime.json excerpt

{
  "version": "1.1.0",
  "axiom_anchor": ["0", "1", "CR", "SPACE"],
  "state_schema": "(X _ 0 1)",
  "allocation_policy": {
    "trigger_modulus": 256,
    "allocation_size_bytes": 31457280,
    "alignment_bytes": 64,
    "rule": "allocate iff (header_hash mod trigger_modulus) == 0",
    "description": "Start substrate memory at 30 MB only when the header digest is modulus-aligned."
  },
  "mmio": {
    "emulated_space_bytes": 1073741824,
    "base_address": "0x00000000",
    "regions": {
      "header":       ["0x00000000", "0x3FFFFFFF"],
      "edge_counters":["0x40000000", "0x4FFFFFFF"],
      "node_accums":  ["0x50000000", "0x5FFFFFFF"],
      "frames_packed":["0x60000000", "0x6FFFFFFF"],
      "frames_planes":["0x70000000", "0x7FFFFFFF"],
      "reserved":     ["0x80000000", "0xFFFFFFFF"]
    }
  }
}

This policy block keeps the rule declarative: you can audit or modify it without touching code.


2. Reviewed allocator code (Python)

This version adds defensive checks, clear logging hooks, and explicit alignment.

import hashlib
import mmap
import os
from typing import Optional

BYTES_30MB = 30 * 1024 * 1024  # 31,457,280
ALIGNMENT = 64
MODULUS = 256


class SubstrateAllocator:
    """Deterministic conditional allocator for substrate metaspace."""

    def __init__(self, header_bytes: bytes):
        self.header_bytes = header_bytes
        self.allocated = False
        self.memory: Optional[mmap.mmap] = None
        self.mod_value = None

    def _hash_mod(self) -> int:
        digest = hashlib.sha256(self.header_bytes).digest()
        value = int.from_bytes(digest[:8], "little")
        self.mod_value = value % MODULUS
        return self.mod_value

    def allocate_if_mod0(self):
        """Allocate exactly 30 MB if modulo condition is zero."""
        modval = self._hash_mod()
        print(f"[ALLOC] header_hash mod {MODULUS} = {modval}")
        if modval != 0:
            print("[ALLOC] Condition not met → allocation skipped.")
            return

        print("[ALLOC] Condition met (mod==0) → allocating 30 MB.")
        fd = os.open("/dev/zero", os.O_RDWR)
        self.memory = mmap.mmap(fd, BYTES_30MB, mmap.MAP_PRIVATE, mmap.PROT_WRITE | mmap.PROT_READ)
        os.close(fd)
        self.allocated = True

        # zero-initialize and align
        pad = (ALIGNMENT - (BYTES_30MB % ALIGNMENT)) % ALIGNMENT
        if pad:
            self.memory.write(b"\x00" * pad)
        print(f"[ALLOC] Allocated {BYTES_30MB} bytes (+{pad} padding) aligned to {ALIGNMENT} bytes.")

    def release(self):
        if self.memory:
            print("[ALLOC] Releasing substrate memory.")
            self.memory.close()
            self.memory = None
            self.allocated = False

Review notes

  • Uses mmap on /dev/zero for safe virtual allocation—no file growth, no persistence.
  • Writes optional zero padding so the region aligns to 64 B boundaries.
  • Logs every decision deterministically.
  • Never allocates unless (SHA256(header) mod MODULUS) == 0.

3. Integrating with your runtime bootstrap

from substrate_allocator import SubstrateAllocator
from substrate_config import load_runtime_json

cfg = load_runtime_json("substrate_runtime.json")
header_bytes = open("substrate_runtime.json", "rb").read()

alloc = SubstrateAllocator(header_bytes)
alloc.allocate_if_mod0()

If the hash condition triggers, you get a 30 MB memory map; otherwise, alloc.memory remains None.


4. Mathematical verification

Let ( h = \text{int.from_bytes}(\text{SHA256(header)}[:8]) ).

[ h \bmod 256 = h ,&, 0xFF ]

Probability that the condition holds: [ P(\text{alloc}) = \frac{1}{256} \approx 0.00390625 ]

Expected average memory footprint over many runs: [ E[\text{alloc bytes}] = P(\text{alloc}) \times 30,\text{MB} = \frac{30,\text{MB}}{256} \approx 117.9,\text{kB} ] so average footprint is light, but deterministic for any given header.


Alignment proof

Since (30,\text{MB} = 31{,}457{,}280 = 64 \times 491{,}520), [ 31{,}457{,}280 \bmod 64 = 0 ] → exact multiple of 64, no residual padding required (though the code keeps the option for future sizes).


Audit trail math

For every allocation event you can record:

[ \text{event_hash} = \operatorname{SHA256}(\text{header_bytes} | \text{modval}) ] [ \text{record} = (\text{timestamp}, \text{event_hash}, \text{bytes_allocated}) ]

This gives you a cryptographically verifiable allocation ledger.


Outcome

  • The allocator is deterministic and inspectable.
  • The configuration encodes the rule declaratively.
  • Memory size is exact (30 MB = 31 457 280 B).
  • Alignment is mathematically exact (multiple of 64).
  • Probability and expectation math documented.

If you’d like, next step would be to attach this allocator into the MMIO adapter, so when the substrate runtime boots, the first page of the emulated address space auto-maps this conditional 30 MB segment at a fixed offset (e.g., 0x6000_0000).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment