Skip to main content

ax_cpu/loongarch64/
asm.rs

1//! Wrapper functions for assembly instructions.
2
3use core::arch::asm;
4
5use ax_memory_addr::{PhysAddr, VirtAddr};
6use loongArch64::register::{crmd, ecfg, eentry, pgdh, pgdl};
7
8/// Allows the current CPU to respond to interrupts.
9#[inline]
10pub fn enable_irqs() {
11    crmd::set_ie(true)
12}
13
14/// Makes the current CPU to ignore interrupts.
15#[inline]
16pub fn disable_irqs() {
17    crmd::set_ie(false)
18}
19
20/// Returns whether the current CPU is allowed to respond to interrupts.
21#[inline]
22pub fn irqs_enabled() -> bool {
23    crmd::read().ie()
24}
25
26/// Relaxes the current CPU and waits for interrupts.
27///
28/// It must be called with interrupts enabled, otherwise it will never return.
29#[inline]
30pub fn wait_for_irqs() {
31    unsafe { loongArch64::asm::idle() }
32}
33
34/// Halt the current CPU.
35#[inline]
36pub fn halt() {
37    disable_irqs();
38    unsafe { loongArch64::asm::idle() }
39}
40
41/// Reads the current page table root register for user space (`PGDL`).
42///
43/// Returns the physical address of the page table root.
44#[inline]
45pub fn read_user_page_table() -> PhysAddr {
46    PhysAddr::from(pgdl::read().base())
47}
48
49/// Reads the current page table root register for kernel space (`PGDH`).
50///
51/// Returns the physical address of the page table root.
52#[inline]
53pub fn read_kernel_page_table() -> PhysAddr {
54    PhysAddr::from(pgdh::read().base())
55}
56
57/// Writes the register to update the current page table root for user space
58/// (`PGDL`).
59///
60/// Note that the TLB is **NOT** flushed after this operation.
61///
62/// # Safety
63///
64/// This function is unsafe as it changes the virtual memory address space.
65pub unsafe fn write_user_page_table(root_paddr: PhysAddr) {
66    pgdl::set_base(root_paddr.as_usize() as _);
67}
68
69/// Writes the register to update the current page table root for kernel space
70/// (`PGDH`).
71///
72/// Note that the TLB is **NOT** flushed after this operation.
73///
74/// # Safety
75///
76/// This function is unsafe as it changes the virtual memory address space.
77pub unsafe fn write_kernel_page_table(root_paddr: PhysAddr) {
78    pgdh::set_base(root_paddr.as_usize());
79}
80
81/// Flushes the TLB.
82///
83/// If `vaddr` is [`None`], flushes the entire TLB. Otherwise, flushes the TLB
84/// entry that maps the given virtual address.
85#[inline]
86pub fn flush_tlb(vaddr: Option<VirtAddr>) {
87    unsafe {
88        if let Some(vaddr) = vaddr {
89            // <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#_dbar>
90            //
91            // Only after all previous load/store access operations are completely
92            // executed, the DBAR 0 instruction can be executed; and only after the
93            // execution of DBAR 0 is completed, all subsequent load/store access
94            // operations can be executed.
95            //
96            // <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#_invtlb>
97            //
98            // formats: invtlb op, asid, addr
99            //
100            // op 0x5: Clear all page table entries with G=0 and ASID equal to the
101            // register specified ASID, and VA equal to the register specified VA.
102            //
103            // When the operation indicated by op does not require an ASID, the
104            // general register rj should be set to r0.
105            asm!("dbar 0; invtlb 0x05, $r0, {reg}", reg = in(reg) vaddr.as_usize());
106        } else {
107            // op 0x0: Clear all page table entries
108            asm!("dbar 0; invtlb 0x00, $r0, $r0");
109        }
110    }
111}
112
113/// Writes the Exception Entry Base Address register (`EENTRY`).
114///
115/// It also set the Exception Configuration register (`ECFG`) to `VS=0`.
116///
117/// - ECFG: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#exception-configuration>
118/// - EENTRY: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#exception-entry-base-address>
119///
120/// # Safety
121///
122/// This function is unsafe as it changes the exception handling behavior of the
123/// current CPU.
124#[inline]
125pub unsafe fn write_exception_entry_base(eentry: usize) {
126    ecfg::set_vs(0);
127    eentry::set_eentry(eentry);
128}
129
130/// Writes the Page Walk Controller registers (`PWCL` and `PWCH`).
131///
132/// # Safety
133///
134/// This function is unsafe as it changes the page walk configuration such as
135/// levels and starting bits.
136///
137/// - `PWCL`: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#page-walk-controller-for-lower-half-address-space>
138/// - `PWCH`: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#page-walk-controller-for-higher-half-address-space>
139#[inline]
140pub unsafe fn write_pwc(pwcl: u32, pwch: u32) {
141    unsafe {
142        asm!(
143            include_asm_macros!(),
144            "csrwr {}, LA_CSR_PWCL",
145            "csrwr {}, LA_CSR_PWCH",
146            in(reg) pwcl,
147            in(reg) pwch
148        )
149    }
150}
151
152/// Reads the thread pointer of the current CPU (`$tp`).
153///
154/// It is used to implement TLS (Thread Local Storage).
155#[inline]
156pub fn read_thread_pointer() -> usize {
157    let tp;
158    unsafe { asm!("move {}, $tp", out(reg) tp) };
159    tp
160}
161
162/// Writes the thread pointer of the current CPU (`$tp`).
163///
164/// It is used to implement TLS (Thread Local Storage).
165///
166/// # Safety
167///
168/// This function is unsafe as it changes the CPU states.
169#[inline]
170pub unsafe fn write_thread_pointer(tp: usize) {
171    unsafe { asm!("move $tp, {}", in(reg) tp) }
172}
173
174/// Enables floating-point instructions by setting `EUEN.FPE`.
175///
176/// - `EUEN`: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#extended-component-unit-enable>
177#[inline]
178pub fn enable_fp() {
179    loongArch64::register::euen::set_fpe(true);
180}
181
182/// Enables LSX extension by setting `EUEN.LSX`.
183///
184/// - `EUEN`: <https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#extended-component-unit-enable>
185pub fn enable_lsx() {
186    loongArch64::register::euen::set_sxe(true);
187}
188
189#[cfg(feature = "uspace")]
190core::arch::global_asm!(include_asm_macros!(), include_str!("user_copy.S"));
191
192#[cfg(feature = "uspace")]
193unsafe extern "C" {
194    /// Copies data from source to destination, where addresses may be in user
195    /// space. Equivalent to memcpy.
196    ///
197    /// # Safety
198    /// This function is unsafe because it performs raw memory operations.
199    ///
200    /// # Returns
201    /// Returns the number of bytes not copied. This means 0 indicates success,
202    /// while a value > 0 indicates failure.
203    pub fn user_copy(dst: *mut u8, src: *const u8, size: usize) -> usize;
204}