Skip to content
kernelitePublic

About

Refractoring Linux driver source code into structured, machine-readable specifications.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

14 Commits

Folders and files

Repository files navigation

πŸ’Ž Kernelite Prism

Automated hardware specification extraction and bare-metal C++ microkernel porting documentation from Linux kernel driver C code.

Python Version JSON Schema License: GPL v3

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:

  1. Machine-Parsable Specification (driver_spec.json / YAML): A strictly typed artifact conforming to JSON Schema Draft 2020-12 (schemas/driver_spec.schema.json and src/schemas/driver_spec.schema.json), containing register maps, bitfields, isolated offset formulas, chronological .probe initialization steps, DMA setup, and interrupt lifecycles for automated C++ code generation.
  2. 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).

πŸ—οΈ Technical Architecture

[ 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)

⚑ Extraction & Analysis Capabilities

  • AST Pre-Processing & Token Optimization: Uses tree-sitter-c (ASTPreProcessor, parse_driver_ast, safe_eval_c_constant) to extract #define register 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 stripping MODULE_* / EXPORT_SYMBOL* boilerplate, debug logging (dev_dbg, pr_debug, netdev_dbg, v4l2_dbg), and CONFIG_PM blocks.
  • Context Aggregation & Token Budgeting: Collects .c files and matching sibling/explicit .h headers (collect_driver_files, aggregate_context, aggregate_with_ast, estimate_tokens) with configurable warning and VRAM-safe token budgets (--max-tokens, default 16000), 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) or offset << 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-half irqreturn_t routines to raw status, mask, and acknowledgment registers (Read-to-Clear vs. 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.

πŸ“ Repository Structure

.
β”œβ”€β”€ 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

πŸš€ Quickstart & Installation

πŸ› οΈ Prerequisites

  • Python 3.11+
  • Optional: NVIDIA GPU with CUDA drivers for quantized local inference (4bit / 8bit), or an OpenAI-compatible API endpoint.

Option A: VS Code Dev Container / GitHub Codespaces (Recommended)

  1. Open the repository in a Dev Container or GitHub Codespaces.
  2. The container automatically configures Python 3.11, installs PyTorch with CUDA support and bitsandbytes, and installs kernelite-prism in editable mode.

Option B: Local Installation

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]"

πŸ” Environment Variables

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"

πŸ’» Command Line Usage

Both kprism and kernelite-prism are installed as CLI entry points.

1. kprism analyze β€” Extract Machine & Human Specifications

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

πŸ§ͺ Examples

# 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.md

2. kprism export-schema β€” Export Canonical JSON Schema (Draft 2020-12)

kprism export-schema --out schemas/driver_spec.schema.json

3. kprism validate β€” Verify Schema Compliance

kprism validate build/driver_spec.json --schema schemas/driver_spec.schema.json

4. kprism render-md β€” Render Markdown Documentation from JSON

kprism render-md build/driver_spec.json --out build/DRIVER_SPEC.md

πŸ§ͺ Running the Verification & Integration Tests

Run 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

πŸ“„ Example Output (driver_spec.json)

{
  "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"
    }
  ]
}

πŸ“œ License

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.

About

Refractoring Linux driver source code into structured, machine-readable specifications.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages