Repository navigation
Description
Severity: high/medium/low · Category: gpu-parallel · Fix order: 5 of 25 — fix this 5th.
Filenames are numbered in reverse fix order: 001 = fix last, 025 = fix first. This file is 021.
Locations: Source/Hydro/CAMR_construct_hydro_source.cpp:178, Source/Hydro/CAMR_construct_hydro_source.cpp:177, Source/Hydro/CAMR_construct_hydro_source.cpp:183
Based on commit 8f87fa8 (line numbers refer to that tree).
The five findings below are one root cause seen through two buffers (dm_as_fine, bcs_d) and two mechanisms (realloc/recycle and overwrite), so they are filed together; a single patch closes all of them.
The defect
Source/Hydro/CAMR_construct_hydro_source.cpp:178 — dm_as_fine's device buffer is reused across MFIter iterations: iteration i+1's setValRunOn::Device(0.0) runs on a different GPU stream while iteration i's async EBFluxRegister::FineAdd kernels (launched at line 218) are still reading the same buffer; no per-iteration Gpu::streamSynchronize exists (unlike amrex Tests/EB_CNS/Source/CNS_advance.cpp:186). Reported independently at this same line by F032, F041; each reviewer's own wording and evidence is under Verification evidence below.
Source/Hydro/CAMR_construct_hydro_source.cpp:183 — bcs_d (Gpu::DeviceVector) is created and destroyed every MFIter iteration; its device memory is freed while MLStateRedistribute kernels launched inside hydro_umdrv_eb still read bcs_d_ptr, and the next iteration's identically-sized bcs_d allocation reuses the block and overwrites it via Gpu::copy on a different stream. Reported independently at this same line by F055; each reviewer's own wording and evidence is under Verification evidence below.
Why it matters
F018: GPU EB build, multi-level run with do_reflux=1, a fine level owning >=2 boxes with cut cells. MFIter cycles 4 streams with no sync in operator++; iteration i+1 zeroes dm_as_fine while iteration i's FineAdd still reads it, so the re-redistribution mass added to the flux register is partially zeroed, corrupting coarse-fine refluxing nondeterministically.
F048: GPU EB build with redistribution_type=StateRedist and >=2 cut-cell boxes per rank: iteration i+1's Gpu::copy (cudaMemcpyAsync on stream B + sync of stream B only, per AMReX_GpuDevice.H htod_memcpy) writes the recycled block while iteration i's StateRedist slope kernels on stream A still dereference d_bcrec_ptr, giving garbage BCRec values and wrong redistribution near domain boundaries.
How to reach it
- Exec/SodPlusSphere: make USE_EB=TRUE USE_CUDA=TRUE with shipped inputs — amr.max_level=1, do_reflux defaults 1, static box1 refinement, plus amr.max_grid_size=16 appended (the deck's last max_grid_size is 64 at inputs:70). The race needs a fine level decomposed into >=2 cut-cell boxes on one rank -- confirm with amr.v=1 grid output rather than assuming it; 4 GPU streams by default.
Note from the audit
F018: F041 is folded into this entry rather than published separately: it anchors on the dm_as_fine resize at CAMR_construct_hydro_source.cpp:177 and this finding on the setVal at :178 — adjacent lines of the same if (fr_as_fine) block, one root cause (the FArrayBox declared outside the MFIter loop is reused across iterations with no per-iteration stream sync). F041's own verifier reached the same conclusion ("same underlying race as F018 via the realloc/recycle path"). The single Gpu::streamSynchronize() in the suggested diff closes F018, F041 and F048 together.
Suggested fix
Add amrex::Gpu::streamSynchronize() as the last statement of the MFIter body, after the CrseAdd/FineAdd calls and outside the EB/regular branch. That is verbatim what the twin loop in amrex/Tests/EB_CNS/Source/CNS_advance.cpp:186 does; CAMR imported that loop with its initial EB commit and git log -S streamSynchronize shows this file never carried the sync.
If you would rather keep MFIter's four-stream overlap, fix lifetimes instead: allocate dm_as_fine per iteration from The_Async_Arena() — the arena flux, q, qaux, src_q already use here, whose free is stream-ordered (PArena::free → cudaFreeAsync/Elixir) — and hoist the loop-invariant bcs_d and its Gpu::copy above the loop, where MFIter::Finalize's all-stream sync outlives every kernel. Both halves are needed: fixing dm_as_fine alone leaves the bcs_d use-after-free. The same reasoning covers the fab_drho_as_crse/fab_rrflag_as_crse dummies, safe today only because as_crse == 0 gates them.
For Source/Hydro/CAMR_construct_hydro_source.cpp:178 (F018):
--- a/Source/Hydro/CAMR_construct_hydro_source.cpp
+++ b/Source/Hydro/CAMR_construct_hydro_source.cpp
@@ -258,7 +258,12 @@
#endif
#ifdef AMREX_USE_EB
} // not covered
+
+ // Synchronize the current stream so that the next iteration cannot
+ // zero or resize dm_as_fine while this iteration's asynchronous
+ // FineAdd kernels (on a different stream) are still reading it.
+ amrex::Gpu::streamSynchronize();
#endif
} // mfi
} // openmpAdds the per-iteration Gpu::streamSynchronize() that the correct twin, amrex/Tests/EB_CNS/Source/CNS_advance.cpp:186, has and CAMR lacks (MFIter::operator++ never syncs). Guarded by AMREX_USE_EB because only the EB path reuses dm_as_fine/bcs_d across iterations; non-EB temporaries are all async-arena. This single sync also closes the F041 and F048 races.
For Source/Hydro/CAMR_construct_hydro_source.cpp:183 (F048):
--- a/Source/Hydro/CAMR_construct_hydro_source.cpp
+++ b/Source/Hydro/CAMR_construct_hydro_source.cpp
@@ -54,6 +54,15 @@
#ifdef AMREX_USE_EB
const auto& ebfact = dynamic_cast<amrex::EBFArrayBoxFactory const&>(Factory());
+
+ // The BCs are loop-invariant; make the device copy once, outside the
+ // MFIter loop, so it is not freed or overwritten while asynchronous
+ // kernels launched inside the loop are still reading it.
+ const amrex::StateDescriptor* desc = state[State_Type].descriptor();
+ const auto& bcs = desc->getBCs();
+ amrex::Gpu::DeviceVector<amrex::BCRec> bcs_d(desc->nComp());
+ amrex::Gpu::copy(
+ amrex::Gpu::hostToDevice, bcs.begin(), bcs.end(), bcs_d.begin());
#endif
#ifdef _OPENMP
@@ -178,12 +187,6 @@
dm_as_fine.setVal<RunOn::Device>(0.0);
}
- const amrex::StateDescriptor* desc = state[State_Type].descriptor();
- const auto& bcs = desc->getBCs();
- amrex::Gpu::DeviceVector<amrex::BCRec> bcs_d(desc->nComp());
- amrex::Gpu::copy(
- amrex::Gpu::hostToDevice, bcs.begin(), bcs.end(), bcs_d.begin());
-
const auto& dxInv = geom.InvCellSizeArray();
// Return hyd_src - centered at half-time if using Godunov methodHoists the loop-invariant bcs_d build above the OMP/MFIter loop; bcs_d then outlives every kernel because MFIter::Finalize synchronizes all used streams before bcs_d's destructor runs (AMReX_MFIter.cpp:246-252). Shared read-only across OMP threads, so no per-thread copy is needed. bcs_d.data() at the hydro_umdrv_eb call is unchanged.
Diff(s) are against 8f87fa8, written from the current source and verified only with git apply --check — never compiled, never run, never applied to the tree. Treat them as precise intent, not tested patches.
Verification evidence
F018 — confirmed (two independent verifier lenses)
Lens 1 (refutation attempt): Loop has no per-iteration sync; MFIter::operator++ only does 'Gpu::Device::setStreamIndex(currentIndex%streams)' (AMReX_MFIter.cpp:526-548) and max_gpu_streams defaults to 4. EBFluxRegister::FineAdd launches async 'eb_flux_reg_fineadd_dm(i,j,k,n,tbxg1,cfa,dma,...)' reading dm (AMReX_EBFluxRegister.cpp:273-276), while iteration i+1 runs 'dm_as_fine.setValRunOn::Device(0.0)' (line 178) on another stream. amrex Tests/EB_CNS/Source/CNS_advance.cpp:186 has the per-iteration Gpu::streamSynchronize() CAMR lacks — may relate to open issue #70.
Lens 2 (reachability/intent): MFIter::operator++ (amrex AMReX_MFIter.cpp:526) only calls setStreamIndex, no sync; loop syncs are pre/post only. CAMR_construct_hydro_source.cpp:65 declares dm_as_fine outside the loop; :178 setVal<RunOn::Device> races iteration i's FineAdd kernels (:218-222), which read dm.const_array() async (AMReX_EBFluxRegister.cpp:262-281, eb_flux_reg_fineadd_dm feeding Reflux). amrex's own EB_CNS (CNS_advance.cpp:186) adds per-iteration Gpu::streamSynchronize for this exact pattern; CAMR never had one (git -S since 0656702).
F041 — confirmed (one verifier lens)
Reported as: dm_as_fine (default-Arena FArrayBox declared outside the MFIter loop) is resized each iteration, freeing memory that asynchronous EBFluxRegister::FineAdd kernels from the previous iteration (line 218, different GPU stream) may still be reading; no per-iteration Gpu::streamSynchronize exists.
Failure scenario: GPU multi-level EB run with do_reflux (any redistribution_type): iteration N launches FineAdd kernels reading dm_as_fine; iteration N+1's dm_as_fine.resize/setVal reuses the freed block on another stream while those kernels run, corrupting the re-redistribution corrections in the flux register and hence the coarse-fine reflux.
Lens 1 (refutation attempt): BaseFab::resize does 'clear(); define();' via The_Arena when nvar*numPts>truesize (AMReX_BaseFab.H:1767ff); CArena::free is not stream-ordered, and no sync exists between iteration i's async FineAdd read of dm_as_fine and iteration i+1's resize on a different stream (operator++ has no sync, 4 streams default). Same underlying race as F018 via the realloc/recycle path; when sizes fit, the setVal race (F018) applies instead.
F032 — confirmed (one verifier lens)
Reported as: dm_as_fine is a per-thread FArrayBox reused across MFIter iterations: iteration N+1's resize/setValRunOn::Device(0.0) races with iteration N's EBFluxRegister::FineAdd device kernels (and redistribution's as_fine atomics) that still read/write the same buffer on a different GPU stream; no per-iteration Gpu::streamSynchronize exists.
Failure scenario: GPU build, USE_EB=TRUE, >=2 AMR levels, do_reflux=1 (any redistribution_type): eb_flux_reg_fineadd_dm kernels from box N read dm_as_fine while box N+1's setVal zeroes it concurrently, so dm mass-redistribution corrections are intermittently dropped or corrupted in the flux register, causing nondeterministic conservation errors at coarse-fine boundaries.
Lens 1 (refutation attempt): Same confirmed race: dm_as_fine declared outside the loop (line 65), written by ApplyMLRedistribution and read by 'getFluxReg(level).FineAdd(..., dm_as_fine, RunOn::Device)' (line 218-222) async on stream i%4; iteration i+1's resize/setValRunOn::Device(0.0) runs on stream (i+1)%4 with no intervening synchronize anywhere in the loop body. Duplicate of F018 in mechanism; corruption of eb_flux_reg_fineadd_dm inputs is nondeterministic as claimed.
F048 — confirmed (one verifier lens)
Lens 1 (refutation attempt): PODVector::~PODVector calls deallocate→arena()->free with no sync (AMReX_PODVector.H:411-417; free_async's doc comment confirms the dtor lacks the in-flight-kernel guarantee); MLStateRedistribute derefs d_bcrec_ptr[n] in device lambdas (AMReX_EB_StateRedistribute.cpp:238-250) launched async at the end of hydro_umdrv_eb with nothing after; Gpu::copy = htod_memcpy_async + streamSynchronize of the CURRENT stream only (AMReX_GpuDevice.H:488-493), so the recycled same-size CArena block can be overwritten from stream i+1 while stream i's StateRedist kernels read it.
F055 — confirmed (one verifier lens)
Reported as: bcs_d (Gpu::DeviceVector, rebuilt every MFIter iteration) is freed at the end of the EB-branch scope while MLStateRedistribute device kernels launched by ApplyMLRedistribution still dereference bcs_d_ptr (AMReX_EB_StateRedistribute.cpp reads d_bcrec_ptr[n] in device code), a use-after-free.
Failure scenario: GPU build, USE_EB=TRUE, redistribution_type=StateRedist: the freed The_Arena block can be handed to any subsequent same-stream-or-other-stream allocation while StateRedist slope kernels are in flight; if reused by a different allocation, the kernels read unrelated bytes as BCRec values, mis-detecting ext_dir/hoextrap boundaries and corrupting redistributed slopes near domain boundaries, nondeterministically.
Lens 1 (refutation attempt): Same confirmed use-after-free: bcs_d destroyed at the EB-branch scope close (after line 224) while ApplyMLRedistribution→MLStateRedistribute kernels reading d_bcrec_ptr may still be in flight on that stream; The_Arena free is host-immediate and not stream-ordered, so the block can be handed to any later allocation. Harm requires reuse plus a cross-stream or host write, so low severity as filed is right; the defect itself is present.
Based on commit 8f87fa8, which is also the tree the audit verified against. From an automated audit of Source/, Tutorials/ and Util/. Audit finding ids: F018, F041, F032, F048, F055. Reviewer unit(s): Hydro-drivers, theme:eb-smallcell, theme:gpu-capture. Nothing here was compiled or run — the failure scenarios are code reasoning, so the reaching configuration above is the cheapest way to confirm or refute it.
Activity
fixes issue 91 92 93 94 95 (AMReX-Fluids#108)