1#![allow(dead_code)]
3#![allow(static_mut_refs)]
4
5extern crate alloc;
6use alloc::vec::Vec;
7
8use super::block::{BlockDevice, MirroredBlockDevice, DATA_SIZE_PER_SECTOR};
9
10const MAX_KEYS: usize = 24;
11const KEY_LEN: usize = 16; #[repr(C, packed)]
19#[derive(Clone, Copy)]
20pub struct BTreeNode {
21 pub node_type: u8, pub num_keys: u8,
23 pub padding: [u8; 2],
24 pub keys: [[u8; KEY_LEN]; MAX_KEYS + 1], pub values: [u32; MAX_KEYS + 2], }
27
28const _: () = assert!(core::mem::size_of::<BTreeNode>() <= DATA_SIZE_PER_SECTOR);
32
33impl BTreeNode {
34 pub fn new(is_leaf: bool) -> Self {
35 Self {
36 node_type: if is_leaf { 0 } else { 1 },
37 num_keys: 0,
38 padding: [0; 2],
39 keys: [[0; KEY_LEN]; MAX_KEYS + 1],
40 values: [0; MAX_KEYS + 2],
41 }
42 }
43
44 pub fn from_bytes(bytes: &[u8]) -> Self {
46 let mut node = Self::new(true);
47 let ptr = &mut node as *mut Self as *mut u8;
48 unsafe {
49 core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, core::mem::size_of::<Self>());
50 }
51 node
52 }
53
54 pub fn to_bytes(&self) -> [u8; DATA_SIZE_PER_SECTOR] {
56 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
57 let ptr = self as *const Self as *const u8;
58 unsafe {
59 core::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), core::mem::size_of::<Self>());
60 }
61 buf
62 }
63
64 fn compare_keys(a: &[u8; KEY_LEN], b: &[u8]) -> core::cmp::Ordering {
66 let b_len = b.len().min(KEY_LEN);
67 let mut b_padded = [0u8; KEY_LEN];
68 b_padded[..b_len].copy_from_slice(&b[..b_len]);
69 a.cmp(&b_padded)
70 }
71}
72
73pub struct CowBTree {
75 root_sector: u32,
76 replaced: core::cell::RefCell<Vec<u32>>,
79}
80
81impl CowBTree {
82 pub fn new(root_sector: u32) -> Self {
83 Self { root_sector, replaced: core::cell::RefCell::new(Vec::new()) }
84 }
85
86 pub fn take_replaced(&mut self) -> Vec<u32> {
89 core::mem::take(&mut *self.replaced.borrow_mut())
90 }
91
92 pub fn get_root(&self) -> u32 {
93 self.root_sector
94 }
95
96 pub fn search<B: BlockDevice>(
99 &self,
100 device: &mut MirroredBlockDevice<B>,
101 key: &[u8; KEY_LEN],
102 ) -> Option<u32> {
103 let mut curr_sector = self.root_sector;
104 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
105 let mut loop_count = 0;
106
107 while curr_sector != 0 {
108 loop_count += 1;
109 if loop_count > 100 {
110 crate::warn!(
111 "[FS] [BTree] search loop exceeded 100 iterations! curr_sector={}",
112 curr_sector
113 );
114 return None;
115 }
116 if device.read_sector(curr_sector as usize, &mut buf).is_err() {
117 return None;
118 }
119 let node = BTreeNode::from_bytes(&buf);
120
121 let mut idx = 0;
123 while idx < node.num_keys as usize {
124 if idx >= MAX_KEYS {
125 crate::warn!(
126 "[FS] [BTree] search node num_keys is corrupted! num_keys={}",
127 node.num_keys
128 );
129 return None;
130 }
131 let cmp = BTreeNode::compare_keys(&node.keys[idx], key);
132 if cmp == core::cmp::Ordering::Equal {
133 if node.node_type == 0 {
134 let v = node.values[idx];
137 return if v == 0 { None } else { Some(v) };
138 } else {
139 idx += 1;
141 break;
142 }
143 } else if cmp == core::cmp::Ordering::Greater {
144 break;
145 }
146 idx += 1;
147 }
148
149 if node.node_type == 0 {
150 break; } else {
152 curr_sector = node.values[idx]; }
154 }
155
156 None
157 }
158
159 pub fn insert<B: BlockDevice>(
162 &mut self,
163 device: &mut MirroredBlockDevice<B>,
164 key: &[u8; KEY_LEN],
165 val_sector: u32,
166 alloc_sector_fn: &mut dyn FnMut() -> u32,
167 ) -> Result<u32, &'static str> {
168 let root_sec = self.root_sector;
169
170 if root_sec == 0 {
172 let new_sec = alloc_sector_fn();
173 if new_sec == 0 {
174 return Err("btree: sector allocation failed");
175 }
176
177 let mut new_node = BTreeNode::new(true);
178 new_node.num_keys = 1;
179 new_node.keys[0] = *key;
180 new_node.values[0] = val_sector;
181
182 device.write_sector(new_sec as usize, &new_node.to_bytes())?;
183 self.root_sector = new_sec;
184 return Ok(new_sec);
185 }
186
187 let result = self.insert_recursive(device, root_sec, key, val_sector, alloc_sector_fn)?;
189
190 match result {
191 InsertResult::Ok(new_sec) => {
192 self.root_sector = new_sec;
193 Ok(new_sec)
194 }
195 InsertResult::Split(new_sec, split_key, split_sibling_sec) => {
196 let new_root_sec = alloc_sector_fn();
198 if new_root_sec == 0 {
199 return Err("btree: sector allocation failed");
200 }
201
202 let mut new_root = BTreeNode::new(false);
203 new_root.num_keys = 1;
204 new_root.keys[0] = split_key;
205 new_root.values[0] = new_sec;
206 new_root.values[1] = split_sibling_sec;
207
208 device.write_sector(new_root_sec as usize, &new_root.to_bytes())?;
209 self.root_sector = new_root_sec;
210 Ok(new_root_sec)
211 }
212 }
213 }
214
215 pub fn collect_leaf_entries<B: BlockDevice>(
217 &self,
218 device: &mut MirroredBlockDevice<B>,
219 out: &mut Vec<([u8; KEY_LEN], u32)>,
220 ) {
221 if self.root_sector == 0 {
222 return;
223 }
224 let mut visited = alloc::collections::BTreeSet::new();
225 self.collect_from_node(device, self.root_sector, out, &mut visited, 0);
226 }
227
228 fn collect_from_node<B: BlockDevice>(
232 &self,
233 device: &mut MirroredBlockDevice<B>,
234 sector: u32,
235 out: &mut Vec<([u8; KEY_LEN], u32)>,
236 visited: &mut alloc::collections::BTreeSet<u32>,
237 depth: usize,
238 ) {
239 if !visited.insert(sector) {
240 crate::warn!(
241 "[FS] [BTree] Circular reference detected in collect_from_node: sector={}",
242 sector
243 );
244 return;
245 }
246 if depth > 32 {
247 crate::warn!("[FS] [BTree] Depth limit exceeded in collect_from_node!");
248 return;
249 }
250
251 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
252 if device.read_sector(sector as usize, &mut buf).is_err() {
253 return;
254 }
255
256 let node = BTreeNode::from_bytes(&buf);
257 if node.node_type == 0 {
258 let limit = (node.num_keys as usize).min(MAX_KEYS);
259 for i in 0..limit {
260 if node.values[i] != 0 {
261 out.push((node.keys[i], node.values[i]));
262 }
263 }
264 return;
265 }
266
267 let limit = (node.num_keys as usize).min(MAX_KEYS);
268 for i in 0..=limit {
269 let child = node.values[i];
270 if child != 0 {
271 self.collect_from_node(device, child, out, visited, depth + 1);
272 }
273 }
274 }
275
276 pub fn build_sorted<B: BlockDevice>(
280 device: &mut MirroredBlockDevice<B>,
281 entries: &[([u8; KEY_LEN], u32)],
282 alloc_sector_fn: &mut dyn FnMut() -> u32,
283 ) -> Result<u32, &'static str> {
284 const FILL: usize = MAX_KEYS - 4;
286 let live: Vec<&([u8; KEY_LEN], u32)> = entries.iter().filter(|(_, v)| *v != 0).collect();
287 if live.is_empty() {
288 return Ok(0);
289 }
290 let mut level: Vec<([u8; KEY_LEN], u32)> = Vec::new();
292 for part in live.chunks(FILL) {
293 let mut node = BTreeNode::new(true);
294 node.num_keys = part.len() as u8;
295 for (i, (k, v)) in part.iter().enumerate() {
296 node.keys[i] = *k;
297 node.values[i] = *v;
298 }
299 let sec = alloc_sector_fn();
300 if sec == 0 {
301 return Err("btree: sector allocation failed");
302 }
303 device.write_sector(sec as usize, &node.to_bytes())?;
304 level.push((part[0].0, sec));
305 }
306 while level.len() > 1 {
307 let mut next: Vec<([u8; KEY_LEN], u32)> = Vec::new();
308 for part in level.chunks(FILL + 1) {
309 let mut node = BTreeNode::new(false);
311 node.num_keys = (part.len() - 1) as u8;
312 for (i, (k, sec)) in part.iter().enumerate() {
313 node.values[i] = *sec;
314 if i > 0 {
315 node.keys[i - 1] = *k;
316 }
317 }
318 let sec = alloc_sector_fn();
319 if sec == 0 {
320 return Err("btree: sector allocation failed");
321 }
322 device.write_sector(sec as usize, &node.to_bytes())?;
323 next.push((part[0].0, sec));
324 }
325 level = next;
326 }
327 Ok(level[0].1)
328 }
329
330 pub fn collect_node_sectors<B: BlockDevice>(&self, device: &mut MirroredBlockDevice<B>, out: &mut Vec<u32>) {
332 let mut stack: Vec<(u32, usize)> = Vec::new();
333 if self.root_sector != 0 {
334 stack.push((self.root_sector, 0));
335 }
336 let mut seen = alloc::collections::BTreeSet::new();
337 while let Some((sector, depth)) = stack.pop() {
338 if depth > 32 || !seen.insert(sector) {
339 continue;
340 }
341 out.push(sector);
342 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
343 if device.read_sector(sector as usize, &mut buf).is_err() {
344 continue;
345 }
346 let node = BTreeNode::from_bytes(&buf);
347 if node.node_type != 0 {
348 let limit = (node.num_keys as usize).min(MAX_KEYS);
349 for i in 0..=limit {
350 if node.values[i] != 0 {
351 stack.push((node.values[i], depth + 1));
352 }
353 }
354 }
355 }
356 }
357
358 fn insert_recursive<B: BlockDevice>(
359 &self,
360 device: &mut MirroredBlockDevice<B>,
361 curr_sector: u32,
362 key: &[u8; KEY_LEN],
363 val_sector: u32,
364 alloc_sector_fn: &mut dyn FnMut() -> u32,
365 ) -> Result<InsertResult, &'static str> {
366 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
367 if curr_sector as usize >= device.total_usable_sectors() {
378 crate::warn!(
379 "[SylFS][BTREE] 節点番号が実在範囲外 curr_sector={} usable={} (索引が壊れている)",
380 curr_sector,
381 device.total_usable_sectors()
382 );
383 return Err("btree: node sector out of range");
384 }
385 if let Err(e) = device.read_sector(curr_sector as usize, &mut buf) {
386 crate::warn!(
387 "[SylFS][BTREE] 節点の読み出しに失敗 curr_sector={} usable={} err={}",
388 curr_sector,
389 device.total_usable_sectors(),
390 e
391 );
392 return Err(e);
393 }
394
395 let mut node = BTreeNode::from_bytes(&buf);
397 let new_sector = alloc_sector_fn();
398 if new_sector == 0 {
399 return Err("btree: sector allocation failed");
400 }
401 self.replaced.borrow_mut().push(curr_sector);
402
403 let mut idx = 0;
405 while idx < node.num_keys as usize {
406 let cmp = BTreeNode::compare_keys(&node.keys[idx], key);
407 if cmp == core::cmp::Ordering::Equal {
408 if node.node_type == 0 {
409 node.values[idx] = val_sector;
411 device.write_sector(new_sector as usize, &node.to_bytes())?;
412 return Ok(InsertResult::Ok(new_sector));
413 } else {
414 idx += 1;
417 break;
418 }
419 } else if cmp == core::cmp::Ordering::Greater {
420 break;
421 }
422 idx += 1;
423 }
424
425 if node.node_type == 0 {
426 for i in (idx..node.num_keys as usize).rev() {
429 node.keys[i + 1] = node.keys[i];
430 node.values[i + 1] = node.values[i];
431 }
432 node.keys[idx] = *key;
433 node.values[idx] = val_sector;
434 node.num_keys += 1;
435
436 if node.num_keys as usize > MAX_KEYS {
437 let split_res = self.split_node(device, &mut node, new_sector, alloc_sector_fn)?;
439 Ok(split_res)
440 } else {
441 device.write_sector(new_sector as usize, &node.to_bytes())?;
443 Ok(InsertResult::Ok(new_sector))
444 }
445 } else {
446 let child_sec = node.values[idx];
448 let sub_result =
449 self.insert_recursive(device, child_sec, key, val_sector, alloc_sector_fn)?;
450
451 match sub_result {
452 InsertResult::Ok(new_child_sec) => {
453 node.values[idx] = new_child_sec;
455 device.write_sector(new_sector as usize, &node.to_bytes())?;
456 Ok(InsertResult::Ok(new_sector))
457 }
458 InsertResult::Split(new_child_sec, split_key, split_sibling_sec) => {
459 node.values[idx] = new_child_sec;
461
462 for i in (idx..node.num_keys as usize).rev() {
463 node.keys[i + 1] = node.keys[i];
464 node.values[i + 2] = node.values[i + 1];
465 }
466 node.keys[idx] = split_key;
467 node.values[idx + 1] = split_sibling_sec;
468 node.num_keys += 1;
469
470 if node.num_keys as usize > MAX_KEYS {
471 let split_res =
473 self.split_node(device, &mut node, new_sector, alloc_sector_fn)?;
474 Ok(split_res)
475 } else {
476 device.write_sector(new_sector as usize, &node.to_bytes())?;
477 Ok(InsertResult::Ok(new_sector))
478 }
479 }
480 }
481 }
482 }
483
484 fn split_node<B: BlockDevice>(
486 &self,
487 device: &mut MirroredBlockDevice<B>,
488 node: &mut BTreeNode,
489 new_sector: u32,
490 alloc_sector_fn: &mut dyn FnMut() -> u32,
491 ) -> Result<InsertResult, &'static str> {
492 let sibling_sector = alloc_sector_fn();
493 if sibling_sector == 0 {
494 return Err("btree: sector allocation failed");
495 }
496
497 let mut sibling = BTreeNode::new(node.node_type == 0);
498 let n = node.num_keys as usize;
500 let mid = n / 2;
501
502 let split_key = node.keys[mid];
504
505 if node.node_type == 0 {
506 let sibling_keys_num = n - mid;
509 for i in 0..sibling_keys_num {
510 sibling.keys[i] = node.keys[mid + i];
511 sibling.values[i] = node.values[mid + i];
512 }
513 sibling.num_keys = sibling_keys_num as u8;
514 } else {
515 let sibling_keys_num = n - mid - 1;
518 for i in 0..sibling_keys_num {
519 sibling.keys[i] = node.keys[mid + 1 + i];
520 sibling.values[i] = node.values[mid + 1 + i];
521 }
522 sibling.values[sibling_keys_num] = node.values[n]; sibling.num_keys = sibling_keys_num as u8;
524 }
525
526 node.num_keys = mid as u8;
528
529 device.write_sector(new_sector as usize, &node.to_bytes())?;
531 device.write_sector(sibling_sector as usize, &sibling.to_bytes())?;
532
533 Ok(InsertResult::Split(new_sector, split_key, sibling_sector))
534 }
535}
536
537enum InsertResult {
539 Ok(u32),
541 Split(u32, [u8; KEY_LEN], u32),
543}