diff --git a/nomt/src/beatree/allocator/free_list.rs b/nomt/src/beatree/allocator/free_list.rs index 0e2b87df33..198b7fbcb9 100644 --- a/nomt/src/beatree/allocator/free_list.rs +++ b/nomt/src/beatree/allocator/free_list.rs @@ -8,38 +8,34 @@ use super::PageNumber; const MAX_PNS_PER_PAGE: usize = (PAGE_SIZE - 6) / 4; -/// In-memory version of FreeList which provides a way to decode from and encode into pages -/// and provide two primitives, one for extracting free pages from the list and one to append -/// freed pages. -/// -/// Pages that are freed due to the fetch of free pages are automatically added back during the encode phase, -/// which also covers the addition of new free pages. +/// In-memory version of the free-list, which is stored on disk as a linked list of pages. #[derive(Clone)] pub struct FreeList { // head is last portion. portions: Vec<(PageNumber, Vec)>, - // Becomes true if something is being popped, false otherwise - pop: bool, len: usize, - // The comment on `fn commit` explains what fragmentation is in detail. + // Databases written before `rewrite` may hold a fragmented list: the head page has exactly one + // item and the second-to-last page one fewer than the maximum. fragmented: bool, - released_portions: Vec, } impl FreeList { + fn new(portions: Vec<(PageNumber, Vec)>) -> Self { + let (len, fragmented) = len_and_fragmented(&portions); + FreeList { + portions, + len, + fragmented, + } + } + pub fn read( page_pool: &PagePool, store_file: &File, free_list_head: Option, ) -> anyhow::Result { let Some(mut free_list_pn) = free_list_head else { - return Ok(FreeList { - portions: vec![], - pop: false, - released_portions: vec![], - fragmented: false, - len: 0, - }); + return Ok(FreeList::new(vec![])); }; // restore free list from file @@ -59,15 +55,7 @@ impl FreeList { free_list_portions.reverse(); - let (len, fragmented) = len_and_fragmented(&free_list_portions); - - Ok(FreeList { - pop: false, - portions: free_list_portions, - released_portions: vec![], - fragmented, - len, - }) + Ok(FreeList::new(free_list_portions)) } /// Get a set of all pages tracked in the free-list. This is all free pages plus all the @@ -87,292 +75,115 @@ impl FreeList { self.portions.last().map(|(head_pn, _)| head_pn).copied() } - fn pop(&mut self) -> Option { - let pn; - let head_empty = { - let head = self.portions.last_mut()?; - // UNWRAP: free-list portions are always non-empty. - pn = head.1.pop().unwrap(); - self.pop = true; - - if head.1.is_empty() { - Some(head.0) - } else { - None - } - }; - - if let Some(prev_head_pn) = head_empty { - let _ = self.portions.pop(); - self.released_portions.push(prev_head_pn); - } - - Some(pn) + /// Get the length of the free-list. + pub fn len(&self) -> usize { + self.len } - /// Discards the first `n` items from the free-list. - /// - /// This returns the number of items discarded. Runtime is O(n) in the number of free-list - /// segments modified. - pub fn discard(&mut self, n: usize) -> usize { - let mut discarded = 0; - while discarded < n { - let Some((head_pn, mut head)) = self.portions.pop() else { - return discarded; - }; - self.pop = true; - - let to_discard = std::cmp::min(head.len(), n - discarded); - head.truncate(head.len() - to_discard); - - if !head.is_empty() { - self.portions.push((head_pn, head)); - } else { - self.released_portions.push(head_pn); - } - - discarded += to_discard; + // All entries in the order `get_nth_pop` hands them out. + fn pop_order(&self) -> Vec { + let mut order = Vec::with_capacity(self.len); + for (_, pns) in self.portions.iter().rev() { + order.extend(pns.iter().rev()); } - - n - } - - /// Get a reference to this free list asserted to be clean. This panics if the free list isn't - /// clean: if any `pop`s have occurred since the last call to `commit`. - pub fn as_clean(&self) -> CleanFreeList<'_> { - assert!(!self.pop); - CleanFreeList(self) + order } - /// Apply the changes resulting from calls to `pop()` and pushing all the `to_push` page numbers - /// to the free list. This returns a vector of pages to write, each tagged with the page number - /// it should be written at. + /// Rewrites the whole free-list in address order, starting after the last page used by this + /// sync, so that the next sync's consecutive allocations land on nearby pages. /// - /// FreeList Pages are stored in the file using a Copy-On-Write (COW) approach. - /// - /// This function only applies `pop` invocations since the last call to this function, - /// creating an encoded version of the updated free list state. - /// - /// The FreeList is conceptually a paginated stack. There are some additional constraints due - /// to the copy-on-write mechanics: all touched pages must have their previous page - /// number pushed at the end, and new page numbers are determined by popping from the list. - /// Additionally, to maintain crash-consistency, we do not reuse any page which is being - /// added afresh to the list within this function. Pops and pushes are therefore heavily - /// intertwined. Pushes can cause pops. Pops reduce the length of the list, making pops - /// possibly unnecessary. Pops can also cause further pops when they touch new pages. - /// - /// These restrictions add some code complexity, as well as the possibility of "fragmentation". - /// This fragmentation is minor and takes a very specific form: the second page will have one - /// fewer items than the maximum and the head page will have exactly one item. This occurs only - /// when the last item pushed would be the first in a new page and the pop to allocate that - /// new page dirties a previously untouched page. Needless to say, it is rare, something like - /// 1-in-a-million (1022^2) and of near-zero consequence if forced somehow by an adversary. - /// - /// The next call to `commit` will eliminate any previous fragmentation, but may result in - /// fragmentation itself. - /// - /// O(n) in the number of pops / pushes. - pub fn commit( + /// `used` is the number of entries the sync allocated (its first `used` pops). The pages that + /// held the previous free-list and the `freed` pages join the list; they stay untouched until + /// the next sync. The new free-list pages are the next free entries in address order, or + /// are bumped when there are not enough. Returns the pages to write. + pub fn rewrite( &mut self, page_pool: &PagePool, - mut to_push: Vec, + used: usize, + freed: Vec, bump: &mut PageNumber, ) -> Vec<(PageNumber, FatPage)> { - // No changes were made - let had_pops = std::mem::replace(&mut self.pop, false); - if !had_pops && to_push.is_empty() { + if used == 0 && freed.is_empty() { return vec![]; } - // append the released free list pages - to_push.extend(self.released_portions.drain(..)); - - let new_pages = self.preallocate(&mut to_push, bump); - let pages = self.push_and_encode(page_pool, &to_push, new_pages); + let order = self.pop_order(); + let remaining = &order[used..]; - // preallocate pops, therefore, we must set it back. - self.pop = false; + let mut entries: Vec = Vec::with_capacity(order.len() + freed.len()); + entries.extend(freed); + entries.extend(self.portions.iter().map(|(pn, _)| *pn)); - let (len, fragmented) = len_and_fragmented(&self.portions); - self.len = len; - self.fragmented = fragmented; - - pages - } - - // determines the exact number of pops and bumps which are needed in order to fulfill the - // request. also schedules pushing of all touched pages' previous page numbers. - fn preallocate( - &mut self, - to_push: &mut Vec, - bump: &mut PageNumber, - ) -> Vec { - let mut new_pages = Vec::new(); - - // allocate a new page for rewriting the head (if any). - let mut new_full_portion = true; - let mut i; - if let Some(pn) = self.pop() { - // check if this freed a page and handle that - match self.released_portions.pop() { - Some(x) => { - if let Some((new_head_pn, new_head_pns)) = self - .portions - .last_mut() - .filter(|p| p.1.len() == MAX_PNS_PER_PAGE - 1) - { - // fix up fragmentation. only the second-to-last page can be fragmented, - // and it is. use this page to rewrite the second-to-last and position - // the cursor at the end of this page instead. - to_push.push(*new_head_pn); - to_push.push(x); - *new_head_pn = pn; - new_full_portion = false; - i = MAX_PNS_PER_PAGE - new_head_pns.len(); - } else { - // previous page was full or doesn't exist. - to_push.push(x); - new_pages.push(pn); - - // new page has already been allocated for this batch. - i = MAX_PNS_PER_PAGE; - } - } - None => { - new_full_portion = false; - - // UNWRAP: protected since pop succeeded but head was not released. - let (head_pn, head_pns) = self.portions.last_mut().unwrap(); - to_push.push(*head_pn); - *head_pn = pn; - - // head is partially full. position cursor at the number of items needed to - // fill it. - i = MAX_PNS_PER_PAGE - head_pns.len(); - } - } - } else { - // nothing popped, free list was totally empty. - // defer to loop to create the page for the next section. - i = 0; - }; - - // loop invariant: free list len + i is always divisible by MAX_PNS_PER_PAGE. - // therefore, the loop condition asks "do we still have items beyond the last page?" - // while accounting for pops and pushes within the loop. - while i < to_push.len() { - if let Some((ref mut head_pn, ref mut head_pns)) = - self.portions.last_mut().filter(|_| new_full_portion) - { - // just popped into a new portion (which we will edit). prepare it for rewrite, - // because we are about to pop from it and alter it. - to_push.push(*head_pn); - - // UNWRAP: new_full_portion guarantees that the new portion is full. - *head_pn = head_pns.pop().unwrap(); - - new_full_portion = false; - - // pop reduces free list length, we adjust i to compensate. - // however, we must unconditionally rewrite this page even if i equals the previous - // value of to_push.len(). That is because if we didn't pop we wouldn't have enough - // pages. - // this is inescapable and is what causes fragmentation. - i += 1; - - continue; - } - - // loop invariant: from this point on, the head page (if any) always has a head_pn which - // was itself drawn from the free-list. - match self.pop() { - Some(pn) => { - new_pages.push(pn); - // pop reduces free list length, we adjust i to compensate - i += 1; - - if let Some(released) = self.released_portions.pop() { - new_full_portion = true; - // note: this is the PN we took out of the new portion; it's fresh. - // - // if i now equals to_push.len(), we have a forced fragmentation. - new_pages.push(released); - } - } - None => { - new_pages.push(*bump); - bump.0 += 1; - } - } - - // jump 'i' to the end of the next page. - i += MAX_PNS_PER_PAGE; + // Take `taken` list pages from the remaining entries and bump the rest, such that the + // list pages exactly hold the entries left over. + let total = remaining.len() + entries.len(); + let pages_for = |taken: usize| (total - taken).div_ceil(MAX_PNS_PER_PAGE); + let mut taken = 0; + while taken < remaining.len() && pages_for(taken + 1) > taken { + taken += 1; } - - new_pages - } - - fn push_and_encode( - &mut self, - page_pool: &PagePool, - to_push: &[PageNumber], - new_pages: Vec, - ) -> Vec<(PageNumber, FatPage)> { - let mut encoded = Vec::new(); - let mut new_pages = new_pages.into_iter().peekable(); - for (i, pn) in to_push.iter().cloned().enumerate() { - // the second condition is checking for the fragmentation described in the commit - // doc comment. fragmentation can only occur in the second page and the head page - // has a single item. - let head_full = self - .portions - .last() - .map_or(true, |h| h.1.len() == MAX_PNS_PER_PAGE); - - let fragmentation = self - .portions - .last() - .map_or(false, |h| h.1.len() == MAX_PNS_PER_PAGE - 1) - && new_pages.peek().is_some() - && i + 1 == to_push.len(); - - if head_full || fragmentation { - encoded.extend(self.encode_head(page_pool)); - // UNWRAP: we've always allocated enough PNs for all appended PNs. - let new_head_pn = new_pages.next().unwrap(); - self.portions.push((new_head_pn, Vec::new())); - } - - self.push(pn); + let mut list_pages: Vec = remaining[..taken].to_vec(); + for _ in taken..pages_for(taken) { + list_pages.push(*bump); + bump.0 += 1; } + let cursor = remaining[..taken].last().or(order[..used].last()).copied(); + entries.extend_from_slice(&remaining[taken..]); - assert!(new_pages.next().is_none()); + entries.sort_unstable(); + if let Some(cursor) = cursor { + let split = entries.partition_point(|pn| *pn <= cursor); + entries.rotate_left(split); + } - encoded.extend(self.encode_head(page_pool)); - encoded + // The last portion is the head and pops from its end, so lay the entries out reversed. + entries.reverse(); + list_pages.sort_unstable(); + self.portions = list_pages + .into_iter() + .zip(entries.chunks(MAX_PNS_PER_PAGE)) + .map(|(pn, pns)| (pn, pns.to_vec())) + .collect(); + self.len = entries.len(); + self.fragmented = false; + + let mut prev = FREELIST_EMPTY; + self.portions + .iter() + .map(|(pn, pns)| { + let page = encode_free_list_page(page_pool, prev, pns); + prev = *pn; + (*pn, page) + }) + .collect() } - fn push(&mut self, pn: PageNumber) { - // UNWRAP: `push` is only called when head is not full. - let head = self.portions.last_mut().unwrap(); - assert!(head.1.len() < MAX_PNS_PER_PAGE); - head.1.push(pn); - } + /// Get the result of the nth pop on this free-list. Panics if n >= len. Runtime: O(1). + pub fn get_nth_pop(&self, mut n: usize) -> PageNumber { + let portions = &self.portions; + let n_portions = portions.len(); + if self.fragmented { + if n == 0 { + portions[n_portions - 1].1[0] + } else if n < MAX_PNS_PER_PAGE { + portions[n_portions - 2].1[MAX_PNS_PER_PAGE - n - 1] + } else { + let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); + n = n % MAX_PNS_PER_PAGE; - fn encode_head(&self, page_pool: &PagePool) -> Option<(PageNumber, FatPage)> { - if let Some((head_pn, head_pns)) = self.portions.last() { - let prev_pn = self - .portions - .len() - .checked_sub(2) - .map_or(FREELIST_EMPTY, |i| self.portions[i].0); - - Some(( - *head_pn, - encode_free_list_page(page_pool, prev_pn, &head_pns), - )) + portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] + } } else { - None + let head_len = portions[n_portions - 1].1.len(); + if n < head_len { + portions[n_portions - 1].1[head_len - n - 1] + } else { + n -= head_len; + let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); + n = n % MAX_PNS_PER_PAGE; + + portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] + } } } } @@ -423,45 +234,6 @@ fn encode_free_list_page(page_pool: &PagePool, prev: PageNumber, pns: &[PageNumb page } -/// A wrapper type which denotes a clean free-list. -pub struct CleanFreeList<'a>(&'a FreeList); - -impl<'a> CleanFreeList<'a> { - /// Get the length of the free-list. - pub fn len(&self) -> usize { - self.0.len - } - - /// Get the result of the nth pop on this free-list. Panics if n >= len. Runtime: O(1). - pub fn get_nth_pop(&self, mut n: usize) -> PageNumber { - let portions = &self.0.portions; - let n_portions = portions.len(); - if self.0.fragmented { - if n == 0 { - portions[n_portions - 1].1[0] - } else if n < MAX_PNS_PER_PAGE { - portions[n_portions - 2].1[MAX_PNS_PER_PAGE - n - 1] - } else { - let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; - - portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] - } - } else { - let head_len = portions[n_portions - 1].1.len(); - if n < head_len { - portions[n_portions - 1].1[head_len - n - 1] - } else { - n -= head_len; - let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; - - portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] - } - } - } -} - // A free page is laid out in the following form: // + prev free page : u32 // + item_count : u16 @@ -503,328 +275,175 @@ impl<'a> FreeListPageMut<'a> { #[cfg(test)] mod tests { - use super::{FreeList, PageNumber, PagePool, MAX_PNS_PER_PAGE}; - - #[test] - fn pop_into_next_portion_one_page_needed() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2)])], - pop: false, - released_portions: Vec::new(), - len: 1, - fragmented: false, - }; + use super::{decode_free_list_page, FreeList, PageNumber, PagePool, MAX_PNS_PER_PAGE}; + use crate::beatree::FREELIST_EMPTY; + use std::collections::BTreeSet; - // expected order of events: - // 1. first (2) is popped for the new head. - // 2. This exhausts the head. We use (2) for a new head and push (1) to the end. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (3..).take(1).map(PageNumber).collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 1); - assert_eq!(result[0].0, PageNumber(2)); + fn pns(range: std::ops::Range) -> Vec { + range.map(PageNumber).collect() + } - assert_eq!(free_list.portions.len(), 1); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[0].1, vec![PageNumber(3), PageNumber(1)]); - assert_eq!(free_list.len, 2); + fn assert_nth_pop_matches_layout(free_list: &FreeList) { + let predicted = (0..free_list.len()) + .map(|i| free_list.get_nth_pop(i)) + .collect::>(); + assert_eq!(predicted, free_list.pop_order()); } #[test] - fn pop_into_next_portion_fragmentation() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2), PageNumber(3)])], - pop: false, - released_portions: Vec::new(), - len: 2, - fragmented: false, - }; - - // expected order of events: - // 1. first (3) is popped for the new head and (1) is pushed. - // 2. We now need a new page to store all the items. (2) is popped. - // 3. This empties the head portion, leaving (3) dangling. to_push == MAX - // 4. We use (3) as a new page for writing the last item, fragmentation was forced. - // If we had pushed (3) to the end of the free-list instead, to_push would be MAX+1 - // and we'd need to take a new page from bump or the previous head, dirtying it and - // allocating unnecessarily. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (4..) - .take(MAX_PNS_PER_PAGE - 1) - .map(PageNumber) - .collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(2)); - assert_eq!(result[1].0, PageNumber(3)); + fn clean_nth_pop() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(1000..1000 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(2), pns(5000..5000 + MAX_PNS_PER_PAGE as u32)), + ( + PageNumber(3), + pns(10000..10000 + MAX_PNS_PER_PAGE as u32 / 2), + ), + ]); + assert!(!free_list.fragmented); + assert_nth_pop_matches_layout(&free_list); + } - assert_eq!(free_list.portions.len(), 2); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE - 1); - assert_eq!(free_list.portions[1].1.len(), 1); - assert_eq!(free_list.len, MAX_PNS_PER_PAGE); + #[test] + fn fragmented_nth_pop() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(1000..1000 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(4), pns(5000..5000 + MAX_PNS_PER_PAGE as u32)), + ( + PageNumber(5), + pns(10000..10000 + MAX_PNS_PER_PAGE as u32 - 1), + ), + (PageNumber(6), vec![PageNumber(7)]), + ]); assert!(free_list.fragmented); + assert_eq!(free_list.len(), MAX_PNS_PER_PAGE * 3); + assert_nth_pop_matches_layout(&free_list); } - #[test] - fn pop_into_next_portion_without_fragmentation() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2), PageNumber(3)])], - pop: false, - released_portions: Vec::new(), - len: 2, - fragmented: false, - }; + // Runs `rewrite` and checks the result against the free list it started from. + fn check_rewrite(mut free_list: FreeList, used: usize, freed: Vec) -> FreeList { + let before = free_list.pop_order(); + let old_list_pages: Vec = free_list.portions.iter().map(|p| p.0).collect(); + let bump_before = PageNumber(1_000_000); + let mut bump = bump_before; - // expected order of events: - // 1. first (3) is popped for the new head and (1) is pushed. - // 2. We now need a new page to store all the items. (2) is popped. - // 3. This empties the head portion, leaving (3) dangling. to_push = MAX + 1 - // 4. We push (2) for the first new page and (3) for the next. (2) is completely full, - // and (3) has the last item. let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (4..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(2)); - assert_eq!(result[1].0, PageNumber(3)); + let written = free_list.rewrite(&page_pool, used, freed.clone(), &mut bump); + + // The written pages encode exactly the new portions, chained in order. + assert_eq!(written.len(), free_list.portions.len()); + let mut prev = FREELIST_EMPTY; + for ((pn, page), (portion_pn, portion)) in written.iter().zip(&free_list.portions) { + assert_eq!(pn, portion_pn); + let (decoded_prev, decoded) = decode_free_list_page(page.clone(), u32::MAX); + assert_eq!(decoded_prev, prev); + assert_eq!(&decoded, portion); + prev = *pn; + } - assert_eq!(free_list.portions.len(), 2); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), 1); - assert_eq!(free_list.len, MAX_PNS_PER_PAGE + 1); + // Every portion but the head is full, so the list is not fragmented. + let (head, rest) = free_list.portions.split_last().unwrap(); + assert!(!head.1.is_empty()); + assert!(rest.iter().all(|p| p.1.len() == MAX_PNS_PER_PAGE)); + assert!(!free_list.fragmented); + assert_nth_pop_matches_layout(&free_list); + + // No page is lost or duplicated. + let list_pages: BTreeSet = free_list.portions.iter().map(|p| p.0).collect(); + let entries: BTreeSet = free_list.pop_order().into_iter().collect(); + assert_eq!(entries.len(), free_list.len()); + assert!(list_pages.is_disjoint(&entries)); + let bumped: BTreeSet = (bump_before.0..bump.0).map(PageNumber).collect(); + let expected: BTreeSet = before[used..] + .iter() + .chain(&freed) + .chain(&old_list_pages) + .copied() + .chain(bumped.iter().copied()) + .collect(); + assert_eq!(&list_pages | &entries, expected); + + // The new list pages are written this sync, so they must not be anything the committed + // state still references (old list pages, freed pages) or this sync's allocations. + let fresh: BTreeSet = before[used..].iter().copied().chain(bumped).collect(); + assert!(list_pages.is_subset(&fresh)); + + // Pops sweep upwards through the file, wrapping around at most once. + let order = free_list.pop_order(); + assert!(order.windows(2).filter(|w| w[0] > w[1]).count() <= 1); + + free_list } #[test] - fn fragmentation_handled() { - let full_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 2) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion), - (PageNumber(4), vec![PageNumber(5)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE + 1, - fragmented: false, - }; + fn rewrite_nothing_to_do() { + let mut free_list = FreeList::new(vec![(PageNumber(1), pns(2..10))]); + let written = free_list.rewrite(&PagePool::new(), 0, vec![], &mut PageNumber(100)); + assert!(written.is_empty()); + assert_eq!(free_list.portions, vec![(PageNumber(1), pns(2..10))]); + } - // expected order of events: - // 1. first (5) is popped for the new head and (4) is pushed. to_push == MAX+1. - // 2. This vacates the head page. (5) is used as a fresh page. - // 2. We need a new page to store all the items. We need to pop into the previously - // full page. - // 3. Its previous head (1) is pushed and (3) is taken to overwrite it. to_push == MAX+2 - // 4. (2) is popped to handle the new page. - // 5. One of the to_push items is written into the full page. to_push == MAX+1 - // 6. We can't write MAX items into the next page and 1 into another, because we'd need - // to pop a new page for that but wouldn't be able to use it. - // 7. The only solution is to pop the next page (69) and have the second-to-last page - // fragmented. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (20000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(), - &mut PageNumber(100000), + #[test] + fn rewrite_empty_list_bumps_list_page() { + let free_list = check_rewrite(FreeList::new(vec![]), 0, pns(5..8)); + assert_eq!( + free_list.portions, + vec![(PageNumber(1_000_000), pns(5..8).into_iter().rev().collect())] ); - - assert_eq!(result.len(), 3); - assert_eq!(result[0].0, PageNumber(3)); - assert_eq!(result[1].0, PageNumber(5)); - assert_eq!(result[2].0, PageNumber(2)); - - assert_eq!(free_list.portions.len(), 3); - - assert_eq!(free_list.portions[0].0, PageNumber(3)); - assert_eq!(free_list.portions[1].0, PageNumber(5)); - assert_eq!(free_list.portions[2].0, PageNumber(2)); - - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), MAX_PNS_PER_PAGE - 1); - assert_eq!(free_list.portions[2].1.len(), 1); - - assert_eq!(free_list.len, MAX_PNS_PER_PAGE * 2); - assert!(free_list.fragmented); } #[test] - fn clean_up_fragmentation() { - let fragmented_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 3) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); - - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), fragmented_portion), - (PageNumber(4), vec![PageNumber(5)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE, - fragmented: true, - }; - - // expected order of operations: - // 1. 5 is popped to rewrite the head. This vacates the head. - // 2. Because the previous portion is fragmented, 5 is taken as its new head and its old - // head and the outdated (1) and (4) are pushed. - // 3. A new page (3) is popped for the new items. - // 4. The fragmented (5) is filled out and the rest of the items are pushed into (3) - let page_pool = PagePool::new(); - let result = free_list.commit(&page_pool, vec![PageNumber(6)], &mut PageNumber(10000)); - - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(5)); - assert_eq!(result[1].0, PageNumber(3)); - - assert_eq!(free_list.portions.len(), 2); - - assert_eq!(free_list.portions[0].0, PageNumber(5)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); - - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), 1); - - assert_eq!(free_list.len, MAX_PNS_PER_PAGE + 1); - assert!(!free_list.fragmented); + fn rewrite_takes_list_pages_from_free_entries() { + let free_list = FreeList::new(vec![(PageNumber(1), pns(2..10))]); + let free_list = check_rewrite(free_list, 3, pns(20..22)); + // used: 9, 8, 7. The next entry in pop order, 6, holds the new list. + assert_eq!(free_list.portions.len(), 1); + assert_eq!(free_list.portions[0].0, PageNumber(6)); + // Pops resume after the cursor at 6 and wrap around. + assert_eq!( + free_list.pop_order(), + [20, 21, 1, 2, 3, 4, 5].map(PageNumber).to_vec() + ); } #[test] - fn rewrite_head_after_pop_only() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2)])], - pop: true, - released_portions: Vec::new(), - len: 1, - fragmented: false, - }; - - // The head must follow CoW. - let page_pool = PagePool::new(); - let result = free_list.commit(&page_pool, Vec::new(), &mut PageNumber(10000)); - - assert_eq!(result.len(), 1); - assert_eq!(result[0].0, PageNumber(2)); - - let (prev_pn, free_list) = super::decode_free_list_page(result[0].1.clone(), 3); - - assert_eq!(prev_pn, super::FREELIST_EMPTY); - assert_eq!(free_list, vec![PageNumber(1)]); + fn rewrite_all_used() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(100..100 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(2), pns(5000..5010)), + ]); + let len = free_list.len(); + let free_list = check_rewrite(free_list, len, vec![]); + // Only the two old list pages remain free; the new list page is bumped. + assert_eq!(free_list.pop_order(), pns(1..3)); } #[test] - fn clean_nth_pop() { - let full_portion_1 = (1000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let full_portion_2 = (5000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let last_portion = (10000..) - .take(MAX_PNS_PER_PAGE / 2) - .map(PageNumber) - .collect::>(); - - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion_1), - (PageNumber(2), full_portion_2), - (PageNumber(3), last_portion), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE * 2 + MAX_PNS_PER_PAGE / 2, - fragmented: false, - }; - - let predicted_pops = { - let clean = free_list.as_clean(); - (0..clean.len()) - .map(|i| clean.get_nth_pop(i)) - .collect::>() - }; - let actual_pops = (0..free_list.len) - .map(|_| free_list.pop().unwrap()) - .collect::>(); - - assert_eq!(predicted_pops, actual_pops); + fn rewrite_multi_page_shuffled() { + // A deterministic shuffle of three and a half pages of entries. + let n = (MAX_PNS_PER_PAGE * 7 / 2) as u32; + let mut all: Vec = (0..n).map(|i| PageNumber(10 + (i * 7919) % n)).collect(); + let freed = all.split_off(all.len() - 500); + let portions = all + .chunks(MAX_PNS_PER_PAGE) + .enumerate() + .map(|(i, c)| (PageNumber(n + 100 + i as u32), c.to_vec())) + .collect(); + let free_list = FreeList::new(portions); + let len = free_list.len(); + let free_list = check_rewrite(free_list, len / 3, freed); + let free_list = check_rewrite(free_list, 10, pns(n + 200..n + 300)); + check_rewrite(free_list, 0, pns(n + 300..n + 301)); } #[test] - fn clean_nth_pop_fragmented() { - let full_portion_1 = (1000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let full_portion_2 = (5000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let fragmented_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 3) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); - - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion_1), - (PageNumber(4), full_portion_2), - (PageNumber(5), fragmented_portion), - (PageNumber(6), vec![PageNumber(7)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE * 3, - fragmented: true, - }; - - let predicted_pops = { - let clean = free_list.as_clean(); - (0..clean.len()) - .map(|i| clean.get_nth_pop(i)) - .collect::>() - }; - let actual_pops = (0..free_list.len) - .map(|_| free_list.pop().unwrap()) - .collect::>(); - - assert_eq!(predicted_pops, actual_pops); + fn rewrite_fragmented() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(100..100 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(4), pns(5000..5000 + MAX_PNS_PER_PAGE as u32 - 1)), + (PageNumber(6), vec![PageNumber(7)]), + ]); + assert!(free_list.fragmented); + check_rewrite(free_list, 5, pns(9000..9003)); } } diff --git a/nomt/src/beatree/allocator/mod.rs b/nomt/src/beatree/allocator/mod.rs index 967f22730e..2244b18fab 100644 --- a/nomt/src/beatree/allocator/mod.rs +++ b/nomt/src/beatree/allocator/mod.rs @@ -99,6 +99,11 @@ impl Store { /// This will block if another sync is in progress. pub fn start_sync(&self) -> (SyncAllocator, SyncFinisher) { let sync = Mutex::lock_arc(&self.sync); + // Reuse free pages only once there are enough of them that the free pages at the cursor + // form long runs. Until then, append. + let free = sync.free_list.len(); + let live = (sync.bump.0 as usize).saturating_sub(free); + let free_len = if free >= FREE_SLACK * live { free } else { 0 }; let (sync_tx, sync_rx) = crossbeam_channel::bounded(1); let finisher = SyncFinisher { @@ -114,6 +119,7 @@ impl Store { sync: Some(sync), send_to_finish: sync_tx, allocations: AtomicUsize::new(0), + free_len, }), }; @@ -168,6 +174,9 @@ struct StoreSync { type StoreSyncGuard = ArcMutexGuard; +/// Free pages are reused once they number this many times the live pages. +const FREE_SLACK: usize = 2; + // Grow the store by 32MB at a time. const GROW_STORE_BY_PAGES: u32 = 8192; @@ -193,11 +202,26 @@ impl SyncAllocator { /// This returns an error when setting the length of the file fails. pub fn allocate(&self) -> std::io::Result { let allocation_index = self.inner.allocations.fetch_add(1, Ordering::Relaxed); + self.page_at(allocation_index) + } + + /// Get the next `n` page numbers, in allocation order. + /// + /// Consecutive allocations come from consecutive free-list entries or from the bump, so a + /// caller writing them in order issues writes that are as close together as the store allows. + /// Page numbers that end up unused must be returned as freed pages. + pub fn allocate_many(&self, n: usize) -> std::io::Result> { + let first = self.inner.allocations.fetch_add(n, Ordering::Relaxed); + (first..first + n).map(|i| self.page_at(i)).collect() + } + + fn page_at(&self, allocation_index: usize) -> std::io::Result { let sync = self.inner.sync(); - let free_list = sync.free_list.as_clean(); - if allocation_index >= free_list.len() { - let pn = PageNumber(sync.bump.0 + (allocation_index - free_list.len()) as u32); + let free_list = &sync.free_list; + let free_len = self.inner.free_len; + if allocation_index >= free_len { + let pn = PageNumber(sync.bump.0 + (allocation_index - free_len) as u32); // fast path: no contention if pn.0 < self.inner.max_bump.load(Ordering::Relaxed) { @@ -232,6 +256,8 @@ impl SyncAllocator { struct SyncAllocatorInner { sync: Option, + // The number of free-list entries this sync allocates from before bumping. + free_len: usize, send_to_finish: Sender, allocations: AtomicUsize, max_bump: AtomicU32, @@ -251,6 +277,7 @@ impl Drop for SyncAllocatorInner { let _ = self.send_to_finish.send(Finish { sync: self.sync.take().unwrap(), allocations: *self.allocations.get_mut(), + free_len: self.free_len, max_bump: *self.set_len_lock.get_mut(), }); } @@ -266,13 +293,23 @@ impl Drop for SyncAllocatorInner { /// Returns the new boundary (the last accessible page) or an I/O error. fn grow(file: &File, page: PageNumber) -> std::io::Result { let next_bump = (page.0 + GROW_STORE_BY_PAGES - 1).next_multiple_of(GROW_STORE_BY_PAGES); - file.set_len(next_bump as u64 * PAGE_SIZE as u64)?; + let len = next_bump as u64 * PAGE_SIZE as u64; + // Allocate the blocks up front: direct writes into holes allocate them one write at a time. + // SAFETY: plain syscall on a valid fd. + #[cfg(target_os = "linux")] + let allocated = unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len as libc::off_t) } == 0; + #[cfg(not(target_os = "linux"))] + let allocated = false; + if !allocated { + file.set_len(len)?; + } Ok(PageNumber(next_bump)) } struct Finish { sync: StoreSyncGuard, allocations: usize, + free_len: usize, max_bump: PageNumber, } @@ -301,14 +338,17 @@ impl SyncFinisher { let Finish { mut sync, allocations, + free_len, mut max_bump, } = self.sync_finish.recv().unwrap(); - let bumps = allocations - sync.free_list.discard(allocations); + let used = allocations.min(free_len); // remaining allocations all logically incremented bump. - let mut next_bump = PageNumber(sync.bump.0 + bumps as u32); - let freelist_pages = sync.free_list.commit(page_pool, freed, &mut next_bump); + let mut next_bump = PageNumber(sync.bump.0 + (allocations - used) as u32); + let freelist_pages = sync + .free_list + .rewrite(page_pool, used, freed, &mut next_bump); // writing the free-list pages might require more bumps, which may require growing the file // further. @@ -334,3 +374,90 @@ pub struct StoreMeta { /// The next free page number. pub bump: u32, } + +#[cfg(test)] +mod tests { + use super::{PageNumber, Store, FREELIST_EMPTY}; + use crate::io::{PagePool, PAGE_SIZE}; + use std::{collections::BTreeSet, os::unix::fs::FileExt, sync::Arc}; + + // Drives many syncs with page churn and checks that no page referenced by the committed state + // is handed out or overwritten, that free pages get reused, and that the free list reloads. + #[test] + fn allocate_many_and_reuse() { + let page_pool = PagePool::new(); + let file = Arc::new(tempfile::tempfile().unwrap()); + let store = Store::open(&page_pool, file.clone(), PageNumber(1), None).unwrap(); + + let mut live: Vec = Vec::new(); + let mut committed_list: BTreeSet = BTreeSet::new(); + let mut reused = false; + let mut last = None; + + for sync_i in 0..40 { + let bump_before = store.sync.lock().bump; + let (allocator, finisher) = store.start_sync(); + let referenced: BTreeSet = live + .iter() + .copied() + .chain(committed_list.iter().copied()) + .collect(); + + let mut allocated = allocator.allocate_many(48).unwrap(); + allocated.push(allocator.allocate().unwrap()); + allocated.extend(allocator.allocate_many(16).unwrap()); + assert_eq!( + allocated.iter().collect::>().len(), + allocated.len() + ); + for pn in &allocated { + assert!(!pn.is_nil()); + assert!( + !referenced.contains(pn), + "sync {sync_i}: {pn:?} is still referenced" + ); + reused |= *pn < bump_before; + } + if allocated.iter().all(|pn| *pn >= bump_before) { + // appending: consecutive allocations are consecutive pages. + assert!(allocated.windows(2).all(|w| w[1].0 == w[0].0 + 1)); + } + drop(allocator); + + // Return the last few allocations unused and free the oldest live pages. + let unused = allocated.split_off(allocated.len() - 5); + let n_free = if live.len() > 300 { 60 } else { 0 }; + let mut freed: Vec = live.drain(..n_free).collect(); + freed.extend(&unused); + live.extend(&allocated); + + let (list_pages, meta) = finisher.finish(&page_pool, freed).unwrap(); + let new_list: BTreeSet = list_pages.iter().map(|(pn, _)| *pn).collect(); + for pn in &new_list { + assert!( + !referenced.contains(pn), + "sync {sync_i}: list page {pn:?} overwrites" + ); + assert!(!allocated.contains(pn) && !unused.contains(pn)); + } + committed_list = new_list; + last = Some((list_pages, meta)); + } + assert!(reused, "free pages were never reused"); + + // Write out the last free list and reopen the store from it. + let (list_pages, meta) = last.unwrap(); + for (pn, page) in &list_pages { + file.write_all_at(&page[..], pn.0 as u64 * PAGE_SIZE as u64) + .unwrap(); + } + let head = (meta.freelist_pn != FREELIST_EMPTY.0).then_some(PageNumber(meta.freelist_pn)); + let reopened = Store::open(&page_pool, file, PageNumber(meta.bump), head).unwrap(); + assert_eq!( + reopened.all_tracked_freelist_pages(), + store.all_tracked_freelist_pages() + ); + let live: BTreeSet = live.into_iter().collect(); + assert!(live.is_disjoint(&store.all_tracked_freelist_pages())); + } +} diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index c47ad4bfc7..b076add3d9 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -22,7 +22,7 @@ use crate::beatree::{ }, Key, ValueChange, }; -use crate::io::{IoCommand, IoHandle, IoKind}; +use crate::io::{IoCommand, IoHandle, IoKind, IoVecs}; use crate::task::{join_task, spawn_task}; /// Tracker of all changes that happen to leaves during an update @@ -202,9 +202,6 @@ fn apply_worker_changes( } let new_pn = leaf_entry.inserted.as_ref().map(|(_, pn)| *pn); - if new_pn.is_some() { - output.submitted_io += 1; - } if let Some(prev_pn) = leaf_entry.deleted { output.freed_pages.push(prev_pn); @@ -213,7 +210,9 @@ fn apply_worker_changes( output.leaf_changeset.push((*key, new_pn)); } - output.submitted_io += worker_output.leaves_tracker.extra_freed.len(); + // Leaves on consecutive pages share writes, and unused allocations are freed without a + // write, so count the writes the worker sent. + output.submitted_io += worker_output.submitted_io; output .freed_pages .extend(worker_output.leaves_tracker.extra_freed.drain(..)); @@ -549,6 +548,8 @@ fn reset_leaf_base_fresh( } struct LeafWorkerOutput { + // The number of leaf writes sent. + submitted_io: usize, leaves_tracker: LeavesTracker, overflow_deleted: Vec>, } @@ -573,6 +574,9 @@ fn run_worker( leaf_writer, leaves_tracker: LeavesTracker::new(), io_handle, + reserved: Vec::new(), + run: WriteRun::default(), + submitted: 0, }; // point leaf updater at first leaf. @@ -665,6 +669,9 @@ fn run_worker( ); } + // No more leaves are produced, so don't hold the last write while waiting on the left worker. + new_leaf_state.flush_run(); + // Now we are safe to send over our right neighbor to the left one // because we're sure to have finished interacting with it has_finished_workload = true; @@ -693,16 +700,70 @@ fn run_worker( } } + new_leaf_state + .leaves_tracker + .extra_freed + .extend(new_leaf_state.reserved); Ok(LeafWorkerOutput { + submitted_io: new_leaf_state.submitted, leaves_tracker: new_leaf_state.leaves_tracker, overflow_deleted, }) } +/// Each worker takes this many consecutive allocations at a time so its leaves land on nearby +/// pages and its writes can be merged. +const LEAF_ALLOCATION_CHUNK: usize = 32; + struct NewLeafHandler { leaf_writer: SyncAllocator, leaves_tracker: LeavesTracker, io_handle: IoHandle, + // Allocated but not yet used page numbers, in reverse allocation order. + reserved: Vec, + run: WriteRun, + // The number of writes sent. + submitted: usize, +} + +/// The most pages merged into one write: 128 KiB. +const MAX_WRITE_RUN: usize = 32; + +/// Leaves on consecutive pages starting at `start`, not yet submitted. +#[derive(Default)] +struct WriteRun { + start: u64, + // Owned so the pages stay alive until the write is sent, whatever happens to the tracker. + leaves: Vec>, +} + +impl WriteRun { + fn continues_at(&self, pn: u64) -> bool { + !self.leaves.is_empty() + && self.leaves.len() < MAX_WRITE_RUN + && pn == self.start + self.leaves.len() as u64 + } +} + +impl NewLeafHandler { + fn flush_run(&mut self) { + let fd = self.leaf_writer.store_fd(); + let start = self.run.start; + let leaves = std::mem::take(&mut self.run.leaves); + let kind = match &leaves[..] { + [] => return, + [leaf] => IoKind::WriteRaw(fd, start, leaf.inner.page()), + _ => IoKind::WriteRawV( + fd, + start, + IoVecs::new(leaves.iter().map(|l| l.inner.page())), + ), + }; + self.submitted += 1; + self.io_handle + .send(IoCommand { kind, user_data: 0 }) + .expect("I/O Pool Down"); + } } impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { @@ -713,17 +774,20 @@ impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { cutoff: Option, ) -> std::io::Result<()> { let leaf = Arc::new(leaf); - let fd = self.leaf_writer.store_fd(); - let page_number = self.leaf_writer.allocate()?; + if self.reserved.is_empty() { + self.reserved = self.leaf_writer.allocate_many(LEAF_ALLOCATION_CHUNK)?; + self.reserved.reverse(); + } + // UNWRAP: refilled above. + let page_number = self.reserved.pop().unwrap(); - let page = leaf.inner.page(); - self.io_handle - .send(IoCommand { - kind: IoKind::WriteRaw(fd, page_number.0 as u64, page), - user_data: 0, - }) - .expect("I/O Pool Down"); + let pn = page_number.0 as u64; + if !self.run.continues_at(pn) { + self.flush_run(); + self.run.start = pn; + } + self.run.leaves.push(leaf.clone()); self.leaves_tracker.insert(key, leaf, cutoff, page_number); Ok(()) diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index a9796bacf1..5766a5cca7 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -208,6 +208,11 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { .offset(page_index * PAGE_SIZE as u64) .build() } + IoKind::WriteRawV(fd, page_index, ref iovs) => { + opcode::Writev::new(types::Fd(fd), iovs.0.as_ptr(), iovs.0.len() as u32) + .offset(page_index * PAGE_SIZE as u64) + .build() + } IoKind::WriteRaw(fd, page_index, ref page) => { opcode::Write::new(types::Fd(fd), page.as_ptr(), PAGE_SIZE as u32) .offset(page_index * PAGE_SIZE as u64) diff --git a/nomt/src/io/mod.rs b/nomt/src/io/mod.rs index 3448d43982..6773495225 100644 --- a/nomt/src/io/mod.rs +++ b/nomt/src/io/mod.rs @@ -53,6 +53,28 @@ pub enum IoKind { Write(RawFd, u64, FatPage), WriteArc(RawFd, u64, Arc), WriteRaw(RawFd, u64, Page), + /// Writes consecutive pages starting at the given page number with one vectored write. + WriteRawV(RawFd, u64, IoVecs), +} + +/// The buffers of a vectored write, one page each. +pub struct IoVecs(Vec); + +// SAFETY: the iovecs point at pages whose owners keep them alive until the write completes, as +// with `Page`. +unsafe impl Send for IoVecs {} + +impl IoVecs { + pub fn new(pages: impl Iterator) -> Self { + IoVecs( + pages + .map(|page| libc::iovec { + iov_base: page.as_ptr() as *mut libc::c_void, + iov_len: PAGE_SIZE, + }) + .collect(), + ) + } } impl fmt::Debug for IoKind { @@ -62,6 +84,9 @@ impl fmt::Debug for IoKind { IoKind::Write(fd, pn, _) => write!(f, "Write(fd={}, pn={})", fd, pn), IoKind::WriteArc(fd, pn, _) => write!(f, "WriteArc(fd={}, pn={})", fd, pn), IoKind::WriteRaw(fd, pn, _) => write!(f, "WriteRaw(fd={}, pn={})", fd, pn), + IoKind::WriteRawV(fd, pn, iovs) => { + write!(f, "WriteRawV(fd={}, pn={}, n={})", fd, pn, iovs.0.len()) + } } } } @@ -77,7 +102,9 @@ impl IoKind { match self { IoKind::Read(_, _, buf) | IoKind::Write(_, _, buf) => buf, IoKind::WriteArc(_, _, _) => panic!("attempted to extract owned buf from write_arc"), - IoKind::WriteRaw(_, _, _) => panic!("attempted to extract buf from write_raw"), + IoKind::WriteRaw(_, _, _) | IoKind::WriteRawV(_, _, _) => { + panic!("attempted to extract buf from write_raw") + } } } @@ -91,6 +118,10 @@ impl IoKind { // there should be no unexpected end-of-file that is not aligned with PAGE_SIZE // when all previous writes have succeeded. IoKind::Read(_, _, _) if res == 0 => IoKindResult::Ok, + IoKind::WriteRawV(_, _, iovs) if res == (iovs.0.len() * PAGE_SIZE) as isize => { + IoKindResult::Ok + } + IoKind::WriteRawV(_, _, _) if res >= 0 => IoKindResult::Retry, // pread and pwrite return the number of bytes read or written _ if res == PAGE_SIZE as isize => IoKindResult::Ok, _ if res == -1 => { diff --git a/nomt/src/io/unix.rs b/nomt/src/io/unix.rs index d4b0a24e85..7e34fe2302 100644 --- a/nomt/src/io/unix.rs +++ b/nomt/src/io/unix.rs @@ -73,6 +73,14 @@ fn execute(mut command: IoCommand) -> CompleteIo { (page_index * PAGE_SIZE as u64) as libc::off_t, ) }, + IoKind::WriteRawV(fd, page_index, ref iovs) => unsafe { + libc::pwritev( + fd, + iovs.0.as_ptr(), + iovs.0.len() as libc::c_int, + (page_index * PAGE_SIZE as u64) as libc::off_t, + ) + }, IoKind::WriteRaw(fd, page_index, ref mut page) => unsafe { libc::pwrite( fd,