Skip to content
Merged
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
26 changes: 12 additions & 14 deletions selene-manager/src/data/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -733,11 +733,11 @@ async fn send_windows(
.write(conn)
.await?;
for (at, u) in parts {
// The granted extent is held until this handler has fenced.
// SAFETY: the granted extent stays immutable until this handler fences.
let data = unsafe {
inner
.regions
.bytes(window.region, window.offset + at, u.stored_length)?
.bytes_read(window.region, window.offset + at, u.stored_length)?
};
conn.write_all(data).await?;
}
Expand Down Expand Up @@ -780,7 +780,7 @@ async fn send_windows(
None => unsafe {
inner
.regions
.bytes(window.region, window.offset, window.shape.length)?
.bytes_read(window.region, window.offset, window.shape.length)?
},
Some((layout, rank)) => {
let (pages, row) = (window.shape.page_count, window.shape.row);
Expand All @@ -789,7 +789,7 @@ async fn send_windows(
}
// SAFETY: as above, over the whole window the slice lies in.
let whole = unsafe {
inner.regions.bytes(
inner.regions.bytes_read(
window.region,
window.offset,
layout.window_bytes(pages, row),
Expand Down Expand Up @@ -931,16 +931,14 @@ async fn receive_windows(
reader.read_exact(&mut packed),
)
.await?;
// SAFETY: as above, over the whole window the slice lies in.
let whole = unsafe {
inner.regions.bytes(
grant.region,
grant.offset,
layout.window_bytes(pages, row),
)?
};
layout
.scatter(*rank, whole, pages, row, &packed)
let (base, len) = inner.regions.ptr_mut(
grant.region,
grant.offset,
layout.window_bytes(pages, row),
)?;
// SAFETY: the put owns the granted window until fenced, and each rank
// writes only its own disjoint slices within `base..base + len`.
unsafe { layout.scatter_disjoint(*rank, base, len, pages, row, &packed) }
.map_err(|error| invalid(error.to_string()))?;
}
}
Expand Down
2 changes: 1 addition & 1 deletion selene-manager/src/pool/pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ fn compute(job: &PassJob, window: &[u8]) -> Result<PassOut, PassError> {
pub fn run(job: PassJob) -> Result<PassOut, PassError> {
let length = job.layout.window_bytes(job.pages, job.row);
// SAFETY: the pool retains this window unchanged until the pass completes.
let window = unsafe { job.regions.bytes(job.region, job.offset, length) }
let window = unsafe { job.regions.bytes_read(job.region, job.offset, length) }
.map_err(|error| PassError::Io(error.to_string()))?;
compute(&job, window)
}
Expand Down
66 changes: 58 additions & 8 deletions selene-manager/src/regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,44 @@ impl LocalRegions {
}
}

fn range(&self, region: Region, offset: u64, length: u64) -> io::Result<(*mut u8, usize)> {
let (base, size) = self.mapping(region);
let end = offset
.checked_add(length)
.ok_or_else(|| invalid("window range overflow"))?;
if end > size as u64 {
return Err(invalid("a window lies outside its region"));
}
// SAFETY: `offset <= end <= size`, so the pointer stays within the mapped region.
Ok((unsafe { base.add(offset as usize) }, length as usize))
}

/// Read-only view of a mapped range that may be shared with concurrent readers.
///
/// # Safety
/// No writer may mutate the range while the slice lives, and the mapping must
/// stay alive.
pub unsafe fn bytes_read<'a>(
&self,
region: Region,
offset: u64,
length: u64,
) -> io::Result<&'a [u8]> {
let (ptr, len) = self.range(region, offset, length)?;
// SAFETY: bounds are checked; immutability and lifetime are the caller's contract.
Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
}

/// Raw writable pointer to a validated range for concurrent disjoint sub-writes.
pub fn ptr_mut(
&self,
region: Region,
offset: u64,
length: u64,
) -> io::Result<(*mut u8, usize)> {
self.range(region, offset, length)
}

/// # Safety
/// The caller must own the range exclusively while the slice lives, and keep
/// this mapping alive. The store leases windows until their handler is fenced.
Expand All @@ -36,15 +74,9 @@ impl LocalRegions {
offset: u64,
length: u64,
) -> io::Result<&'a mut [u8]> {
let (base, size) = self.mapping(region);
let end = offset
.checked_add(length)
.ok_or_else(|| invalid("window range overflow"))?;
if end > size as u64 {
return Err(invalid("a window lies outside its region"));
}
let (ptr, len) = self.range(region, offset, length)?;
// SAFETY: bounds are checked; ownership and lifetime are the caller's contract.
Ok(unsafe { std::slice::from_raw_parts_mut(base.add(offset as usize), length as usize) })
Ok(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
}

Expand Down Expand Up @@ -92,6 +124,24 @@ mod tests {
assert!(regions.bytes(Region::Staging, 16 * 1024, 1).is_err());
assert!(regions.bytes(Region::Arena, u64::MAX, 2).is_err());
assert!(regions.bytes(Region::Staging, 32 * 1024, 1).is_err());
assert!(regions.bytes_read(Region::Arena, 64 * 1024, 1).is_err());
assert!(regions.ptr_mut(Region::Staging, 16 * 1024, 1).is_err());
}
}

#[test]
fn bytes_read_allows_overlapping_shared_views() {
let regions = regions();
// SAFETY: exclusive write finishes before shared immutable borrows begin.
unsafe {
regions
.bytes(Region::Arena, 4096, 4)
.unwrap()
.copy_from_slice(b"data");
let a = regions.bytes_read(Region::Arena, 4096, 4).unwrap();
let b = regions.bytes_read(Region::Arena, 4096, 4).unwrap();
assert_eq!(a, b"data");
assert_eq!(b, b"data");
}
}
}
6 changes: 3 additions & 3 deletions selene/src/composite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1616,14 +1616,14 @@ impl HostStore for CompositeStore {
events.clear();
std::thread::sleep(Duration::from_millis(1));
}
self.disk.close()?;
self.memory.close()?;
let disk = self.disk.close();
let memory = self.memory.close();
self.outbound.clear();
self.parked.clear();
self.inbound.clear();
self.jobs.clear();
self.stale.clear();
Ok(())
disk.and(memory)
}
}

Expand Down
4 changes: 4 additions & 0 deletions selene/src/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2029,6 +2029,10 @@ impl ReadAhead {
return Err(invalid("read-ahead range is not block aligned"));
}
let ring = Ring::new()?;
#[cfg(windows)]
ring.queue
.attach(&file)
.map_err(|e| io_failure("attach read-ahead file", e))?;
let (free, recycled) = mpsc::channel::<AlignedBuffer>();
let (sender, blocks) = mpsc::channel::<Result<AheadBlock>>();
let count = AHEAD_BLOCKS.min(((end - start) as usize).div_ceil(AHEAD_BLOCK_BYTES).max(1));
Expand Down
4 changes: 2 additions & 2 deletions selene/src/disk_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,11 @@ impl Buffers {
/// The threads and pool every pipeline draws on, with the counters that keep
/// submissions within the queues' depths so a refusal is a failure, not backpressure.
struct Resources {
/// Declared before `pool` so Drop joins `DiskThread` before unmapping pinned slabs.
/// Declared before `pool` so Drop joins `DiskThread` and copy threads before unmapping slabs.
disk: DiskThread,
transfers: SharedCopier,
/// Shared slots for device transfers; host-buffer-only users may omit them.
pool: Option<SlabPool>,
transfers: SharedCopier,
/// Disk jobs submitted whose replies have not been polled.
disk_outstanding: usize,
next_disk: u64,
Expand Down
43 changes: 33 additions & 10 deletions selene/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2021,14 +2021,20 @@ impl AsyncCompressor {
let slab_bytes = self.slab_bytes;
let tx = self.tx.clone();
let active = self.active.clone();
struct ActiveGuard(Arc<(Mutex<usize>, Condvar)>);
impl Drop for ActiveGuard {
fn drop(&mut self) {
let mut count = self.0.0.lock().unwrap_or_else(PoisonError::into_inner);
*count = count.saturating_sub(1);
if *count == 0 {
self.0.1.notify_all();
}
}
}
pool.spawn(move || {
let _guard = ActiveGuard(active);
let record = encode_host_task(pool, &encoder, &layout, slab_bytes, scratch, task);
let _ = tx.send(record);
let mut count = active.0.lock().unwrap_or_else(PoisonError::into_inner);
*count = count.saturating_sub(1);
if *count == 0 {
active.1.notify_all();
}
});
}
}
Expand Down Expand Up @@ -2231,12 +2237,12 @@ fn encode_host_task(

pub struct MemoryStore {
pass_through: bool,
// Dropped first: checksum and async compression threads read slots the core frees.
// Dropped first: checksum, async compression, and copy threads access slabs the core owns.
announce: Option<Announce>,
#[cfg(feature = "codec")]
compressor: Option<AsyncCompressor>,
core: Core,
transfers: SharedCopier,
core: Core,
/// Reply scratch reused across polls.
replies: Vec<Reply>,
/// Completions produced outside `poll`, delivered by the next `poll`.
Expand Down Expand Up @@ -3086,11 +3092,28 @@ impl HostStore for MemoryStore {
std::thread::sleep(Duration::from_millis(1));
}
}
self.transfers
#[cfg(feature = "codec")]
let compressor_busy = self.compressor.as_ref().is_some_and(|c| !c.is_idle());
#[cfg(not(feature = "codec"))]
let compressor_busy = false;
let closed = self
.transfers
.lock()
.unwrap_or_else(PoisonError::into_inner)
.close()
.inspect_err(|_| self.core.pool.leak())?;
.close();
if closed.is_err() || compressor_busy {
self.core.pool.leak();
}
closed?;
if compressor_busy {
#[cfg(feature = "codec")]
if let Some(compressor) = self.compressor.take() {
std::mem::forget(compressor);
}
return Err(Error::new(
"host KV compression did not finish before close",
));
}
self.core.abandon();
self.events.clear();
Ok(())
Expand Down
11 changes: 1 addition & 10 deletions selene/src/offload/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,16 +656,7 @@ fn disk_and_memory_share_one_registration_with_independent_copiers_and_safe_clos
);
assert_eq!(store.close().is_err(), fail.is_some());
let order = factory.closed.lock().unwrap().clone();
assert_eq!(
order,
if warm == 0 {
vec![0]
} else if fail == Some(1) {
vec![1]
} else {
vec![1, 0]
}
);
assert_eq!(order, if warm == 0 { vec![0] } else { vec![1, 0] });
drop(store);
assert_eq!(*registrar.drops.lock().unwrap(), 0);
pool.release_page(slot);
Expand Down
3 changes: 3 additions & 0 deletions selene/src/pool/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1729,6 +1729,9 @@ impl Agent {
if let Some(att) = &self.att {
std::mem::forget(att.regions.clone());
}
if let Some((_, regions)) = self.shared.take() {
std::mem::forget(regions);
}
if let Some(staging) = self.staging.take() {
std::mem::forget(staging);
}
Expand Down
1 change: 1 addition & 0 deletions selene/src/pool/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ async fn shutdown(engine: &mut Engine, link: &Link) -> Result<()> {
if engine.quiet() && !engine.quarantined() {
Ok(())
} else {
engine.quarantine();
Err(Error::new(
"the pool could not drain its transfers at close",
))
Expand Down
8 changes: 7 additions & 1 deletion selene/src/pool/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ impl Engine {

/// Drain cannot be established: keep every pin, mapping and registration
/// for the life of the process and report it.
fn quarantine(&mut self) {
pub(crate) fn quarantine(&mut self) {
if self.quarantined {
return;
}
Expand All @@ -555,6 +555,12 @@ impl Engine {
for regions in self.draining.drain(..) {
std::mem::forget(regions);
}
if let Some(regions) = self.sess.as_mut().and_then(|sess| sess.regions.take()) {
std::mem::forget(regions);
}
if let Some(super::shm::Attachment::Shm { regions, .. }) = self.attachment.take() {
std::mem::forget(regions);
}
if let Some(staging) = self.net.take() {
std::mem::forget(staging);
}
Expand Down
20 changes: 20 additions & 0 deletions selene/src/pool/engine/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1568,6 +1568,26 @@ fn a_copy_that_never_drains_quarantines_the_pin_and_the_regions() {
assert!(matches!(rig.shared.status(), PoolStatus::Disabled(_)));
}

#[test]
fn mid_session_quarantine_retains_active_session_and_attachment_regions() {
let mut rig = Rig::new();
rig.open();
rig.engine.attachment = Some(super::super::shm::Attachment::Shm {
shared: wire::SharedMemory::default(),
regions: rig.regions.clone(),
});
let weak = Arc::downgrade(&rig.regions);
let regions = rig.regions.clone();
rig.engine.quarantine();
assert!(rig.engine.quarantined());
drop(rig);
drop(regions);
assert!(
weak.upgrade().is_some(),
"quarantined SHM regions must remain mapped after the engine drops"
);
}

#[test]
fn a_failed_d2h_fails_the_fill_and_ends_the_export_after_the_drain() {
let mut rig = Rig::new();
Expand Down
10 changes: 3 additions & 7 deletions selene/src/pool/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub(crate) struct Staging {
/// Registrations by local data socket address. Declared first so staging is
/// unregistered before the region is unmapped.
rdma: Mutex<HashMap<IpAddr, Option<Arc<rdma::Device>>>>,
region: Region,
region: Arc<Region>,
slot_bytes: u64,
free: Mutex<Vec<u32>>,
permits: Semaphore,
Expand Down Expand Up @@ -89,7 +89,7 @@ impl Staging {
region.register(registrar, context)?;
Ok(Self {
rdma: Mutex::new(HashMap::new()),
region,
region: Arc::new(region),
slot_bytes,
free: Mutex::new((0..slots).rev().collect()),
permits: Semaphore::new(slots as usize),
Expand All @@ -111,11 +111,7 @@ impl Staging {
.unwrap()
.entry(local_address)
.or_insert_with(|| {
// SAFETY: the region stays mapped at this address for as long as `self`
// lives, and the device is dropped first (field order).
match unsafe {
rdma::Device::open(self.region.base() as *mut u8, self.region.len(), local_address)
} {
match rdma::Device::open(self.region.clone(), local_address) {
Ok(device) => Some(device),
Err(error) => {
eprintln!(
Expand Down
Loading
Loading