phytium-mci 0.1.1

A no_std Rust driver for SD/MMC cards on Phytium E2000 series SoCs
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! # MCI (Memory Card Interface) Controller Module
//!
//! This module provides the core functionality for the Phytium SD/MMC host controller.
//! It handles low-level register operations, command execution, and data transfer.
//!
//! ## Note on Module Structure
//!
//! Submodules with names that conflict with `mci_host` submodule names should not be
//! marked as `pub` to avoid naming conflicts when re-exported at the crate level.
//!
//! ## Modules
//!
//! - **constants**: Hardware register offsets and configuration constants
//! - **err**: Error types and Result definitions
//! - **regs**: Register access utilities
//! - **mci_data**: Data transfer structures
//! - **mci_dma**: DMA transfer support (feature-gated)
//! - **mci_config**: Configuration structures
//!
//! Note: Submodules with duplicate names should not be marked as pub
pub mod constants;
pub mod err;
pub mod regs;

mod mci_cmd;
mod mci_cmddata;
mod mci_config;
pub mod mci_data;
#[cfg(feature = "dma")]
pub mod mci_dma;
mod mci_hardware;
mod mci_intr;
#[cfg(feature = "pio")]
mod mci_pio;
mod mci_timing;

pub use err::*;

use constants::*;
#[cfg(feature = "dma")]
use dma_api::DSlice;

#[cfg(feature = "dma")]
use mci_dma::{FSdifIDmaDesc, FSdifIDmaDescList};

use log::*;
use regs::*;

pub use mci_cmddata::*;
pub use mci_config::*;
pub use mci_timing::*;

use crate::{IoPad, regs::*, sleep};
use core::time::Duration;

/// MCI (Memory Card Interface) controller driver.
///
/// This struct manages the SD/MMC host controller hardware, providing:
/// - Controller initialization and deinitialization
/// - Command and data transfer (DMA/PIO)
/// - Clock frequency control
/// - Card detection
/// - Error handling and recovery
///
/// # Example
///
/// ```rust
/// use phytium_mci::mci::{MCI, MCIConfig};
///
/// let config = MCIConfig::new(/* parameters */);
/// let mut mci = MCI::new(config);
/// mci.config_init(&config)?;
/// ```
pub struct MCI {
    config: MCIConfig,
    is_ready: bool,
    prev_cmd: u32, // TODO: This needs to be implemented as an enum that implements Command
    curr_timing: MCITiming,
    cur_cmd: Option<MCICmdData>,
    io_pad: Option<IoPad>,
    #[cfg(feature = "dma")]
    desc_list: FSdifIDmaDescList,
}

impl MCI {
    const SWITCH_VOLTAGE: u32 = 11;
    const EXT_APP_CMD: u32 = 55;

    pub(crate) fn relax_handler() {
        sleep(Duration::from_micros(10));
    }

    pub(crate) fn new(config: MCIConfig) -> Self {
        MCI {
            config,
            is_ready: false,
            prev_cmd: 0,
            curr_timing: MCITiming::new(),
            cur_cmd: None,
            io_pad: None,
            #[cfg(feature = "dma")]
            desc_list: FSdifIDmaDescList::new(),
        }
    }

    pub(crate) fn new_restart(config: MCIConfig) -> Self {
        MCI {
            config,
            is_ready: true,
            prev_cmd: 0,
            curr_timing: MCITiming::new(),
            cur_cmd: None,
            io_pad: None,
            #[cfg(feature = "dma")]
            desc_list: FSdifIDmaDescList::new(),
        }
    }
}

/// MCI pub API
impl MCI {
    /// Set the I/O pad for signal timing configuration.
    ///
    /// The I/O pad is used to configure delay settings for optimal signal timing.
    pub fn iopad_set(&mut self, iopad: IoPad) {
        self.io_pad = Some(iopad);
    }

    /// Take and remove the I/O pad from this MCI instance.
    ///
    /// Returns `None` if no I/O pad was set.
    pub fn iopad_take(&mut self) -> Option<IoPad> {
        self.io_pad.take()
    }

    // TODO: Used clone first to avoid ownership issues
    pub fn cur_cmd_set(&mut self, cmd: &MCICmdData) {
        self.cur_cmd = Some(cmd.clone());
    }

    /// Initialize the SDIF controller instance.
    ///
    /// This function performs hardware initialization including:
    /// - Resetting the controller
    /// - Configuring clock and power
    /// - Setting up interrupts
    /// - Initializing DMA descriptors (if DMA mode is enabled)
    ///
    /// # Errors
    ///
    /// Returns an error if hardware initialization fails.
    pub fn config_init(&mut self, config: &MCIConfig) -> MCIResult {
        if self.is_ready {
            warn!("Device is already initialized!!!");
        }
        if *config != self.config {
            self.config = config.clone();
        }
        if self.reset().is_ok() {
            self.is_ready = true;
            info!("Device initialize success !!!");
        }
        Ok(())
    }

    /// Deinitialize the SDIF controller instance.
    ///
    /// This function performs cleanup operations:
    /// - Disables interrupts (controller and DMA)
    /// - Clears interrupt status
    /// - Powers off the card
    /// - Disables card clock
    /// - Resets voltage to default 3.3V
    pub fn config_deinit(&mut self) -> MCIResult {
        self.interrupt_mask_set(MCIIntrType::GeneralIntr, MCIIntMask::ALL_BITS.bits(), false); /* Disable controller interrupt bits */
        self.interrupt_mask_set(MCIIntrType::DmaIntr, MCIDMACIntEn::ALL_BITS.bits(), false); /* Disable DMA interrupt bits */

        self.raw_status_clear(); /* Clear interrupt status */
        self.dma_status_clear();

        self.power_set(false); /* Power off */
        self.clock_set(false); /* Disable card clock */

        let reg = self.config.reg();
        reg.clear_reg(MCIClkSrc::UHS_EXT_CLK_ENA); /* Disable external clock */
        reg.clear_reg(MCIUhsReg::VOLT_180); /* Restore to 3.3V default voltage */

        self.is_ready = false;
        Ok(())
    }

    /// Setup DMA descriptor list for SDIF controller instance.
    ///
    /// # Features
    ///
    /// This function is only available when the `dma` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The device is not initialized
    /// - The device is not configured in DMA transfer mode
    #[cfg(feature = "dma")]
    pub fn set_idma_list(&mut self, desc: &PoolBuffer, desc_num: u32) -> MCIResult {
        if !self.is_ready {
            error!("Device is not yet initialized!");
            return Err(MCIError::NotInit);
        }

        if self.config.trans_mode() != MCITransMode::DMA {
            error!("Device is not configured in DMA transfer mode!");
            return Err(MCIError::InvalidState);
        }

        // TODO: Not very elegant, consider modifying later
        let desc_vec = unsafe {
            core::mem::ManuallyDrop::new(Vec::from_raw_parts(
                desc.addr().as_ptr(),
                desc_num as usize,
                desc_num as usize,
            ))
        };
        let slice = DSlice::from(&desc_vec[..]); // Get physical address
        error!(
            "set idma list, desc addr: 0x{:x}, desc num: {}",
            slice.bus_addr(),
            desc_num
        );
        self.desc_list.first_desc_dma = slice.bus_addr() as usize;
        self.desc_list.first_desc = desc.addr().as_ptr() as *mut FSdifIDmaDesc;
        self.desc_list.desc_num = desc_num;
        self.desc_list.desc_trans_sz = FSDIF_IDMAC_MAX_BUF_SIZE;

        debug!("idma_list set success!");

        Ok(())
    }

    /// Set the card clock frequency.
    ///
    /// This function configures the card clock to the specified frequency.
    /// It will:
    /// - Select appropriate timing configuration
    /// - Update pad delay settings
    /// - Configure clock divider
    /// - Enable/disable clock as needed
    ///
    /// # Arguments
    ///
    /// * `clk_hz` - Target clock frequency in Hz. Set to 0 to disable the clock.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No timing configuration is available for the requested frequency
    /// - Clock update fails
    pub fn clk_freq_set(&mut self, clk_hz: u32) -> MCIResult {
        let reg = self.config.reg();
        let mut reg_val = MCICmd::UPD_CLK;

        let cmd_reg = reg.read_reg::<MCICmd>();
        let cur_cmd_index = cmd_reg.index_get();

        info!("Set clk as {}", clk_hz);
        if cur_cmd_index == Self::SWITCH_VOLTAGE {
            reg_val |= MCICmd::VOLT_SWITCH;
        }

        if clk_hz > 0 {
            /* select board-related time-tuning configurations */
            let target_timing = MCIConfig::get_tuning(clk_hz.into(), self.config.non_removable())
                .ok_or_else(|| {
                error!("No available timing !!!");
                MCIError::InvalidTiming
            })?;
            /* update pad delay */
            target_timing.pad_delay(self.io_pad.as_mut().unwrap(), self.config.instance_id());

            /* update clock source setting */
            self.update_exteral_clk(MCIClkSrc::from_bits_retain(target_timing.clk_src()))?;

            self.clock_set(false);

            /* update clock for clock source */
            if let Err(err) = if cur_cmd_index == Self::SWITCH_VOLTAGE {
                self.private_cmd11_send(reg_val | cmd_reg)
            } else {
                self.private_cmd_send(reg_val, 0)
            } {
                error!("update ext clock failed !!!");
                return Err(err);
            }

            /* set clock divider */
            reg.write_reg(MCIClkDiv::from_bits_truncate(target_timing.clk_div()));
            reg.write_reg(MCIEnableShift::from_bits_truncate(target_timing.shift()));
            info!(
                "clk_src: 0x{:x} clk_div: 0x{:x}, shift: 0x{:x}",
                reg.read_reg::<MCIClkSrc>(),
                reg.read_reg::<MCIClkDiv>(),
                reg.read_reg::<MCIEnableShift>()
            );

            self.clock_set(true);

            /* update clock for clock divider */
            if cur_cmd_index == Self::SWITCH_VOLTAGE {
                self.private_cmd11_send(reg_val | cmd_reg)?;
            } else {
                self.private_cmd_send(reg_val, 0)?;
            }

            self.curr_timing = target_timing;
        } else {
            /* close bus clock in case target clock is 0 */
            self.clock_set(false);

            if cur_cmd_index == Self::SWITCH_VOLTAGE {
                self.private_cmd11_send(reg_val | cmd_reg)?;
            } else {
                self.private_cmd_send(reg_val, 0)?;
            }

            reg.clear_reg(MCIClkSrc::UHS_EXT_CLK_ENA);

            self.curr_timing = MCITiming::new();
        }
        Ok(())
    }

    /// Start command and data transfer in DMA mode.
    ///
    /// This function initiates a DMA-based transfer. It will:
    /// - Wait for the card to be ready
    /// - Reset FIFO and DMA
    /// - Configure and transfer data if present
    /// - Send the command
    ///
    /// # Features
    ///
    /// This function is only available when the `dma` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The device is not initialized
    /// - DMA mode is not configured
    /// - Card is not detected (for removable media)
    /// - Card is busy
    #[cfg(feature = "dma")]
    pub fn dma_transfer(&mut self, cmd_data: &mut MCICmdData) -> MCIResult {
        cmd_data.success_set(false);
        self.cur_cmd_set(&cmd_data);

        if !self.is_ready {
            error!("Device is not yet initialized!");
            return Err(MCIError::NotInit);
        }

        if self.config.trans_mode() != MCITransMode::DMA {
            error!("Device is not configured in DMA transfer mode!");
            return Err(MCIError::InvalidState);
        }

        // for removable media, check if card exists
        if !self.config.non_removable() && !self.check_if_card_exist() {
            error!("card is not detected !!!");
            return Err(MCIError::NoCard);
        }

        // wait previous command finished and card not busy
        self.poll_wait_busy_card()?;

        // Clear raw interrupt register
        self.config
            .reg()
            .write_reg(MCIRawInts::from_bits_truncate(0xFFFFE));

        /* reset fifo and DMA before transfer */
        self.ctrl_reset(MCICtrl::FIFO_RESET | MCICtrl::DMA_RESET)?;

        // enable use of DMA
        self.config
            .reg()
            .modify_reg(|reg| MCICtrl::USE_INTERNAL_DMAC | reg);
        self.config.reg().modify_reg(|reg| MCIBusMode::DE | reg);

        // transfer data
        if cmd_data.get_data().is_some() {
            self.dma_transfer_data(cmd_data.get_data().unwrap())?;
        }

        // transfer command
        self.cmd_transfer(&cmd_data)?;

        Ok(())
    }

    /// Wait for DMA transfer to finish by polling.
    ///
    /// This function polls the interrupt status registers until the transfer
    /// is complete or a timeout occurs.
    ///
    /// # Features
    ///
    /// This function is only available when the `dma` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The device is not initialized
    /// - DMA mode is not configured
    /// - Transfer timeout occurs
    #[cfg(feature = "dma")]
    pub fn poll_wait_dma_end(&mut self, cmd_data: &mut MCICmdData) -> MCIResult {
        let wait_bits = if cmd_data.get_data().is_none() {
            MCIIntMask::CMD_BIT.bits()
        } else {
            MCIIntMask::CMD_BIT.bits() | MCIIntMask::DTO_BIT.bits()
        };
        let mut reg_val;

        if !self.is_ready {
            error!("Device is not yet initialized!");
            return Err(MCIError::NotInit);
        }

        if self.config.trans_mode() != MCITransMode::DMA {
            error!("Device is not configured in DMA transfer mode!");
            return Err(MCIError::InvalidState);
        }

        /* wait command done or data timeout */
        let mut delay = RETRIES_TIMEOUT;
        loop {
            reg_val = self.config.reg().read_reg::<MCIRawInts>().bits();
            if delay % 1000 == 0 {
                debug!("polling dma end, reg_val = 0x{:x}", reg_val);
            }
            // TODO: relax handler?

            delay -= 1;
            if wait_bits & reg_val == wait_bits || delay == 0 {
                break;
            }
        }

        /* clear status to ack data done */
        self.raw_status_clear();

        if wait_bits & reg_val != wait_bits && delay <= 0 {
            error!("Wait command done timeout, raw ints: 0x{:x}!", reg_val);
            return Err(MCIError::CmdTimeout);
        }

        if cmd_data.get_data().is_some() {
            let read = cmd_data.flag().contains(MCICmdFlag::READ_DATA);
            if !read {
                unsafe {
                    dsb();
                }
            }
        }

        Ok(())
    }

    /// Start command and data transfer in PIO mode.
    ///
    /// This function initiates a PIO (Programmed I/O) based transfer.
    /// For write operations, data is written to FIFO before sending the command.
    ///
    /// # Features
    ///
    /// This function is only available when the `pio` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The device is not initialized
    /// - PIO mode is not configured
    /// - Card is not detected (for removable media)
    /// - Card is busy
    /// - Data size exceeds FIFO capacity (0x800 bytes)
    #[cfg(feature = "pio")]
    pub fn pio_transfer(&self, cmd_data: &mut MCICmdData) -> MCIResult {
        #[cfg(feature = "pio")]
        let read = cmd_data.flag().contains(MCICmdFlag::READ_DATA);
        let reg = self.config.reg();

        cmd_data.success_set(false);

        if !self.is_ready {
            error!("device is not yet initialized!!!");
            return Err(MCIError::NotInit);
        }
        if self.config.trans_mode() != MCITransMode::PIO {
            error!("device is not configure in PIO transfer mode.");
            return Err(MCIError::InvalidState);
        }

        /* for removable media, check if card exists */
        if !self.config.non_removable() && !self.check_if_card_exist() {
            error!("card is not detected !!!");
            return Err(MCIError::NoCard);
        }

        /* wait previous command finished and card not busy */
        self.poll_wait_busy_card()?;

        /* reset fifo and not use DMA */
        reg.clear_reg(MCICtrl::USE_INTERNAL_DMAC);
        self.ctrl_reset(MCICtrl::FIFO_RESET)?;
        reg.clear_reg(MCIBusMode::DE);

        /* transfer data */
        if let Some(data) = cmd_data.get_mut_data() {
            /* while in PIO mode, max data transferred is 0x800 */
            if data.datalen() > MCI_MAX_FIFO_CNT {
                error!(
                    "Fifo do not support writing more than {:x}.",
                    MCI_MAX_FIFO_CNT
                );
                return Err(MCIError::NotSupport);
            }

            /* set transfer data length and block size */
            self.trans_bytes_set(data.datalen());
            self.blksize_set(data.blksz());

            /* if need to write, write to fifo before send command */
            #[cfg(feature = "pio")]
            if !read {
                /* invalide buffer for data to write */
                unsafe { dsb() };
                self.pio_write_data(data)?;
            }
        }
        self.cmd_transfer(cmd_data)?;
        Ok(())
    }

    /// Wait for PIO transfer to finish by polling.
    ///
    /// This function polls the interrupt status registers until:
    /// - Command transfer is complete
    /// - Data transfer is complete (if data is present)
    ///
    /// For read operations, data is read from FIFO after the command completes.
    ///
    /// # Features
    ///
    /// This function is only available when the `pio` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The device is not initialized
    /// - PIO mode is not configured
    /// - Transfer timeout occurs
    #[cfg(feature = "pio")]
    pub fn poll_wait_pio_end(&mut self, cmd_data: &mut MCICmdData) -> MCIResult {
        let read = cmd_data.flag().contains(MCICmdFlag::READ_DATA);
        let reg = self.config.reg();

        if !self.is_ready {
            error!("device is not yet initialized!!!");
            return Err(MCIError::NotInit);
        }

        if MCITransMode::PIO != self.config.trans_mode() {
            error!("device is not configure in PIO transfer mode.");
            return Err(MCIError::InvalidState);
        }

        trace!("wait for PIO cmd to finish ...");
        if let Err(err) = reg.retry_for(
            |reg: MCIRawInts| {
                let result = reg.contains(MCIRawInts::CMD_BIT);
                MCI::relax_handler();
                result
            },
            Some(RETRIES_TIMEOUT),
        ) {
            error!(
                "wait cmd done timeout, raw ints: 0x{:x}",
                self.raw_status_get()
            );
            return Err(err);
        }

        /* if need to read data, read fifo after send command */
        if cmd_data.get_data().is_some() && read {
            trace!("wait for PIO data to read ...");
            if let Err(err) = reg.retry_for(
                |reg| {
                    MCI::relax_handler();
                    (MCIRawInts::DTO_BIT & reg).bits() != 0
                },
                Some(RETRIES_TIMEOUT),
            ) {
                self.raw_status_clear();
                return Err(err);
            }

            /* clear status to ack */
            self.raw_status_clear();
            trace!(
                "card cnt: 0x{:x}, fifo cnt: 0x{:x}",
                reg.read_reg::<MCITranCardCnt>(),
                reg.read_reg::<MCITranFifoCnt>()
            );
        }
        /* clear status to ack cmd done */
        self.raw_status_clear();
        Ok(())
    }

    /* Read PIO data, it works in IRQ mode */
    // TODO: Unknown if the protocol stack layer needs to call this, already implemented.
    /* Get cmd response and received data after wait poll status or interrupt signal */
    // TODO Unknown if the protocol stack layer needs to call this, already implemented.

    /* Interrupt handler for SDIF instance */
    // TODO: Will be used in interrupt mode
    /* Register event call-back function as handler for interrupt events */
    // TODO: Will be used in interrupt mode

    /// Reset controller from error state.
    ///
    /// This function attempts to recover the controller from an error condition:
    /// - Resets FIFO
    /// - Resets card busy state
    /// - Restarts clock
    /// - Resets internal DMA (if DMA mode is enabled)
    ///
    /// # Errors
    ///
    /// Returns an error if the device is not initialized or reset operations fail.
    pub fn restart(&self) -> MCIResult {
        if !self.is_ready {
            error!("Device is not yet initialized!!!");
            return Err(MCIError::NotInit);
        }

        /* reset controller */
        self.ctrl_reset(MCICtrl::FIFO_RESET)?;

        /* reset controller if in busy state */
        self.busy_card_reset()?;

        /* reset clock */
        self.clk_restart()?;

        /* reset internal DMA */
        if self.config.trans_mode() == MCITransMode::DMA {
            debug!("DMA enabled, reseting internal DMA!");
            self.idma_reset();
        }
        Ok(())
    }

    /// Dump all register values of the SDIF instance.
    ///
    /// This function logs the current values of all hardware registers
    /// for debugging purposes.
    pub fn register_dump(&self) {
        let reg = self.config.reg();
        warn!("cntrl: 0x{:x}", reg.read_reg::<MCICtrl>());
        warn!("pwren: 0x{:x}", reg.read_reg::<MCIPwrEn>());
        warn!("clkdiv: 0x{:x}", reg.read_reg::<MCIClkDiv>());
        warn!("clkena: 0x{:x}", reg.read_reg::<MCIClkEn>());
        warn!("tmout: 0x{:x}", reg.read_reg::<MCITimeout>());
        warn!("ctype: 0x{:x}", reg.read_reg::<MCICType>());
        warn!("blksz: 0x{:x}", reg.read_reg::<MCIBlkSiz>());
        warn!("blkcnt: 0x{:x}", reg.read_reg::<MCIBytCnt>());
        warn!("intmask: 0x{:x}", reg.read_reg::<MCIIntMask>());
        warn!("cmdarg: 0x{:x}", reg.read_reg::<MCICmdArg>());
        warn!("cmd: 0x{:x}", reg.read_reg::<MCICmd>());
        warn!("resp0: 0x{:x}", reg.read_reg::<MCIResp0>());
        warn!("reps1: 0x{:x}", reg.read_reg::<MCIResp1>());
        warn!("resp2: 0x{:x}", reg.read_reg::<MCIResp2>());
        warn!("resp3: 0x{:x}", reg.read_reg::<MCIResp3>());
        warn!("maskints: 0x{:x}", reg.read_reg::<MCIMaskedInts>());
        warn!("rawints: 0x{:x}", reg.read_reg::<MCIRawInts>());
        warn!("status: 0x{:x}", reg.read_reg::<MCIStatus>());
        warn!("fifoth: 0x{:x}", reg.read_reg::<MCIFifoTh>());
        warn!("carddet: 0x{:x}", reg.read_reg::<MCICardDetect>());
        warn!("wrtprt: 0x{:x}", reg.read_reg::<MCICardWrtp>());
        warn!("cksts: 0x{:x}", reg.read_reg::<MCIClkSts>());
        warn!("trans_cardcnt: 0x{:x}", reg.read_reg::<MCITranCardCnt>());
        warn!("trans_fifocnt: 0x{:x}", reg.read_reg::<MCITranFifoCnt>());
        warn!("debnce: 0x{:x}", reg.read_reg::<MCIDebnce>());
        warn!("uid: 0x{:x}", reg.read_reg::<MCIUid>());
        warn!("vid: 0x{:x}", reg.read_reg::<MCIVid>());
        warn!("hwconf: 0x{:x}", reg.read_reg::<MCIHwconf>());
        warn!("uhsreg: 0x{:x}", reg.read_reg::<MCIUhsReg>());
        warn!("cardreset: 0x{:x}", reg.read_reg::<MCICardReset>());
        warn!("busmode: 0x{:x}", reg.read_reg::<MCIBusMode>());
        warn!("descaddrl: 0x{:x}", reg.read_reg::<MCIDescListAddrL>());
        warn!("descaddrh: 0x{:x}", reg.read_reg::<MCIDescListAddrH>());
        warn!("dmacstatus: 0x{:x}", reg.read_reg::<MCIDMACStatus>());
        warn!("dmacinten: 0x{:x}", reg.read_reg::<MCIDMACIntEn>());
        warn!("curdescaddrl: 0x{:x}", reg.read_reg::<MCICurDescAddrL>());
        warn!("curdescaddrh: 0x{:x}", reg.read_reg::<MCIDescAddrH>());
        warn!("curbufaddrl: 0x{:x}", reg.read_reg::<MCICurBufAddrL>());
        warn!("curbufaddrh: 0x{:x}", reg.read_reg::<MCIBufAddrH>());
        warn!("card_thrctl: 0x{:x}", reg.read_reg::<MCICardThrctl>());
        warn!("clock_src: 0x{:x}", reg.read_reg::<MCIClkSrc>());
        warn!("emmcddr: 0x{:x}", reg.read_reg::<MCIEmmcDdrReg>());
        warn!("enableshift: 0x{:x}", reg.read_reg::<MCIEnableShift>());
    }

    /// Dump command and data transfer information.
    ///
    /// This function logs detailed information about a command/data transfer
    /// including command index, arguments, response, and data buffer details.
    ///
    /// # Arguments
    ///
    /// * `cmd_data` - Reference to the command data structure to dump
    pub fn cmd_info_dump(cmd_data: &MCICmdData) {
        debug!("cmd struct @{:p}", cmd_data);
        debug!("   opcode: {}", cmd_data.cmdidx());
        debug!("   arg: 0x{:x}", cmd_data.cmdarg());
        let response = cmd_data.get_response();
        debug!(
            "   resp@{:p}: 0x{:x} 0x{:x} 0x{:x} 0x{:x}",
            response, response[0], response[1], response[2], response[3]
        );
        debug!("   flag: 0x{:x}", cmd_data.flag());
        debug!("   data @{:p}", cmd_data.get_data().unwrap());

        if let Some(data) = cmd_data.get_data() {
            debug!("   buf: {:p}, len: {}", data, data.datalen());
            debug!("   blk sz: {}", data.blksz());
            debug!("   blk cnt: {}", data.blkcnt());
        }
    }
}

/// MCI private API
impl MCI {
    fn reset(&self) -> MCIResult {
        /* set fifo */
        self.fifoth_set(
            MCIFifoThDMATransSize::DMATrans8,
            MCIFifoTh::RX_WMARK,
            MCIFifoTh::TX_WMARK,
        );

        /* set card threshold */
        self.cardthr_set(MCIFifoDepth::Depth8);

        /* disable clock and update ext clk */
        self.clock_set(false);

        /* set 1st clock */
        if let Err(err) = self.init_external_clk() {
            error!("Update extern clock failed: {:?}", err);
            return Err(err);
        }

        /* power on */
        self.power_set(true);
        self.clock_set(true);
        self.clock_src_set(true);

        /* set voltage as 3.3v */
        self.voltage_1_8v_set(false);

        /* set bus width as 1 */
        self.bus_width_set(1);

        /* reset controller and card */
        if let Err(err) = if self.config.trans_mode() == MCITransMode::DMA {
            self.ctrl_reset(MCICtrl::FIFO_RESET | MCICtrl::DMA_RESET)
        } else {
            self.ctrl_reset(MCICtrl::FIFO_RESET)
        } {
            error!("Reset controller failed: {:?}", err);
            return Err(err);
        }

        /* send private command to update clock */
        self.private_cmd_send(MCICmd::UPD_CLK, 0)?;

        /* reset card for no-removeable media, e.g. eMMC */
        self.cardreset_config();

        /* clear interrupt status */
        self.clear_interrupt_status();

        /* get base address */
        let reg = self.config.reg();

        /* enable card detect interrupt */
        if !self.config.non_removable() {
            reg.set_reg(MCIIntMask::CD_BIT);
        }

        /* enable controller and internal DMA */
        reg.set_reg(MCICtrl::INT_ENABLE | MCICtrl::USE_INTERNAL_DMAC);

        /* set data and resp timeout */
        reg.write_reg(MCITimeout::timeout_data(
            MCITimeout::MAX_DATA_TIMEOUT,
            MCITimeout::MAX_RESP_TIMEOUT,
        ));

        /* reset descriptors and dma */
        if self.config.trans_mode() == MCITransMode::DMA {
            self.descriptor_set(0);
            self.idma_reset();
        }

        info!("Reset hardware done !!!");
        Ok(())
    }

    fn poll_wait_busy_card(&self) -> MCIResult {
        let busy_bits = MCIStatus::DATA_BUSY | MCIStatus::DATA_STATE_MC_BUSY;
        let reg = self.config.reg();
        let reg_val = reg.read_reg::<MCIStatus>();
        if reg_val.contains(busy_bits) {
            warn!("Card is busy, waiting ...");
        }
        if let Err(err) = reg.retry_for(
            |reg: MCIStatus| {
                let result = !reg.contains(busy_bits);
                MCI::relax_handler();
                result
            },
            Some(RETRIES_TIMEOUT),
        ) {
            error!("Wait card busy timeout !!!");
            return Err(err);
        }
        Ok(())
    }

    fn busy_card_reset(&self) -> MCIResult {
        let reg = self.config.reg();

        reg.set_reg(MCICtrl::CONTROLLER_RESET);

        reg.retry_for(
            |reg_val: MCIStatus| {
                reg.set_reg(MCICtrl::CONTROLLER_RESET);
                !reg_val.contains(MCIStatus::DATA_BUSY)
            },
            Some(RETRIES_TIMEOUT),
        )?;

        Ok(())
    }

    fn clk_restart(&self) -> MCIResult {
        let reg = self.config.reg();

        /* wait command finish if previous command is in error state */
        reg.retry_for(
            |reg| (MCICmd::START & reg).bits() == 0,
            Some(RETRIES_TIMEOUT),
        )?;

        /* update clock */
        self.clock_set(false);

        let clk_div = reg.read_reg::<MCIClkDiv>();
        let uhs = reg.read_reg::<MCIClkSrc>();

        self.update_exteral_clk(uhs)?;

        reg.write_reg(clk_div);

        self.clock_set(true);

        self.private_cmd_send(MCICmd::UPD_CLK, 0)?;
        Ok(())
    }
}