// Heap.home (see heap.bend): migrates Bend's heap (CUDA managed memory) back to the CPU in one bulk prefetch. // Uses Bend runtime internals (e.mem, gpu_dev). #include Term heap_home_run(Env e, Term* f, IoWork* w) { uint32_t mib = 0; #if BEND_CUDA uint32_t want = (uint32_t)f[0]; CUcontext ctx; if (cuDevicePrimaryCtxRetain(&ctx, gpu_dev) != CUDA_SUCCESS || cuCtxSetCurrent(ctx) != CUDA_SUCCESS) { fprintf(stderr, "Heap.home: no CUDA context\n"); exit(1); } CUdeviceptr base; size_t size; if (cuMemGetAddressRange(&base, &size, (CUdeviceptr)e.mem) != CUDA_SUCCESS) { fprintf(stderr, "Heap.home: no range\n"); exit(1); } if (want != 0 && (size_t)want << 20 < size) size = (size_t)want << 20; struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); CUmemLocation host = {CU_MEM_LOCATION_TYPE_HOST, 0}; if (cuCtxSynchronize() != CUDA_SUCCESS || cuMemPrefetchAsync(base, size, host, 0, 0) != CUDA_SUCCESS || cuCtxSynchronize() != CUDA_SUCCESS) { fprintf(stderr, "Heap.home: prefetch failed\n"); exit(1); } clock_gettime(CLOCK_MONOTONIC, &t1); if (getenv("HEAP_TRACE")) fprintf(stderr, "Heap.home: %zu MiB (heap at +%zu MiB) in %.0f ms\n", size >> 20, (size_t)((CUdeviceptr)e.mem - base) >> 20, (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6); mib = (uint32_t)(size >> 20); #endif return (Term)mib; } static void __attribute__((constructor)) heap_use(void) { #ifdef CID(Heap.home) io_eff(CID(Heap.home), heap_home_run); #endif }