lib.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. //! `aml` is a pure-Rust AML (ACPI Machine Language) parser, used for parsing the DSDT and
  2. //! SSDT tables from ACPI. This crate can be used by kernels to gather information about the
  3. //! hardware, and invoke control methods (this is not yet supported) to query and change the state
  4. //! of devices in a hardware-independent way.
  5. //!
  6. //! ### Using the library
  7. //! To use the library, you will mostly interact with the `AmlContext` type. You should create an
  8. //! instance of this type using `AmlContext::new()`, and then pass it tables containing AML
  9. //! (probably from the `acpi` crate), which you've mapped into the virtual address space. This will
  10. //! parse the table, populating the namespace with objects encoded by the AML. After this, you may
  11. //! unmap the memory the table was mapped into - all the information needed will be extracted and
  12. //! allocated on the heap.
  13. //!
  14. //! You can then access specific objects by name like so: e.g.
  15. //! ```ignore
  16. //! let my_aml_value = aml_context.lookup(&AmlName::from_str("\\_SB.PCI0.S08._ADR").unwrap());
  17. //! ```
  18. // TODO: add example of invoking a method
  19. //!
  20. //! ### About the parser
  21. //! The parser is written using a set of custom parser combinators - the code can be confusing on
  22. //! first reading, but provides an extensible and type-safe way to write parsers. For an easy
  23. //! introduction to parser combinators and the foundations used for this library, I suggest reading
  24. //! [Bodil's fantastic blog post](https://bodil.lol/parser-combinators/).
  25. //!
  26. //! The actual combinators can be found in `parser.rs`. Various tricks are used to provide a nice
  27. //! API and work around limitations in the type system, such as the concrete types like
  28. //! `MapWithContext`.
  29. //!
  30. //! The actual parsers are then grouped into categories based loosely on the AML grammar sections in
  31. //! the ACPI spec. Most are written in terms of combinators, but some have to be written in a more
  32. //! imperitive style, either because they're clearer, or because we haven't yet found good
  33. //! combinator patterns to express the parse.
  34. #![no_std]
  35. #![feature(decl_macro, type_ascription, box_syntax, bool_to_option)]
  36. extern crate alloc;
  37. #[cfg(test)]
  38. extern crate std;
  39. #[cfg(test)]
  40. mod test_utils;
  41. pub(crate) mod expression;
  42. pub(crate) mod misc;
  43. pub(crate) mod name_object;
  44. pub(crate) mod namespace;
  45. pub(crate) mod opcode;
  46. pub(crate) mod parser;
  47. pub mod pci_routing;
  48. pub(crate) mod pkg_length;
  49. pub mod resource;
  50. pub(crate) mod statement;
  51. pub(crate) mod term_object;
  52. pub mod value;
  53. pub use crate::{namespace::*, value::AmlValue};
  54. use alloc::{boxed::Box, string::ToString};
  55. use core::mem;
  56. use log::{error, warn};
  57. use misc::{ArgNum, LocalNum};
  58. use name_object::Target;
  59. use parser::{Parser, Propagate};
  60. use pkg_length::PkgLength;
  61. use term_object::term_list;
  62. use value::{AmlType, Args};
  63. /// AML has a `RevisionOp` operator that returns the "AML interpreter revision". It's not clear
  64. /// what this is actually used for, but this is ours.
  65. pub const AML_INTERPRETER_REVISION: u64 = 0;
  66. /// Describes how much debug information the parser should emit. Set the "maximum" expected verbosity in
  67. /// the context's `debug_verbosity` - everything will be printed that is less or equal in 'verbosity'.
  68. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
  69. pub enum DebugVerbosity {
  70. /// Print no debug information
  71. None,
  72. /// Print heads and tails when entering and leaving scopes of major objects, but not more minor ones.
  73. Scopes,
  74. /// Print heads and tails when entering and leaving scopes of all objects.
  75. AllScopes,
  76. /// Print heads and tails of all objects, and extra debug information as it's parsed.
  77. All,
  78. }
  79. struct MethodContext {
  80. /// AML local variables. These are used when we invoke a control method. A `None` value represents a null AML
  81. /// object.
  82. locals: [Option<AmlValue>; 8],
  83. /// If we're currently invoking a control method, this stores the arguments that were passed to
  84. /// it. It's `None` if we aren't invoking a method.
  85. args: Args,
  86. }
  87. impl MethodContext {
  88. fn new(args: Args) -> MethodContext {
  89. // XXX: this is required because `Option<AmlValue>` is not `Copy`, so it can't be used to initialize an
  90. // array, but consts can :(
  91. const NONE_BUT_CONST: Option<AmlValue> = None;
  92. MethodContext { locals: [NONE_BUT_CONST; 8], args }
  93. }
  94. }
  95. pub struct AmlContext {
  96. /// The `Handler` passed from the library user. This is stored as a boxed trait object simply to avoid having
  97. /// to add a lifetime and type parameter to `AmlContext`, as they would massively complicate the parser types.
  98. handler: Box<dyn Handler>,
  99. pub namespace: Namespace,
  100. method_context: Option<MethodContext>,
  101. /*
  102. * These track the state of the context while it's parsing an AML table.
  103. */
  104. current_scope: AmlName,
  105. scope_indent: usize,
  106. debug_verbosity: DebugVerbosity,
  107. }
  108. impl AmlContext {
  109. /// Creates a new `AmlContext` - the central type in managing the AML tables. Only one of these should be
  110. /// created, and it should be passed the DSDT and all SSDTs defined by the hardware.
  111. pub fn new(handler: Box<dyn Handler>, debug_verbosity: DebugVerbosity) -> AmlContext {
  112. let mut context = AmlContext {
  113. handler,
  114. namespace: Namespace::new(),
  115. method_context: None,
  116. current_scope: AmlName::root(),
  117. scope_indent: 0,
  118. debug_verbosity,
  119. };
  120. context.add_predefined_objects();
  121. context
  122. }
  123. pub fn parse_table(&mut self, stream: &[u8]) -> Result<(), AmlError> {
  124. if stream.len() == 0 {
  125. return Err(AmlError::UnexpectedEndOfStream);
  126. }
  127. let table_length = PkgLength::from_raw_length(stream, stream.len() as u32).unwrap();
  128. match term_object::term_list(table_length).parse(stream, self) {
  129. Ok(_) => Ok(()),
  130. Err((_, _, Propagate::Err(err))) => {
  131. error!("Failed to parse AML stream. Err = {:?}", err);
  132. Err(err)
  133. }
  134. Err((_, _, other)) => {
  135. error!("AML table evaluated to unexpected result: {:?}", other);
  136. Err(AmlError::MalformedStream)
  137. }
  138. }
  139. }
  140. // TODO: docs
  141. pub fn invoke_method(&mut self, path: &AmlName, args: Args) -> Result<AmlValue, AmlError> {
  142. use value::MethodCode;
  143. match self.namespace.get_by_path(path)?.clone() {
  144. AmlValue::Method { flags, code } => {
  145. /*
  146. * First, set up the state we expect to enter the method with, but clearing local
  147. * variables to "null" and setting the arguments. Save the current method state and scope, so if we're
  148. * already executing another control method, we resume into it correctly.
  149. */
  150. let old_context = mem::replace(&mut self.method_context, Some(MethodContext::new(args)));
  151. let old_scope = mem::replace(&mut self.current_scope, path.clone());
  152. /*
  153. * Create a namespace level to store local objects created by the invocation.
  154. */
  155. self.namespace.add_level(path.clone(), LevelType::MethodLocals)?;
  156. let return_value = match code {
  157. MethodCode::Aml(ref code) => {
  158. match term_list(PkgLength::from_raw_length(code, code.len() as u32).unwrap())
  159. .parse(code, self)
  160. {
  161. // If the method doesn't return a value, we implicitly return `0`
  162. Ok(_) => Ok(AmlValue::Integer(0)),
  163. Err((_, _, Propagate::Return(result))) => Ok(result),
  164. Err((_, _, Propagate::Break)) => Err(AmlError::BreakInInvalidPosition),
  165. Err((_, _, Propagate::Continue)) => Err(AmlError::ContinueInInvalidPosition),
  166. Err((_, _, Propagate::Err(err))) => {
  167. error!("Failed to execute control method: {:?}", err);
  168. Err(err)
  169. }
  170. }
  171. }
  172. MethodCode::Native(ref method) => match (method)(self) {
  173. Ok(result) => Ok(result),
  174. Err(err) => {
  175. error!("Failed to execute control method: {:?}", err);
  176. Err(err)
  177. }
  178. },
  179. };
  180. /*
  181. * Locally-created objects should be destroyed on method exit (see §5.5.2.3 of the ACPI spec). We do
  182. * this by simply removing the method's local object layer.
  183. */
  184. // TODO: this should also remove objects created by the method outside the method's scope, if they
  185. // weren't statically created. This is harder.
  186. self.namespace.remove_level(path.clone())?;
  187. /*
  188. * Restore the old state.
  189. */
  190. self.method_context = old_context;
  191. self.current_scope = old_scope;
  192. return_value
  193. }
  194. /*
  195. * AML can encode methods that don't require any computation simply as the value that would otherwise be
  196. * returned (e.g. a `_STA` object simply being an `AmlValue::Integer`, instead of a method that just
  197. * returns an integer).
  198. */
  199. value => Ok(value),
  200. }
  201. }
  202. // TODO: docs
  203. pub fn initialize_objects(&mut self) -> Result<(), AmlError> {
  204. use name_object::NameSeg;
  205. use value::StatusObject;
  206. /*
  207. * If `\_SB._INI` exists, we unconditionally execute it at the beginning of device initialization.
  208. */
  209. match self.invoke_method(&AmlName::from_str("\\_SB._INI").unwrap(), Args::default()) {
  210. Ok(_) => (),
  211. Err(AmlError::ValueDoesNotExist(_)) => (),
  212. Err(err) => return Err(err),
  213. }
  214. /*
  215. * Next, we traverse the namespace, looking for devices.
  216. *
  217. * XXX: we clone the namespace here, which obviously drives up heap burden quite a bit (not as much as you
  218. * might first expect though - we're only duplicating the level data structure, not all the objects). The
  219. * issue here is that we need to access the namespace during traversal (e.g. to invoke a method), which the
  220. * borrow checker really doesn't like. A better solution could be a iterator-like traversal system that
  221. * keeps track of the namespace without keeping it borrowed. This works for now.
  222. */
  223. self.namespace.clone().traverse(|path, level: &NamespaceLevel| match level.typ {
  224. LevelType::Device => {
  225. let status = if level.values.contains_key(&NameSeg::from_str("_STA").unwrap()) {
  226. self.invoke_method(&AmlName::from_str("_STA").unwrap().resolve(&path)?, Args::default())?
  227. .as_status()?
  228. } else {
  229. StatusObject::default()
  230. };
  231. /*
  232. * If the device is present and has an `_INI` method, invoke it.
  233. */
  234. if status.present && level.values.contains_key(&NameSeg::from_str("_INI").unwrap()) {
  235. log::info!("Invoking _INI at level: {}", path);
  236. self.invoke_method(&AmlName::from_str("_INI").unwrap().resolve(&path)?, Args::default())?;
  237. }
  238. /*
  239. * We traverse the children of this device if it's present, or isn't present but is functional.
  240. */
  241. Ok(status.present || status.functional)
  242. }
  243. LevelType::Scope => Ok(true),
  244. // TODO: can any of these contain devices?
  245. LevelType::Processor => Ok(false),
  246. LevelType::PowerResource => Ok(false),
  247. LevelType::ThermalZone => Ok(false),
  248. LevelType::MethodLocals => Ok(false),
  249. })?;
  250. Ok(())
  251. }
  252. pub(crate) fn read_target(&self, target: &Target) -> Result<&AmlValue, AmlError> {
  253. match target {
  254. Target::Null => todo!(),
  255. Target::Name(name) => {
  256. let (_, handle) = self.namespace.search(name, &self.current_scope)?;
  257. self.namespace.get(handle)
  258. }
  259. Target::Debug => todo!(),
  260. Target::Arg(arg) => self.current_arg(*arg),
  261. Target::Local(local) => self.local(*local),
  262. }
  263. }
  264. /// Get the value of an argument by its argument number. Can only be executed from inside a control method.
  265. pub(crate) fn current_arg(&self, arg: ArgNum) -> Result<&AmlValue, AmlError> {
  266. self.method_context.as_ref().ok_or(AmlError::NotExecutingControlMethod)?.args.arg(arg)
  267. }
  268. /// Get the current value of a local by its local number. Can only be executed from inside a control method.
  269. pub(crate) fn local(&self, local: LocalNum) -> Result<&AmlValue, AmlError> {
  270. if let None = self.method_context {
  271. return Err(AmlError::NotExecutingControlMethod);
  272. }
  273. if local > 7 {
  274. return Err(AmlError::InvalidLocalAccess(local));
  275. }
  276. self.method_context.as_ref().unwrap().locals[local as usize]
  277. .as_ref()
  278. .ok_or(AmlError::InvalidLocalAccess(local))
  279. }
  280. /// Perform a store into a `Target`, according to the rules specified by §19.3.5.8. This returns a value read
  281. /// out of the target, if neccessary, as values can be altered during a store in some circumstances. When
  282. /// required, this also performs required implicit conversions, otherwise stores are semantically equivalent to
  283. /// a `CopyObject`.
  284. pub(crate) fn store(&mut self, target: Target, value: AmlValue) -> Result<AmlValue, AmlError> {
  285. match target {
  286. Target::Name(ref path) => {
  287. let (_, handle) = self.namespace.search(path, &self.current_scope)?;
  288. match self.namespace.get(handle).unwrap().type_of() {
  289. AmlType::FieldUnit => {
  290. let mut field = self.namespace.get(handle).unwrap().clone();
  291. field.write_field(value, self)?;
  292. field.read_field(self)
  293. }
  294. AmlType::BufferField => {
  295. let mut buffer_field = self.namespace.get(handle).unwrap().clone();
  296. buffer_field.write_buffer_field(value.clone(), self)?;
  297. Ok(value)
  298. }
  299. typ => {
  300. *self.namespace.get_mut(handle)? = value.as_type(typ, self)?;
  301. Ok(self.namespace.get(handle)?.clone())
  302. }
  303. }
  304. }
  305. Target::Debug => {
  306. // TODO
  307. unimplemented!()
  308. }
  309. Target::Arg(arg_num) => {
  310. if let None = self.method_context {
  311. return Err(AmlError::NotExecutingControlMethod);
  312. }
  313. /*
  314. * Stores into `Arg` objects are simply copied with no conversion applied, unless the `Arg`
  315. * contains an Object Reference, in which case an automatic de-reference occurs and the object is
  316. * copied to the target of the Object Reference, instead of overwriting the `Arg.`
  317. */
  318. // TODO: implement behaviour for object references
  319. self.method_context.as_mut().unwrap().args.store_arg(arg_num, value.clone())?;
  320. Ok(value)
  321. }
  322. Target::Local(local_num) => {
  323. if let None = self.method_context {
  324. return Err(AmlError::NotExecutingControlMethod);
  325. }
  326. /*
  327. * Stores into `Local` objects are always simply copied into the destination with no conversion
  328. * applied, even if it contains an Object Reference.
  329. */
  330. self.method_context.as_mut().unwrap().locals[local_num as usize] = Some(value.clone());
  331. Ok(value)
  332. }
  333. Target::Null => Ok(value),
  334. }
  335. }
  336. /// Read from an operation-region, performing only standard-sized reads (supported powers-of-2 only. If a field
  337. /// is not one of these sizes, it may need to be masked, or multiple reads may need to be performed).
  338. pub(crate) fn read_region(&self, region_handle: AmlHandle, offset: u64, length: u64) -> Result<u64, AmlError> {
  339. use bit_field::BitField;
  340. use core::convert::TryInto;
  341. use value::RegionSpace;
  342. let (region_space, region_base, region_length, parent_device) = {
  343. if let AmlValue::OpRegion { region, offset, length, parent_device } =
  344. self.namespace.get(region_handle)?
  345. {
  346. (region, offset, length, parent_device)
  347. } else {
  348. return Err(AmlError::FieldRegionIsNotOpRegion);
  349. }
  350. };
  351. match region_space {
  352. RegionSpace::SystemMemory => {
  353. let address = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  354. match length {
  355. 8 => Ok(self.handler.read_u8(address) as u64),
  356. 16 => Ok(self.handler.read_u16(address) as u64),
  357. 32 => Ok(self.handler.read_u32(address) as u64),
  358. 64 => Ok(self.handler.read_u64(address)),
  359. _ => Err(AmlError::FieldInvalidAccessSize),
  360. }
  361. }
  362. RegionSpace::SystemIo => {
  363. let port = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  364. match length {
  365. 8 => Ok(self.handler.read_io_u8(port) as u64),
  366. 16 => Ok(self.handler.read_io_u16(port) as u64),
  367. 32 => Ok(self.handler.read_io_u32(port) as u64),
  368. _ => Err(AmlError::FieldInvalidAccessSize),
  369. }
  370. }
  371. RegionSpace::PciConfig => {
  372. /*
  373. * First, we need to get some extra information out of objects in the parent object. Both
  374. * `_SEG` and `_BBN` seem optional, with defaults that line up with legacy PCI implementations
  375. * (e.g. systems with a single segment group and a single root, respectively).
  376. */
  377. let parent_device = parent_device.as_ref().unwrap();
  378. let seg = match self.namespace.search(&AmlName::from_str("_SEG").unwrap(), parent_device) {
  379. Ok((_, handle)) => self
  380. .namespace
  381. .get(handle)?
  382. .as_integer(self)?
  383. .try_into()
  384. .map_err(|_| AmlError::FieldInvalidAddress)?,
  385. Err(AmlError::ValueDoesNotExist(_)) => 0,
  386. Err(err) => return Err(err),
  387. };
  388. let bbn = match self.namespace.search(&AmlName::from_str("_BBN").unwrap(), parent_device) {
  389. Ok((_, handle)) => self
  390. .namespace
  391. .get(handle)?
  392. .as_integer(self)?
  393. .try_into()
  394. .map_err(|_| AmlError::FieldInvalidAddress)?,
  395. Err(AmlError::ValueDoesNotExist(_)) => 0,
  396. Err(err) => return Err(err),
  397. };
  398. let adr = {
  399. let (_, handle) = self.namespace.search(&AmlName::from_str("_ADR").unwrap(), parent_device)?;
  400. self.namespace.get(handle)?.as_integer(self)?
  401. };
  402. let device = adr.get_bits(16..24) as u8;
  403. let function = adr.get_bits(0..8) as u8;
  404. let offset = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  405. match length {
  406. 8 => Ok(self.handler.read_pci_u8(seg, bbn, device, function, offset) as u64),
  407. 16 => Ok(self.handler.read_pci_u16(seg, bbn, device, function, offset) as u64),
  408. 32 => Ok(self.handler.read_pci_u32(seg, bbn, device, function, offset) as u64),
  409. _ => Err(AmlError::FieldInvalidAccessSize),
  410. }
  411. }
  412. // TODO
  413. _ => unimplemented!(),
  414. }
  415. }
  416. pub(crate) fn write_region(
  417. &mut self,
  418. region_handle: AmlHandle,
  419. offset: u64,
  420. length: u64,
  421. value: u64,
  422. ) -> Result<(), AmlError> {
  423. use bit_field::BitField;
  424. use core::convert::TryInto;
  425. use value::RegionSpace;
  426. let (region_space, region_base, region_length, parent_device) = {
  427. if let AmlValue::OpRegion { region, offset, length, parent_device } =
  428. self.namespace.get(region_handle)?
  429. {
  430. (region, offset, length, parent_device)
  431. } else {
  432. return Err(AmlError::FieldRegionIsNotOpRegion);
  433. }
  434. };
  435. match region_space {
  436. RegionSpace::SystemMemory => {
  437. let address = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  438. match length {
  439. 8 => Ok(self.handler.write_u8(address, value as u8)),
  440. 16 => Ok(self.handler.write_u16(address, value as u16)),
  441. 32 => Ok(self.handler.write_u32(address, value as u32)),
  442. 64 => Ok(self.handler.write_u64(address, value)),
  443. _ => Err(AmlError::FieldInvalidAccessSize),
  444. }
  445. }
  446. RegionSpace::SystemIo => {
  447. let port = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  448. match length {
  449. 8 => Ok(self.handler.write_io_u8(port, value as u8)),
  450. 16 => Ok(self.handler.write_io_u16(port, value as u16)),
  451. 32 => Ok(self.handler.write_io_u32(port, value as u32)),
  452. _ => Err(AmlError::FieldInvalidAccessSize),
  453. }
  454. }
  455. RegionSpace::PciConfig => {
  456. /*
  457. * First, we need to get some extra information out of objects in the parent object. Both
  458. * `_SEG` and `_BBN` seem optional, with defaults that line up with legacy PCI implementations
  459. * (e.g. systems with a single segment group and a single root, respectively).
  460. */
  461. let parent_device = parent_device.as_ref().unwrap();
  462. let seg = match self.namespace.search(&AmlName::from_str("_SEG").unwrap(), parent_device) {
  463. Ok((_, handle)) => self
  464. .namespace
  465. .get(handle)?
  466. .as_integer(self)?
  467. .try_into()
  468. .map_err(|_| AmlError::FieldInvalidAddress)?,
  469. Err(AmlError::ValueDoesNotExist(_)) => 0,
  470. Err(err) => return Err(err),
  471. };
  472. let bbn = match self.namespace.search(&AmlName::from_str("_BBN").unwrap(), parent_device) {
  473. Ok((_, handle)) => self
  474. .namespace
  475. .get(handle)?
  476. .as_integer(self)?
  477. .try_into()
  478. .map_err(|_| AmlError::FieldInvalidAddress)?,
  479. Err(AmlError::ValueDoesNotExist(_)) => 0,
  480. Err(err) => return Err(err),
  481. };
  482. let adr = {
  483. let (_, handle) = self.namespace.search(&AmlName::from_str("_ADR").unwrap(), parent_device)?;
  484. self.namespace.get(handle)?.as_integer(self)?
  485. };
  486. let device = adr.get_bits(16..24) as u8;
  487. let function = adr.get_bits(0..8) as u8;
  488. let offset = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  489. match length {
  490. 8 => Ok(self.handler.write_pci_u8(seg, bbn, device, function, offset, value as u8)),
  491. 16 => Ok(self.handler.write_pci_u16(seg, bbn, device, function, offset, value as u16)),
  492. 32 => Ok(self.handler.write_pci_u32(seg, bbn, device, function, offset, value as u32)),
  493. _ => Err(AmlError::FieldInvalidAccessSize),
  494. }
  495. }
  496. // TODO
  497. _ => unimplemented!(),
  498. }
  499. }
  500. fn add_predefined_objects(&mut self) {
  501. /*
  502. * These are the scopes predefined by the spec. Some tables will try to access them without defining them
  503. * themselves, and so we have to pre-create them.
  504. */
  505. self.namespace.add_level(AmlName::from_str("\\_GPE").unwrap(), LevelType::Scope).unwrap();
  506. self.namespace.add_level(AmlName::from_str("\\_SB").unwrap(), LevelType::Scope).unwrap();
  507. self.namespace.add_level(AmlName::from_str("\\_SI").unwrap(), LevelType::Scope).unwrap();
  508. self.namespace.add_level(AmlName::from_str("\\_PR").unwrap(), LevelType::Scope).unwrap();
  509. self.namespace.add_level(AmlName::from_str("\\_TZ").unwrap(), LevelType::Scope).unwrap();
  510. /*
  511. * In the dark ages of ACPI 1.0, before `\_OSI`, `\_OS` was used to communicate to the firmware which OS
  512. * was running. This was predictably not very good, and so was replaced in ACPI 3.0 with `_OSI`, which
  513. * allows support for individual capabilities to be queried. `_OS` should not be used by modern firmwares,
  514. * but to avoid problems we follow Linux in returning `"Microsoft Windows NT"`.
  515. *
  516. * See https://www.kernel.org/doc/html/latest/firmware-guide/acpi/osi.html for more information.
  517. */
  518. self.namespace
  519. .add_value(AmlName::from_str("\\_OS").unwrap(), AmlValue::String("Microsoft Windows NT".to_string()))
  520. .unwrap();
  521. /*
  522. * `\_OSI` was introduced by ACPI 3.0 to improve the situation created by `\_OS`. Unfortunately, exactly
  523. * the same problem was immediately repeated by introducing capabilities reflecting that an ACPI
  524. * implementation is exactly the same as a particular version of Windows' (e.g. firmwares will call
  525. * `\_OSI("Windows 2001")`).
  526. *
  527. * We basically follow suit with whatever Linux does, as this will hopefully minimise breakage:
  528. * - We always claim `Windows *` compatability
  529. * - We answer 'yes' to `_OSI("Darwin")
  530. * - We answer 'no' to `_OSI("Linux")`, and report that the tables are doing the wrong thing
  531. */
  532. self.namespace
  533. .add_value(
  534. AmlName::from_str("\\_OSI").unwrap(),
  535. AmlValue::native_method(1, false, 0, |context| {
  536. Ok(match context.current_arg(0)?.as_string(context)?.as_str() {
  537. "Windows 2000" => true, // 2000
  538. "Windows 2001" => true, // XP
  539. "Windows 2001 SP1" => true, // XP SP1
  540. "Windows 2001 SP2" => true, // XP SP2
  541. "Windows 2001.1" => true, // Server 2003
  542. "Windows 2001.1 SP1" => true, // Server 2003 SP1
  543. "Windows 2006" => true, // Vista
  544. "Windows 2006 SP1" => true, // Vista SP1
  545. "Windows 2006 SP2" => true, // Vista SP2
  546. "Windows 2006.1" => true, // Server 2008
  547. "Windows 2009" => true, // 7 and Server 2008 R2
  548. "Windows 2012" => true, // 8 and Server 2012
  549. "Windows 2013" => true, // 8.1 and Server 2012 R2
  550. "Windows 2015" => true, // 10
  551. "Windows 2016" => true, // 10 version 1607
  552. "Windows 2017" => true, // 10 version 1703
  553. "Windows 2017.2" => true, // 10 version 1709
  554. "Windows 2018" => true, // 10 version 1803
  555. "Windows 2018.2" => true, // 10 version 1809
  556. "Windows 2019" => true, // 10 version 1903
  557. "Darwin" => true,
  558. "Linux" => {
  559. // TODO: should we allow users to specify that this should be true? Linux has a
  560. // command line option for this.
  561. warn!("ACPI evaluated `_OSI(\"Linux\")`. This is a bug. Reporting no support.");
  562. false
  563. }
  564. "Extended Address Space Descriptor" => true,
  565. // TODO: support module devices
  566. "Module Device" => false,
  567. "3.0 Thermal Model" => true,
  568. "3.0 _SCP Extensions" => true,
  569. // TODO: support processor aggregator devices
  570. "Processor Aggregator Device" => false,
  571. _ => false,
  572. }
  573. .then_some(AmlValue::ones())
  574. .unwrap_or(AmlValue::zero()))
  575. }),
  576. )
  577. .unwrap();
  578. /*
  579. * `\_REV` evaluates to the version of the ACPI specification supported by this interpreter. Linux did this
  580. * correctly until 2015, but firmwares misused this to detect Linux (as even modern versions of Windows
  581. * return `2`), and so they switched to just returning `2` (as we'll also do). `_REV` should be considered
  582. * useless and deprecated (this is mirrored in newer specs, which claim `2` means "ACPI 2 or greater").
  583. */
  584. self.namespace.add_value(AmlName::from_str("\\_REV").unwrap(), AmlValue::Integer(2)).unwrap();
  585. }
  586. }
  587. // TODO: docs
  588. pub trait Handler: Send + Sync {
  589. fn read_u8(&self, address: usize) -> u8;
  590. fn read_u16(&self, address: usize) -> u16;
  591. fn read_u32(&self, address: usize) -> u32;
  592. fn read_u64(&self, address: usize) -> u64;
  593. fn write_u8(&mut self, address: usize, value: u8);
  594. fn write_u16(&mut self, address: usize, value: u16);
  595. fn write_u32(&mut self, address: usize, value: u32);
  596. fn write_u64(&mut self, address: usize, value: u64);
  597. fn read_io_u8(&self, port: u16) -> u8;
  598. fn read_io_u16(&self, port: u16) -> u16;
  599. fn read_io_u32(&self, port: u16) -> u32;
  600. fn write_io_u8(&self, port: u16, value: u8);
  601. fn write_io_u16(&self, port: u16, value: u16);
  602. fn write_io_u32(&self, port: u16, value: u32);
  603. fn read_pci_u8(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u8;
  604. fn read_pci_u16(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u16;
  605. fn read_pci_u32(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u32;
  606. fn write_pci_u8(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u8);
  607. fn write_pci_u16(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u16);
  608. fn write_pci_u32(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u32);
  609. fn handle_fatal_error(&self, fatal_type: u8, fatal_code: u32, fatal_arg: u64) {
  610. panic!("Fatal error while executing AML (encountered DefFatal op). fatal_type = {:?}, fatal_code = {:?}, fatal_arg = {:?}", fatal_type, fatal_code, fatal_arg);
  611. }
  612. }
  613. #[derive(Clone, PartialEq, Eq, Debug)]
  614. pub enum AmlError {
  615. /*
  616. * Errors produced parsing the AML stream.
  617. */
  618. UnexpectedEndOfStream,
  619. UnexpectedByte(u8),
  620. /// Produced when the stream evaluates to something other than nothing or an error.
  621. MalformedStream,
  622. InvalidNameSeg,
  623. InvalidPkgLength,
  624. InvalidFieldFlags,
  625. UnterminatedStringConstant,
  626. InvalidStringConstant,
  627. InvalidRegionSpace(u8),
  628. /// Produced when a `DefPackage` contains a different number of elements to the package's length.
  629. MalformedPackage,
  630. /// Produced when a `DefBuffer` contains more bytes that its size.
  631. MalformedBuffer,
  632. /// Emitted by a parser when it's clear that the stream doesn't encode the object parsed by
  633. /// that parser (e.g. the wrong opcode starts the stream). This is handled specially by some
  634. /// parsers such as `or` and `choice!`.
  635. WrongParser,
  636. /// Returned when a `DefFatal` op is encountered. This is separately reported using [`Handler::handle_fatal_error`].
  637. FatalError,
  638. /*
  639. * Errors produced manipulating AML names.
  640. */
  641. EmptyNamesAreInvalid,
  642. /// Produced when trying to normalize a path that does not point to a valid level of the
  643. /// namespace. E.g. `\_SB.^^PCI0` goes above the root of the namespace. The contained value is the name that
  644. /// normalization was attempted upon.
  645. InvalidNormalizedName(AmlName),
  646. RootHasNoParent,
  647. /*
  648. * Errors produced working with the namespace.
  649. */
  650. /// Produced when a sub-level or value is added to a level that has not yet been added to the namespace. The
  651. /// `AmlName` is the name of the entire sub-level/value.
  652. LevelDoesNotExist(AmlName),
  653. ValueDoesNotExist(AmlName),
  654. /// Produced when two values with the same name are added to the namespace.
  655. NameCollision(AmlName),
  656. TriedToRemoveRootNamespace,
  657. /*
  658. * Errors produced executing control methods.
  659. */
  660. /// Produced when AML tries to do something only possible in a control method (e.g. read from an argument)
  661. /// when there's no control method executing.
  662. NotExecutingControlMethod,
  663. /// Produced when a method accesses an argument it does not have (e.g. a method that takes 2
  664. /// arguments accesses `Arg4`). The inner value is the number of the argument accessed.
  665. InvalidArgAccess(ArgNum),
  666. /// Produced when a method accesses a local that it has not stored into.
  667. InvalidLocalAccess(LocalNum),
  668. /// Tried to invoke a method with too many arguments.
  669. TooManyArgs,
  670. /// A `DefBreak` operation was performed outside of a `DefWhile` or `DefSwitch`.
  671. BreakInInvalidPosition,
  672. /// A `DefContinue` operation was performed outside of a `DefWhile`.
  673. ContinueInInvalidPosition,
  674. /*
  675. * Errors produced parsing the PCI routing tables (_PRT objects).
  676. */
  677. PrtInvalidAddress,
  678. PrtInvalidPin,
  679. PrtInvalidSource,
  680. PrtInvalidGsi,
  681. /// Produced when the PRT doesn't contain an entry for the requested address + pin
  682. PrtNoEntry,
  683. /*
  684. * Errors produced parsing Resource Descriptors.
  685. */
  686. ReservedResourceType,
  687. ResourceDescriptorTooShort,
  688. ResourceDescriptorTooLong,
  689. UnexpectedResourceType,
  690. /*
  691. * Errors produced working with AML values.
  692. */
  693. IncompatibleValueConversion {
  694. current: AmlType,
  695. target: AmlType,
  696. },
  697. InvalidStatusObject,
  698. InvalidShiftLeft,
  699. InvalidShiftRight,
  700. FieldRegionIsNotOpRegion,
  701. FieldInvalidAddress,
  702. FieldInvalidAccessSize,
  703. TypeCannotBeCompared(AmlType),
  704. /// Produced when the `Mid` operator is applied to a value of a type other than `Buffer` or `String`.
  705. TypeCannotBeSliced(AmlType),
  706. TypeCannotBeWrittenToBufferField(AmlType),
  707. BufferFieldIndexesOutOfBounds,
  708. }
  709. #[cfg(test)]
  710. mod tests {
  711. use super::*;
  712. #[test]
  713. fn test_send_sync() {
  714. // verify that AmlContext implements Send and Sync
  715. fn test_send_sync<T: Send + Sync>() {}
  716. test_send_sync::<AmlContext>();
  717. }
  718. }