Skip to content

Commit 304dd3a

Browse files
committed
Fix Selene DMA lifetime, quarantine, and shared-region aliasing bugs
Active GPU DMA, host compression, NIC RDMA, and concurrent data-channel workers can access mapped host or shared-memory ranges across close, panic unwind, quarantine, and multi-rank scatter paths. Unmapping a region before every local copier, RDMA queue pair, and compression worker has drained causes use-after-unmap, and constructing overlapping `&mut [u8]` slices in `LocalRegions` is undefined behavior under concurrent readers or multi-rank writes. - Declare `transfers` before `core`/`pool` in `MemoryStore` and `disk_store::Resources`, close both tiers in `CompositeStore::close`, guard `AsyncCompressor`'s active count with an RAII drop guard, and leak the slab pool and report an error if compression does not finish before `MemoryStore::close` (`selene/src/memory.rs`, `selene/src/disk_store.rs`, `selene/src/composite.rs`). - Retain `sess.regions` and `Attachment::Shm` in `Engine::quarantine`, retain `self.shared` in `Agent::quarantine`, and invoke `engine.quarantine()` when `conn::shutdown` fails to drain (`selene/src/pool/engine/mod.rs`, `selene/src/pool/conn.rs`, `selene/src/pool/agent.rs`). - Wrap `Staging.region` in `Arc<Region>` and retain it inside `rdma::Device` so quarantined RDMA queue pairs keep their registered staging mapped (`selene/src/pool/rdma.rs`, `selene/src/pool/net.rs`). - Add `LocalRegions::bytes_read`, `LocalRegions::ptr_mut`, and `SliceLayout::scatter_disjoint` so concurrent read paths borrow `&[u8]` and multi-rank data-channel scatter writes only each rank's disjoint byte ranges without aliasing `&mut [u8]` (`selene/src/shared/slice.rs`, `selene-manager/src/regions.rs`, `selene-manager/src/pool/pass.rs`, `selene-manager/src/data/channel.rs`). - Attach `ReadAhead`'s overlapped file handle to its IOCP queue on Windows (`selene/src/disk.rs`). Every affected teardown, quarantine, RDMA, and concurrent region access path now preserves backing mappings and disjoint ownership until all DMA, RDMA, and worker accesses finish. Validated on Linux (rebased onto post-#607 main `5df8edd3c`), GB10, and SM120 hardware across `selene`, `selene-manager`, and `helios offload::`. Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b
1 parent 5df8edd commit 304dd3a

15 files changed

Lines changed: 225 additions & 71 deletions

File tree

‎selene-manager/src/data/channel.rs‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -733,11 +733,11 @@ async fn send_windows(
733733
.write(conn)
734734
.await?;
735735
for (at, u) in parts {
736-
// The granted extent is held until this handler has fenced.
736+
// SAFETY: the granted extent stays immutable until this handler fences.
737737
let data = unsafe {
738738
inner
739739
.regions
740-
.bytes(window.region, window.offset + at, u.stored_length)?
740+
.bytes_read(window.region, window.offset + at, u.stored_length)?
741741
};
742742
conn.write_all(data).await?;
743743
}
@@ -780,7 +780,7 @@ async fn send_windows(
780780
None => unsafe {
781781
inner
782782
.regions
783-
.bytes(window.region, window.offset, window.shape.length)?
783+
.bytes_read(window.region, window.offset, window.shape.length)?
784784
},
785785
Some((layout, rank)) => {
786786
let (pages, row) = (window.shape.page_count, window.shape.row);
@@ -789,7 +789,7 @@ async fn send_windows(
789789
}
790790
// SAFETY: as above, over the whole window the slice lies in.
791791
let whole = unsafe {
792-
inner.regions.bytes(
792+
inner.regions.bytes_read(
793793
window.region,
794794
window.offset,
795795
layout.window_bytes(pages, row),
@@ -931,16 +931,14 @@ async fn receive_windows(
931931
reader.read_exact(&mut packed),
932932
)
933933
.await?;
934-
// SAFETY: as above, over the whole window the slice lies in.
935-
let whole = unsafe {
936-
inner.regions.bytes(
937-
grant.region,
938-
grant.offset,
939-
layout.window_bytes(pages, row),
940-
)?
941-
};
942-
layout
943-
.scatter(*rank, whole, pages, row, &packed)
934+
let (base, len) = inner.regions.ptr_mut(
935+
grant.region,
936+
grant.offset,
937+
layout.window_bytes(pages, row),
938+
)?;
939+
// SAFETY: the put owns the granted window until fenced, and each rank
940+
// writes only its own disjoint slices within `base..base + len`.
941+
unsafe { layout.scatter_disjoint(*rank, base, len, pages, row, &packed) }
944942
.map_err(|error| invalid(error.to_string()))?;
945943
}
946944
}

‎selene-manager/src/pool/pass.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ fn compute(job: &PassJob, window: &[u8]) -> Result<PassOut, PassError> {
171171
pub fn run(job: PassJob) -> Result<PassOut, PassError> {
172172
let length = job.layout.window_bytes(job.pages, job.row);
173173
// SAFETY: the pool retains this window unchanged until the pass completes.
174-
let window = unsafe { job.regions.bytes(job.region, job.offset, length) }
174+
let window = unsafe { job.regions.bytes_read(job.region, job.offset, length) }
175175
.map_err(|error| PassError::Io(error.to_string()))?;
176176
compute(&job, window)
177177
}

‎selene-manager/src/regions.rs‎

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,44 @@ impl LocalRegions {
2727
}
2828
}
2929

30+
fn range(&self, region: Region, offset: u64, length: u64) -> io::Result<(*mut u8, usize)> {
31+
let (base, size) = self.mapping(region);
32+
let end = offset
33+
.checked_add(length)
34+
.ok_or_else(|| invalid("window range overflow"))?;
35+
if end > size as u64 {
36+
return Err(invalid("a window lies outside its region"));
37+
}
38+
// SAFETY: `offset <= end <= size`, so the pointer stays within the mapped region.
39+
Ok((unsafe { base.add(offset as usize) }, length as usize))
40+
}
41+
42+
/// Read-only view of a mapped range that may be shared with concurrent readers.
43+
///
44+
/// # Safety
45+
/// No writer may mutate the range while the slice lives, and the mapping must
46+
/// stay alive.
47+
pub unsafe fn bytes_read<'a>(
48+
&self,
49+
region: Region,
50+
offset: u64,
51+
length: u64,
52+
) -> io::Result<&'a [u8]> {
53+
let (ptr, len) = self.range(region, offset, length)?;
54+
// SAFETY: bounds are checked; immutability and lifetime are the caller's contract.
55+
Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
56+
}
57+
58+
/// Raw writable pointer to a validated range for concurrent disjoint sub-writes.
59+
pub fn ptr_mut(
60+
&self,
61+
region: Region,
62+
offset: u64,
63+
length: u64,
64+
) -> io::Result<(*mut u8, usize)> {
65+
self.range(region, offset, length)
66+
}
67+
3068
/// # Safety
3169
/// The caller must own the range exclusively while the slice lives, and keep
3270
/// this mapping alive. The store leases windows until their handler is fenced.
@@ -36,15 +74,9 @@ impl LocalRegions {
3674
offset: u64,
3775
length: u64,
3876
) -> io::Result<&'a mut [u8]> {
39-
let (base, size) = self.mapping(region);
40-
let end = offset
41-
.checked_add(length)
42-
.ok_or_else(|| invalid("window range overflow"))?;
43-
if end > size as u64 {
44-
return Err(invalid("a window lies outside its region"));
45-
}
77+
let (ptr, len) = self.range(region, offset, length)?;
4678
// SAFETY: bounds are checked; ownership and lifetime are the caller's contract.
47-
Ok(unsafe { std::slice::from_raw_parts_mut(base.add(offset as usize), length as usize) })
79+
Ok(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
4880
}
4981
}
5082

@@ -92,6 +124,24 @@ mod tests {
92124
assert!(regions.bytes(Region::Staging, 16 * 1024, 1).is_err());
93125
assert!(regions.bytes(Region::Arena, u64::MAX, 2).is_err());
94126
assert!(regions.bytes(Region::Staging, 32 * 1024, 1).is_err());
127+
assert!(regions.bytes_read(Region::Arena, 64 * 1024, 1).is_err());
128+
assert!(regions.ptr_mut(Region::Staging, 16 * 1024, 1).is_err());
129+
}
130+
}
131+
132+
#[test]
133+
fn bytes_read_allows_overlapping_shared_views() {
134+
let regions = regions();
135+
// SAFETY: exclusive write finishes before shared immutable borrows begin.
136+
unsafe {
137+
regions
138+
.bytes(Region::Arena, 4096, 4)
139+
.unwrap()
140+
.copy_from_slice(b"data");
141+
let a = regions.bytes_read(Region::Arena, 4096, 4).unwrap();
142+
let b = regions.bytes_read(Region::Arena, 4096, 4).unwrap();
143+
assert_eq!(a, b"data");
144+
assert_eq!(b, b"data");
95145
}
96146
}
97147
}

‎selene/src/composite.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1616,14 +1616,14 @@ impl HostStore for CompositeStore {
16161616
events.clear();
16171617
std::thread::sleep(Duration::from_millis(1));
16181618
}
1619-
self.disk.close()?;
1620-
self.memory.close()?;
1619+
let disk = self.disk.close();
1620+
let memory = self.memory.close();
16211621
self.outbound.clear();
16221622
self.parked.clear();
16231623
self.inbound.clear();
16241624
self.jobs.clear();
16251625
self.stale.clear();
1626-
Ok(())
1626+
disk.and(memory)
16271627
}
16281628
}
16291629

‎selene/src/disk.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2029,6 +2029,10 @@ impl ReadAhead {
20292029
return Err(invalid("read-ahead range is not block aligned"));
20302030
}
20312031
let ring = Ring::new()?;
2032+
#[cfg(windows)]
2033+
ring.queue
2034+
.attach(&file)
2035+
.map_err(|e| io_failure("attach read-ahead file", e))?;
20322036
let (free, recycled) = mpsc::channel::<AlignedBuffer>();
20332037
let (sender, blocks) = mpsc::channel::<Result<AheadBlock>>();
20342038
let count = AHEAD_BLOCKS.min(((end - start) as usize).div_ceil(AHEAD_BLOCK_BYTES).max(1));

‎selene/src/disk_store.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,11 +206,11 @@ impl Buffers {
206206
/// The threads and pool every pipeline draws on, with the counters that keep
207207
/// submissions within the queues' depths so a refusal is a failure, not backpressure.
208208
struct Resources {
209-
/// Declared before `pool` so Drop joins `DiskThread` before unmapping pinned slabs.
209+
/// Declared before `pool` so Drop joins `DiskThread` and copy threads before unmapping slabs.
210210
disk: DiskThread,
211+
transfers: SharedCopier,
211212
/// Shared slots for device transfers; host-buffer-only users may omit them.
212213
pool: Option<SlabPool>,
213-
transfers: SharedCopier,
214214
/// Disk jobs submitted whose replies have not been polled.
215215
disk_outstanding: usize,
216216
next_disk: u64,

‎selene/src/memory.rs‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2021,14 +2021,20 @@ impl AsyncCompressor {
20212021
let slab_bytes = self.slab_bytes;
20222022
let tx = self.tx.clone();
20232023
let active = self.active.clone();
2024+
struct ActiveGuard(Arc<(Mutex<usize>, Condvar)>);
2025+
impl Drop for ActiveGuard {
2026+
fn drop(&mut self) {
2027+
let mut count = self.0.0.lock().unwrap_or_else(PoisonError::into_inner);
2028+
*count = count.saturating_sub(1);
2029+
if *count == 0 {
2030+
self.0.1.notify_all();
2031+
}
2032+
}
2033+
}
20242034
pool.spawn(move || {
2035+
let _guard = ActiveGuard(active);
20252036
let record = encode_host_task(pool, &encoder, &layout, slab_bytes, scratch, task);
20262037
let _ = tx.send(record);
2027-
let mut count = active.0.lock().unwrap_or_else(PoisonError::into_inner);
2028-
*count = count.saturating_sub(1);
2029-
if *count == 0 {
2030-
active.1.notify_all();
2031-
}
20322038
});
20332039
}
20342040
}
@@ -2231,12 +2237,12 @@ fn encode_host_task(
22312237

22322238
pub struct MemoryStore {
22332239
pass_through: bool,
2234-
// Dropped first: checksum and async compression threads read slots the core frees.
2240+
// Dropped first: checksum, async compression, and copy threads access slabs the core owns.
22352241
announce: Option<Announce>,
22362242
#[cfg(feature = "codec")]
22372243
compressor: Option<AsyncCompressor>,
2238-
core: Core,
22392244
transfers: SharedCopier,
2245+
core: Core,
22402246
/// Reply scratch reused across polls.
22412247
replies: Vec<Reply>,
22422248
/// Completions produced outside `poll`, delivered by the next `poll`.
@@ -3086,11 +3092,28 @@ impl HostStore for MemoryStore {
30863092
std::thread::sleep(Duration::from_millis(1));
30873093
}
30883094
}
3089-
self.transfers
3095+
#[cfg(feature = "codec")]
3096+
let compressor_busy = self.compressor.as_ref().is_some_and(|c| !c.is_idle());
3097+
#[cfg(not(feature = "codec"))]
3098+
let compressor_busy = false;
3099+
let closed = self
3100+
.transfers
30903101
.lock()
30913102
.unwrap_or_else(PoisonError::into_inner)
3092-
.close()
3093-
.inspect_err(|_| self.core.pool.leak())?;
3103+
.close();
3104+
if closed.is_err() || compressor_busy {
3105+
self.core.pool.leak();
3106+
}
3107+
closed?;
3108+
if compressor_busy {
3109+
#[cfg(feature = "codec")]
3110+
if let Some(compressor) = self.compressor.take() {
3111+
std::mem::forget(compressor);
3112+
}
3113+
return Err(Error::new(
3114+
"host KV compression did not finish before close",
3115+
));
3116+
}
30943117
self.core.abandon();
30953118
self.events.clear();
30963119
Ok(())

‎selene/src/offload/tests.rs‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -656,16 +656,7 @@ fn disk_and_memory_share_one_registration_with_independent_copiers_and_safe_clos
656656
);
657657
assert_eq!(store.close().is_err(), fail.is_some());
658658
let order = factory.closed.lock().unwrap().clone();
659-
assert_eq!(
660-
order,
661-
if warm == 0 {
662-
vec![0]
663-
} else if fail == Some(1) {
664-
vec![1]
665-
} else {
666-
vec![1, 0]
667-
}
668-
);
659+
assert_eq!(order, if warm == 0 { vec![0] } else { vec![1, 0] });
669660
drop(store);
670661
assert_eq!(*registrar.drops.lock().unwrap(), 0);
671662
pool.release_page(slot);

‎selene/src/pool/agent.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1729,6 +1729,9 @@ impl Agent {
17291729
if let Some(att) = &self.att {
17301730
std::mem::forget(att.regions.clone());
17311731
}
1732+
if let Some((_, regions)) = self.shared.take() {
1733+
std::mem::forget(regions);
1734+
}
17321735
if let Some(staging) = self.staging.take() {
17331736
std::mem::forget(staging);
17341737
}

‎selene/src/pool/conn.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ async fn shutdown(engine: &mut Engine, link: &Link) -> Result<()> {
216216
if engine.quiet() && !engine.quarantined() {
217217
Ok(())
218218
} else {
219+
engine.quarantine();
219220
Err(Error::new(
220221
"the pool could not drain its transfers at close",
221222
))

0 commit comments

Comments
 (0)