1#![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; pub trait BlockDevice {
14 fn total_sectors(&self) -> usize;
16
17 fn read_raw_sector(&mut self, sector: usize, buf: &mut [u8]) -> Result<(), &'static str>;
19
20 fn write_raw_sector(&mut self, sector: usize, buf: &[u8]) -> Result<(), &'static str>;
22
23 fn should_mirror(&self) -> bool {
25 false
26 }
27}
28
29pub struct RAMDisk {
31 base_ptr: *mut u8,
32 size_bytes: usize,
33 sectors: usize,
34 _allocated: Option<Vec<u8>>,
35 pub write_budget: Option<usize>,
38}
39
40unsafe impl Send for RAMDisk {}
41unsafe impl Sync for RAMDisk {}
42
43impl RAMDisk {
44 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 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 false
113 }
114}
115
116pub struct MirroredBlockDevice<B: BlockDevice> {
120 backend: B,
121 mirrored: bool,
122 usable_sectors: usize,
123 read_failures: u64,
125 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 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 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 let mut buf = [0u8; SECTOR_SIZE];
189 buf[..data.len()].copy_from_slice(data);
190
191 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 self.backend.write_raw_sector(sector, &buf)?;
198
199 if self.mirrored {
201 self.backend
202 .write_raw_sector(sector + self.usable_sectors, &buf)?;
203 }
204
205 Ok(())
206 }
207
208 pub fn read_count(&self) -> u64 {
210 self.read_count
211 }
212
213 pub fn read_failures(&self) -> u64 {
215 self.read_failures
216 }
217
218 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 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 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 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 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 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]; self.backend.write_raw_sector(sector, &corrupt_buf)
317 }
318}
319
320pub struct SDCard {
322 offset_sectors: usize,
323}
324
325impl SDCard {
326 pub fn new() -> Result<Self, &'static str> {
327 crate::kernel::sdhost::init()?;
329 let sd = Self {
331 offset_sectors: 524288,
332 };
333
334 Self::probe_data_path(&sd)?;
338 Ok(sd)
339 }
340
341 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 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 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 true
373 }
374}
375
376pub 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}