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
use core::cell::{Cell, RefCell};
use core::mem::take;
use core::ptr::NonNull;
use core::time::Duration;

use alloc::vec::Vec;
#[cfg(feature = "dma")]
use dma_api::DSlice;
use log::*;

use super::MCIHost;
use super::constants::SDStatus;
use crate::mci::constants::*;
use crate::mci::mci_data::MCIData;
use crate::mci::regs::MCIIntMask;
use crate::mci::{MCI, MCICmdData, MCIConfig};
use crate::mci_host::MCIHostCardIntFn;
use crate::mci_host::constants::*;
use crate::mci_host::err::*;
use crate::mci_host::mci_host_card_detect::MCIHostCardDetect;
use crate::mci_host::mci_host_config::*;
use crate::mci_host::mci_host_device::MCIHostDevice;
use crate::mci_host::mci_host_transfer::MCIHostTransfer;
use crate::mci_host::sd::constants::SdCmd;
use crate::tools::swap_half_word_byte_sequence_u32;
use crate::{IoPad, sleep};

#[cfg(feature = "dma")]
use crate::mci::mci_dma::FSdifIDmaDesc;

pub(crate) struct SDIFDev {
    hc: RefCell<MCI>,           // SDIF hardware controller
    hc_cfg: RefCell<MCIConfig>, // SDIF configuration
    #[cfg(feature = "dma")]
    rw_desc: PoolBuffer, // DMA descriptor pointer, for managing data transfer TODO: Consider using vec or DVec directly
    desc_num: Cell<u32>, // Descriptor count, representing the number of DMA descriptors
}

impl SDIFDev {
    pub fn new(addr: NonNull<u8>, desc_num: usize) -> Self {
        #[cfg(feature = "dma")]
        {
            let align = SD_BLOCK_SIZE;
            let length = core::mem::size_of::<FSdifIDmaDesc>() * desc_num;
            let rw_desc = match osa_alloc_aligned(length, align) {
                Err(e) => {
                    error!("alloc internal buffer failed! err: {:?}", e);
                    panic!("Failed to allocate internal buffer");
                }
                Ok(buffer) => buffer,
            };

            Self {
                hc: MCI::new(MCIConfig::new(addr)).into(),
                hc_cfg: MCIConfig::new(addr).into(),
                rw_desc,
                desc_num: (desc_num as u32).into(),
            }
        }

        #[cfg(feature = "pio")]
        Self {
            hc: MCI::new(MCIConfig::new(addr)).into(),
            hc_cfg: MCIConfig::new(addr).into(),
            desc_num: (desc_num as u32).into(),
        }
    }
    pub fn iopad_set(&self, iopad: IoPad) {
        self.hc.borrow_mut().iopad_set(iopad);
    }
}

impl MCIHostDevice for SDIFDev {
    fn init(&self, addr: NonNull<u8>, host: &MCIHost) -> MCIHostStatus {
        let num_of_desc = host.config.max_trans_size / host.config.def_block_size;
        self.desc_num.set(num_of_desc as u32);
        self.do_init(addr, host)
    }

    fn do_init(&self, addr: NonNull<u8>, host: &MCIHost) -> MCIHostStatus {
        let mci_config = MCIConfig::lookup_config(addr);
        let iopad = self
            .hc
            .borrow_mut()
            .iopad_take()
            .ok_or(MCIHostError::NoData)?;

        *self.hc.borrow_mut() = MCI::new(MCIConfig::lookup_config(addr));
        self.hc.borrow_mut().iopad_set(iopad);

        // Force restart
        let restart_mci = MCI::new_restart(MCIConfig::restart(addr));
        restart_mci
            .restart()
            .unwrap_or_else(|e| error!("restart failed: {:?}", e));

        if self.hc.borrow_mut().config_init(&mci_config).is_err() {
            info!("Sdio ctrl init failed.");
            return Err(MCIHostError::Fail);
        }

        if host.config.enable_irq {
            // TODO
        }

        #[cfg(feature = "dma")]
        if host.config.enable_dma {
            if let Err(_) = self
                .hc
                .borrow_mut()
                .set_idma_list(&self.rw_desc, self.desc_num.get())
            {
                error!("idma list set failed!");
                return Err(MCIHostError::Fail);
            }
        }

        *self.hc_cfg.borrow_mut() = mci_config;
        Ok(())
    }

    fn deinit(&self) {
        // TODO FSDIFHOST_RevokeIrq
        let _ = self.hc.borrow_mut().config_deinit();
        info!("Sdio ctrl deinited !!!")
    }

    fn reset(&self) -> MCIHostStatus {
        match self.hc.borrow_mut().restart() {
            Ok(_) => Ok(()),
            Err(_) => Err(MCIHostError::Fail),
        }
    }

    fn switch_to_voltage(&self, voltage: MCIHostOperationVoltage, host: &MCIHost) -> MCIHostStatus {
        match voltage {
            MCIHostOperationVoltage::Voltage300V => {
                host.curr_voltage.set(voltage);
                self.hc.borrow_mut().voltage_1_8v_set(false);
                info!("Switch to 3.0V");
            }
            MCIHostOperationVoltage::Voltage330V => {
                host.curr_voltage.set(voltage);
                self.hc.borrow_mut().voltage_1_8v_set(false);
                info!("Switch to 3.0V");
            }
            MCIHostOperationVoltage::Voltage180V => {
                host.curr_voltage.set(voltage);
                self.hc.borrow_mut().voltage_1_8v_set(true);
                info!("Switch to 1.8V");
            }
            _ => {
                info!("Invalid target voltage !!!");
            }
        }
        Ok(())
    }

    fn execute_tuning(
        &self,
        _tuning_cmd: u32,
        _rev_buf: &mut Vec<u32>,
        _block_size: u32,
    ) -> MCIHostStatus {
        Ok(())
    }

    fn enable_ddr_mode(&self, _enable: bool, _nibble_pos: u32) {
        // TODO  Not implemented yet
    }

    fn enable_hs400_mode(&self, _enable: bool) {
        info!("Enable HS400 mode Not Implemented !!!");
    }

    fn enable_strobe_dll(&self, _enable: bool) {
        info!("Enable Strobe DLL Not Implemented !!!");
    }

    fn get_signal_line_status(&self, _signal_line: u32) -> bool {
        !self.hc.borrow().check_if_card_busy()
    }

    #[allow(clippy::too_many_arguments)]
    fn convert_data_to_little_endian(
        &self,
        data: &mut Vec<u32>,
        word_size: usize,
        format: MCIHostDataPacketFormat,
        host: &MCIHost,
    ) -> MCIHostStatus {
        if host.config.endian_mode == MCIHostEndianMode::Little
            && format == MCIHostDataPacketFormat::MSBFirst
        {
            for val in data.iter_mut().take(word_size) {
                *val = val.swap_bytes();
            }
        } else if host.config.endian_mode == MCIHostEndianMode::HalfWordBig {
            for val in data.iter_mut().take(word_size) {
                *val = swap_half_word_byte_sequence_u32(*val);
            }
        } else if host.config.endian_mode == MCIHostEndianMode::Big
            && format == MCIHostDataPacketFormat::LSBFirst
        {
            for val in data.iter_mut().take(word_size) {
                *val = val.swap_bytes();
            }
        }
        Ok(())
    }

    fn card_detect_init(&self, _cd: &MCIHostCardDetect) -> MCIHostStatus {
        Ok(())
    }

    fn card_power_set(&self, _enable: bool) {}

    fn card_int_enable(&self, enable: bool, host: &MCIHost) -> MCIHostStatus {
        if MCIHostCardType::SDIO == host.config.card_type {
            self.hc.borrow().interrupt_mask_set(
                MCIIntrType::GeneralIntr,
                MCIIntMask::SDIO_BIT.bits(),
                enable,
            );
        }
        Ok(())
    }

    fn card_int_init(&self, _sdio_int: &MCIHostCardIntFn) -> MCIHostStatus {
        Ok(())
    }

    fn card_bus_width_set(&self, data_bus_width: MCIHostBusWdith) {
        match data_bus_width {
            MCIHostBusWdith::Bit1 => {
                self.hc.borrow().bus_width_set(data_bus_width as u32);
                info!("Set bus width to 1 bit");
            }
            MCIHostBusWdith::Bit4 => {
                self.hc.borrow().bus_width_set(data_bus_width as u32);
                info!("Set bus width to 4 bit");
            }
            MCIHostBusWdith::Bit8 => {
                self.hc.borrow().bus_width_set(data_bus_width as u32);
                info!("Set bus width to 8 bit");
            }
        }
    }

    fn card_detect_status_polling(
        &self,
        wait_card_status: SDStatus,
        _timeout: u32,
        host: &MCIHost,
    ) -> MCIHostStatus {
        let cd = host.cd.as_ref().ok_or(MCIHostError::NoData)?;

        let mut retry_times: usize = 100;

        /* Wait card inserted. */
        loop {
            let is_card_inserted = self.card_detect_status() == SDStatus::Inserted;
            sleep(Duration::from_millis(cd.cd_debounce_ms as u64));
            if wait_card_status == SDStatus::Inserted && is_card_inserted {
                break;
            }

            if wait_card_status == SDStatus::Removed && !is_card_inserted {
                break;
            }

            if retry_times == 0 {
                info!("Wait card insert timeout !!!");
                return Err(MCIHostError::Timeout);
            }

            retry_times -= 1;
        }
        Ok(())
    }

    fn card_detect_status(&self) -> SDStatus {
        if self.hc.borrow().check_if_card_exist() {
            SDStatus::Inserted
        } else {
            SDStatus::Removed
        }
    }

    fn card_active_send(&self) {}

    fn card_clock_set(&self, target_clock: u32, host: &MCIHost) -> u32 {
        // If current clock frequency is already target frequency, return directly
        if host.curr_clock_freq.get() == target_clock {
            return host.curr_clock_freq.get();
        }
        // Try to set clock frequency
        if self.hc.borrow_mut().clk_freq_set(target_clock).is_ok() {
            info!("BUS CLOCK: {}", target_clock);
            // Update instance clock frequency
            host.curr_clock_freq.set(target_clock);
        } else {
            info!("Failed to update clock");
        }

        host.curr_clock_freq.get()
    }

    fn force_clock_on(&self, enable: bool) {
        self.hc.borrow().clock_set(enable);
    }

    fn card_is_busy(&self) -> bool {
        self.hc.borrow().check_if_card_busy()
    }

    fn pre_command(&self, content: &mut MCIHostTransfer, host: &MCIHost) -> MCIHostStatus {
        let cmd = match content.cmd() {
            Some(cmd) => cmd,
            None => return Err(MCIHostError::NoData),
        };

        let data = match content.data() {
            Some(data) => data,
            None => return Ok(()),
        };

        if cmd.index() == MCIHostCommonCmd::ReadMultipleBlock as u32
            || cmd.index() == MCIHostCommonCmd::WriteMultipleBlock as u32
        {
            let block_count = data.block_count();

            if block_count > 1 {
                return host.block_count_set(block_count);
            }
        }
        Ok(())
    }

    fn covert_command_info(&self, in_trans: &mut MCIHostTransfer) -> MCICmdData {
        let in_cmd = match in_trans.cmd() {
            Some(cmd) => cmd,
            None => panic!("Not Inited intrans"),
        };

        let index = in_cmd.index();
        let arg: u32 = in_cmd.argument();
        let mut flag = MCICmdFlag::empty();

        if index == MCIHostCommonCmd::GoIdleState as u32 {
            flag |= MCICmdFlag::NEED_INIT;
        }

        if index == MCIHostCommonCmd::GoInactiveState as u32
            || (index == MCISDIOCommand::RWIODirect as u32
                && (arg >> 9 & 0x1FFFF) == MCISDIOCCCRAddr::IOAbort as u32)
        {
            flag |= MCICmdFlag::ABORT;
        }

        let response_type = in_cmd.response_type();

        if response_type != MCIHostResponseType::None {
            flag |= MCICmdFlag::EXP_RESP;
            if response_type == MCIHostResponseType::R2 {
                /* need 136 bits long response */
                flag |= MCICmdFlag::EXP_LONG_RESP;
            }

            if response_type != MCIHostResponseType::R3 && response_type != MCIHostResponseType::R4
            {
                /* most cmds need CRC */
                flag |= MCICmdFlag::NEED_RESP_CRC;
            }
        }

        if index == SdCmd::VoltageSwitch as u32 {
            /* CMD11 need switch voltage */
            flag |= MCICmdFlag::SWITCH_VOLTAGE;
        }

        let out_data = if let Some(in_data) = in_trans.data_mut() {
            let mut out_data = MCIData::new();

            flag |= MCICmdFlag::EXP_DATA;

            let buf = if let Some(rx_data) = in_data.rx_data_mut() {
                // Handle receive data
                flag |= MCICmdFlag::READ_DATA;
                // TODO The CLONE here will reduce driver speed, need to solve this performance issue - taking it out directly might be better
                // rx_data.clone()
                take(rx_data)
            } else if let Some(tx_data) = in_data.tx_data_mut() {
                // Handle transmit data
                flag |= MCICmdFlag::WRITE_DATA;
                take(tx_data)
            } else {
                // Neither rx_data nor tx_data is available
                panic!("Transaction data initialized but contains neither rx_data nor tx_data");
            };

            out_data.blksz_set(in_data.block_size() as u32);
            out_data.blkcnt_set(in_data.block_count());
            out_data.datalen_set(in_data.block_size() as u32 * in_data.block_count());

            #[cfg(feature = "dma")]
            {
                let slice = DSlice::from(&buf[..]);
                out_data.buf_dma_set(slice.bus_addr() as usize);
                drop(slice);
            }

            out_data.buf_set(Some(buf));

            #[cfg(feature = "dma")]
            debug!(
                "buf PA: 0x{:x}, blksz: {}, datalen: {}",
                out_data.buf_dma(),
                out_data.blksz(),
                out_data.datalen()
            );

            Some(out_data)
        } else {
            None
        };

        let mut out_trans = MCICmdData::new();

        out_trans.cmdidx_set(index);
        out_trans.cmdarg_set(arg);
        out_trans.set_data(out_data);
        out_trans.flag_set(flag);

        unsafe {
            dsb();
        }

        out_trans
    }

    fn transfer_function(&self, content: &mut MCIHostTransfer, host: &MCIHost) -> MCIHostStatus {
        self.pre_command(content, host)?;

        let mut cmd_data = self.covert_command_info(content);

        if host.config.enable_dma {
            #[cfg(feature = "dma")]
            if let Err(_) = self.hc.borrow_mut().dma_transfer(&mut cmd_data) {
                return Err(MCIHostError::NoData);
            }
            #[cfg(feature = "dma")]
            if let Err(_) = self.hc.borrow_mut().poll_wait_dma_end(&mut cmd_data) {
                return Err(MCIHostError::NoData);
            }
        } else {
            #[cfg(feature = "pio")]
            if self.hc.borrow_mut().pio_transfer(&mut cmd_data).is_err() {
                return Err(MCIHostError::NoData);
            }
            #[cfg(feature = "pio")]
            if self
                .hc
                .borrow_mut()
                .poll_wait_pio_end(&mut cmd_data)
                .is_err()
            {
                return Err(MCIHostError::NoData);
            }
        }

        debug!(
            "Transfer cmd: {}, arg: 0x{:x}, flag: {:?}",
            cmd_data.cmdidx(),
            cmd_data.cmdarg(),
            cmd_data.flag()
        );

        if self
            .hc
            .borrow_mut()
            .cmd_response_get(&mut cmd_data)
            .is_err()
        {
            info!("Transfer cmd and data failed !!!");
            return Err(MCIHostError::Timeout);
        }

        // TODO: The `CLONE` here will reduce driver speed, need to solve this performance issue - taking it out directly might be better
        if content.data().is_some() {
            let data = cmd_data.get_data().unwrap();
            unsafe {
                invalidate(
                    data.buf().unwrap().as_ptr() as *const u8,
                    data.buf().unwrap().len() * 4,
                );
            }
            if let Some(rx_data) = data.buf()
                && let Some(in_data) = content.data_mut()
            {
                in_data.rx_data_set(Some(rx_data.clone()));
            }
        }

        if let Some(cmd) = content.cmd_mut()
            && cmd.response_type() != MCIHostResponseType::None
        {
            cmd.response_mut()
                .copy_from_slice(&cmd_data.get_response()[..4]);
        }

        trace!("Transfer completed successfully");

        Ok(())
    }
}