1 use core::{arch::x86_64::_rdtsc, hint::spin_loop}; 2 3 use alloc::{boxed::Box, sync::Arc}; 4 5 use crate::{ 6 arch::{sched::sched, CurrentIrqArch}, 7 exception::InterruptArch, 8 include::bindings::bindings::{useconds_t, Cpu_tsc_freq}, 9 process::ProcessManager, 10 syscall::SystemError, 11 }; 12 13 use super::{ 14 timer::{next_n_us_timer_jiffies, Timer, WakeUpHelper}, 15 TimeSpec, 16 }; 17 18 /// @brief 休眠指定时间(单位:纳秒) 19 /// 20 /// @param sleep_time 指定休眠的时间 21 /// 22 /// @return Ok(TimeSpec) 剩余休眠时间 23 /// 24 /// @return Err(SystemError) 错误码 25 pub fn nanosleep(sleep_time: TimeSpec) -> Result<TimeSpec, SystemError> { 26 if sleep_time.tv_nsec < 0 || sleep_time.tv_nsec >= 1000000000 { 27 return Err(SystemError::EINVAL); 28 } 29 // 对于小于500us的时间,使用spin/rdtsc来进行定时 30 31 if sleep_time.tv_nsec < 500000 { 32 let expired_tsc: u64 = 33 unsafe { _rdtsc() + (sleep_time.tv_nsec as u64 * Cpu_tsc_freq) / 1000000000 }; 34 while unsafe { _rdtsc() } < expired_tsc { 35 spin_loop() 36 } 37 return Ok(TimeSpec { 38 tv_sec: 0, 39 tv_nsec: 0, 40 }); 41 } 42 // 创建定时器 43 let handler: Box<WakeUpHelper> = WakeUpHelper::new(ProcessManager::current_pcb()); 44 let timer: Arc<Timer> = Timer::new( 45 handler, 46 next_n_us_timer_jiffies((sleep_time.tv_nsec / 1000) as u64), 47 ); 48 49 let irq_guard: crate::exception::IrqFlagsGuard = 50 unsafe { CurrentIrqArch::save_and_disable_irq() }; 51 ProcessManager::mark_sleep(true).ok(); 52 timer.activate(); 53 54 drop(irq_guard); 55 56 sched(); 57 58 // TODO: 增加信号唤醒的功能后,返回正确的剩余时间 59 60 return Ok(TimeSpec { 61 tv_sec: 0, 62 tv_nsec: 0, 63 }); 64 } 65 66 /// @brief 休眠指定时间(单位:微秒) 67 /// 68 /// @param usec 微秒 69 /// 70 /// @return Ok(TimeSpec) 剩余休眠时间 71 /// 72 /// @return Err(SystemError) 错误码 73 pub fn usleep(sleep_time: TimeSpec) -> Result<TimeSpec, SystemError> { 74 match nanosleep(sleep_time) { 75 Ok(value) => return Ok(value), 76 Err(err) => return Err(err), 77 }; 78 } 79 80 //===== 以下为提供给C的接口 ===== 81 82 /// @brief 休眠指定时间(单位:微秒)(提供给C的接口) 83 /// 84 /// @param usec 微秒 85 /// 86 /// @return Ok(i32) 0 87 /// 88 /// @return Err(SystemError) 错误码 89 #[no_mangle] 90 pub extern "C" fn rs_usleep(usec: useconds_t) -> i32 { 91 let sleep_time = TimeSpec { 92 tv_sec: (usec / 1000000) as i64, 93 tv_nsec: ((usec % 1000000) * 1000) as i64, 94 }; 95 match usleep(sleep_time) { 96 Ok(_) => { 97 return 0; 98 } 99 Err(err) => { 100 return err.to_posix_errno(); 101 } 102 }; 103 } 104