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
mod frame;
pub mod syndrome;

use self::frame::TrapFrame;
use self::syndrome::Fault;
use self::syndrome::Syndrome;
use super::lower::synchronous;
use crate::cpu;
use crate::event::realmexit::{ExitSyncType, RecExitReason};
use crate::mm::translation::PageTable;
use crate::realm::vcpu::VCPU;

use armv9a::regs::*;

#[repr(u16)]
#[derive(Debug, Copy, Clone)]
pub enum Source {
    CurrentSPEL0,
    CurrentSPELx,
    LowerAArch64,
    LowerAArch32,
}

#[repr(u16)]
#[derive(Debug, Copy, Clone)]
pub enum Kind {
    Synchronous,
    Irq,
    Fiq,
    SError,
}

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Info {
    source: Source,
    kind: Kind,
}

/// This function is called when an exception occurs from CurrentSPEL0, CurrentSPELx.
/// The `info` parameter specifies source (first 16 bits) and kind (following 16
/// bits) of the exception.
/// The `esr` has the value of a syndrome register (ESR_ELx) holding the cause
/// of the Synchronous and SError exception.
/// The `tf` has the TrapFrame of current context.
#[no_mangle]
#[allow(unused_variables)]
pub extern "C" fn handle_exception(info: Info, esr: u32, tf: &mut TrapFrame) {
    match info.kind {
        Kind::Synchronous => match Syndrome::from(esr) {
            Syndrome::Brk(b) => {
                debug!("brk #{}", b);
                debug!("{:?}\nESR: {:X}\n{:#X?}", info, esr, tf);
                tf.elr += 4; //continue
            }
            Syndrome::PCAlignmentFault => {
                debug!("PCAlignmentFault");
            }
            Syndrome::DataAbort(fault) => {
                let far = unsafe { FAR_EL2.get() };
                debug!("Data Abort (higher), far:{:X}", far);
                match fault {
                    Fault::AddressSize { level } => {
                        debug!("address size, level:{}", level);
                    }
                    Fault::Translation { level } => {
                        debug!("translation, level:{}, esr:{:X}", level, esr);
                        PageTable::get_ref().map(far as usize, true);
                        tf.elr += 4; //continue
                    }
                    Fault::AccessFlag { level } => {
                        debug!("access flag, level:{}", level);
                    }
                    Fault::Permission { level } => {
                        debug!("permission, level:{}", level);
                    }
                    Fault::Alignment => {
                        debug!("alignment");
                    }
                    Fault::TLBConflict => {
                        debug!("tlb conflict");
                    }
                    Fault::Other(_x) => {
                        debug!("other");
                    }
                }
            }
            Syndrome::InstructionAbort(v) => {
                debug!("Instruction Abort (higher)");
            }
            Syndrome::HVC => {
                debug!("HVC");
            }
            Syndrome::SMC => {
                debug!("SMC");
            }
            Syndrome::SysRegInst => {
                debug!("SysRegInst");
            }
            Syndrome::WFX => {
                debug!("WFX");
            }
            Syndrome::Other(v) => {
                debug!("Other");
            }
            undefined => {
                panic!(
                    "{:?} and esr {:x}, TrapFrame: {:?} on cpu::id {:?}",
                    info,
                    esr,
                    tf,
                    cpu::id()
                );
            }
        },
        _ => {
            panic!(
                "Unknown exception! Info={:?}, ESR={:x} on CPU {:?}",
                info,
                esr,
                cpu::id()
            );
        }
    }
}

pub const RET_TO_REC: u64 = 0;
pub const RET_TO_RMM: u64 = 1;
/// This function is called when an exception occurs from LowerAArch64.
/// To enter RMM (EL2), return 1. Otherwise, return 0 to go back to EL1.
/// The `info` parameter specifies source (first 16 bits) and kind (following 16
/// bits) of the exception.
/// The `esr` has the value of a syndrome register (ESR_ELx) holding the cause
/// of the Synchronous and SError exception.
/// The `vcpu` has the VCPU context.
/// The `tf` has the TrapFrame of current context.
///
/// Do not write sys_regs of VCPU here. (ref. HANDLE_LOWER in vectors.s)
#[no_mangle]
#[allow(unused_variables)]
pub extern "C" fn handle_lower_exception(
    info: Info,
    esr: u32,
    vcpu: &mut VCPU,
    tf: &mut TrapFrame,
) -> u64 {
    match info.kind {
        // TODO: adjust elr according to the decision that kvm made
        Kind::Synchronous => match Syndrome::from(esr) {
            Syndrome::HVC => {
                debug!("Synchronous: HVC: {:#X}", vcpu.context.gp_regs[0]);

                // Inject undefined exception to the realm
                unsafe {
                    SPSR_EL1.set(vcpu.context.spsr);
                    ELR_EL1.set(vcpu.context.elr);

                    let esr = EsrEl1::new(0)
                        .set_masked_value(EsrEl1::EC, ESR_EL1_EC_UNKNOWN)
                        .set_bits(EsrEl1::IL)
                        .get();

                    ESR_EL1.set(esr);
                }

                // Return to realm's exception handler
                let vbar = vcpu.context.sys_regs.vbar;
                const SPSR_EL2_MODE_EL1H_OFFSET: u64 = 0x200;
                vcpu.context.elr = vbar + SPSR_EL2_MODE_EL1H_OFFSET;

                tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into();
                tf.regs[1] = esr as u64;
                tf.regs[2] = 0;
                tf.regs[3] = unsafe { FAR_EL2.get() };
                RET_TO_REC
            }
            Syndrome::SMC => {
                tf.regs[0] = RecExitReason::Sync(ExitSyncType::RSI).into();
                tf.regs[1] = vcpu.context.gp_regs[0]; // RSI command
                advance_pc(vcpu);
                RET_TO_RMM
            }
            Syndrome::InstructionAbort(_) | Syndrome::DataAbort(_) => {
                debug!("Synchronous: InstructionAbort | DataAbort");
                if let Syndrome::InstructionAbort(_) = Syndrome::from(esr) {
                    tf.regs[0] = RecExitReason::Sync(ExitSyncType::InstAbort).into()
                } else {
                    tf.regs[0] = RecExitReason::Sync(ExitSyncType::DataAbort).into();
                }
                tf.regs[1] = esr as u64;
                tf.regs[2] = unsafe { HPFAR_EL2.get() };
                tf.regs[3] = unsafe { FAR_EL2.get() };
                let fipa = unsafe { HPFAR_EL2.get_masked(HPFAR_EL2::FIPA) } << 8;
                debug!("fipa: {:X}", fipa);
                debug!("esr_el2: {:X}", esr);
                RET_TO_RMM
            }
            Syndrome::SysRegInst => {
                debug!("Synchronous: MRS, MSR System Register Instruction");
                let ret = synchronous::sys_reg::handle(vcpu, esr as u64);
                advance_pc(vcpu);
                ret
            }
            Syndrome::WFX => {
                debug!("Synchronous: WFx");
                tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into();
                tf.regs[1] = esr as u64;
                tf.regs[2] = unsafe { HPFAR_EL2.get() };
                tf.regs[3] = unsafe { FAR_EL2.get() };
                advance_pc(vcpu);
                RET_TO_RMM
            }
            undefined => {
                debug!("Synchronous: Other");
                tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into();
                tf.regs[1] = esr as u64;
                tf.regs[2] = unsafe { HPFAR_EL2.get() };
                tf.regs[3] = unsafe { FAR_EL2.get() };
                RET_TO_RMM
            }
        },
        Kind::Irq => {
            debug!("IRQ");
            tf.regs[0] = RecExitReason::IRQ.into();
            // IRQ isn't interpreted with esr. It just hold previsou info. Void them out.
            tf.regs[1] = 0;
            tf.regs[2] = 0;
            tf.regs[3] = 0;
            RET_TO_RMM
        }
        _ => {
            error!(
                "Unknown exception! Info={:?}, ESR={:x} on CPU {:?}",
                info,
                esr,
                cpu::id()
            );
            RET_TO_REC
        }
    }
}

#[inline(always)]
fn advance_pc(vcpu: &mut VCPU) {
    vcpu.context.elr += 4;
}