1 //! Residency: which model is on which device, and what that costs.2 //!3 //! The ledger answers "is there room"; this module answers "who holds it". A4 //! device is declared once, from the catalogue that the plugin printed or from5 //! the operator's deploy file, and every load takes a reservation that it gives6 //! back when the model leaves.7 //!8 //! A model leaves only when its child dies, so this module also remembers the9 //! intent that decides which child goes: a pin, an idle window, and the last10 //! time a job used it. The loader trait is the process side of that decision;11 //! the ledger is the byte side, and neither knows the other.12 //!13 //! A child that stops does not free its mmapped weights at once. The14 //! reservation waits on the driver's own free number, because releasing it15 //! first refuses the next load for room that is about to appear.16 17 use std::collections::{BTreeMap, BTreeSet};18 use std::sync::{Arc, Mutex, MutexGuard};19 use std::time::{Duration, Instant};20 21 use crate::refusal::RefusalCode;22 use inf3r_host::{device_free_bytes, process_tree, process_tree_bytes, process_vram_bytes};23 use inf3r_ledger::{Ledger, LedgerError, Reservation};24 25 /// The reason a model could not be resident.26 #[derive(Clone, PartialEq, Eq, Debug)]27 pub enum ResidencyError {28 /// The ledger has no room on one device.29 NoRoom {30 /// The device.31 device: String,32 /// Bytes that were wanted.33 want: u64,34 /// Bytes that are free.35 free: u64,36 },37 /// The device never reported the bytes that the caller wanted.38 Settled {39 /// The device.40 device: String,41 /// Bytes that were wanted.42 want: u64,43 /// The last number that the device reported, or zero when it reported44 /// none.45 free: u64,46 /// How long the caller waited for the number.47 waited: Duration,48 },49 /// The device was never declared, so no number describes it.50 Unknown {51 /// The device.52 device: String,53 },54 /// The child holds less resident memory than its declaration implies.55 Short {56 /// Bytes that the catalogue declared.57 declared: u64,58 /// Bytes that the child holds, or zero when it is gone.59 measured: u64,60 /// The child process.61 pid: u32,62 },63 }64 65 impl ResidencyError {66 /// The client code for this failure.67 pub fn code(&self) -> RefusalCode {68 match self {69 ResidencyError::NoRoom { .. } | ResidencyError::Settled { .. } => RefusalCode::NoRoom,70 ResidencyError::Short { .. } => RefusalCode::NoRoom,71 ResidencyError::Unknown { .. } => RefusalCode::Mismatch,72 }73 }74 }75 76 impl std::fmt::Display for ResidencyError {77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {78 match self {79 ResidencyError::NoRoom { device, want, free } => write!(80 f,81 "{device} has {free} bytes free and the model wants {want}"82 ),83 ResidencyError::Settled {84 device,85 want,86 free,87 waited,88 } => write!(89 f,90 "{device} freed {free} bytes after {waited:?}, but the model wants {want}"91 ),92 ResidencyError::Unknown { device } => {93 write!(f, "no device {device} was declared")94 }95 ResidencyError::Short {96 declared,97 measured,98 pid,99 } => write!(100 f,101 "pid {pid} holds {measured} resident bytes of the {declared} it declared"102 ),103 }104 }105 }106 107 impl std::error::Error for ResidencyError {}108 109 /// How long to wait for the driver to report the bytes of a stopped child.110 ///111 /// The fields are public so that a test and a deploy can choose a clock instead112 /// of inheriting one that was chosen for the busiest host.113 #[derive(Clone, Copy, PartialEq, Eq, Debug)]114 pub struct Settle {115 /// The longest wait before the caller releases the reservation anyway.116 pub budget: Duration,117 /// The pause between two reads of the device.118 pub step: Duration,119 }120 121 impl Default for Settle {122 fn default() -> Settle {123 Settle {124 budget: DEFAULT_SETTLE_BUDGET,125 step: DEFAULT_SETTLE_STEP,126 }127 }128 }129 130 /// The longest wait for the driver to free a stopped child's bytes.131 ///132 /// A driver frees mmapped weights some time after the process exits. Two133 /// seconds covers a busy host without keeping a reservation past the next134 /// load's patience.135 pub const DEFAULT_SETTLE_BUDGET: Duration = Duration::from_secs(2);136 137 /// The pause between two reads of a device's free bytes.138 ///139 /// A shorter pause spends more driver queries for no more certainty, and a140 /// longer one adds that delay to every unload.141 pub const DEFAULT_SETTLE_STEP: Duration = Duration::from_millis(50);142 143 /// The shortest pause that still lets a loop reach its budget. A zero step144 /// would spin without advancing the clock.145 const MIN_SETTLE_STEP: Duration = Duration::from_millis(1);146 147 /// The denominator of the resident check.148 ///149 /// A runtime's own allocator, page tables, and the CUDA context make resident150 /// bytes exceed the weight file, so the check asks that the child holds at151 /// least `declared / RSS_TOLERANCE`. Two means half: a child that holds less152 /// than half of what it declared did not load the weights it was granted.153 pub const RSS_TOLERANCE: u64 = 2;154 155 /// A source of a device's free bytes and of the time between two reads.156 ///157 /// The trait exists so that a test can count time instead of sleeping, and so158 /// that the real waiter is one implementation rather than a loop in every159 /// caller.160 pub trait Waiter {161 /// Bytes that the device reports free now, or `None` when it reports none.162 fn sample(&mut self, device: &str) -> Option<u64>;163 /// Waits for `d`.164 fn sleep(&mut self, d: Duration);165 }166 167 /// The waiter that asks the host and sleeps in real time.168 #[derive(Clone, Copy, Debug, Default)]169 pub struct HostWaiter;170 171 impl Waiter for HostWaiter {172 fn sample(&mut self, device: &str) -> Option<u64> {173 // One query for one device. A full probe would read every card and174 // every soname for a number that this loop needs once per step.175 device_free_bytes(device)176 }177 178 fn sleep(&mut self, d: Duration) {179 std::thread::sleep(d);180 }181 }182 183 /// A waiter that asks the installed free sampler.184 struct SamplerWaiter {185 sampler: FreeSampler,186 slept: Duration,187 }188 189 impl Waiter for SamplerWaiter {190 fn sample(&mut self, device: &str) -> Option<u64> {191 (self.sampler)(device)192 }193 194 fn sleep(&mut self, d: Duration) {195 self.slept += d;196 std::thread::sleep(d);197 }198 }199 200 /// A source of the bytes that a process tree holds.201 ///202 /// A GPU engine keeps its weights in device memory and a bound engine keeps203 /// them in a child, so "resident bytes" is not one number from one file. The204 /// trait keeps the choice testable without a GPU, and lets a container probe205 /// answer for a host pid that the control's `/proc` cannot see.206 pub trait Memory {207 /// Resident bytes of the tree rooted at `root` (a host pid).208 fn rss(&self, root: u32) -> Option<u64>;209 /// Bytes of one device that the tree rooted at `root` holds.210 fn vram(&self, root: u32, device: &str) -> Option<u64>;211 }212 213 /// The probe that asks the host.214 #[derive(Clone, Copy, Debug, Default)]215 pub struct HostMemory;216 217 impl Memory for HostMemory {218 fn rss(&self, root: u32) -> Option<u64> {219 process_tree_bytes(root)220 }221 222 fn vram(&self, root: u32, device: &str) -> Option<u64> {223 let pids = process_tree(root);224 process_vram_bytes(&pids, device)225 }226 }227 228 /// The intent and the last use of one plugin.229 struct Slot {230 pin: bool,231 idle: Option<Duration>,232 last_used: Instant,233 models: BTreeSet<String>,234 reservation: Option<Reservation>,235 }236 237 impl Slot {238 fn new() -> Slot {239 Slot {240 pin: false,241 idle: None,242 last_used: Instant::now(),243 models: BTreeSet::new(),244 reservation: None,245 }246 }247 }248 249 /// The devices of one host, the reservations on them, and the intent of each250 /// plugin that holds one.251 pub struct Residency {252 ledger: Mutex<Ledger>,253 slots: Mutex<BTreeMap<String, Slot>>,254 measured: Mutex<BTreeMap<String, u64>>,255 /// Free bytes on each device immediately before a plugin's child starts.256 /// A stop must return the card to this line, not to its nominal capacity:257 /// the desktop or another process owns the rest of the card.258 baseline: Mutex<BTreeMap<String, BTreeMap<String, u64>>>,259 settle: Mutex<Settle>,260 /// Where the settle loop reads free bytes. `None` is the local host; a261 /// container control installs a probe that crosses its namespaces.262 free_sampler: Mutex<Option<FreeSampler>>,263 }264 265 /// A function that reads one device's free bytes.266 type FreeSampler = Arc<dyn Fn(&str) -> Option<u64> + Send + Sync>;267 268 impl Default for Residency {269 fn default() -> Residency {270 Residency::new()271 }272 }273 274 impl Residency {275 /// A host with no device.276 pub fn new() -> Residency {277 Residency::with_settle(Settle::default())278 }279 280 /// A host with a chosen settle clock.281 pub fn with_settle(settle: Settle) -> Residency {282 Residency {283 ledger: Mutex::new(Ledger::new([])),284 slots: Mutex::new(BTreeMap::new()),285 measured: Mutex::new(BTreeMap::new()),286 baseline: Mutex::new(BTreeMap::new()),287 settle: Mutex::new(settle),288 free_sampler: Mutex::new(None),289 }290 }291 292 /// Replaces the source of a device's free bytes.293 ///294 /// The local probe reads `nvidia-smi` in this namespace. A container295 /// control has no GPU and cannot see host pids, so it installs the probe296 /// helper here. Both answer the same one question.297 pub fn set_free_sampler<F>(&self, sampler: F)298 where299 F: Fn(&str) -> Option<u64> + Send + Sync + 'static,300 {301 *lock(&self.free_sampler) = Some(Arc::new(sampler));302 }303 304 fn sample_free(&self, device: &str) -> Option<u64> {305 let sampler = lock(&self.free_sampler).clone();306 match sampler {307 Some(sampler) => sampler(device),308 None => device_free_bytes(device),309 }310 }311 312 /// Replaces the settle clock after the core was built from the deploy file.313 pub fn set_settle(&self, settle: Settle) {314 *lock(&self.settle) = settle;315 }316 317 /// Records the served names of one plugin.318 ///319 /// The names are what a job asks for; the loader and the ledger work on the320 /// plugin that serves them. Both sides need the mapping, so it lives here.321 pub fn serve(&self, plugin: &str, models: impl IntoIterator<Item = String>) {322 let mut slots = lock(&self.slots);323 let slot = slots.entry(plugin.to_string()).or_insert_with(Slot::new);324 slot.models = models.into_iter().collect();325 slot.last_used = Instant::now();326 }327 328 /// Declares whether a plugin may be unloaded and after how long.329 ///330 /// A pin is an operator promise: it is never chosen for eviction. An absent331 /// idle window means the only reason to unload is room for another model.332 pub fn declare_intent(&self, plugin: &str, pin: bool, idle: Option<Duration>) {333 let mut slots = lock(&self.slots);334 let slot = slots.entry(plugin.to_string()).or_insert_with(Slot::new);335 slot.pin = pin;336 slot.idle = idle;337 }338 339 /// Records that a job of this plugin finished.340 ///341 /// The clock is read here, not in the schedule: last use is a property of342 /// the plugin and survives the job that touched it.343 pub fn touch(&self, plugin: &str) {344 let mut slots = lock(&self.slots);345 let slot = slots.entry(plugin.to_string()).or_insert_with(Slot::new);346 slot.last_used = Instant::now();347 }348 349 /// Attaches a reservation to the plugin that holds it.350 pub fn hold(&self, plugin: &str, reservation: Reservation) {351 let mut slots = lock(&self.slots);352 let slot = slots.entry(plugin.to_string()).or_insert_with(Slot::new);353 slot.reservation = Some(reservation);354 slot.last_used = Instant::now();355 }356 357 /// Takes the reservation back so that the caller can wait and release it.358 pub fn release_plugin(&self, plugin: &str) -> Option<Reservation> {359 let mut slots = lock(&self.slots);360 slots361 .get_mut(plugin)362 .and_then(|slot| slot.reservation.take())363 }364 365 /// Whether the plugin holds a reservation now.366 pub fn resident(&self, plugin: &str) -> bool {367 lock(&self.slots)368 .get(plugin)369 .is_some_and(|slot| slot.reservation.is_some())370 }371 372 /// Unpinned resident plugins that have been idle past their window.373 ///374 /// The order is oldest first so that the caller stops the coldest model375 /// when it stops several. A busy plugin is not idle however old its last376 /// job is.377 pub fn idle_candidates(&self, now: Instant, busy: &BTreeSet<String>) -> Vec<String> {378 let slots = lock(&self.slots);379 let mut candidates: Vec<(Instant, String)> = slots380 .iter()381 .filter(|(plugin, slot)| {382 !slot.pin383 && !busy.contains(*plugin)384 && slot.reservation.is_some()385 && slot386 .idle387 .is_some_and(|idle| now.saturating_duration_since(slot.last_used) > idle)388 })389 .map(|(plugin, slot)| (slot.last_used, (*plugin).clone()))390 .collect();391 candidates.sort();392 candidates.into_iter().map(|(_, plugin)| plugin).collect()393 }394 395 /// The unpinned resident plugin that has waited longest since its last job.396 ///397 /// It is the eviction order of the ledger. A plugin with a job in flight is398 /// skipped because stopping it would cut a live stream.399 pub fn lru(&self, busy: &BTreeSet<String>) -> Option<String> {400 self.lru_skipping(busy, &BTreeSet::new())401 }402 403 /// The LRU victim that is neither busy nor already stopping.404 ///405 /// A plugin that another thread is stopping must not be chosen again: its406 /// reservation is still in the ledger until its stop finishes, but it is407 /// not a victim that this caller can stop a second time.408 pub fn lru_skipping(409 &self,410 busy: &BTreeSet<String>,411 stopping: &BTreeSet<String>,412 ) -> Option<String> {413 let slots = lock(&self.slots);414 slots415 .iter()416 .filter(|(plugin, slot)| {417 !slot.pin418 && !busy.contains(*plugin)419 && !stopping.contains(*plugin)420 && slot.reservation.is_some()421 })422 .min_by_key(|(plugin, slot)| (slot.last_used, (*plugin).clone()))423 .map(|(plugin, _)| plugin.clone())424 }425 426 /// The LRU victim that actually holds bytes on the short device.427 ///428 /// A host has more than one device class. Evicting the oldest plugin when429 /// a card is short can stop a CPU model that frees nothing on that card and430 /// then leave the card just as full. The caller names the device from the431 /// ledger refusal, so only a reservation that charges that device is a432 /// candidate.433 pub fn lru_on(434 &self,435 device: &str,436 busy: &BTreeSet<String>,437 stopping: &BTreeSet<String>,438 ) -> Option<String> {439 let slots = lock(&self.slots);440 slots441 .iter()442 .filter(|(plugin, slot)| {443 !slot.pin444 && !busy.contains(*plugin)445 && !stopping.contains(*plugin)446 && slot.reservation.as_ref().is_some_and(|reservation| {447 reservation.held().get(device).copied().unwrap_or(0) > 0448 })449 })450 .min_by_key(|(plugin, slot)| (slot.last_used, (*plugin).clone()))451 .map(|(plugin, _)| plugin.clone())452 }453 454 /// Declares the bytes of one device. The first declaration wins: a second455 /// plugin that reports a different number for the same card is a manifest456 /// error, and taking the larger number would hide it.457 pub fn declare(&self, device: &str, bytes: u64) {458 // Adding one device must not rebuild the ledger: a new card that a459 // later bind names would erase every reservation already held on the460 // cards before it.461 lock(&self.ledger).add_device(device, bytes);462 }463 464 /// Reserves the bytes that one model needs.465 pub fn reserve(&self, wants: &BTreeMap<String, u64>) -> Result<Reservation, ResidencyError> {466 // A device that wants zero bytes is still named, so a typo in a device467 // name is caught instead of reserved as nothing.468 for device in wants.keys() {469 if lock(&self.ledger).total(device).is_none() {470 return Err(ResidencyError::Unknown {471 device: device.clone(),472 });473 }474 }475 lock(&self.ledger).reserve(wants).map_err(|why| match why {476 LedgerError::NoRoom { device, free, want } => {477 ResidencyError::NoRoom { device, want, free }478 }479 LedgerError::Unknown { device } => ResidencyError::Unknown { device },480 // A release that does not match is unreachable from a fresh481 // reservation; report it as no room rather than panic.482 LedgerError::Spent { .. } => ResidencyError::Unknown {483 device: "ledger".to_string(),484 },485 })486 }487 488 /// Checks that the child holds the memory that the catalogue declared.489 ///490 /// A declaration is trusted until it is checked. A child that holds less491 /// than `declared / RSS_TOLERANCE` did not load the weights it was granted.492 /// The number is returned so that the caller can keep it for the stats row;493 /// a child that declared nothing has no number to check.494 pub fn verify_bytes(&self, pid: u32, declared: u64) -> Result<Option<u64>, ResidencyError> {495 self.verify_devices(pid, declared, &[], &HostMemory)496 }497 498 /// Checks the host-RAM half of a split resident set.499 ///500 /// A target that keeps some weights in host RAM names those bytes in its501 /// profile. The child tree must hold at least half of them, with the same502 /// tolerance that the device half uses: a runtime's own allocator and page503 /// tables make an exact equality meaningless, while a child that holds504 /// less than half did not load the part that its target promised.505 pub fn verify_ram(506 &self,507 pid: u32,508 declared: u64,509 memory: &dyn Memory,510 ) -> Result<Option<u64>, ResidencyError> {511 if declared == 0 {512 return Ok(None);513 }514 let want = declared / RSS_TOLERANCE;515 match memory.rss(pid) {516 Some(bytes) if bytes >= want => Ok(Some(bytes)),517 measured => Err(ResidencyError::Short {518 declared,519 measured: measured.unwrap_or(0),520 pid,521 }),522 }523 }524 525 /// Checks a load on the devices that the bind named.526 ///527 /// A GPU target is measured in device memory: its host RSS is small even528 /// when every weight is loaded. A CPU target is measured by the resident529 /// bytes of the process tree, because a bound bundle holds the weights in530 /// its engine child rather than in the launcher that the core started.531 pub fn verify_devices(532 &self,533 pid: u32,534 declared: u64,535 devices: &[String],536 memory: &dyn Memory,537 ) -> Result<Option<u64>, ResidencyError> {538 if declared == 0 {539 return Ok(None);540 }541 let want = declared / RSS_TOLERANCE;542 let measured = if devices.iter().any(|device| device.starts_with("cuda:")) {543 let mut total = Some(0u64);544 let mut seen = BTreeSet::new();545 for device in devices {546 if !seen.insert(device) || !device.starts_with("cuda:") {547 continue;548 }549 total = total.and_then(|sum| {550 memory551 .vram(pid, device)552 .map(|bytes| sum.saturating_add(bytes))553 });554 }555 total556 } else {557 memory.rss(pid)558 };559 match measured {560 Some(bytes) if bytes >= want => Ok(Some(bytes)),561 measured => Err(ResidencyError::Short {562 declared,563 measured: measured.unwrap_or(0),564 pid,565 }),566 }567 }568 569 /// Keeps the resident bytes that a child reported after its load passed.570 ///571 /// The catalogue declares the bytes; this number is what the process holds,572 /// and the two side by side are what makes a bad declaration visible.573 pub fn remember_measured(&self, plugin: &str, bytes: u64) {574 lock(&self.measured).insert(plugin.to_string(), bytes);575 }576 577 /// The last resident bytes that a plugin reported, if it reported any.578 pub fn measured(&self, plugin: &str) -> Option<u64> {579 lock(&self.measured).get(plugin).copied()580 }581 582 /// Records the free bytes of every declared device before a child starts.583 ///584 /// The nominal capacity is not the target after a stop: a desktop compositor585 /// or another process may hold part of the card. The line that the child586 /// must return to is the line it left.587 pub fn capture_free(&self, plugin: &str) {588 let devices: Vec<String> = self589 .devices()590 .into_iter()591 .map(|(device, _, _)| device)592 .collect();593 self.capture_free_on(plugin, &devices);594 }595 596 /// Records the free line for the devices that a bind named, before the597 /// ledger has seen them. A warm start asks this before the child exists.598 pub fn capture_free_on(&self, plugin: &str, devices: &[String]) {599 let mut line = BTreeMap::new();600 for device in devices {601 if !device.starts_with("cuda:") {602 continue;603 }604 if let Some(free) = self.sample_free(device) {605 line.insert(device.clone(), free);606 }607 }608 if !line.is_empty() {609 lock(&self.baseline).insert(plugin.to_string(), line);610 }611 }612 613 /// The free line that one device must reach after a plugin stops.614 pub fn stop_target(&self, plugin: &str, device: &str, released: u64) -> Option<u64> {615 let total = self.total(device)?;616 if let Some(line) = lock(&self.baseline).get(plugin)617 && let Some(free) = line.get(device)618 {619 return Some((*free).min(total));620 }621 self.free_after(device, released)622 }623 624 /// Forgets the last measured number after a crash.625 ///626 /// The slot and its intent stay: the plugin may start again. The number627 /// belonged to the process that died, so it must not describe the next one.628 pub fn forget_measured(&self, plugin: &str) {629 lock(&self.measured).remove(plugin);630 }631 632 fn forget_baseline(&self, plugin: &str) {633 lock(&self.baseline).remove(plugin);634 }635 636 /// Forgets a plugin that will not come back: a switch, not an unload.637 pub fn forget(&self, plugin: &str) {638 lock(&self.slots).remove(plugin);639 lock(&self.measured).remove(plugin);640 self.forget_baseline(plugin);641 }642 643 /// Free bytes that a device will have after a reservation is released.644 ///645 /// A settle wait must compare the driver with the number that the ledger646 /// will report after the release, not with the bytes of the reservation.647 /// A device that already had more free bytes than the reservation would648 /// otherwise pass before the driver freed anything.649 pub fn free_after(&self, device: &str, released: u64) -> Option<u64> {650 let ledger = lock(&self.ledger);651 let total = ledger.total(device)?;652 let held = ledger.held(device);653 Some(total.saturating_sub(held.saturating_sub(released)))654 }655 656 /// Waits until the device reports at least `want` free bytes, or the657 /// budget passes. Returns the wait it took.658 ///659 /// A device that reports no number makes no progress: the wait still ends660 /// at the budget, and the error reports zero because no other number was661 /// read.662 pub fn settle(663 &self,664 device: &str,665 want: u64,666 w: &mut dyn Waiter,667 ) -> Result<Duration, ResidencyError> {668 if self.total(device).is_none() {669 return Err(ResidencyError::Unknown {670 device: device.to_string(),671 });672 }673 let settle = *lock(&self.settle);674 let step = settle.step.max(MIN_SETTLE_STEP);675 let mut waited = Duration::ZERO;676 let mut free = None;677 loop {678 if let Some(sample) = w.sample(device) {679 free = Some(sample);680 if sample >= want {681 return Ok(waited);682 }683 }684 if waited >= settle.budget {685 return Err(ResidencyError::Settled {686 device: device.to_string(),687 want,688 free: free.unwrap_or(0),689 waited,690 });691 }692 let pause = step.min(settle.budget - waited);693 w.sleep(pause);694 waited += pause;695 }696 }697 698 /// Waits with the sampler that this host installed, or the local one.699 pub fn settle_default(&self, device: &str, want: u64) -> Result<Duration, ResidencyError> {700 let sampler = lock(&self.free_sampler).clone();701 match sampler {702 Some(sampler) => {703 let mut waiter = SamplerWaiter {704 sampler,705 slept: Duration::ZERO,706 };707 self.settle(device, want, &mut waiter)708 }709 None => {710 let mut waiter = HostWaiter;711 self.settle(device, want, &mut waiter)712 }713 }714 }715 716 /// Gives the bytes back.717 pub fn release(&self, reservation: Reservation) {718 let _ = lock(&self.ledger).release(reservation);719 }720 721 /// Takes every reservation back without waiting for a settle.722 ///723 /// This is the process exit path. A reservation must reach its ledger724 /// before the residency value is dropped, or the drop assertion reports a725 /// load that nobody gave back.726 pub fn release_all(&self) {727 let reservations: Vec<Reservation> = {728 let mut slots = lock(&self.slots);729 slots730 .values_mut()731 .filter_map(|slot| slot.reservation.take())732 .collect()733 };734 for reservation in reservations {735 self.release(reservation);736 }737 }738 739 /// Bytes in use on one device.740 pub fn held(&self, device: &str) -> u64 {741 lock(&self.ledger).held(device)742 }743 744 /// Bytes that one device has.745 pub fn total(&self, device: &str) -> Option<u64> {746 lock(&self.ledger).total(device)747 }748 749 /// Every device with its bytes and its held bytes.750 pub fn devices(&self) -> Vec<(String, u64, u64)> {751 let ledger = lock(&self.ledger);752 ledger753 .devices()754 .map(|(device, total, free)| (device.to_string(), total, total - free))755 .collect()756 }757 }758 759 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {760 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())761 }