Line data Source code
1 : //!
2 : //! Low-level Block-oriented I/O functions
3 : //!
4 :
5 : use super::ephemeral_file::EphemeralFile;
6 : use super::storage_layer::delta_layer::{Adapter, DeltaLayerInner};
7 : use crate::context::RequestContext;
8 : use crate::page_cache::{self, FileId, PageReadGuard, PageWriteGuard, ReadBufResult, PAGE_SZ};
9 : use crate::virtual_file::VirtualFile;
10 : use bytes::Bytes;
11 : use std::ops::Deref;
12 :
13 : /// This is implemented by anything that can read 8 kB (PAGE_SZ)
14 : /// blocks, using the page cache
15 : ///
16 : /// There are currently two implementations: EphemeralFile, and FileBlockReader
17 : /// below.
18 : pub trait BlockReader {
19 : ///
20 : /// Create a new "cursor" for reading from this reader.
21 : ///
22 : /// A cursor caches the last accessed page, allowing for faster
23 : /// access if the same block is accessed repeatedly.
24 : fn block_cursor(&self) -> BlockCursor<'_>;
25 : }
26 :
27 : impl<B> BlockReader for &B
28 : where
29 : B: BlockReader,
30 : {
31 344 : fn block_cursor(&self) -> BlockCursor<'_> {
32 344 : (*self).block_cursor()
33 344 : }
34 : }
35 :
36 : /// Reference to an in-memory copy of an immutable on-disk block.
37 : pub enum BlockLease<'a> {
38 : PageReadGuard(PageReadGuard<'static>),
39 : EphemeralFileMutableTail(&'a [u8; PAGE_SZ]),
40 : Slice(&'a [u8; PAGE_SZ]),
41 : #[cfg(test)]
42 : Arc(std::sync::Arc<[u8; PAGE_SZ]>),
43 : #[cfg(test)]
44 : Vec(Vec<u8>),
45 : }
46 :
47 : impl From<PageReadGuard<'static>> for BlockLease<'static> {
48 2635070 : fn from(value: PageReadGuard<'static>) -> BlockLease<'static> {
49 2635070 : BlockLease::PageReadGuard(value)
50 2635070 : }
51 : }
52 :
53 : #[cfg(test)]
54 : impl<'a> From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'a> {
55 1016930 : fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self {
56 1016930 : BlockLease::Arc(value)
57 1016930 : }
58 : }
59 :
60 : impl<'a> Deref for BlockLease<'a> {
61 : type Target = [u8; PAGE_SZ];
62 :
63 15620629 : fn deref(&self) -> &Self::Target {
64 15620629 : match self {
65 5097482 : BlockLease::PageReadGuard(v) => v.deref(),
66 649156 : BlockLease::EphemeralFileMutableTail(v) => v,
67 8821769 : BlockLease::Slice(v) => v,
68 : #[cfg(test)]
69 1016930 : BlockLease::Arc(v) => v.deref(),
70 : #[cfg(test)]
71 35292 : BlockLease::Vec(v) => {
72 35292 : TryFrom::try_from(&v[..]).expect("caller must ensure that v has PAGE_SZ")
73 : }
74 : }
75 15620629 : }
76 : }
77 :
78 : /// Provides the ability to read blocks from different sources,
79 : /// similar to using traits for this purpose.
80 : ///
81 : /// Unlike traits, we also support the read function to be async though.
82 : pub(crate) enum BlockReaderRef<'a> {
83 : FileBlockReader(&'a FileBlockReader<'a>),
84 : EphemeralFile(&'a EphemeralFile),
85 : Adapter(Adapter<&'a DeltaLayerInner>),
86 : Slice(&'a [u8]),
87 : #[cfg(test)]
88 : TestDisk(&'a super::disk_btree::tests::TestDisk),
89 : #[cfg(test)]
90 : VirtualFile(&'a VirtualFile),
91 : }
92 :
93 : impl<'a> BlockReaderRef<'a> {
94 : #[inline(always)]
95 8627784 : async fn read_blk(
96 8627784 : &self,
97 8627784 : blknum: u32,
98 8627784 : ctx: &RequestContext,
99 8627784 : ) -> Result<BlockLease, std::io::Error> {
100 8627784 : use BlockReaderRef::*;
101 8627784 : match self {
102 550920 : FileBlockReader(r) => r.read_blk(blknum, ctx).await,
103 524822 : EphemeralFile(r) => r.read_blk(blknum, ctx).await,
104 2083002 : Adapter(r) => r.read_blk(blknum, ctx).await,
105 4431194 : Slice(s) => Self::read_blk_slice(s, blknum),
106 : #[cfg(test)]
107 1016930 : TestDisk(r) => r.read_blk(blknum),
108 : #[cfg(test)]
109 20916 : VirtualFile(r) => r.read_blk(blknum, ctx).await,
110 : }
111 8627784 : }
112 : }
113 :
114 : impl<'a> BlockReaderRef<'a> {
115 4431194 : fn read_blk_slice(slice: &[u8], blknum: u32) -> std::io::Result<BlockLease> {
116 4431194 : let start = (blknum as usize).checked_mul(PAGE_SZ).unwrap();
117 4431194 : let end = start.checked_add(PAGE_SZ).unwrap();
118 4431194 : if end > slice.len() {
119 0 : return Err(std::io::Error::new(
120 0 : std::io::ErrorKind::UnexpectedEof,
121 0 : format!("slice too short, len={} end={}", slice.len(), end),
122 0 : ));
123 4431194 : }
124 4431194 : let slice = &slice[start..end];
125 4431194 : let page_sized: &[u8; PAGE_SZ] = slice
126 4431194 : .try_into()
127 4431194 : .expect("we add PAGE_SZ to start, so the slice must have PAGE_SZ");
128 4431194 : Ok(BlockLease::Slice(page_sized))
129 4431194 : }
130 : }
131 :
132 : ///
133 : /// A "cursor" for efficiently reading multiple pages from a BlockReader
134 : ///
135 : /// You can access the last page with `*cursor`. 'read_blk' returns 'self', so
136 : /// that in many cases you can use a BlockCursor as a drop-in replacement for
137 : /// the underlying BlockReader. For example:
138 : ///
139 : /// ```no_run
140 : /// # use pageserver::tenant::block_io::{BlockReader, FileBlockReader};
141 : /// # use pageserver::context::RequestContext;
142 : /// # let reader: FileBlockReader = unimplemented!("stub");
143 : /// # let ctx: RequestContext = unimplemented!("stub");
144 : /// let cursor = reader.block_cursor();
145 : /// let buf = cursor.read_blk(1, &ctx);
146 : /// // do stuff with 'buf'
147 : /// let buf = cursor.read_blk(2, &ctx);
148 : /// // do stuff with 'buf'
149 : /// ```
150 : ///
151 : pub struct BlockCursor<'a> {
152 : pub(super) read_compressed: bool,
153 : reader: BlockReaderRef<'a>,
154 : }
155 :
156 : impl<'a> BlockCursor<'a> {
157 3082524 : pub(crate) fn new(reader: BlockReaderRef<'a>) -> Self {
158 3082524 : Self::new_with_compression(reader, false)
159 3082524 : }
160 3360441 : pub(crate) fn new_with_compression(reader: BlockReaderRef<'a>, read_compressed: bool) -> Self {
161 3360441 : BlockCursor {
162 3360441 : read_compressed,
163 3360441 : reader,
164 3360441 : }
165 3360441 : }
166 : // Needed by cli
167 0 : pub fn new_fileblockreader(reader: &'a FileBlockReader) -> Self {
168 0 : BlockCursor {
169 0 : read_compressed: false,
170 0 : reader: BlockReaderRef::FileBlockReader(reader),
171 0 : }
172 0 : }
173 :
174 : /// Read a block.
175 : ///
176 : /// Returns a "lease" object that can be used to
177 : /// access to the contents of the page. (For the page cache, the
178 : /// lease object represents a lock on the buffer.)
179 : #[inline(always)]
180 8627784 : pub async fn read_blk(
181 8627784 : &self,
182 8627784 : blknum: u32,
183 8627784 : ctx: &RequestContext,
184 8627784 : ) -> Result<BlockLease, std::io::Error> {
185 8627784 : self.reader.read_blk(blknum, ctx).await
186 8627784 : }
187 : }
188 :
189 : /// An adapter for reading a (virtual) file using the page cache.
190 : ///
191 : /// The file is assumed to be immutable. This doesn't provide any functions
192 : /// for modifying the file, nor for invalidating the cache if it is modified.
193 : #[derive(Clone)]
194 : pub struct FileBlockReader<'a> {
195 : pub file: &'a VirtualFile,
196 :
197 : /// Unique ID of this file, used as key in the page cache.
198 : file_id: page_cache::FileId,
199 :
200 : compressed_reads: bool,
201 : }
202 :
203 : impl<'a> FileBlockReader<'a> {
204 2297639 : pub fn new(file: &'a VirtualFile, file_id: FileId) -> Self {
205 2297639 : FileBlockReader {
206 2297639 : file_id,
207 2297639 : file,
208 2297639 : compressed_reads: true,
209 2297639 : }
210 2297639 : }
211 :
212 : /// Read a page from the underlying file into given buffer.
213 52813 : async fn fill_buffer(
214 52813 : &self,
215 52813 : buf: PageWriteGuard<'static>,
216 52813 : blkno: u32,
217 52813 : ctx: &RequestContext,
218 52813 : ) -> Result<PageWriteGuard<'static>, std::io::Error> {
219 52813 : assert!(buf.len() == PAGE_SZ);
220 52813 : self.file
221 52813 : .read_exact_at_page(buf, blkno as u64 * PAGE_SZ as u64, ctx)
222 32883 : .await
223 52813 : }
224 : /// Read a block.
225 : ///
226 : /// Returns a "lease" object that can be used to
227 : /// access to the contents of the page. (For the page cache, the
228 : /// lease object represents a lock on the buffer.)
229 2635070 : pub async fn read_blk<'b>(
230 2635070 : &self,
231 2635070 : blknum: u32,
232 2635070 : ctx: &RequestContext,
233 2635070 : ) -> Result<BlockLease<'b>, std::io::Error> {
234 2635070 : let cache = page_cache::get();
235 2635070 : match cache
236 2635070 : .read_immutable_buf(self.file_id, blknum, ctx)
237 30850 : .await
238 2635070 : .map_err(|e| {
239 0 : std::io::Error::new(
240 0 : std::io::ErrorKind::Other,
241 0 : format!("Failed to read immutable buf: {e:#}"),
242 0 : )
243 2635070 : })? {
244 2582257 : ReadBufResult::Found(guard) => Ok(guard.into()),
245 52813 : ReadBufResult::NotFound(write_guard) => {
246 : // Read the page from disk into the buffer
247 52813 : let write_guard = self.fill_buffer(write_guard, blknum, ctx).await?;
248 52813 : Ok(write_guard.mark_valid().into())
249 : }
250 : }
251 2635070 : }
252 : }
253 :
254 : impl BlockReader for FileBlockReader<'_> {
255 277885 : fn block_cursor(&self) -> BlockCursor<'_> {
256 277885 : BlockCursor::new_with_compression(
257 277885 : BlockReaderRef::FileBlockReader(self),
258 277885 : self.compressed_reads,
259 277885 : )
260 277885 : }
261 : }
262 :
263 : ///
264 : /// Trait for block-oriented output
265 : ///
266 : pub trait BlockWriter {
267 : ///
268 : /// Write a page to the underlying storage.
269 : ///
270 : /// 'buf' must be of size PAGE_SZ. Returns the block number the page was
271 : /// written to.
272 : ///
273 : fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error>;
274 : }
275 :
276 : ///
277 : /// A simple in-memory buffer of blocks.
278 : ///
279 : pub struct BlockBuf {
280 : pub blocks: Vec<Bytes>,
281 : }
282 : impl BlockWriter for BlockBuf {
283 14311 : fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error> {
284 14311 : assert!(buf.len() == PAGE_SZ);
285 14311 : let blknum = self.blocks.len();
286 14311 : self.blocks.push(buf);
287 14311 : Ok(blknum as u32)
288 14311 : }
289 : }
290 :
291 : impl BlockBuf {
292 1650 : pub fn new() -> Self {
293 1650 : BlockBuf { blocks: Vec::new() }
294 1650 : }
295 :
296 2023972 : pub fn size(&self) -> u64 {
297 2023972 : (self.blocks.len() * PAGE_SZ) as u64
298 2023972 : }
299 : }
300 : impl Default for BlockBuf {
301 0 : fn default() -> Self {
302 0 : Self::new()
303 0 : }
304 : }
|