Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions docs/TURING_OPTIMIZATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Turing (TU104 / TU106 / TU116) WindowServer Stutter & 256 MB BAR1 Fix

## Overview

On macOS 15 running NVIDIA Turing GPUs (RTX 2060 SUPER / TU106, RTX 2070 / TU104, GTX 1660 / TU116) with a 256 MB BAR1 aperture, desktop interaction can exhibit:
- UI micro-stutters when dragging windows or resuming interaction after brief idle periods.
- WindowServer surface allocation drops or black window contents under rapid compositing.

## Root Causes

1. **Metal Small-BAR1 Pooling & Headroom (`nvrm610.conf`)**
Default Metal pooling and buffer grace settings hoard GPU allocations and exhaust a 256 MB BAR1 window under WindowServer load. Setting `NVMTL_VRAM_HEADROOM_MB=48`, enabling `NVMTL_NO_SURFACE_PAGEOFF=0`, disabling buffer reuse/grace pools (`NVMTL_NO_BUFREUSE=1`, `NVMTL_IMAGE_POOL=0`, `NVMTL_PRIVATE_POOL=0`, `NVMTL_BUFFER_GRACE=0`, `NVMTL_IMAGE_GRACE=0`), and enabling `NVMTL_GSUB_HOSTPTR_LIFT=1` stabilizes surface allocation.

2. **Framebuffer 256 MB VRAM Grant Ceiling (`NVRMFB.kext`)**
On driver `3.0` (macOS 15), `vramGrant` in `NVRMFB` checks an internal 256 MB grant ceiling at file offset `0x21ea3` (`0f 8e 6d 01 00 00` -> `e9 6e 01 00 00 90`), returning `kIOReturnNoMemory` under heavy WindowServer surface turnover.

3. **Inactivity Surface Eviction & Sticky VM Churn (`NVAccel.kext`)**
On driver `3.0` (macOS 15), `gSurfGpuOn` (`0x251e0`) and `gVmSticky` (`0x23f1c`) evict idle surfaces and retain sticky VM mappings (`debug.nvaccel_surface_gpu_on`, `debug.nvaccel_vm_sticky`).

## Architecture Split in 1401

1. **Main Installation Path (Safe Metal Rules — `mac/Resources/nullmoth-rules.json`)**
`turing-bar1-stutter-optimization` matches `{"arch": ["turing"]}` and passes its `NVMTL_*` / `NVK_*` knobs through `nullmoth-setup.sh` into `# --- 1401 per-system rules ---` inside `/Library/GPUBundles/nvmtl/nvrm610.conf`.
`nullmoth-setup.sh` never modifies kext binaries in place, preserving SHA-256 package verification, per-OS kext manifests (`/Library/NullMoth/kexts/{15,26}`), and audited uninstallation.

2. **Optional Standalone Kext Tool (`tools/apply-turing-fix.sh`)**
Users who still hit `NVRMFB`/`NVAccel` drops on verified driver `3.0` / macOS `15` builds can run `tools/apply-turing-fix.sh` manually. Before touching any kext binary, it verifies:
- Root privileges and disabled SIP filesystem protections.
- macOS major `15`, installed driver version `3.0`, and a Turing PCI device ID (`1e00..21ff`).
- 64-bit Mach-O magic, bounds, expected `NVAccel` sysctl symbol strings, optional `--accel-sha256` / `--fb-sha256` pins, and exact expected bytes at each offset.
- SHA-256-recorded backups under `/Library/NullMoth/turing-backup/` and `kmutil inspect` verification with automatic rollback on failure.
- Non-destructive marked `# --- 1401 turing-fix ---` block updates in `nvrm610.conf` (preserving existing rules and user settings).

### Usage

```bash
# Inspect status without modifying files
bash tools/apply-turing-fix.sh --check

# Apply optional kext patches (driver 3.0 / macOS 15)
sudo bash tools/apply-turing-fix.sh --apply

# Apply only the marked Metal nvrm610.conf block
sudo bash tools/apply-turing-fix.sh --conf-only

# Verify backup SHA256SUMS and restore stock binaries + AuxKC
sudo bash tools/apply-turing-fix.sh --revert
```

## Hardware Tested

- **CPU**: AMD Ryzen 5 5600
- **GPU**: NVIDIA GeForce RTX 2060 SUPER 8 GB (`10de:1f06`, Turing TU106, 256 MB BAR1)
- **OS**: macOS Sequoia 15.8.3 (x86_64)
- **Observed**: Smooth 60 FPS window dragging with no black surfaces or WindowServer hitches; NVENC remains active.
41 changes: 41 additions & 0 deletions mac/Resources/nullmoth-rules.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,47 @@
"match": {"arch": ["turing"]},
"conf": {"NVK_CMDPOOL_GPU_UNCACHED": "1", "NVK_SYSMEM_GPU_UNCACHED": "1"}
},
{
"id": "turing-bar1-stutter-optimization",
"why": "On Turing cards (TU104/TU106/TU116) with a 256 MB BAR1 window, WindowServer dragging can stutter or drop surfaces when Metal hoards chunk pools, defers buffer frees, and runs out of VRAM headroom. Keeping 48 MB headroom, allowing surface page-off, disabling buffer reuse/grace pooling, and lifting hostptrs stabilizes window dragging via nvrm610.conf without modifying signed driver binaries.",
"evidence": [
"macOS 15.8.3 on AMD Ryzen 5 5600 + RTX 2060 SUPER (TU106, 10de:1f06): eliminates WindowServer drag stutter and black surfaces",
"Applies Metal driver nvrm610.conf knobs through the standard per-system rules block"
],
"match": {"arch": ["turing"]},
"conf": {
"NVK_LOCAL_MAP_SYSMEM": "1",
"NVMTL_MANAGED_SYSMEM": "1",
"NVMTL_SHARED_VRAM": "0",
"NVMTL_SHARED_POOL_VRAM": "0",
"NVK_BAR_VRAM": "0",
"NVMTL_VRAM_HEADROOM_MB": "48",
"NVMTL_SHARED_VRAM_BUDGET_MB": "0",
"NVMTL_NO_SURFACE_PAGEOFF": "0",
"NVMTL_FRESH_ZERO": "1",
"NVMTL_RES2_WS": "1",
"NVMTL_NO_RES2": "0",
"NVMTL_NO_RES2_EVICT": "0",
"NVMTL_NO_PURGE_RECLAIM": "0",
"NVMTL_RES2_MARGIN_MB": "32",
"NVMTL_GSUB_HOSTPTR_LIFT": "1",
"NVMTL_NAK_ARR_SCRATCH": "0",
"NVMTL_SURFACE_BUSY": "1",
"NVMTL_SURFIN_ORDERED": "1",
"NVMTL_SCHEDULE_AFTER_SURFACE_WRITES": "1",
"NVMTL_PRESENT_INLINE": "1",
"NVMTL_WS_WAIT_COMPLETION": "1",
"NVMTL_NO_BUFREUSE": "1",
"NVMTL_IMAGE_POOL": "0",
"NVMTL_PRIVATE_POOL": "0",
"NVMTL_BUFFER_GRACE": "0",
"NVMTL_IMAGE_GRACE": "0",
"NVMTL_SURF_IMPORT_CACHE": "0",
"NVMTL_POOL_POLL_MS": "0",
"NVMTL_CMD_POOL_MAX_CHUNKS": "256",
"NVMTL_SURFACE_DEFER_FREE_MS": "0"
}
},
{
"id": "image-size-pre-blackwell",
"builtin": true,
Expand Down
65 changes: 65 additions & 0 deletions tests/test_turing_stutter_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Tests for Turing micro-stutter rules and standalone tool safety guards."""
import json
import pathlib
import re
import unittest

ROOT = pathlib.Path(__file__).resolve().parents[1]
RULES_PATH = ROOT / "mac/Resources/nullmoth-rules.json"
SETUP_PATH = ROOT / "mac/Resources/nullmoth-setup.sh"
TOOL_PATH = ROOT / "tools/apply-turing-fix.sh"
LEGACY_RES_SCRIPT = ROOT / "mac/Resources/nullmoth-turing-optimize.sh"


class TuringStutterRulesTest(unittest.TestCase):
def setUp(self):
self.data = json.loads(RULES_PATH.read_text(encoding="utf-8"))
self.rules = self.data.get("rules", [])

def test_turing_stutter_rule_exists_and_configured(self):
rule = next((r for r in self.rules if r.get("id") == "turing-bar1-stutter-optimization"), None)
self.assertIsNotNone(rule, "turing-bar1-stutter-optimization rule must exist in nullmoth-rules.json")

match = rule.get("match", {})
self.assertEqual(match.get("arch"), ["turing"], "Rule must match turing architecture")

conf = rule.get("conf", {})
self.assertEqual(conf.get("NVMTL_VRAM_HEADROOM_MB"), "48", "VRAM headroom must be 48MB for small BAR1")
self.assertEqual(conf.get("NVMTL_NO_SURFACE_PAGEOFF"), "0", "Surface page-off must not be forced off")
self.assertEqual(conf.get("NVMTL_NO_BUFREUSE"), "1", "Buffer reuse must be disabled")
self.assertEqual(conf.get("NVMTL_CMD_POOL_MAX_CHUNKS"), "256")

# Validate that no rule breaks hardware video encoding on Turing
self.assertNotIn("NVMTL_NO_NVENC", conf)
self.assertNotIn("NVMTL_NO_NVENC_HEVC", conf)

def test_all_rule_conf_keys_and_values_valid_for_profile_swift(self):
key_re = re.compile(r"^(NVMTL|NVK|NVRM)_[A-Z0-9_]+$")
val_re = re.compile(r"^[A-Za-z0-9._-]{0,64}$")

for rule in self.rules:
for k, v in rule.get("conf", {}).items():
self.assertTrue(key_re.match(k), f"Invalid conf key: {k} in rule {rule.get('id')}")
self.assertTrue(val_re.match(str(v)), f"Invalid conf value: {v} in rule {rule.get('id')}")

def test_setup_script_does_not_patch_signed_kext_binaries(self):
setup_src = SETUP_PATH.read_text(encoding="utf-8")
for forbidden in ("patch_turing_stutter", "0x21ea3", "0x251e0", "0x23f1c", "NVAccel.orig.bin"):
self.assertNotIn(forbidden, setup_src, f"nullmoth-setup.sh must not contain binary patcher token {forbidden}")
self.assertFalse(LEGACY_RES_SCRIPT.exists(), "duplicate script must not live in mac/Resources/")

def test_standalone_tool_has_version_checksum_and_rollback_guards(self):
self.assertTrue(TOOL_PATH.is_file(), "tools/apply-turing-fix.sh must exist")
src = TOOL_PATH.read_text(encoding="utf-8")
self.assertTrue(src.startswith("#!/bin/bash\n"), "apply-turing-fix.sh must use LF line endings and bash shebang")
self.assertNotIn("\r", src, "apply-turing-fix.sh must not contain CRLF line endings")
self.assertIn('EXPECTED_OS_MAJOR="15"', src)
self.assertIn('EXPECTED_DRIVER_VERSION="3.0"', src)
self.assertIn("shasum -a 256 --strict -c SHA256SUMS", src)
self.assertIn("rollback_on_error", src)
self.assertIn("kmutil inspect", src)
self.assertIn("# --- 1401 turing-fix ---", src)


if __name__ == "__main__":
unittest.main()
Loading