Skip to content

drm/asahi: g17: copy and prepare VM_BIND batches in kvmalloc memory - #3920

Merged
DjDeveloperr merged 1 commit into
aurora-silicon:mainfrom
joske:fix/g17-vm-bind-kvvec
Dec 2, 2026
Merged

DjDeveloperr merged 1 commit into
aurora-silicon:mainfrom
joske:fix/g17-vm-bind-kvvec

Conversation

@joske

@joske joske commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

What: vm_bind_g17() holds a batch's user copy (32 bytes an operation) and its prepared operations (160 bytes each) in KVec, which is kmalloc memory and so physically contiguous. A batch of about 210,000 operations needs more than 32 MiB. The page allocator then warns, VM_BIND fails with ENOMEM, and Borealis reports a lost device. One vkQueueBindSparse of 100,000 sparse-image blocks is enough to cause this, since Borealis binds each 64 KiB block as four operations. Both buffers are now KVVec, which falls back to vmalloc.
Tested: J614c (M4 Max) at 90f7cf5411: one vkQueueBindSparse of 100,000 and of 200,000 blocks (400,000 and 800,000 operations) binds with no warning and completes; before this change both warned and failed with ENOMEM.
Risk: two-way door · all Macs: vm_bind() hands every GPU with tracked submission to vm_bind_g17() (G14 on firmware 27.2, G15, G16, G17, G18, M3, M5)
Not yet: other Macs.

Details

vm_bind_g17() reads the user's array with read_all() into a KVec<u8> (stride x count bytes). It then builds PreparedUserBindBatch::new(&vm, count), which is KVec::with_capacity(count) of PreparedUserBindOp, 160 bytes an operation on arm64. The second buffer is the one that fails. In the warning below, x22 = 0x3d09000 = 64,000,000 bytes = 400,000 operations x 160. A Mario Kart World run hit the same warning with 59,211,200 bytes (370,070 operations).

Neither buffer is handed to hardware or needs to be physically contiguous, so KVVec (kvmalloc: kmalloc first, vmalloc above what kmalloc can give) changes nothing else. Indexing, iter(), iter_mut(), drain(start..) and chunks_exact() work the same on it.

The count is still bounded only by what userspace asks for: the batch costs 192 bytes an operation in kernel memory. A bind_batch_limit() for G17 could cap it with EINVAL, but Borealis would then have to split its batches. I left that out of this change.

Warning on main + Borealis, one vkQueueBindSparse of 100,000 blocks:

WARNING: mm/page_alloc.c:5340 at __alloc_frozen_pages_noprof+0x294/0x3dc, CPU#0: bigbind/12245
 ___kmalloc_large_node+0x50/0xd4
 __kmalloc_large_node_noprof+0x28/0x7c
 __kmalloc_node_track_caller_noprof+0x27c/0x330
 krealloc_node_align_noprof+0xe8/0x1c0
 rust_helper_krealloc_node_align+0x10/0x1c
 <asahi_core driver IOCTLS ASAHI_VM_BIND>+0x280/0x1680 [aurora]
 drm_ioctl_kernel+0xc0/0x108
 drm_ioctl+0x244/0x3ac

Borealis then logs DRM_IOCTL_ASAHI_VM_BIND failed: Cannot allocate memory (vm=1, ops=400000), and vkQueueWaitIdle returns VK_ERROR_DEVICE_LOST.

Evidence

Repro bigbind: one vkQueueBindSparse that binds N 64 KiB blocks of a sparse 16384x16384 RGBA8 array image (aliased) to one 64 KiB allocation. Source below.

N blocks VM_BIND ops before (43.5: main b98bf00b32 + #2170 + #3200) after (43.6: the same + this change)
1,000 / 20,000 / 48,000 4,000 / 80,000 / 192,000 ok ok
100,000 400,000 WARNING, ENOMEM, vkQueueWaitIdle -4 no warning, bind ok
200,000 800,000 same no warning, bind ok

With 43.6, binds of 100,000 blocks and more succeeded, but the queue still hung afterwards on older Mesa. That came from a separate Borealis bug: sparse images of 4 GiB or more got a 32-bit address range (mesa fix: https://github.com/joske/mesa/tree/fix/borealis-sparse-image-4gib, PR to aurora-silicon/mesa follows). With that fixed as well, 100,000 and 200,000 blocks bind and complete with no kernel message.

At the head of this PR (90f7cf5411 on main 5a870d0f0b), booted on J614c, with Borealis at aurora-wip 689b2fe3dbf plus the mesa fix:

N blocks VM_BIND ops result
48,000 192,000 ok
100,000 400,000 ok, no kernel message
200,000 800,000 ok, no kernel message

With Borealis without the mesa fix on the same kernel, 100,000 and 200,000 blocks also bind with no warning, and then hang on the 4 GiB address bug, as described above.

RADV (RX 6800) binds 200,000 blocks in one call without issue.

/* One vkQueueBindSparse that binds N blocks of a sparse 2D array image to the
 * same 64 KiB of memory (aliased), as a game filling unbound blocks with one
 * zero page does. Borealis binds each 64 KiB block as two 32 KiB halves,
 * each with its read-only shadow: four VM_BIND ops a block, all in one
 * VM_BIND ioctl.
 *
 * Build: cc -O2 -Wall -o bigbind bigbind.c -lvulkan
 * Run:   ./bigbind <blocks> [binds per vkQueueBindSparse call, default all]
 *        BIG_LAYERS=n: n array layers (1 GiB each) regardless of <blocks>
 * Prints the VkResult of each call and of a final vkQueueWaitIdle.
 */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <vulkan/vulkan.h>

#define CHECK(x)                                                               \
   do {                                                                        \
      VkResult r_ = (x);                                                       \
      if (r_ != VK_SUCCESS) {                                                  \
         fprintf(stderr, "%s failed: %d (line %d)\n", #x, r_, __LINE__);      \
         exit(2);                                                              \
      }                                                                        \
   } while (0)

int main(int argc, char **argv)
{
   const uint32_t want = argc > 1 ? (uint32_t)strtoul(argv[1], NULL, 0) : 1000;
   uint32_t per_call = argc > 2 ? (uint32_t)strtoul(argv[2], NULL, 0) : want;
   if (per_call == 0)
      per_call = want;

   VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
                            .apiVersion = VK_API_VERSION_1_3};
   VkInstanceCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
                              .pApplicationInfo = &app};
   VkInstance inst;
   CHECK(vkCreateInstance(&ii, NULL, &inst));
   uint32_t np = 1;
   VkPhysicalDevice phys;
   vkEnumeratePhysicalDevices(inst, &np, &phys);
   VkPhysicalDeviceProperties props;
   vkGetPhysicalDeviceProperties(phys, &props);
   printf("device: %s, driver version 0x%x\n", props.deviceName, props.driverVersion);

   uint32_t qn = 16;
   VkQueueFamilyProperties qf[16];
   vkGetPhysicalDeviceQueueFamilyProperties(phys, &qn, qf);
   uint32_t qfam = 0;
   while (qfam < qn && !(qf[qfam].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
      qfam++;
   if (qfam == qn) {
      fprintf(stderr, "no sparse binding queue\n");
      return 2;
   }
   float prio = 1;
   VkDeviceQueueCreateInfo qci = {.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
                                  .queueFamilyIndex = qfam, .queueCount = 1,
                                  .pQueuePriorities = &prio};
   VkPhysicalDeviceFeatures feat = {.sparseBinding = VK_TRUE,
                                    .sparseResidencyImage2D = VK_TRUE,
                                    .sparseResidencyAliased = VK_TRUE};
   VkDeviceCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
                             .queueCreateInfoCount = 1, .pQueueCreateInfos = &qci,
                             .pEnabledFeatures = &feat};
   VkDevice dev;
   CHECK(vkCreateDevice(phys, &dci, NULL, &dev));
   VkQueue queue;
   vkGetDeviceQueue(dev, qfam, 0, &queue);

   /* 16384x16384 RGBA8 with 64 KiB (128x128) blocks: 16384 blocks a layer. */
   const uint32_t size = 16384, per_layer = (size / 128) * (size / 128);
   /* BIG_LAYERS=n makes the image n layers whatever the block count; the
    * blocks are still bound from layer 0 on. */
   const char *bl = getenv("BIG_LAYERS");
   const uint32_t layers = bl ? (uint32_t)atoi(bl) : (want + per_layer - 1) / per_layer;
   VkImageCreateInfo ici = {
      .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
      .flags = VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT |
               VK_IMAGE_CREATE_SPARSE_ALIASED_BIT,
      .imageType = VK_IMAGE_TYPE_2D, .format = VK_FORMAT_R8G8B8A8_UNORM,
      .extent = {size, size, 1}, .mipLevels = 1, .arrayLayers = layers ? layers : 1,
      .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
      .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT};
   VkImage img;
   CHECK(vkCreateImage(dev, &ici, NULL, &img));

   uint32_t nreq = 1;
   VkSparseImageMemoryRequirements sreq;
   vkGetImageSparseMemoryRequirements(dev, img, &nreq, &sreq);
   VkExtent3D gran = sreq.formatProperties.imageGranularity;
   printf("image %ux%u x %u layers, block %ux%u\n", size, size, ici.arrayLayers, gran.width,
          gran.height);
   const uint32_t bx = size / gran.width, by = size / gran.height;

   VkMemoryRequirements mr;
   vkGetImageMemoryRequirements(dev, img, &mr);
   VkPhysicalDeviceMemoryProperties mp;
   vkGetPhysicalDeviceMemoryProperties(phys, &mp);
   uint32_t mt = 0;
   while (mt < mp.memoryTypeCount &&
          !((mr.memoryTypeBits & (1u << mt)) &&
            (mp.memoryTypes[mt].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)))
      mt++;
   VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
                               .allocationSize = mr.alignment, .memoryTypeIndex = mt};
   VkDeviceMemory mem;
   CHECK(vkAllocateMemory(dev, &mai, NULL, &mem));

   VkSparseImageMemoryBind *binds = calloc(want, sizeof(*binds));
   for (uint32_t i = 0; i < want; i++) {
      const uint32_t layer = i / (bx * by), in_layer = i % (bx * by);
      binds[i] = (VkSparseImageMemoryBind){
         .subresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, layer},
         .offset = {(int32_t)((in_layer % bx) * gran.width),
                    (int32_t)((in_layer / bx) * gran.height), 0},
         .extent = gran,
         .memory = mem,
         .memoryOffset = 0};
   }

   int failed = 0;
   for (uint32_t done = 0; done < want; done += per_call) {
      const uint32_t n = want - done < per_call ? want - done : per_call;
      VkSparseImageMemoryBindInfo ib = {.image = img, .bindCount = n, .pBinds = binds + done};
      VkBindSparseInfo bsi = {.sType = VK_STRUCTURE_TYPE_BIND_SPARSE_INFO,
                              .imageBindCount = 1, .pImageBinds = &ib};
      VkResult r = vkQueueBindSparse(queue, 1, &bsi, VK_NULL_HANDLE);
      printf("vkQueueBindSparse of %u binds (blocks %u..%u): %d\n", n, done, done + n - 1, r);
      if (r != VK_SUCCESS) {
         failed = 1;
         break;
      }
   }
   VkResult r = vkQueueWaitIdle(queue);
   printf("vkQueueWaitIdle: %d\n", r);
   return failed || r != VK_SUCCESS;
}

vm_bind_g17() copies the user's array of bind operations into a KVec and
prepares every operation into a PreparedUserBindBatch whose KVec has room
for all of them, 160 bytes an operation on arm64. Both are kmalloc'ed,
so physically contiguous. A batch of about 210,000 operations or more
asks kmalloc for more than 32 MiB: the page allocator warns
(mm/page_alloc.c, __alloc_frozen_pages_noprof), VM_BIND fails with
ENOMEM and Borealis reports a lost device. One vkQueueBindSparse of
100,000 blocks of a sparse image is enough, since Borealis binds each
64 KiB block as two 32 KiB halves, each with its read-only shadow.

Neither buffer needs to be physically contiguous. Use KVVec, which falls
back to vmalloc, for both.

Signed-off-by: Jos Dehaes <jos.dehaes@gmail.com>
@joske
joske requested review from a team and DjDeveloperr as code owners December 2, 2026 11:02
@github-actions github-actions Bot added area:gpu Area from CODEOWNERS (bot) blast:all Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Merge readiness at 90f7cf54: ready to merge

Check Detail
CI at head ok 4 checks passed
Review ok approved by satchlj
Requested changes ok none
Hardware row at head ok in the PR body at 90f7cf54
Conflicts ok none
PR text ok Risk: two-way · all Macs: vmbind() hands every GPU with tracked submission to vmbindg17() (G14 on firmware 27.2, G15, G16, G17, G18, M3, M5)

Areas: area:gpu
Merge: gh pr merge 3920 --merge (Owners and Core through the bypass: add --admin).

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@satchlj satchlj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 90f7cf541193: bytes in vm_bind_g17() and PreparedUserBindBatch::ops are host-only buffers never passed to DMA or required to be physically contiguous, and UserSliceReader::read_all() is generic over Allocator, so switching both to KVVec cleanly avoids kmalloc order-limit warnings and ENOMEM on large sparse VM_BIND batches.

Non-blocking follow-up note: VmLifetime's state.unmaps (drivers/gpu/drm/asahi/mmu/lifetime.rs) is still a KVec<PreparedUserUnmap> and calls state.unmaps.reserve(batch.ops.len() - start, GFP_KERNEL) in defer_bind_batch(), so a large (>~210k op) all-unmap batch against a quarantined VM would hit the same kmalloc ceiling.

@github-actions github-actions Bot added ready-to-merge Meets the merge policy: merge it (bot) and removed needs-review No approving review from Core or Omarchy Mac yet (bot) labels Dec 2, 2026
@satchlj

satchlj commented Dec 2, 2026

Copy link
Copy Markdown
Member

Exact-head M5 Max (J775c, G17C B1) verification at 90f7cf5411932c0c643fd98f5a5041e004d6964d vs parent main 5a870d0f0b3f69ef09998e05cad063230f4d4aeb (default command line, Borealis with aurora-silicon/mesa#1528 at 4464bb5cbd5f): PASS, 0 warnings, 0 GPU faults.

Reproducer (bigbind from PR body — one vkQueueBindSparse of N 64 KiB aliased sparse-image blocks, 4 VM_BIND ops/block):

N blocks VM_BIND ops Parent 5a870d0f0b3f (7.3.0-1-50.20261202-ARCH) PR 90f7cf541193 (7.3.0-1-52.20261202-ARCH)
1,000 4,000 — vkQueueBindSparse: 0, vkQueueWaitIdle: 0, stderr=0 B
20,000 80,000 — vkQueueBindSparse: 0, vkQueueWaitIdle: 0, stderr=0 B
48,000 192,000 vkQueueBindSparse: 0, vkQueueWaitIdle: 0 vkQueueBindSparse: 0, vkQueueWaitIdle: 0, stderr=0 B
100,000 400,000 WARNING: mm/page_alloc.c:5340 in ASAHI_VM_BIND, ENOMEM, vkQueueWaitIdle: -4 vkQueueBindSparse: 0, vkQueueWaitIdle: 0, stderr=0 B
200,000 800,000 ENOMEM, vkQueueWaitIdle: -4 vkQueueBindSparse: 0, vkQueueWaitIdle: 0, stderr=0 B
  • Trial boot (7.3.0-1-52.20261202-ARCH): failed units: 0, 0 kernel WARNING/BUG/Oops and 0 GPU faults in dmesg before and after all 5 runs; returned cleanly to default boot.

@satchlj

satchlj commented Dec 2, 2026

Copy link
Copy Markdown
Member

Exact-head J413 (MacBook Air 13" M2, apple,j413, T8112, Apple M2 (G14G B0) on macOS 27.2 26B123 stub, boot_id=89fbf167-6235-4ad1-bab3-c7c7940ee3ee, default command line) hardware row at 90f7cf5411932c0c643fd98f5a5041e004d6964d (7.3.0-pr3920-ARCH+, vulkan-aurora 1:26.3.0_devel.202611260351.36623c0a4a5-3, driver 0x6802063):

Tested with bigbind wrapping binds across BIG_LAYERS=3 (3 GiB sparse 2D array image, staying under the separate 4 GiB Borealis sparse-image bug on packaged Mesa) so each vkQueueBindSparse still submits the full 4-ops-per-block DRM_IOCTL_ASAHI_VM_BIND batch:

N blocks VM_BIND ops Baseline (main 5a870d0f0b3f) #3920 (90f7cf541193)
48,000 192,000 vkQueueBindSparse: 0, vkQueueWaitIdle: 0 vkQueueBindSparse: 0, vkQueueWaitIdle: 0
100,000 400,000 WARNING: mm/page_alloc.c:5340 at __alloc_frozen_pages_noprof via ASAHI_VM_BIND, ENOMEM, VK_ERROR_DEVICE_LOST (-4) vkQueueBindSparse: 0, vkQueueWaitIdle: 0, 0 kernel warnings / 0 GPU or DART faults
200,000 800,000 — vkQueueBindSparse: 0, vkQueueWaitIdle: 0, 0 kernel warnings / 0 GPU or DART faults

System booted with 0 failed units and clean dmesg across all three sparse-bind runs. (Suspend/resume was not exercised on this boot.)

@github-actions github-actions Bot added ready-to-merge Meets the merge policy: merge it (bot) and removed ready-to-merge Meets the merge policy: merge it (bot) labels Dec 2, 2026
@DjDeveloperr

Copy link
Copy Markdown
Contributor

Local CI for head 90f7cf541193 on current main: no new failures.

Hosted Actions on this fork PR still wait for approval, so I ran the affected workflow steps on pc on a merge tree.

Workflow step Command Result
apple-build make LLVM=1 W=1 modules_prepare drivers/gpu/drm/asahi/ ... (defconfig + asahi.config, Rust, warm O= dir), main and merge rc 0 on both; asahi_core.o rebuilt; the W=1 warning set is identical to main
host-tests tools/asahi/run-host-tests.py --jobs 8 in the host-tests.yml image (ubuntu 24.04, clang 18, gcc 13, rust 1.96.0) 948/952 with #3812 in the tree. display26-tests fails because of #3812 (reported there). Three tests hit the runner timeout under host load; on main + this PR + #3805, all four pass at --jobs 2
KUnit plan scripts/ci/apple-kunit.py plan selects asahi
KUnit asahi kunit.py build --arch=arm64 --make_options LLVM=1 --kunitconfig=drivers/gpu/drm/asahi/.kunitconfig builds, rc 0. It was not run: QEMU is not used on pc

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

Labels

area:gpu Area from CODEOWNERS (bot) blast:all Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) ready-to-merge Meets the merge policy: merge it (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants