Automated hardware specification extraction and bare-metal C++ microkernel porting documentation from Linux kernel driver C code.
Kernelite Prism (kernelite-prism / kprism, v0.2.0) is an AI-driven static analysis and specification extraction pipeline built to accelerate porting Linux device drivers to bare-metal C++ microkernels.
By combining deterministic Tree-sitter C AST pre-processing with schema-constrained LLM extraction, Prism parses Linux kernel driver source trees (.c and .h) and generates two verified artifacts:
- Machine-Parsable Specification (
driver_spec.json/ YAML): A strictly typed artifact conforming to JSON Schema Draft 2020-12 (schemas/driver_spec.schema.jsonandsrc/schemas/driver_spec.schema.json), containing register maps, bitfields, isolated offset formulas, chronological.probeinitialization steps, DMA setup, and interrupt lifecycles for automated C++ code generation. - Human-Readable Specification (
DRIVER_SPEC.md): Self-contained Markdown documentation featuring register memory tables, Mermaid.js initialization and interrupt sequence diagrams, abstract concurrency lock mappings, and a C++20 bare-metal driver skeleton (microkernel::drivers::<driver>::<Driver>Driver).
[ Linux Source Code (.c, .h) ]
β
βΌ
[ Tree-sitter C AST Parser ] βββΊ Extracts register macros, bitmasks, driver structs,
(ast_parser.py & aggregator.py) MMIO/IRQ/lock/DMA calls; strips kernel boilerplate
β
βΌ
[ Constrained LLM Engine ] βββΊ Enforces driver_spec.schema.json via Transformers,
(extractor.py) Outlines, OpenAI Structured Outputs, or Instructor
β
βββββββββ΄ββββββββββββββββββββββββ
βΌ βΌ
[ driver_spec.json ] [ Verification Harness ]
(models/ & serializer.py) (validator.py: Schema + AST Grounding + Parity)
β
βΌ
[ Jinja2 + Mermaid Generator ] βββΊ [ DRIVER_SPEC.md ]
(doc_generator.py) (Register Tables, Sequence Diagrams, C++20 Notes)
- AST Pre-Processing & Token Optimization: Uses
tree-sitter-c(ASTPreProcessor,parse_driver_ast,safe_eval_c_constant) to extract#defineregister offsets, function macros,BIT()/BIT_ULL()/GENMASK()/GENMASK_ULL()/ shift bitmasks,MODULE_*/module_param*metadata, driver structs (platform_driver,pci_driver,virtio_driver,uart_driver,console,net_device_ops,uart_ops,file_operations,of_device_id,pci_device_id,usb_device_id,acpi_device_id,i2c_device_id,spi_device_id,platform_device_id,hid_device_id), and MMIO/IRQ/lock/DMA calls (readl,writel,ioread32,iowrite32,request_irq,spin_lock_irqsave,mutex_lock,dma_alloc_coherent,devm_ioremap_resource), while optionally strippingMODULE_*/EXPORT_SYMBOL*boilerplate, debug logging (dev_dbg,pr_debug,netdev_dbg,v4l2_dbg), andCONFIG_PMblocks. - Context Aggregation & Token Budgeting: Collects
.cfiles and matching sibling/explicit.hheaders (collect_driver_files,aggregate_context,aggregate_with_ast,estimate_tokens) with configurable warning and VRAM-safe token budgets (--max-tokens, default16000), automatically compacting oversized contexts to AST macros, driver structs, and key MMIO/IRQ/probe/DMA functions. - Deterministic Register Grounding: Evaluates C constant expressions safely and verifies extracted offsets and bitmasks against AST-parsed header definitions (
ground_spec_with_ast,verify_register_determinism), backfilling omitted registers,MODULE_*metadata, and driver structs while inferring bit positions (infer_bits_from_macro). - Dynamic Offset Expression Isolation: Separates base hexadecimal offsets (
offset) from indexed or shifted C offset arithmetic (offset_expression, e.g.,0x03800 + (i * 0x100)oroffset << port->regshift). - Probe & Interrupt Lifecycle Parity: Captures ordered initialization steps (
MMIO Map,Hardware Reset,Write Register,Read & Poll,Read Register,Memory Allocate,DMA Setup,Interrupt Hook,Clock/Reset Control,Register Device,Lock Acquire,Lock Release) and maps top-halfirqreturn_troutines to raw status, mask, and acknowledgment registers (Read-to-Clearvs.W1C), rendering both as Mermaid sequence diagrams (verify_sequence_parity,verify_markdown_completeness). - Concurrency & Microkernel Porting Guidance: Translates Linux synchronization primitives (
spin_lock_irqsave,spin_lock,mutex_lock) into abstract concurrency locks (IRQSafeSpinlock,Spinlock,SleepableMutex,ReadWriteLock,Atomic,None) alongside Linux-to-C++ API migration tables and a C++20 MMIO driver skeleton.
.
βββ schemas/
β βββ driver_spec.schema.json # Canonical JSON Schema Draft 2020-12 specification
βββ src/
β βββ schemas/
β β βββ driver_spec.schema.json # Packaged JSON Schema copy
β βββ kernelite_prism/
β βββ __init__.py # Public package exports (__version__ = "0.2.0") & lazy __getattr__
β βββ cli.py # Click CLI (analyze, render-md, validate, export-schema)
β βββ config.py # Settings & runtime/quantization/backend validation
β βββ exceptions.py # KernelitePrismError hierarchy
β βββ core/
β β βββ __init__.py # Core pipeline exports
β β βββ aggregator.py # File discovery, token estimation & AST context compaction
β β βββ ast_parser.py # Tree-sitter C AST analyzer & safe constant evaluator
β β βββ doc_generator.py # Jinja2 + Mermaid DRIVER_SPEC.md & C++20 skeleton renderer
β β βββ extractor.py # Transformers, Outlines, OpenAI & Instructor extraction + grounding
β β βββ serializer.py # JSON, YAML, and Markdown serialization
β β βββ validator.py # Schema, AST determinism, sequence parity & Markdown checks
β βββ models/
β βββ __init__.py # Pydantic model exports
β βββ base.py # DriverSpec root model, alias sync & Draft 2020-12 export
β βββ hardware.py # HardwareInfo, SequenceStep, DMASpec, InterruptLifecycle, locks
β βββ interfaces.py # file_operations, sysfs, procfs, and ioctl models
β βββ lifecycle.py # Probe, remove, PM, and init/exit callbacks
β βββ matching.py # OF, PCI, USB, ACPI, I2C, SPI, platform & HID match tables
β βββ metadata.py # Author, license, description & module parameters
β βββ registers.py # RegisterMap, Bitfield & bit-inference helpers
βββ pyproject.toml # Package metadata (v0.2.0), dependencies & pytest config
- Python 3.11+
- Optional: NVIDIA GPU with CUDA drivers for quantized local inference (
4bit/8bit), or an OpenAI-compatible API endpoint.
- Open the repository in a Dev Container or GitHub Codespaces.
- The container automatically configures Python 3.11, installs PyTorch with CUDA support and
bitsandbytes, and installskernelite-prismin editable mode.
git clone [https://github.com/your-org/kernelite.git](https://github.com/your-org/kernelite.git)
cd prism
# Install core package and runtime dependencies
pip install -e .
# Optional: Install pytest and coverage tools for running the test suite
pip install -e ".[dev]"Depending on your chosen inference backend, configure the relevant credentials:
# For gated Hugging Face models (local transformers / outlines backends)
export HF_TOKEN="your-huggingface-token"
# For OpenAI Structured Outputs or Instructor backends
export OPENAI_API_KEY="your-openai-api-key"
# Optional custom OpenAI-compatible endpoint (e.g., vLLM, Ollama, LocalAI)
export OPENAI_BASE_URL="http://localhost:8000/v1"Both kprism and kernelite-prism are installed as CLI entry points.
Usage: kprism analyze [OPTIONS] TARGET_PATH
Options:
-f, --format [json|yaml|md] Output format (default: json)
-o, --out PATH Output path for driver_spec.json / YAML
--md-out PATH Simultaneously write DRIVER_SPEC.md
--model TEXT Model ID or path (default: Qwen/Qwen2.5-Coder-3B-Instruct)
--backend [transformers|outlines|openai|instructor] Structured output backend (default: transformers)
-q, --quant [4bit|8bit|none] Quantization precision (default: 4bit)
--device TEXT Execution device: cuda, cuda:0, cpu (default: cuda)
--token TEXT Hugging Face API token
-I, --include PATH Additional C header file(s) to parse into AST context
--max-tokens INTEGER Max input tokens before AST compaction (default: 16000)
--max-new-tokens INTEGER Max output tokens for specification (default: 8192)
--no-ast-prune Disable AST boilerplate stripping
--help Show this message and exit
# Local GPU inference (4-bit quantized Qwen2.5-Coder-3B-Instruct) emitting JSON + Markdown
kprism analyze drivers/virtio/virtio_mmio.c \
--out build/driver_spec.json \
--md-out build/DRIVER_SPEC.md
# Local inference with Outlines grammar-constrained decoding and extra UAPI header
kprism analyze drivers/net/ethernet/intel/e1000/ \
--backend outlines \
-I include/uapi/linux/virtio_mmio.h \
--out build/e1000_spec.json \
--md-out build/E1000_SPEC.md
# CPU-only local execution (disables bitsandbytes quantization)
kprism analyze drivers/tty/serial/8250/8250_early.c \
--device cpu \
--quant none \
--out build/8250_early.json
# API-based structured output extraction via Instructor or OpenAI
kprism analyze drivers/virtio/virtio_mmio.c \
--backend instructor \
--model gpt-4o-mini \
--out build/driver_spec.json \
--md-out build/DRIVER_SPEC.mdkprism export-schema --out schemas/driver_spec.schema.jsonkprism validate build/driver_spec.json --schema schemas/driver_spec.schema.jsonkprism render-md build/driver_spec.json --out build/DRIVER_SPEC.mdRun the test suite covering JSON Schema Draft 2020-12 compliance, Tree-sitter AST constant grounding, probe sequence parity, and Markdown generation across reference drivers (8250_early.c, e1000_main.c, and virtio_mmio.c):
pytest -v{
"device_name": "VirtIO MMIO Transport",
"driver_name": "virtio_mmio",
"compatibility": [
"virtio,mmio"
],
"hardware_info": {
"bus_type": "platform",
"compatible_strings": [
"virtio,mmio"
],
"base_address_offsets": [
{
"region_id": "0",
"name": "VIRTIO_MMIO_REGS",
"base_offset": "0x000",
"size_hint": "0x200",
"description": "VirtIO MMIO control and virtqueue configuration registers"
}
],
"endianness": "little"
},
"lifecycle": {
"probe_function": "virtio_mmio_probe",
"remove_function": "virtio_mmio_remove"
},
"structs": [
"of_device_id",
"platform_driver"
],
"register_map": [
{
"name": "VIRTIO_MMIO_MAGIC_VALUE",
"offset": "0x000",
"width": 32,
"access": "RO",
"reset_value": "0x74726976",
"description": "Magic value ('virt' in little-endian)"
},
{
"name": "VIRTIO_MMIO_INTERRUPT_STATUS",
"offset": "0x060",
"width": 32,
"access": "RO",
"description": "Interrupt status flags",
"bitfields": [
{
"name": "VIRTIO_MMIO_INT_VRING",
"bits": "0",
"mask_macro": "BIT(0)"
},
{
"name": "VIRTIO_MMIO_INT_CONFIG",
"bits": "1",
"mask_macro": "BIT(1)"
}
]
},
{
"name": "VIRTIO_MMIO_INTERRUPT_ACK",
"offset": "0x064",
"width": 32,
"access": "WO",
"description": "Interrupt acknowledge register (Write-1-to-Clear)"
}
],
"init_sequence": [
{
"step": 1,
"operation": "MMIO Map",
"source_function": "virtio_mmio_probe",
"value_or_mask": "resource 0",
"description": "Map platform MMIO memory region via devm_platform_ioremap_resource"
},
{
"step": 2,
"operation": "Read Register",
"source_function": "virtio_mmio_probe",
"target_register": "VIRTIO_MMIO_MAGIC_VALUE",
"offset": "0x000",
"value_or_mask": "0x74726976",
"description": "Verify 'virt' magic signature"
}
]
}This project is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later). See the LICENSE file for details.