1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use crate::latch::RwLatch;
use crate::page_id::{PAGE_SIZE, PageId};
/// A buffer frame: a PAGE_SIZE block of memory with metadata for buffer management.
///
/// # Safety
///
/// The `data` pointer is allocated via `std::alloc` and must be freed via `Frame::drop`.
/// Access to the data must be coordinated through:
/// - `pin_count > 0` (frame is in use, cannot be evicted)
/// - `latch` (read/write access to the page data)
pub struct Frame {
/// Raw pointer to PAGE_SIZE bytes of aligned memory.
data: *mut u8,
/// Which page is currently loaded in this frame (encoded as u64).
page_id: AtomicU64,
/// Number of threads currently using this frame. >0 prevents eviction.
pin_count: AtomicU32,
/// Whether the frame has been modified since loading.
dirty: AtomicBool,
/// Whether the frame was recently accessed (for clock eviction).
recently_used: AtomicBool,
/// Reader-writer latch protecting the page data.
latch: RwLatch,
}
// Frame is safe to share across threads: all mutable state is atomic or latch-protected.
unsafe impl Send for Frame {}
unsafe impl Sync for Frame {}
impl Frame {
/// Allocate a new frame with zeroed PAGE_SIZE memory.
pub fn new() -> Self {
let layout =
std::alloc::Layout::from_size_align(PAGE_SIZE, PAGE_SIZE).expect("invalid page layout");
// SAFETY: Layout is valid (non-zero, power-of-two alignment).
let data = unsafe { std::alloc::alloc_zeroed(layout) };
if data.is_null() {
std::alloc::handle_alloc_error(layout);
}
Self {
data,
page_id: AtomicU64::new(PageId::INVALID.to_u64()),
pin_count: AtomicU32::new(0),
dirty: AtomicBool::new(false),
recently_used: AtomicBool::new(false),
latch: RwLatch::new(),
}
}
/// Get a shared (read-only) reference to the page data.
///
/// # Safety
///
/// Caller must hold a shared latch or pin and ensure no writer exists.
pub unsafe fn data(&self) -> &[u8] {
// SAFETY: data was allocated with PAGE_SIZE bytes and is valid for the lifetime of Frame.
unsafe { std::slice::from_raw_parts(self.data, PAGE_SIZE) }
}
/// Get an exclusive (mutable) reference to the page data.
///
/// # Safety
///
/// Caller must hold an exclusive latch. The `&self` signature is
/// intentional: `Frame` uses interior mutability via a raw pointer,
/// coordinated by pin_count and latch.
#[allow(clippy::mut_from_ref)]
pub unsafe fn data_mut(&self) -> &mut [u8] {
// SAFETY: data was allocated with PAGE_SIZE bytes. Exclusive access is ensured by the caller.
unsafe { std::slice::from_raw_parts_mut(self.data, PAGE_SIZE) }
}
/// Get the page ID currently loaded in this frame.
pub fn page_id(&self) -> PageId {
PageId::from_u64(self.page_id.load(Ordering::Acquire))
}
/// Set the page ID for this frame.
pub fn set_page_id(&self, pid: PageId) {
self.page_id.store(pid.to_u64(), Ordering::Release);
}
/// Get the current pin count.
pub fn pin_count(&self) -> u32 {
self.pin_count.load(Ordering::Acquire)
}
/// Increment the pin count.
pub fn pin(&self) -> u32 {
self.pin_count.fetch_add(1, Ordering::AcqRel) + 1
}
/// Decrement the pin count.
pub fn unpin(&self) -> u32 {
let prev = self.pin_count.fetch_sub(1, Ordering::AcqRel);
debug_assert!(prev > 0, "unpin called on unpinned frame");
prev - 1
}
/// Check if the frame is pinned.
pub fn is_pinned(&self) -> bool {
self.pin_count() > 0
}
/// Check if the frame is dirty.
pub fn is_dirty(&self) -> bool {
self.dirty.load(Ordering::Acquire)
}
/// Mark the frame as dirty.
pub fn set_dirty(&self) {
self.dirty.store(true, Ordering::Release);
}
/// Clear the dirty flag.
pub fn clear_dirty(&self) {
self.dirty.store(false, Ordering::Release);
}
/// Check if the frame was recently used.
pub fn is_recently_used(&self) -> bool {
self.recently_used.load(Ordering::Relaxed)
}
/// Mark the frame as recently used.
pub fn set_recently_used(&self) {
self.recently_used.store(true, Ordering::Relaxed);
}
/// Clear the recently-used flag (second-chance eviction).
pub fn clear_recently_used(&self) {
self.recently_used.store(false, Ordering::Relaxed);
}
/// Get a reference to the latch.
pub fn latch(&self) -> &RwLatch {
&self.latch
}
/// Reset the frame to an empty state (for after eviction).
pub fn reset(&self) {
self.page_id
.store(PageId::INVALID.to_u64(), Ordering::Release);
self.dirty.store(false, Ordering::Release);
self.recently_used.store(false, Ordering::Relaxed);
// pin_count should already be 0 when resetting
debug_assert_eq!(self.pin_count(), 0);
}
/// Check if this frame holds a valid page.
pub fn has_valid_page(&self) -> bool {
self.page_id().is_valid()
}
}
impl Drop for Frame {
fn drop(&mut self) {
let layout =
std::alloc::Layout::from_size_align(PAGE_SIZE, PAGE_SIZE).expect("invalid page layout");
// SAFETY: data was allocated with this exact layout in Frame::new().
unsafe {
std::alloc::dealloc(self.data, layout);
}
}
}
impl Default for Frame {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::page_id::FileId;
#[test]
fn new_frame() {
let frame = Frame::new();
assert!(!frame.has_valid_page());
assert_eq!(frame.pin_count(), 0);
assert!(!frame.is_dirty());
assert!(!frame.is_recently_used());
assert!(!frame.is_pinned());
}
#[test]
fn data_is_zeroed() {
let frame = Frame::new();
// SAFETY: No concurrent access in this test.
let data = unsafe { frame.data() };
assert!(data.iter().all(|&b| b == 0));
assert_eq!(data.len(), PAGE_SIZE);
}
#[test]
fn write_and_read_data() {
let frame = Frame::new();
// SAFETY: No concurrent access in this test.
unsafe {
let data = frame.data_mut();
data[0] = 0xDE;
data[1] = 0xAD;
data[PAGE_SIZE - 1] = 0xFF;
}
let data = unsafe { frame.data() };
assert_eq!(data[0], 0xDE);
assert_eq!(data[1], 0xAD);
assert_eq!(data[PAGE_SIZE - 1], 0xFF);
}
#[test]
fn set_page_id() {
let frame = Frame::new();
let pid = PageId::new(FileId(1), 42);
frame.set_page_id(pid);
assert_eq!(frame.page_id(), pid);
assert!(frame.has_valid_page());
}
#[test]
fn pin_and_unpin() {
let frame = Frame::new();
assert_eq!(frame.pin(), 1);
assert_eq!(frame.pin(), 2);
assert!(frame.is_pinned());
assert_eq!(frame.unpin(), 1);
assert_eq!(frame.unpin(), 0);
assert!(!frame.is_pinned());
}
#[test]
fn dirty_flag() {
let frame = Frame::new();
assert!(!frame.is_dirty());
frame.set_dirty();
assert!(frame.is_dirty());
frame.clear_dirty();
assert!(!frame.is_dirty());
}
#[test]
fn recently_used_flag() {
let frame = Frame::new();
assert!(!frame.is_recently_used());
frame.set_recently_used();
assert!(frame.is_recently_used());
frame.clear_recently_used();
assert!(!frame.is_recently_used());
}
#[test]
fn reset() {
let frame = Frame::new();
frame.set_page_id(PageId::new(FileId(1), 0));
frame.set_dirty();
frame.set_recently_used();
frame.reset();
assert!(!frame.has_valid_page());
assert!(!frame.is_dirty());
assert!(!frame.is_recently_used());
}
#[test]
fn latch_access() {
let frame = Frame::new();
frame.latch().lock_shared();
assert!(!frame.latch().is_unlocked());
frame.latch().unlock_shared();
assert!(frame.latch().is_unlocked());
}
}