thin-provisioning-tools/src/write_batcher.rs

109 lines
2.7 KiB
Rust
Raw Normal View History

2020-11-04 18:08:35 +05:30
use anyhow::{anyhow, Result};
2021-03-24 19:50:20 +05:30
use std::collections::BTreeSet;
2020-11-04 18:08:35 +05:30
use std::sync::{Arc, Mutex};
use crate::checksum;
use crate::io_engine::*;
use crate::pdata::space_map::*;
//------------------------------------------
#[derive(Clone)]
2020-11-04 18:08:35 +05:30
pub struct WriteBatcher {
pub engine: Arc<dyn IoEngine + Send + Sync>,
2021-03-24 19:50:20 +05:30
// FIXME: this doesn't need to be in a mutex
pub sm: Arc<Mutex<dyn SpaceMap>>,
2020-11-04 18:08:35 +05:30
batch_size: usize,
queue: Vec<Block>,
2021-03-24 19:50:20 +05:30
allocations: BTreeSet<u64>,
2020-11-04 18:08:35 +05:30
}
impl WriteBatcher {
pub fn new(
engine: Arc<dyn IoEngine + Send + Sync>,
sm: Arc<Mutex<dyn SpaceMap>>,
batch_size: usize,
) -> WriteBatcher {
WriteBatcher {
engine,
sm,
batch_size,
queue: Vec::with_capacity(batch_size),
2021-03-24 19:50:20 +05:30
allocations: BTreeSet::new(),
2020-11-04 18:08:35 +05:30
}
}
2021-03-24 19:50:20 +05:30
pub fn alloc(&mut self) -> Result<Block> {
2020-11-04 18:08:35 +05:30
let mut sm = self.sm.lock().unwrap();
let b = sm.alloc()?;
if b.is_none() {
return Err(anyhow!("out of metadata space"));
}
self.allocations.insert(b.unwrap());
2021-03-24 19:50:20 +05:30
Ok(Block::new(b.unwrap()))
}
pub fn alloc_zeroed(&mut self) -> Result<Block> {
let mut sm = self.sm.lock().unwrap();
let b = sm.alloc()?;
if b.is_none() {
return Err(anyhow!("out of metadata space"));
}
self.allocations.insert(b.unwrap());
Ok(Block::zeroed(b.unwrap()))
}
2021-03-24 19:50:20 +05:30
pub fn clear_allocations(&mut self) -> BTreeSet<u64> {
let mut tmp = BTreeSet::new();
std::mem::swap(&mut tmp, &mut self.allocations);
tmp
2020-11-04 18:08:35 +05:30
}
pub fn write(&mut self, b: Block, kind: checksum::BT) -> Result<()> {
checksum::write_checksum(&mut b.get_data(), kind)?;
if self.queue.len() == self.batch_size {
2021-03-24 19:50:20 +05:30
let mut tmp = Vec::new();
std::mem::swap(&mut tmp, &mut self.queue);
self.flush_(tmp)?;
2020-11-04 18:08:35 +05:30
}
self.queue.push(b);
Ok(())
}
pub fn read(&mut self, blocknr: u64) -> Result<Block> {
for b in self.queue.iter().rev() {
if b.loc == blocknr {
let r = Block::new(b.loc);
r.get_data().copy_from_slice(b.get_data());
return Ok(r);
}
}
2021-05-04 13:40:20 +05:30
self.engine
.read(blocknr)
.map_err(|_| anyhow!("read block error"))
}
2021-03-24 19:50:20 +05:30
pub fn flush_(&mut self, queue: Vec<Block>) -> Result<()> {
self.engine.write_many(&queue)?;
Ok(())
}
2020-11-04 18:08:35 +05:30
pub fn flush(&mut self) -> Result<()> {
2021-03-24 19:50:20 +05:30
let mut tmp = Vec::new();
std::mem::swap(&mut tmp, &mut self.queue);
self.flush_(tmp)?;
2020-11-04 18:08:35 +05:30
Ok(())
}
}
//------------------------------------------