1#![allow(dead_code)]
3#![allow(static_mut_refs)]
4
5use core::sync::atomic::{AtomicBool, Ordering};
6
7const GPIO_BASE: usize = 0x3F20_0000;
9const GPFSEL4: *mut u32 = (GPIO_BASE + 0x10) as *mut u32;
10const GPFSEL5: *mut u32 = (GPIO_BASE + 0x14) as *mut u32;
11const GPPUD: *mut u32 = (GPIO_BASE + 0x94) as *mut u32;
12const GPPUDCLK1: *mut u32 = (GPIO_BASE + 0x9C) as *mut u32;
13
14const SDHOST_BASE: usize = 0x3F20_2000;
16
17const SDCMD: *mut u32 = SDHOST_BASE as *mut u32;
18const SDARG: *mut u32 = (SDHOST_BASE + 0x04) as *mut u32;
19const SDTOUT: *mut u32 = (SDHOST_BASE + 0x08) as *mut u32;
20const SDCDIV: *mut u32 = (SDHOST_BASE + 0x0C) as *mut u32;
21const SDRSP0: *mut u32 = (SDHOST_BASE + 0x10) as *mut u32;
22const SDRSP1: *mut u32 = (SDHOST_BASE + 0x14) as *mut u32;
23const SDRSP2: *mut u32 = (SDHOST_BASE + 0x18) as *mut u32;
24const SDRSP3: *mut u32 = (SDHOST_BASE + 0x1C) as *mut u32;
25const SDHSTS: *mut u32 = (SDHOST_BASE + 0x20) as *mut u32;
26const SDVDD: *mut u32 = (SDHOST_BASE + 0x30) as *mut u32;
27const SDEDM: *mut u32 = (SDHOST_BASE + 0x34) as *mut u32;
28const SDHCFG: *mut u32 = (SDHOST_BASE + 0x38) as *mut u32;
29const SDHBCT: *mut u32 = (SDHOST_BASE + 0x3C) as *mut u32;
31const SDDATA: *mut u32 = (SDHOST_BASE + 0x40) as *mut u32;
32const SDHBLC: *mut u32 = (SDHOST_BASE + 0x50) as *mut u32;
40
41const SDCMD_NEW_CMD: u32 = 0x8000;
60const SDCMD_FAIL_ERROR: u32 = 0x4000;
61const SDCMD_BUSYWAIT: u32 = 0x0800;
62const SDCMD_NO_RESPONSE: u32 = 0x0400;
63const SDCMD_LONG_RESPONSE: u32 = 0x0200;
64const SDCMD_WRITE: u32 = 0x0080;
68const SDCMD_READ: u32 = 0x0040;
70
71const SDCMD_RESP_NONE: u32 = SDCMD_NO_RESPONSE;
73const SDCMD_RESP_48: u32 = 0x0000;
74const SDCMD_RESP_136: u32 = SDCMD_LONG_RESPONSE;
75
76const SDHCFG_REL_CMD_LINE: u32 = 0x0001;
78const SDHCFG_WIDE_INT_BUS: u32 = 0x0002;
80const SDHCFG_WIDE_EXT_BUS: u32 = 0x0004;
83const SDHCFG_SLOW_CARD: u32 = 0x0008;
84const SDHCFG_DATA_IRPT_EN: u32 = 0x0010;
85
86const SDEDM_WRITE_THRESHOLD_SHIFT: u32 = 9;
88const SDEDM_READ_THRESHOLD_SHIFT: u32 = 14;
89const SDEDM_THRESHOLD_MASK: u32 = 0x1F;
90const FIFO_READ_THRESHOLD: u32 = 4;
91const FIFO_WRITE_THRESHOLD: u32 = 4;
92
93const SDHSTS_FIFO_ERROR: u32 = 0x0008;
102const SDHSTS_CRC7_ERROR: u32 = 0x0010;
103const SDHSTS_CRC16_ERROR: u32 = 0x0020;
104const SDHSTS_CMD_TIME_OUT: u32 = 0x0040;
105const SDHSTS_REW_TIME_OUT: u32 = 0x0080;
106const SDHSTS_ERROR: u32 = SDHSTS_FIFO_ERROR
108 | SDHSTS_CRC7_ERROR
109 | SDHSTS_CRC16_ERROR
110 | SDHSTS_CMD_TIME_OUT
111 | SDHSTS_REW_TIME_OUT;
112const SDHSTS_CLEAR_ALL: u32 = 0x07FF;
114
115const SDEDM_FIFO_LEVEL_SHIFT: u32 = 4;
118const SDEDM_FIFO_LEVEL_MASK: u32 = 0x1F;
119const SDEDM_FIFO_WORDS: u32 = 16;
121const SDEDM_FSM_MASK: u32 = 0xF;
123const SDEDM_FSM_IDENTMODE: u32 = 0x0;
124const SDEDM_FSM_DATAMODE: u32 = 0x1;
125
126static SD_INITIALIZED: AtomicBool = AtomicBool::new(false);
128static mut RCA: u32 = 0;
129static mut CARD_SECTORS: usize = 0;
130static IS_SDHC: AtomicBool = AtomicBool::new(false);
132
133fn delay_us(us: u32) {
135 let start = crate::kernel::timer::get_system_time_us();
136 while crate::kernel::timer::get_system_time_us() - start < us as u64 {
137 core::hint::spin_loop();
138 }
139}
140
141fn setup_gpio() {
143 unsafe {
144 let mut fsel4 = core::ptr::read_volatile(GPFSEL4);
147 fsel4 &= !(0b111 << 24); fsel4 |= 0b100 << 24; fsel4 &= !(0b111 << 27); fsel4 |= 0b100 << 27; core::ptr::write_volatile(GPFSEL4, fsel4);
152
153 let mut fsel5 = core::ptr::read_volatile(GPFSEL5);
156 for pin in 50..=53 {
157 let shift = (pin - 50) * 3;
158 fsel5 &= !(0b111 << shift);
159 fsel5 |= 0b100 << shift;
160 }
161 core::ptr::write_volatile(GPFSEL5, fsel5);
162
163 core::ptr::write_volatile(GPPUD, 2); delay_us(10);
166 core::ptr::write_volatile(GPPUDCLK1, (1 << (48 - 32)) | (1 << (49 - 32)) | (1 << (50 - 32)) | (1 << (51 - 32)) | (1 << (53 - 32)));
167 delay_us(10);
168 core::ptr::write_volatile(GPPUD, 0);
169 core::ptr::write_volatile(GPPUDCLK1, 0);
170
171 core::ptr::write_volatile(GPPUD, 1); delay_us(10);
173 core::ptr::write_volatile(GPPUDCLK1, 1 << (52 - 32)); delay_us(10);
175 core::ptr::write_volatile(GPPUD, 0);
176 core::ptr::write_volatile(GPPUDCLK1, 0);
177 }
178}
179
180fn send_command(cmd_idx: u32, arg: u32, resp_type: u32) -> Result<[u32; 4], &'static str> {
182 unsafe {
183 let mut timeout = 100000;
185 while (core::ptr::read_volatile(SDCMD) & SDCMD_NEW_CMD) != 0 {
186 timeout -= 1;
187 if timeout == 0 {
188 return Err("SDHOST: send_command previous timeout");
189 }
190 core::hint::spin_loop();
191 }
192
193 core::ptr::write_volatile(SDARG, arg);
195
196 let cmd = (cmd_idx & 0x3F) | resp_type | SDCMD_NEW_CMD;
198 core::ptr::write_volatile(SDCMD, cmd);
199
200 timeout = 100000;
202 while (core::ptr::read_volatile(SDCMD) & SDCMD_NEW_CMD) != 0 {
203 timeout -= 1;
204 if timeout == 0 {
205 return Err("SDHOST: command execution timeout");
206 }
207 core::hint::spin_loop();
208 }
209
210 let cmd_status = core::ptr::read_volatile(SDCMD);
211 if (cmd_status & SDCMD_FAIL_ERROR) != 0 {
212 core::ptr::write_volatile(SDHSTS, SDHSTS_ERROR);
214 return Err("SDHOST: command execution failed");
215 }
216
217 let mut resp = [0u32; 4];
219 resp[0] = core::ptr::read_volatile(SDRSP0);
220 if resp_type == SDCMD_RESP_136 {
221 resp[1] = core::ptr::read_volatile(SDRSP1);
222 resp[2] = core::ptr::read_volatile(SDRSP2);
223 resp[3] = core::ptr::read_volatile(SDRSP3);
224 }
225
226 Ok(resp)
227 }
228}
229
230fn set_clock(hz: u32) {
232 unsafe {
233 let host_clk = 250_000_000;
235 let mut div = host_clk / hz;
236 if div < 2 {
237 div = 2;
238 }
239 let cdiv = if div >= 2 { (div / 2) - 1 } else { 0 };
241 core::ptr::write_volatile(SDCDIV, cdiv & 0x7FF);
242 delay_us(100);
243 }
244}
245
246pub fn init() -> Result<(), &'static str> {
248 if SD_INITIALIZED.load(Ordering::SeqCst) {
249 return Ok(());
250 }
251
252 crate::info!("[SD] Initializing BCM2835 SDHOST controller...");
253
254 setup_gpio();
255
256 unsafe {
257 core::ptr::write_volatile(SDVDD, 1); core::ptr::write_volatile(SDTOUT, 0xF00000); core::ptr::write_volatile(SDHSTS, SDHSTS_CLEAR_ALL); core::ptr::write_volatile(SDHCFG, 0); }
263
264 set_clock(400_000);
266
267 delay_us(10000);
269
270 if let Err(e) = send_command(0, 0, SDCMD_RESP_NONE) {
272 crate::warn!("[FS] SD CMD0 (GO_IDLE_STATE) failed: {}", e);
273 }
274 delay_us(5000);
275
276 let has_hc = match send_command(8, 0x1AA, SDCMD_RESP_48) {
278 Ok(resp) => (resp[0] & 0xFF) == 0xAA,
279 Err(_) => false,
280 };
281
282 let mut ocr = 0x0010_0000; if has_hc {
285 ocr |= 0x4000_0000; }
287
288 let mut ready = false;
289 for _ in 0..100 {
290 if send_command(55, 0, SDCMD_RESP_48).is_err() {
292 continue;
293 }
294 if let Ok(resp) = send_command(41, ocr, SDCMD_RESP_48) {
295 if (resp[0] & 0x8000_0000) != 0 {
296 ready = true;
297 ocr = resp[0];
298 break;
299 }
300 }
301 delay_us(10000);
302 }
303
304 if !ready {
305 return Err("SDHOST: Card initialization failed (ACMD41 timeout)");
306 }
307
308 let is_sdhc = (ocr & 0x4000_0000) != 0;
309 IS_SDHC.store(is_sdhc, Ordering::SeqCst);
310 crate::info!("[SD] Card detected: SDHC={}", is_sdhc);
311
312 let _cid = send_command(2, 0, SDCMD_RESP_136)?;
314
315 let resp3 = send_command(3, 0, SDCMD_RESP_48)?;
317 let rca = resp3[0] & 0xFFFF_0000;
318 unsafe {
319 RCA = rca;
320 }
321
322 let csd = send_command(9, rca, SDCMD_RESP_136)?;
324 parse_csd(csd)?;
325
326 let _resp = send_command(7, rca, SDCMD_RESP_48)?;
328
329 let _resp = send_command(16, 512, SDCMD_RESP_48)?;
331
332 let _resp = send_command(55, rca, SDCMD_RESP_48)?;
334 let _resp = send_command(6, 2, SDCMD_RESP_48)?; set_clock(25_000_000);
338
339 unsafe {
358 core::ptr::write_volatile(SDHCFG, SDHCFG_WIDE_INT_BUS | SDHCFG_WIDE_EXT_BUS);
359
360 let mut edm = core::ptr::read_volatile(SDEDM);
367 edm &= !((SDEDM_THRESHOLD_MASK << SDEDM_READ_THRESHOLD_SHIFT)
368 | (SDEDM_THRESHOLD_MASK << SDEDM_WRITE_THRESHOLD_SHIFT));
369 edm |= (FIFO_READ_THRESHOLD << SDEDM_READ_THRESHOLD_SHIFT)
370 | (FIFO_WRITE_THRESHOLD << SDEDM_WRITE_THRESHOLD_SHIFT);
371 core::ptr::write_volatile(SDEDM, edm);
372 }
373
374 SD_INITIALIZED.store(true, Ordering::SeqCst);
375 unsafe {
376 crate::info!("[SD] SDCard initialization success. Capacity: {} sectors ({} MiB)", CARD_SECTORS, (CARD_SECTORS * 512) / (1024 * 1024));
377 }
378
379 Ok(())
380}
381
382fn parse_csd(rsp: [u32; 4]) -> Result<(), &'static str> {
388 let sectors = crate::kernel::sd_csd::csd_sectors([rsp[3], rsp[2], rsp[1], rsp[0]]);
389 if sectors == 0 {
390 return Err("SDHOST: CSD reports zero capacity");
391 }
392 unsafe {
393 CARD_SECTORS = sectors;
394 }
395 Ok(())
396}
397
398pub fn get_total_sectors() -> usize {
400 unsafe { CARD_SECTORS }
401}
402
403fn block_address(lba: usize) -> Result<u32, &'static str> {
405 crate::kernel::sd_csd::block_address(lba, IS_SDHC.load(Ordering::SeqCst)).ok_or("SDHOST: sector address out of range")
406}
407
408fn fifo_level() -> u32 {
410 unsafe { (core::ptr::read_volatile(SDEDM) >> SDEDM_FIFO_LEVEL_SHIFT) & SDEDM_FIFO_LEVEL_MASK }
411}
412
413fn prepare_transfer() {
416 unsafe {
417 let mut guard = 64;
418 while fifo_level() != 0 && guard > 0 {
419 let _ = core::ptr::read_volatile(SDDATA);
420 guard -= 1;
421 }
422 core::ptr::write_volatile(SDHSTS, SDHSTS_CLEAR_ALL);
423 core::ptr::write_volatile(SDHBCT, 512);
424 core::ptr::write_volatile(SDHBLC, 1);
425 }
426}
427
428fn finish_transfer(timeout_msg: &'static str, error_msg: &'static str) -> Result<(), &'static str> {
430 unsafe {
431 let mut timeout = 1_000_000;
432 loop {
433 let fsm = core::ptr::read_volatile(SDEDM) & SDEDM_FSM_MASK;
434 if fsm == SDEDM_FSM_DATAMODE || fsm == SDEDM_FSM_IDENTMODE {
435 break;
436 }
437 timeout -= 1;
438 if timeout == 0 {
439 return Err(timeout_msg);
440 }
441 core::hint::spin_loop();
442 }
443 let hsts = core::ptr::read_volatile(SDHSTS);
444 if (hsts & SDHSTS_ERROR) != 0 {
445 core::ptr::write_volatile(SDHSTS, SDHSTS_ERROR); return Err(error_msg);
447 }
448 }
449 Ok(())
450}
451
452pub fn read_sector(lba: usize, buf: &mut [u8]) -> Result<(), &'static str> {
454 if !SD_INITIALIZED.load(Ordering::SeqCst) {
455 return Err("SDHOST: not initialized");
456 }
457 if buf.len() < 512 {
458 return Err("SDHOST: read buffer too small");
459 }
460 let arg = block_address(lba)?;
461 prepare_transfer();
462 send_command(17, arg, SDCMD_RESP_48 | SDCMD_READ)?;
464
465 let mut timeout = 2_000_000;
467 let mut words_read = 0;
468 while words_read < 128 {
469 if fifo_level() != 0 {
470 let data = unsafe { core::ptr::read_volatile(SDDATA) };
471 buf[words_read * 4..words_read * 4 + 4].copy_from_slice(&data.to_le_bytes());
472 words_read += 1;
473 continue;
474 }
475 let hsts = unsafe { core::ptr::read_volatile(SDHSTS) };
476 if (hsts & SDHSTS_ERROR) != 0 {
477 unsafe { core::ptr::write_volatile(SDHSTS, SDHSTS_ERROR) };
478 return Err("SDHOST: error flag during read");
479 }
480 timeout -= 1;
481 if timeout == 0 {
482 return Err("SDHOST: read timeout waiting for FIFO data");
483 }
484 core::hint::spin_loop();
485 }
486 finish_transfer("SDHOST: read did not finish", "SDHOST: read error flag set in host status")
487}
488
489pub fn write_sector(lba: usize, buf: &[u8]) -> Result<(), &'static str> {
491 if !SD_INITIALIZED.load(Ordering::SeqCst) {
492 return Err("SDHOST: not initialized");
493 }
494 if buf.len() < 512 {
495 return Err("SDHOST: write buffer too small");
496 }
497 let arg = block_address(lba)?;
498 prepare_transfer();
499 send_command(24, arg, SDCMD_RESP_48 | SDCMD_WRITE)?;
500
501 let mut timeout = 2_000_000;
504 let mut words_written = 0;
505 while words_written < 128 {
506 if fifo_level() < SDEDM_FIFO_WORDS {
507 let mut w = [0u8; 4];
508 w.copy_from_slice(&buf[words_written * 4..words_written * 4 + 4]);
509 unsafe { core::ptr::write_volatile(SDDATA, u32::from_le_bytes(w)) };
510 words_written += 1;
511 continue;
512 }
513 let hsts = unsafe { core::ptr::read_volatile(SDHSTS) };
514 if (hsts & SDHSTS_ERROR) != 0 {
515 unsafe { core::ptr::write_volatile(SDHSTS, SDHSTS_ERROR) };
516 return Err("SDHOST: error flag during write");
517 }
518 timeout -= 1;
519 if timeout == 0 {
520 return Err("SDHOST: write timeout waiting for FIFO space");
521 }
522 core::hint::spin_loop();
523 }
524 finish_transfer("SDHOST: write did not finish", "SDHOST: write error flag set in host status")
525}