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
use crate::arch::x86_64::mm::paging::{BasePageSize, PageSize, PageTableEntryFlags};
use crate::arch::x86_64::mm::{paging, virtualmem};
use crate::arch::x86_64::mm::{PhysAddr, VirtAddr};
use crate::x86::io::*;
use core::{mem, slice, str};
const EBDA_PTR_LOCATION: PhysAddr = PhysAddr(0x0000_040E);
const EBDA_MINIMUM_ADDRESS: PhysAddr = PhysAddr(0x400);
const EBDA_WINDOW_SIZE: usize = 1024;
const RSDP_SEARCH_ADDRESS_LOW: PhysAddr = PhysAddr(0xE_0000);
const RSDP_SEARCH_ADDRESS_HIGH: PhysAddr = PhysAddr(0xF_FFFF);
const RSDP_CHECKSUM_LENGTH: usize = 20;
const RSDP_XCHECKSUM_LENGTH: usize = 36;
const AML_NAMEOP: u8 = 0x08;
const AML_PACKAGEOP: u8 = 0x12;
const AML_ZEROOP: u8 = 0x00;
const AML_ONEOP: u8 = 0x01;
const AML_BYTEPREFIX: u8 = 0x0A;
const SLP_EN: u16 = 1 << 13;
static mut MADT: Option<AcpiTable<'_>> = None;
static mut PM1A_CNT_BLK: Option<u16> = None;
static mut SLP_TYPA: Option<u8> = None;
#[repr(C, packed)]
struct AcpiRsdp {
signature: [u8; 8],
checksum: u8,
oem_id: [u8; 6],
revision: u8,
rsdt_physical_address: u32,
length: u32,
xsdt_physical_address: u64,
extended_checksum: u8,
reserved: [u8; 3],
}
impl AcpiRsdp {
fn oem_id(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.oem_id) }
}
fn signature(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.signature) }
}
}
#[repr(C, packed)]
struct AcpiSdtHeader {
signature: [u8; 4],
length: u32,
revision: u8,
checksum: u8,
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
creator_id: u32,
creator_revision: u32,
}
impl AcpiSdtHeader {
fn signature(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.signature) }
}
}
pub struct AcpiTable<'a> {
header: &'a AcpiSdtHeader,
allocated_virtual_address: VirtAddr,
allocated_length: usize,
}
impl<'a> AcpiTable<'a> {
fn map(physical_address: PhysAddr) -> Self {
let mut flags = PageTableEntryFlags::empty();
flags.normal().read_only().execute_disable();
let mut allocated_length = 2 * BasePageSize::SIZE;
let mut count = allocated_length / BasePageSize::SIZE;
let physical_map_address = physical_address.align_down_to_base_page();
let offset: usize = (physical_address - physical_map_address).into();
let mut virtual_address = virtualmem::allocate(allocated_length).unwrap();
paging::map::<BasePageSize>(virtual_address, physical_map_address, count, flags);
let mut header_ptr: *const AcpiSdtHeader = (virtual_address + offset).as_ptr();
let table_length = unsafe { (*header_ptr).length } as usize;
if table_length > allocated_length - offset {
virtualmem::deallocate(virtual_address, allocated_length);
allocated_length = align_up!(table_length + offset, BasePageSize::SIZE);
count = allocated_length / BasePageSize::SIZE;
virtual_address = virtualmem::allocate(allocated_length).unwrap();
paging::map::<BasePageSize>(virtual_address, physical_map_address, count, flags);
header_ptr = (virtual_address + offset).as_ptr();
}
Self {
header: unsafe { &*header_ptr },
allocated_virtual_address: virtual_address,
allocated_length,
}
}
pub fn header_start_address(&self) -> usize {
self.header as *const _ as usize
}
pub fn table_start_address(&self) -> usize {
self.header_start_address() + mem::size_of::<AcpiSdtHeader>()
}
pub fn table_end_address(&self) -> usize {
self.header_start_address() + self.header.length as usize
}
}
impl<'a> Drop for AcpiTable<'a> {
fn drop(&mut self) {
virtualmem::deallocate(self.allocated_virtual_address, self.allocated_length);
}
}
#[repr(C, packed)]
struct AcpiGenericAddress {
address_space: u8,
bit_width: u8,
bit_offset: u8,
access_size: u8,
address: u64,
}
const GENERIC_ADDRESS_IO_SPACE: u8 = 1;
#[repr(C, packed)]
struct AcpiFadt {
firmware_ctrl: u32,
dsdt: u32,
reserved1: u8,
preferred_pm_profile: u8,
sci_int: u16,
smi_cmd: u32,
acpi_enable: u8,
acpi_disable: u8,
s4bios_req: u8,
pstate_cnt: u8,
pm1a_evt_blk: u32,
pm1b_evt_blk: u32,
pm1a_cnt_blk: u32,
pm1b_cnt_blk: u32,
pm2_cnt_blk: u32,
pm_tmr_blk: u32,
gpe0_blk: u32,
gpe1_blk: u32,
pm1_evt_len: u8,
pm1_cnt_len: u8,
pm2_cnt_len: u8,
pm_tmr_len: u8,
gpe0_blk_len: u8,
gpe1_blk_len: u8,
gpe1_base: u8,
cst_cnt: u8,
p_lvl2_lat: u16,
p_lvl3_lat: u16,
flush_size: u16,
flush_stride: u16,
duty_offset: u8,
duty_width: u8,
day_alrm: u8,
mon_alrm: u8,
century: u8,
iapc_boot_arch: u16,
reserved2: u8,
flags: u32,
reset_reg: AcpiGenericAddress,
reset_value: u8,
arm_boot_arch: u16,
fadt_minor_version: u8,
x_firmware_ctrl: u64,
x_dsdt: u64,
x_pm1a_evt_blk: AcpiGenericAddress,
x_pm1b_evt_blk: AcpiGenericAddress,
x_pm1a_cnt_blk: AcpiGenericAddress,
x_pm1b_cnt_blk: AcpiGenericAddress,
x_pm2_cnt_blk: AcpiGenericAddress,
x_pm_tmr_blk: AcpiGenericAddress,
x_gpe0_blk: AcpiGenericAddress,
x_gpe1_blk: AcpiGenericAddress,
sleep_control_reg: AcpiGenericAddress,
sleep_status_reg: AcpiGenericAddress,
hypervisor_vendor_id: u64,
}
fn verify_checksum(start_address: usize, length: usize) -> Result<(), ()> {
let slice = unsafe { slice::from_raw_parts(start_address as *const u8, length) };
let checksum = slice.iter().fold(0, |acc: u8, x| acc.wrapping_add(*x));
if checksum == 0 {
Ok(())
} else {
Err(())
}
}
fn detect_rsdp(start_address: PhysAddr, end_address: PhysAddr) -> Result<&'static AcpiRsdp, ()> {
let mut current_page = 0;
for current_address in (start_address.as_usize()..end_address.as_usize()).step_by(16) {
if current_address / BasePageSize::SIZE > current_page {
paging::identity_map(
PhysAddr::from(current_address),
PhysAddr::from(current_address),
);
current_page = current_address / BasePageSize::SIZE;
}
let rsdp = unsafe { &*(current_address as *const AcpiRsdp) };
if rsdp.signature() != "RSD PTR " {
continue;
}
if verify_checksum(current_address, RSDP_CHECKSUM_LENGTH).is_err() {
debug!(
"Found an ACPI table at {:#X}, but its RSDP checksum is invalid",
current_address
);
continue;
}
if rsdp.revision >= 2 && verify_checksum(current_address, RSDP_XCHECKSUM_LENGTH).is_err() {
debug!(
"Found an ACPI table at {:#X}, but its RSDP extended checksum is invalid",
current_address
);
continue;
}
info!(
"Found an ACPI revision {} table at {:#X} with OEM ID \"{}\"",
rsdp.revision,
current_address,
rsdp.oem_id()
);
return Ok(rsdp);
}
Err(())
}
fn detect_acpi() -> Result<&'static AcpiRsdp, ()> {
paging::identity_map(EBDA_PTR_LOCATION, EBDA_PTR_LOCATION);
let ebda_ptr_location: &u16 =
unsafe { &*(VirtAddr::from(EBDA_PTR_LOCATION.as_u64()).as_ptr()) };
let ebda_address = PhysAddr((*ebda_ptr_location as u64) << 4);
if ebda_address > EBDA_MINIMUM_ADDRESS {
if let Ok(rsdp) = detect_rsdp(ebda_address, ebda_address + EBDA_WINDOW_SIZE) {
return Ok(rsdp);
}
}
if let Ok(rsdp) = detect_rsdp(RSDP_SEARCH_ADDRESS_LOW, RSDP_SEARCH_ADDRESS_HIGH) {
return Ok(rsdp);
}
Err(())
}
fn search_s5_in_table(table: AcpiTable<'_>) {
let aml = unsafe {
slice::from_raw_parts(
table.table_start_address() as *const u8,
table.table_end_address() - table.table_start_address(),
)
};
let s5 = [b'_', b'S', b'5', b'_', AML_PACKAGEOP];
let s5_position = aml.windows(s5.len()).position(|window| window == s5);
if let Some(i) = s5_position {
if i > 2 && (aml[i - 1] == AML_NAMEOP || (aml[i - 2] == AML_NAMEOP && aml[i - 1] == b'\\'))
{
let pkg_length = aml[i + 5];
let num_elements = aml[i + 6];
if pkg_length & 0b1100_0000 == 0 && num_elements > 0 {
let op = aml[i + 7];
let slp_typa;
match op {
AML_ZEROOP => slp_typa = 0,
AML_ONEOP => slp_typa = 1,
AML_BYTEPREFIX => slp_typa = aml[i + 8],
_ => return,
}
unsafe {
SLP_TYPA = Some(slp_typa);
}
}
}
}
}
fn parse_fadt(fadt: AcpiTable<'_>) {
let fadt_table = unsafe { &*(fadt.table_start_address() as *const AcpiFadt) };
let x_pm1a_cnt_blk_field_address = &fadt_table.x_pm1a_cnt_blk as *const _ as usize;
let pm1a_cnt_blk = if x_pm1a_cnt_blk_field_address < fadt.table_end_address()
&& fadt_table.x_pm1a_cnt_blk.address_space == GENERIC_ADDRESS_IO_SPACE
{
fadt_table.x_pm1a_cnt_blk.address as u16
} else {
fadt_table.pm1a_cnt_blk as u16
};
unsafe {
PM1A_CNT_BLK = Some(pm1a_cnt_blk);
}
let x_dsdt = core::ptr::addr_of!(fadt_table.x_dsdt);
let x_dsdt_field_address = unsafe { x_dsdt.read_unaligned() as usize };
let dsdt_address = if x_dsdt_field_address < fadt.table_end_address() && fadt_table.x_dsdt > 0 {
PhysAddr(fadt_table.x_dsdt)
} else {
PhysAddr(fadt_table.dsdt.into())
};
let dsdt = AcpiTable::map(dsdt_address);
assert!(
dsdt.header.signature() == "DSDT",
"DSDT at {:#X} has invalid signature \"{}\"",
dsdt_address,
dsdt.header.signature()
);
assert!(
verify_checksum(dsdt.header_start_address(), dsdt.header.length as usize).is_ok(),
"DSDT at {:#X} has invalid checksum",
dsdt_address
);
search_s5_in_table(dsdt);
}
fn parse_ssdt(ssdt: AcpiTable<'_>) {
if unsafe { SLP_TYPA }.is_some() {
return;
}
search_s5_in_table(ssdt);
}
pub fn get_madt() -> Option<&'static AcpiTable<'static>> {
unsafe { MADT.as_ref() }
}
pub fn poweroff() {
unsafe {
if let (Some(pm1a_cnt_blk), Some(slp_typa)) = (PM1A_CNT_BLK, SLP_TYPA) {
let bits = (u16::from(slp_typa) << 10) | SLP_EN;
debug!(
"Powering Off through ACPI (port {:#X}, bitmask {:#X})",
pm1a_cnt_blk, bits
);
outw(pm1a_cnt_blk, bits);
} else {
debug!("ACPI Power Off is not available");
}
}
}
pub fn init() {
let rsdp = detect_acpi().expect("HermitCore requires an ACPI-compliant system");
let rsdt_physical_address = if rsdp.revision >= 2 {
PhysAddr(rsdp.xsdt_physical_address)
} else {
PhysAddr(rsdp.rsdt_physical_address.into())
};
let rsdt = AcpiTable::map(rsdt_physical_address);
let mut current_address = rsdt.table_start_address();
while current_address < rsdt.table_end_address() {
let table_physical_address = if rsdp.revision >= 2 {
let address = PhysAddr(unsafe { *(current_address as *const u64) });
current_address += mem::size_of::<u64>();
address
} else {
let address = PhysAddr((unsafe { *(current_address as *const u32) }).into());
current_address += mem::size_of::<u32>();
address
};
let table = AcpiTable::map(table_physical_address);
debug!("Found ACPI table: {}", table.header.signature());
if table.header.signature() == "APIC" {
assert!(
verify_checksum(table.header_start_address(), table.header.length as usize).is_ok(),
"MADT at {:#X} has invalid checksum",
table_physical_address
);
unsafe {
MADT = Some(table);
}
} else if table.header.signature() == "FACP" {
assert!(
verify_checksum(table.header_start_address(), table.header.length as usize).is_ok(),
"FADT at {:#X} has invalid checksum",
table_physical_address
);
parse_fadt(table);
} else if table.header.signature() == "SSDT" {
assert!(
verify_checksum(table.header_start_address(), table.header.length as usize).is_ok(),
"SSDT at {:#X} has invalid checksum",
table_physical_address
);
parse_ssdt(table);
}
}
}