Skip to main content

atmos/kernel/fs/
block.rs

1// block.rs - Block Device Abstraction, RAM Disk Backend, and Mirrored (Redundant) Layer
2#![allow(dead_code)]
3#![allow(static_mut_refs)]
4
5extern crate alloc;
6use super::checksum::crc32;
7use alloc::vec::Vec;
8
9pub const SECTOR_SIZE: usize = 512;
10pub const DATA_SIZE_PER_SECTOR: usize = 508; // 512 - 4 (CRC32)
11
12/// 抽象ブロックデバイスの動作を規定するトレイト
13pub trait BlockDevice {
14    /// デバイスの総セクタ数を取得します
15    fn total_sectors(&self) -> usize;
16
17    /// 生セクタ (512バイト) の読み込みを行います (チェックサム検証なし)
18    fn read_raw_sector(&mut self, sector: usize, buf: &mut [u8]) -> Result<(), &'static str>;
19
20    /// 生セクタ (512バイト) の書き込みを行います (チェックサム検証なし)
21    fn write_raw_sector(&mut self, sector: usize, buf: &[u8]) -> Result<(), &'static str>;
22
23    /// データの二重化(ミラーリング)が必要な外部記憶デバイスかどうか
24    fn should_mirror(&self) -> bool {
25        false
26    }
27}
28
29/// メモリ上にファイルシステム全体を格納する仮想RAMディスク
30pub struct RAMDisk {
31    base_ptr: *mut u8,
32    size_bytes: usize,
33    sectors: usize,
34    _allocated: Option<Vec<u8>>,
35    /// 電源断の模擬(単体試験用。2026-11-10)。`Some(n)` なら n 回書いた後の書き込みを全部失敗させる
36    /// (その時点で電源が落ちたのと同じく、以後ディスクの中身は変わらない)。`None` なら制限なし。
37    pub write_budget: Option<usize>,
38}
39
40unsafe impl Send for RAMDisk {}
41unsafe impl Sync for RAMDisk {}
42
43impl RAMDisk {
44    /// ヒープからメモリを確保する仮想RAMディスク(単体テストや小規模環境用)
45    pub fn new(size_bytes: usize) -> Self {
46        let mut storage = alloc::vec![0u8; size_bytes];
47        let base_ptr = storage.as_mut_ptr();
48        let sectors = size_bytes / SECTOR_SIZE;
49        Self {
50            base_ptr,
51            size_bytes,
52            sectors,
53            _allocated: Some(storage),
54            write_budget: None,
55        }
56    }
57
58    /// 物理メモリ上の特定領域(ヒープ外の専用RAM領域)を直接使用するRAMディスク(実機カーネル用)
59    ///
60    /// # Safety
61    /// `base_addr` から `size_bytes` の領域が他モジュールと重複せず、排他的に使用可能である必要があります。
62    pub unsafe fn from_raw_memory(base_addr: usize, size_bytes: usize) -> Self {
63        let base_ptr = base_addr as *mut u8;
64        let sectors = size_bytes / SECTOR_SIZE;
65        Self {
66            base_ptr,
67            size_bytes,
68            sectors,
69            _allocated: None,
70            write_budget: None,
71        }
72    }
73}
74
75impl BlockDevice for RAMDisk {
76    fn total_sectors(&self) -> usize {
77        self.sectors
78    }
79
80    fn read_raw_sector(&mut self, sector: usize, buf: &mut [u8]) -> Result<(), &'static str> {
81        if sector >= self.sectors || buf.len() < SECTOR_SIZE {
82            return Err("read_raw_sector: sector out of range or buffer too small");
83        }
84        let offset = sector * SECTOR_SIZE;
85        unsafe {
86            let src = self.base_ptr.add(offset);
87            core::ptr::copy_nonoverlapping(src, buf.as_mut_ptr(), SECTOR_SIZE);
88        }
89        Ok(())
90    }
91
92    fn write_raw_sector(&mut self, sector: usize, buf: &[u8]) -> Result<(), &'static str> {
93        if sector >= self.sectors || buf.len() < SECTOR_SIZE {
94            return Err("write_raw_sector: sector out of range or buffer too small");
95        }
96        if let Some(b) = self.write_budget.as_mut() {
97            if *b == 0 {
98                return Err("write_raw_sector: power lost (simulated)");
99            }
100            *b -= 1;
101        }
102        let offset = sector * SECTOR_SIZE;
103        unsafe {
104            let dst = self.base_ptr.add(offset);
105            core::ptr::copy_nonoverlapping(buf.as_ptr(), dst, SECTOR_SIZE);
106        }
107        Ok(())
108    }
109
110    fn should_mirror(&self) -> bool {
111        // RAMディスクは揮発性メモリのため二重化不要(RAM容量を100%有効活用)
112        false
113    }
114}
115
116/// データの二重化 (ミラーリング) & 自動自己修復 (Self-Healing) を提供する上位ブロックデバイス層
117/// SDカード等の外部不揮発性ストレージでは二重化を行い、
118/// RAMディスク等の揮発性メモリでは多重化を行わずに全RAM容量を有効活用する。
119pub struct MirroredBlockDevice<B: BlockDevice> {
120    backend: B,
121    mirrored: bool,
122    usable_sectors: usize,
123    /// 読めなかった回数(両系とも駄目だった読み出し)。読んだ結果を覚えておく側が、途中で失敗が無かったかを確かめる。
124    read_failures: u64,
125    /// 読み出しの回数(診断用。覚えた結果を使い回せているかを確かめる)。
126    read_count: u64,
127}
128
129impl<B: BlockDevice> MirroredBlockDevice<B> {
130    pub fn new(backend: B) -> Self {
131        let mirrored = backend.should_mirror();
132        let usable_sectors = if mirrored {
133            backend.total_sectors() / 2
134        } else {
135            backend.total_sectors()
136        };
137        Self {
138            backend,
139            mirrored,
140            usable_sectors,
141            read_failures: 0,
142            read_count: 0,
143        }
144    }
145
146    pub fn new_mirrored(backend: B) -> Self {
147        let usable_sectors = backend.total_sectors() / 2;
148        Self {
149            backend,
150            mirrored: true,
151            usable_sectors,
152            read_failures: 0,
153            read_count: 0,
154        }
155    }
156
157    pub fn new_single(backend: B) -> Self {
158        let usable_sectors = backend.total_sectors();
159        Self {
160            backend,
161            mirrored: false,
162            usable_sectors,
163            read_failures: 0,
164            read_count: 0,
165        }
166    }
167
168    /// 下の記憶装置(単体試験で電源断を模擬するため)。
169    pub fn backend_mut(&mut self) -> &mut B {
170        &mut self.backend
171    }
172
173    pub fn is_mirrored(&self) -> bool {
174        self.mirrored
175    }
176
177    pub fn total_usable_sectors(&self) -> usize {
178        self.usable_sectors
179    }
180
181    /// チェックサム (CRC32) 付きでデータをセクタに書き込みします
182    pub fn write_sector(&mut self, sector: usize, data: &[u8]) -> Result<(), &'static str> {
183        if sector >= self.usable_sectors || data.len() > DATA_SIZE_PER_SECTOR {
184            return Err("write_sector: sector out of range or data too large");
185        }
186
187        // 512バイトの書き込み用一時バッファを用意
188        let mut buf = [0u8; SECTOR_SIZE];
189        buf[..data.len()].copy_from_slice(data);
190
191        // データのチェックサムを計算し、セクタの末尾4バイトに格納
192        let crc = crc32(&buf[..DATA_SIZE_PER_SECTOR]);
193        let crc_bytes = crc.to_le_bytes();
194        buf[DATA_SIZE_PER_SECTOR..SECTOR_SIZE].copy_from_slice(&crc_bytes);
195
196        // 1. プライマリ領域に書き込み
197        self.backend.write_raw_sector(sector, &buf)?;
198
199        // 2. ミラーリング有効時(SD/SSD等の外部記憶)のみセカンダリ領域に同一データを書き込み
200        if self.mirrored {
201            self.backend
202                .write_raw_sector(sector + self.usable_sectors, &buf)?;
203        }
204
205        Ok(())
206    }
207
208    /// 読み出しの回数(起動からの累計。診断用)。
209    pub fn read_count(&self) -> u64 {
210        self.read_count
211    }
212
213    /// 読めなかった読み出しの回数(起動からの累計)。
214    pub fn read_failures(&self) -> u64 {
215        self.read_failures
216    }
217
218    /// チェックサム (CRC32) 検証付きでセクタからデータを読み込みます (外部記憶ミラーリング時は破損から自動修復)
219    pub fn read_sector(&mut self, sector: usize, data: &mut [u8]) -> Result<(), &'static str> {
220        self.read_count += 1;
221        let r = self.read_sector_checked(sector, data);
222        if r.is_err() {
223            self.read_failures += 1;
224        }
225        r
226    }
227
228    fn read_sector_checked(&mut self, sector: usize, data: &mut [u8]) -> Result<(), &'static str> {
229        if sector >= self.usable_sectors || data.len() < DATA_SIZE_PER_SECTOR {
230            return Err("read_sector: sector out of range or buffer too small");
231        }
232
233        let mut buf = [0u8; SECTOR_SIZE];
234
235        // 1. プライマリ領域からの読み込み試行
236        if self.backend.read_raw_sector(sector, &mut buf).is_ok() {
237            let crc_stored = u32::from_le_bytes([
238                buf[DATA_SIZE_PER_SECTOR],
239                buf[DATA_SIZE_PER_SECTOR + 1],
240                buf[DATA_SIZE_PER_SECTOR + 2],
241                buf[DATA_SIZE_PER_SECTOR + 3],
242            ]);
243            let crc_calc = crc32(&buf[..DATA_SIZE_PER_SECTOR]);
244
245            if crc_stored == crc_calc {
246                // プライマリデータは健全
247                data[..DATA_SIZE_PER_SECTOR].copy_from_slice(&buf[..DATA_SIZE_PER_SECTOR]);
248                return Ok(());
249            } else if self.mirrored {
250                crate::warn!(
251                    "CRC mismatch on Primary Sector {}. Initiating Self-Healing...",
252                    sector
253                );
254            } else {
255                crate::warn!(
256                    "CRC mismatch on Sector {}. RAMDisk is unmirrored.",
257                    sector
258                );
259                return Err("read_sector: crc mismatch");
260            }
261        }
262
263        // 2. ミラーリング有効時かつプライマリが破損していた場合、セカンダリ (ミラー) 領域から読み込み
264        if self.mirrored {
265            let mirror_sector = sector + self.usable_sectors;
266            if self
267                .backend
268                .read_raw_sector(mirror_sector, &mut buf)
269                .is_ok()
270            {
271                let crc_stored = u32::from_le_bytes([
272                    buf[DATA_SIZE_PER_SECTOR],
273                    buf[DATA_SIZE_PER_SECTOR + 1],
274                    buf[DATA_SIZE_PER_SECTOR + 2],
275                    buf[DATA_SIZE_PER_SECTOR + 3],
276                ]);
277                let crc_calc = crc32(&buf[..DATA_SIZE_PER_SECTOR]);
278
279                if crc_stored == crc_calc {
280                    crate::info!(
281                        "Mirror Sector {} is healthy. Healing Primary Sector {}...",
282                        mirror_sector,
283                        sector
284                    );
285                    if let Err(e) = self.backend.write_raw_sector(sector, &buf) {
286                        crate::warn!(
287                            "[BLOCK] 自己修復の書き戻しに失敗 sector={} mirror_sector={} err={:?}",
288                            sector,
289                            mirror_sector,
290                            e
291                        );
292                    }
293
294                    data[..DATA_SIZE_PER_SECTOR].copy_from_slice(&buf[..DATA_SIZE_PER_SECTOR]);
295                    return Ok(());
296                }
297            }
298
299            // 両系とも破損していた場合
300            crate::error!(
301                "Dual-redundancy failure on Sector {}. Data is unrecoverable!",
302                sector
303            );
304            return Err("read_sector: both primary and mirror corrupted");
305        }
306
307        Err("read_sector: read failed")
308    }
309
310    /// デバッグ検証用: 意図的に特定の生セクタを破壊します (自己修復のテストに使用)
311    pub fn force_corrupt_raw_sector(&mut self, sector: usize) -> Result<(), &'static str> {
312        if sector >= self.backend.total_sectors() {
313            return Err("force_corrupt: sector out of range");
314        }
315        let corrupt_buf = [0u8; SECTOR_SIZE]; // ゼロクリアで完全に上書き破壊
316        self.backend.write_raw_sector(sector, &corrupt_buf)
317    }
318}
319
320/// オンボードのブート用 microSD カード (SDHOST 制御) 用のブロックデバイス実装
321pub struct SDCard {
322    offset_sectors: usize,
323}
324
325impl SDCard {
326    pub fn new() -> Result<Self, &'static str> {
327        // SDHOST コントローラと物理カードの初期化を実行
328        crate::kernel::sdhost::init()?;
329        // オフセットは 256 MiB (256 * 1024 * 1024 / 512 = 524,288 セクタ)
330        let sd = Self {
331            offset_sectors: 524288,
332        };
333
334        // コントローラの初期化に成功しても、データ転送(CMD17/CMD24 と FIFO)が動かなければファイルシステムは
335        // 使えない。初期化の直後に 1 セクタ読んでみて、読めなければエラーを返して RAMDisk へ退避させる
336        // (2026-07-26。データ転送そのものは 2026-11-12 に QEMU のモデルと Linux のドライバの定義に合わせて直した)。
337        Self::probe_data_path(&sd)?;
338        Ok(sd)
339    }
340
341    /// データ転送経路が最低限機能しているかの疎通確認(読み出し 1 セクタ)。
342    fn probe_data_path(sd: &Self) -> Result<(), &'static str> {
343        let mut buf = [0u8; 512];
344        crate::kernel::sdhost::read_sector(sd.offset_sectors, &mut buf)
345            .map_err(|_| "SDHOST: data path probe failed (read)")
346    }
347}
348
349impl BlockDevice for SDCard {
350    fn total_sectors(&self) -> usize {
351        let total = crate::kernel::sdhost::get_total_sectors();
352        // ブート領域 (256MiB) を差し引いた残りの全セクタ数を SylFS に公開
353        total.saturating_sub(self.offset_sectors)
354    }
355
356    fn read_raw_sector(&mut self, sector: usize, buf: &mut [u8]) -> Result<(), &'static str> {
357        let target_sector = sector + self.offset_sectors;
358        crate::kernel::sdhost::read_sector(target_sector, buf)
359    }
360
361    fn write_raw_sector(&mut self, sector: usize, buf: &[u8]) -> Result<(), &'static str> {
362        let target_sector = sector + self.offset_sectors;
363        // 防御的セキュリティ: 誤ってブート用 FAT32 パーティション領域 (先頭 256MiB) を破壊する書き込みをブロック
364        if target_sector < self.offset_sectors {
365            return Err("SDCard write blocked: Attempted to write to boot/OS partition area!");
366        }
367        crate::kernel::sdhost::write_sector(target_sector, buf)
368    }
369
370    fn should_mirror(&self) -> bool {
371        // SDカード・外部SSD等の不揮発性ストレージはビット破損や物理不良対策のため二重化(ミラーリング)する
372        true
373    }
374}
375
376/// 実行環境に応じて RAMDisk と SDCard を安全に切り替えるためのデバイスラッパー
377pub enum BackendDevice {
378    RAM(RAMDisk),
379    SD(SDCard),
380}
381
382impl BlockDevice for BackendDevice {
383    fn total_sectors(&self) -> usize {
384        match self {
385            BackendDevice::RAM(d) => d.total_sectors(),
386            BackendDevice::SD(d) => d.total_sectors(),
387        }
388    }
389
390    fn read_raw_sector(&mut self, sector: usize, buf: &mut [u8]) -> Result<(), &'static str> {
391        match self {
392            BackendDevice::RAM(d) => d.read_raw_sector(sector, buf),
393            BackendDevice::SD(d) => d.read_raw_sector(sector, buf),
394        }
395    }
396
397    fn write_raw_sector(&mut self, sector: usize, buf: &[u8]) -> Result<(), &'static str> {
398        match self {
399            BackendDevice::RAM(d) => d.write_raw_sector(sector, buf),
400            BackendDevice::SD(d) => d.write_raw_sector(sector, buf),
401        }
402    }
403
404    fn should_mirror(&self) -> bool {
405        match self {
406            BackendDevice::RAM(d) => d.should_mirror(),
407            BackendDevice::SD(d) => d.should_mirror(),
408        }
409    }
410}