lib.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. //!
  19. //! ### About the parser
  20. //! The parser is written using a set of custom parser combinators - the code can be confusing on
  21. //! first reading, but provides an extensible and type-safe way to write parsers. For an easy
  22. //! introduction to parser combinators and the foundations used for this library, I suggest reading
  23. //! [Bodil's fantastic blog post](https://bodil.lol/parser-combinators/).
  24. //!
  25. //! The actual combinators can be found in `parser.rs`. Various tricks are used to provide a nice
  26. //! API and work around limitations in the type system, such as the concrete types like
  27. //! `MapWithContext`, and the `make_parser_concrete` hack macro.
  28. //!
  29. //! The actual parsers are then grouped into categories based loosely on the AML grammar sections in
  30. //! the ACPI spec. Most are written in terms of combinators, but some have to be written in a more
  31. //! imperitive style, either because they're clearer, or because we haven't yet found good
  32. //! combinator patterns to express the parse.
  33. #![no_std]
  34. #![feature(decl_macro, type_ascription, box_syntax)]
  35. extern crate alloc;
  36. #[cfg(test)]
  37. extern crate std;
  38. #[cfg(test)]
  39. mod test_utils;
  40. pub(crate) mod misc;
  41. pub(crate) mod name_object;
  42. pub(crate) mod namespace;
  43. pub(crate) mod opcode;
  44. pub(crate) mod parser;
  45. pub mod pci_routing;
  46. pub(crate) mod pkg_length;
  47. pub mod resource;
  48. pub(crate) mod term_object;
  49. pub(crate) mod type1;
  50. pub(crate) mod type2;
  51. pub mod value;
  52. pub use crate::{
  53. namespace::{AmlHandle, AmlName, Namespace},
  54. value::AmlValue,
  55. };
  56. use alloc::boxed::Box;
  57. use core::mem;
  58. use log::error;
  59. use misc::{ArgNum, LocalNum};
  60. use name_object::Target;
  61. use namespace::LevelType;
  62. use parser::Parser;
  63. use pkg_length::PkgLength;
  64. use term_object::term_list;
  65. use value::{AmlType, Args};
  66. /// AML has a `RevisionOp` operator that returns the "AML interpreter revision". It's not clear
  67. /// what this is actually used for, but this is ours.
  68. pub const AML_INTERPRETER_REVISION: u64 = 0;
  69. /// Describes how much debug information the parser should emit. Set the "maximum" expected verbosity in
  70. /// the context's `debug_verbosity` - everything will be printed that is less or equal in 'verbosity'.
  71. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
  72. pub enum DebugVerbosity {
  73. /// Print no debug information
  74. None,
  75. /// Print heads and tails when entering and leaving scopes of major objects, but not more minor ones.
  76. Scopes,
  77. /// Print heads and tails when entering and leaving scopes of all objects.
  78. AllScopes,
  79. /// Print heads and tails of all objects, and extra debug information as it's parsed.
  80. All,
  81. }
  82. struct MethodContext {
  83. /*
  84. * AML local variables. These are used when we invoke a control method. A `None` value
  85. * represents a null AML object.
  86. */
  87. local_0: Option<AmlValue>,
  88. local_1: Option<AmlValue>,
  89. local_2: Option<AmlValue>,
  90. local_3: Option<AmlValue>,
  91. local_4: Option<AmlValue>,
  92. local_5: Option<AmlValue>,
  93. local_6: Option<AmlValue>,
  94. local_7: Option<AmlValue>,
  95. /// If we're currently invoking a control method, this stores the arguments that were passed to
  96. /// it. It's `None` if we aren't invoking a method.
  97. args: Args,
  98. }
  99. impl MethodContext {
  100. fn new(args: Args) -> MethodContext {
  101. MethodContext {
  102. local_0: None,
  103. local_1: None,
  104. local_2: None,
  105. local_3: None,
  106. local_4: None,
  107. local_5: None,
  108. local_6: None,
  109. local_7: None,
  110. args,
  111. }
  112. }
  113. }
  114. pub struct AmlContext {
  115. /// The `Handler` passed from the library user. This is stored as a boxed trait object simply to avoid having
  116. /// to add a lifetime and type parameter to `AmlContext`, as they would massively complicate the parser types.
  117. handler: Box<dyn Handler>,
  118. legacy_mode: bool,
  119. pub namespace: Namespace,
  120. method_context: Option<MethodContext>,
  121. /*
  122. * These track the state of the context while it's parsing an AML table.
  123. */
  124. current_scope: AmlName,
  125. scope_indent: usize,
  126. debug_verbosity: DebugVerbosity,
  127. }
  128. impl AmlContext {
  129. /// Creates a new `AmlContext` - the central type in managing the AML tables. Only one of these should be
  130. /// created, and it should be passed the DSDT and all SSDTs defined by the hardware.
  131. ///
  132. /// ### Legacy mode
  133. /// If `true` is passed in `legacy_mode`, the library will try and remain compatible with a ACPI 1.0
  134. /// implementation. The following changes/assumptions are made:
  135. /// - Two extra root namespaces are predefined: `\_PR` and `_TZ`
  136. /// - Processors are expected to be defined with `DefProcessor`, instead of `DefDevice`
  137. /// - Processors are expected to be found in `\_PR`, instead of `\_SB`
  138. /// - Thermal zones are expected to be found in `\_TZ`, instead of `\_SB`
  139. pub fn new(handler: Box<dyn Handler>, legacy_mode: bool, debug_verbosity: DebugVerbosity) -> AmlContext {
  140. let mut context = AmlContext {
  141. handler,
  142. legacy_mode,
  143. namespace: Namespace::new(),
  144. method_context: None,
  145. current_scope: AmlName::root(),
  146. scope_indent: 0,
  147. debug_verbosity,
  148. };
  149. /*
  150. * Add the predefined root namespaces.
  151. */
  152. context.namespace.add_level(AmlName::from_str("\\_GPE").unwrap(), LevelType::Scope).unwrap();
  153. context.namespace.add_level(AmlName::from_str("\\_SB").unwrap(), LevelType::Scope).unwrap();
  154. context.namespace.add_level(AmlName::from_str("\\_SI").unwrap(), LevelType::Scope).unwrap();
  155. if legacy_mode {
  156. context.namespace.add_level(AmlName::from_str("\\_PR").unwrap(), LevelType::Scope).unwrap();
  157. context.namespace.add_level(AmlName::from_str("\\_TZ").unwrap(), LevelType::Scope).unwrap();
  158. }
  159. context
  160. }
  161. pub fn parse_table(&mut self, stream: &[u8]) -> Result<(), AmlError> {
  162. if stream.len() == 0 {
  163. return Err(AmlError::UnexpectedEndOfStream);
  164. }
  165. let table_length = PkgLength::from_raw_length(stream, stream.len() as u32).unwrap();
  166. match term_object::term_list(table_length).parse(stream, self) {
  167. Ok(_) => Ok(()),
  168. Err((_, _, err)) => {
  169. error!("Failed to parse AML stream. Err = {:?}", err);
  170. Err(err)
  171. }
  172. }
  173. }
  174. pub fn invoke_method(&mut self, path: &AmlName, args: Args) -> Result<AmlValue, AmlError> {
  175. match self.namespace.get_by_path(path)?.clone() {
  176. AmlValue::Method { flags, code } => {
  177. /*
  178. * First, set up the state we expect to enter the method with, but clearing local
  179. * variables to "null" and setting the arguments. Save the current method state and scope, so if we're
  180. * already executing another control method, we resume into it correctly.
  181. */
  182. let old_context = mem::replace(&mut self.method_context, Some(MethodContext::new(args)));
  183. let old_scope = mem::replace(&mut self.current_scope, path.clone());
  184. /*
  185. * Create a namespace level to store local objects created by the invocation.
  186. */
  187. self.namespace.add_level(path.clone(), LevelType::MethodLocals)?;
  188. let return_value = match term_list(PkgLength::from_raw_length(&code, code.len() as u32).unwrap())
  189. .parse(&code, self)
  190. {
  191. // If the method doesn't return a value, we implicitly return `0`
  192. Ok(_) => Ok(AmlValue::Integer(0)),
  193. Err((_, _, AmlError::Return(result))) => Ok(result),
  194. Err((_, _, err)) => {
  195. error!("Failed to execute control method: {:?}", err);
  196. Err(err)
  197. }
  198. };
  199. /*
  200. * Locally-created objects should be destroyed on method exit (see §5.5.2.3 of the ACPI spec). We do
  201. * this by simply removing the method's local object layer.
  202. */
  203. // TODO: this should also remove objects created by the method outside the method's scope, if they
  204. // weren't statically created. This is harder.
  205. self.namespace.remove_level(path.clone())?;
  206. /*
  207. * Restore the old state.
  208. */
  209. self.method_context = old_context;
  210. self.current_scope = old_scope;
  211. return_value
  212. }
  213. /*
  214. * AML can encode methods that don't require any computation simply as the value that would otherwise be
  215. * returned (e.g. a `_STA` object simply being an `AmlValue::Integer`, instead of a method that just
  216. * returns an integer).
  217. */
  218. value => Ok(value),
  219. }
  220. }
  221. pub fn initialize_objects(&mut self) -> Result<(), AmlError> {
  222. use name_object::NameSeg;
  223. use namespace::NamespaceLevel;
  224. use value::StatusObject;
  225. /*
  226. * If `\_SB._INI` exists, we unconditionally execute it at the beginning of device initialization.
  227. */
  228. match self.invoke_method(&AmlName::from_str("\\_SB._INI").unwrap(), Args::default()) {
  229. Ok(_) => (),
  230. Err(AmlError::ValueDoesNotExist(_)) => (),
  231. Err(err) => return Err(err),
  232. }
  233. /*
  234. * Next, we traverse the namespace, looking for devices.
  235. *
  236. * XXX: we clone the namespace here, which obviously drives up heap burden quite a bit (not as much as you
  237. * might first expect though - we're only duplicating the level data structure, not all the objects). The
  238. * issue here is that we need to access the namespace during traversal (e.g. to invoke a method), which the
  239. * borrow checker really doesn't like. A better solution could be a iterator-like traversal system that
  240. * keeps track of the namespace without keeping it borrowed. This works for now.
  241. */
  242. self.namespace.clone().traverse(|path, level: &NamespaceLevel| match level.typ {
  243. LevelType::Device => {
  244. let status = if level.values.contains_key(&NameSeg::from_str("_STA").unwrap()) {
  245. self.invoke_method(&AmlName::from_str("_STA").unwrap().resolve(&path)?, Args::default())?
  246. .as_status()?
  247. } else {
  248. StatusObject::default()
  249. };
  250. /*
  251. * If the device is present and has an `_INI` method, invoke it.
  252. */
  253. if status.present && level.values.contains_key(&NameSeg::from_str("_INI").unwrap()) {
  254. log::info!("Invoking _INI at level: {}", path);
  255. self.invoke_method(&AmlName::from_str("_INI").unwrap().resolve(&path)?, Args::default())?;
  256. }
  257. /*
  258. * We traverse the children of this device if it's present, or isn't present but is functional.
  259. */
  260. Ok(status.present || status.functional)
  261. }
  262. LevelType::Scope => Ok(true),
  263. // TODO: can either of these contain devices?
  264. LevelType::Processor => Ok(false),
  265. LevelType::MethodLocals => Ok(false),
  266. })?;
  267. Ok(())
  268. }
  269. /// Get the value of an argument by its argument number. Can only be executed from inside a control method.
  270. pub(crate) fn current_arg(&self, arg: ArgNum) -> Result<&AmlValue, AmlError> {
  271. self.method_context.as_ref().ok_or(AmlError::NotExecutingControlMethod)?.args.arg(arg)
  272. }
  273. /// Get the current value of a local by its local number. Can only be executed from inside a control method.
  274. pub(crate) fn local(&self, local: LocalNum) -> Result<&AmlValue, AmlError> {
  275. if let None = self.method_context {
  276. return Err(AmlError::NotExecutingControlMethod);
  277. }
  278. match local {
  279. 0 => self.method_context.as_ref().unwrap().local_0.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  280. 1 => self.method_context.as_ref().unwrap().local_1.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  281. 2 => self.method_context.as_ref().unwrap().local_2.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  282. 3 => self.method_context.as_ref().unwrap().local_3.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  283. 4 => self.method_context.as_ref().unwrap().local_4.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  284. 5 => self.method_context.as_ref().unwrap().local_5.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  285. 6 => self.method_context.as_ref().unwrap().local_6.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  286. 7 => self.method_context.as_ref().unwrap().local_7.as_ref().ok_or(AmlError::InvalidLocalAccess(local)),
  287. _ => Err(AmlError::InvalidLocalAccess(local)),
  288. }
  289. }
  290. /// Perform a store into a `Target`. This returns a value read out of the target, if neccessary, as values can
  291. /// be altered during a store in some circumstances. If the target is a `Name`, this also performs required
  292. /// implicit conversions. Stores to other targets are semantically equivalent to a `CopyObject`.
  293. pub(crate) fn store(&mut self, target: Target, value: AmlValue) -> Result<AmlValue, AmlError> {
  294. match target {
  295. Target::Name(ref path) => {
  296. let (_, handle) = self.namespace.search(path, &self.current_scope)?;
  297. let converted_object = match self.namespace.get(handle).unwrap().type_of() {
  298. /*
  299. * We special-case FieldUnits here because we don't have the needed information to actually do
  300. * the write if we try and convert using `as_type`.
  301. */
  302. AmlType::FieldUnit => {
  303. let mut field = self.namespace.get(handle).unwrap().clone();
  304. field.write_field(value, self)?;
  305. field.read_field(self)?
  306. }
  307. typ => value.as_type(typ, self)?,
  308. };
  309. *self.namespace.get_mut(handle)? = converted_object;
  310. Ok(self.namespace.get(handle)?.clone())
  311. }
  312. Target::Debug => {
  313. // TODO
  314. unimplemented!()
  315. }
  316. Target::Arg(arg_num) => {
  317. if let None = self.method_context {
  318. return Err(AmlError::NotExecutingControlMethod);
  319. }
  320. match arg_num {
  321. 1 => self.method_context.as_mut().unwrap().args.arg_1 = Some(value.clone()),
  322. 2 => self.method_context.as_mut().unwrap().args.arg_2 = Some(value.clone()),
  323. 3 => self.method_context.as_mut().unwrap().args.arg_3 = Some(value.clone()),
  324. 4 => self.method_context.as_mut().unwrap().args.arg_4 = Some(value.clone()),
  325. 5 => self.method_context.as_mut().unwrap().args.arg_5 = Some(value.clone()),
  326. 6 => self.method_context.as_mut().unwrap().args.arg_6 = Some(value.clone()),
  327. _ => return Err(AmlError::InvalidArgAccess(arg_num)),
  328. }
  329. Ok(value)
  330. }
  331. Target::Local(local_num) => {
  332. if let None = self.method_context {
  333. return Err(AmlError::NotExecutingControlMethod);
  334. }
  335. match local_num {
  336. 0 => self.method_context.as_mut().unwrap().local_0 = Some(value.clone()),
  337. 1 => self.method_context.as_mut().unwrap().local_1 = Some(value.clone()),
  338. 2 => self.method_context.as_mut().unwrap().local_2 = Some(value.clone()),
  339. 3 => self.method_context.as_mut().unwrap().local_3 = Some(value.clone()),
  340. 4 => self.method_context.as_mut().unwrap().local_4 = Some(value.clone()),
  341. 5 => self.method_context.as_mut().unwrap().local_5 = Some(value.clone()),
  342. 6 => self.method_context.as_mut().unwrap().local_6 = Some(value.clone()),
  343. 7 => self.method_context.as_mut().unwrap().local_7 = Some(value.clone()),
  344. _ => return Err(AmlError::InvalidLocalAccess(local_num)),
  345. }
  346. Ok(value)
  347. }
  348. Target::Null => Ok(value),
  349. }
  350. }
  351. /// Read from an operation-region, performing only standard-sized reads (supported powers-of-2 only. If a field
  352. /// is not one of these sizes, it may need to be masked, or multiple reads may need to be performed).
  353. pub(crate) fn read_region(&self, region_handle: AmlHandle, offset: u64, length: u64) -> Result<u64, AmlError> {
  354. use bit_field::BitField;
  355. use core::convert::TryInto;
  356. use value::RegionSpace;
  357. let (region_space, region_base, region_length, parent_device) = {
  358. if let AmlValue::OpRegion { region, offset, length, parent_device } =
  359. self.namespace.get(region_handle)?
  360. {
  361. (region, offset, length, parent_device)
  362. } else {
  363. return Err(AmlError::FieldRegionIsNotOpRegion);
  364. }
  365. };
  366. match region_space {
  367. RegionSpace::SystemMemory => {
  368. let address = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  369. match length {
  370. 8 => Ok(self.handler.read_u8(address) as u64),
  371. 16 => Ok(self.handler.read_u16(address) as u64),
  372. 32 => Ok(self.handler.read_u32(address) as u64),
  373. 64 => Ok(self.handler.read_u64(address)),
  374. _ => Err(AmlError::FieldInvalidAccessSize),
  375. }
  376. }
  377. RegionSpace::SystemIo => {
  378. let port = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  379. match length {
  380. 8 => Ok(self.handler.read_io_u8(port) as u64),
  381. 16 => Ok(self.handler.read_io_u16(port) as u64),
  382. 32 => Ok(self.handler.read_io_u32(port) as u64),
  383. _ => Err(AmlError::FieldInvalidAccessSize),
  384. }
  385. }
  386. RegionSpace::PciConfig => {
  387. /*
  388. * First, we need to get some extra information out of objects in the parent object. Both
  389. * `_SEG` and `_BBN` seem optional, with defaults that line up with legacy PCI implementations
  390. * (e.g. systems with a single segment group and a single root, respectively).
  391. */
  392. let parent_device = parent_device.as_ref().unwrap();
  393. let seg = match self.namespace.search(&AmlName::from_str("_SEG").unwrap(), parent_device) {
  394. Ok((_, handle)) => self
  395. .namespace
  396. .get(handle)?
  397. .as_integer(self)?
  398. .try_into()
  399. .map_err(|_| AmlError::FieldInvalidAddress)?,
  400. Err(AmlError::ValueDoesNotExist(_)) => 0,
  401. Err(err) => return Err(err),
  402. };
  403. let bbn = match self.namespace.search(&AmlName::from_str("_BBN").unwrap(), parent_device) {
  404. Ok((_, handle)) => self
  405. .namespace
  406. .get(handle)?
  407. .as_integer(self)?
  408. .try_into()
  409. .map_err(|_| AmlError::FieldInvalidAddress)?,
  410. Err(AmlError::ValueDoesNotExist(_)) => 0,
  411. Err(err) => return Err(err),
  412. };
  413. let adr = {
  414. let (_, handle) = self.namespace.search(&AmlName::from_str("_ADR").unwrap(), parent_device)?;
  415. self.namespace.get(handle)?.as_integer(self)?
  416. };
  417. let device = adr.get_bits(16..24) as u8;
  418. let function = adr.get_bits(0..8) as u8;
  419. let offset = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  420. match length {
  421. 8 => Ok(self.handler.read_pci_u8(seg, bbn, device, function, offset) as u64),
  422. 16 => Ok(self.handler.read_pci_u16(seg, bbn, device, function, offset) as u64),
  423. 32 => Ok(self.handler.read_pci_u32(seg, bbn, device, function, offset) as u64),
  424. _ => Err(AmlError::FieldInvalidAccessSize),
  425. }
  426. }
  427. // TODO
  428. _ => unimplemented!(),
  429. }
  430. }
  431. pub(crate) fn write_region(
  432. &mut self,
  433. region_handle: AmlHandle,
  434. offset: u64,
  435. length: u64,
  436. value: u64,
  437. ) -> Result<(), AmlError> {
  438. use bit_field::BitField;
  439. use core::convert::TryInto;
  440. use value::RegionSpace;
  441. let (region_space, region_base, region_length, parent_device) = {
  442. if let AmlValue::OpRegion { region, offset, length, parent_device } =
  443. self.namespace.get(region_handle)?
  444. {
  445. (region, offset, length, parent_device)
  446. } else {
  447. return Err(AmlError::FieldRegionIsNotOpRegion);
  448. }
  449. };
  450. match region_space {
  451. RegionSpace::SystemMemory => {
  452. let address = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  453. match length {
  454. 8 => Ok(self.handler.write_u8(address, value as u8)),
  455. 16 => Ok(self.handler.write_u16(address, value as u16)),
  456. 32 => Ok(self.handler.write_u32(address, value as u32)),
  457. 64 => Ok(self.handler.write_u64(address, value)),
  458. _ => Err(AmlError::FieldInvalidAccessSize),
  459. }
  460. }
  461. RegionSpace::SystemIo => {
  462. let port = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  463. match length {
  464. 8 => Ok(self.handler.write_io_u8(port, value as u8)),
  465. 16 => Ok(self.handler.write_io_u16(port, value as u16)),
  466. 32 => Ok(self.handler.write_io_u32(port, value as u32)),
  467. _ => Err(AmlError::FieldInvalidAccessSize),
  468. }
  469. }
  470. RegionSpace::PciConfig => {
  471. /*
  472. * First, we need to get some extra information out of objects in the parent object. Both
  473. * `_SEG` and `_BBN` seem optional, with defaults that line up with legacy PCI implementations
  474. * (e.g. systems with a single segment group and a single root, respectively).
  475. */
  476. let parent_device = parent_device.as_ref().unwrap();
  477. let seg = match self.namespace.search(&AmlName::from_str("_SEG").unwrap(), parent_device) {
  478. Ok((_, handle)) => self
  479. .namespace
  480. .get(handle)?
  481. .as_integer(self)?
  482. .try_into()
  483. .map_err(|_| AmlError::FieldInvalidAddress)?,
  484. Err(AmlError::ValueDoesNotExist(_)) => 0,
  485. Err(err) => return Err(err),
  486. };
  487. let bbn = match self.namespace.search(&AmlName::from_str("_BBN").unwrap(), parent_device) {
  488. Ok((_, handle)) => self
  489. .namespace
  490. .get(handle)?
  491. .as_integer(self)?
  492. .try_into()
  493. .map_err(|_| AmlError::FieldInvalidAddress)?,
  494. Err(AmlError::ValueDoesNotExist(_)) => 0,
  495. Err(err) => return Err(err),
  496. };
  497. let adr = {
  498. let (_, handle) = self.namespace.search(&AmlName::from_str("_ADR").unwrap(), parent_device)?;
  499. self.namespace.get(handle)?.as_integer(self)?
  500. };
  501. let device = adr.get_bits(16..24) as u8;
  502. let function = adr.get_bits(0..8) as u8;
  503. let offset = (region_base + offset).try_into().map_err(|_| AmlError::FieldInvalidAddress)?;
  504. match length {
  505. 8 => Ok(self.handler.write_pci_u8(seg, bbn, device, function, offset, value as u8)),
  506. 16 => Ok(self.handler.write_pci_u16(seg, bbn, device, function, offset, value as u16)),
  507. 32 => Ok(self.handler.write_pci_u32(seg, bbn, device, function, offset, value as u32)),
  508. _ => Err(AmlError::FieldInvalidAccessSize),
  509. }
  510. }
  511. // TODO
  512. _ => unimplemented!(),
  513. }
  514. }
  515. }
  516. pub trait Handler {
  517. fn read_u8(&self, address: usize) -> u8;
  518. fn read_u16(&self, address: usize) -> u16;
  519. fn read_u32(&self, address: usize) -> u32;
  520. fn read_u64(&self, address: usize) -> u64;
  521. fn write_u8(&mut self, address: usize, value: u8);
  522. fn write_u16(&mut self, address: usize, value: u16);
  523. fn write_u32(&mut self, address: usize, value: u32);
  524. fn write_u64(&mut self, address: usize, value: u64);
  525. fn read_io_u8(&self, port: u16) -> u8;
  526. fn read_io_u16(&self, port: u16) -> u16;
  527. fn read_io_u32(&self, port: u16) -> u32;
  528. fn write_io_u8(&self, port: u16, value: u8);
  529. fn write_io_u16(&self, port: u16, value: u16);
  530. fn write_io_u32(&self, port: u16, value: u32);
  531. fn read_pci_u8(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u8;
  532. fn read_pci_u16(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u16;
  533. fn read_pci_u32(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16) -> u32;
  534. fn write_pci_u8(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u8);
  535. fn write_pci_u16(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u16);
  536. fn write_pci_u32(&self, segment: u16, bus: u8, device: u8, function: u8, offset: u16, value: u32);
  537. }
  538. #[derive(Clone, Debug, PartialEq, Eq)]
  539. pub enum AmlError {
  540. /*
  541. * Errors produced parsing the AML stream.
  542. */
  543. UnexpectedEndOfStream,
  544. UnexpectedByte(u8),
  545. InvalidNameSeg,
  546. InvalidPkgLength,
  547. InvalidFieldFlags,
  548. IncompatibleValueConversion,
  549. UnterminatedStringConstant,
  550. InvalidStringConstant,
  551. InvalidRegionSpace(u8),
  552. /// Produced when a `DefPackage` contains a different number of elements to the package's length.
  553. InvalidPackage,
  554. /// Produced when a `DefBuffer` contains more bytes that its size.
  555. MalformedBuffer,
  556. /// Emitted by a parser when it's clear that the stream doesn't encode the object parsed by
  557. /// that parser (e.g. the wrong opcode starts the stream). This is handled specially by some
  558. /// parsers such as `or` and `choice!`.
  559. WrongParser,
  560. /*
  561. * Errors produced manipulating AML names.
  562. */
  563. EmptyNamesAreInvalid,
  564. /// Produced when trying to normalize a path that does not point to a valid level of the
  565. /// namespace. E.g. `\_SB.^^PCI0` goes above the root of the namespace. The contained value is the name that
  566. /// normalization was attempted upon.
  567. InvalidNormalizedName(AmlName),
  568. RootHasNoParent,
  569. /*
  570. * Errors produced working with the namespace.
  571. */
  572. /// Produced when a sub-level or value is added to a level that has not yet been added to the namespace. The
  573. /// `AmlName` is the name of the entire sub-level/value.
  574. LevelDoesNotExist(AmlName),
  575. ValueDoesNotExist(AmlName),
  576. /// Produced when two values with the same name are added to the namespace.
  577. NameCollision(AmlName),
  578. TriedToRemoveRootNamespace,
  579. /*
  580. * Errors produced executing control methods.
  581. */
  582. /// Produced when AML tries to do something only possible in a control method (e.g. read from an argument)
  583. /// when there's no control method executing.
  584. NotExecutingControlMethod,
  585. /// Produced when a method accesses an argument it does not have (e.g. a method that takes 2
  586. /// arguments accesses `Arg4`). The inner value is the number of the argument accessed.
  587. InvalidArgAccess(ArgNum),
  588. /// Produced when a method accesses a local that it has not stored into.
  589. InvalidLocalAccess(LocalNum),
  590. /// This is not a real error, but is used to propagate return values from within the deep
  591. /// parsing call-stack. It should only be emitted when parsing a `DefReturn`. We use the
  592. /// error system here because the way errors are propagated matches how we want to handle
  593. /// return values.
  594. Return(AmlValue),
  595. /*
  596. * Errors produced parsing the PCI routing tables (_PRT objects).
  597. */
  598. PrtInvalidAddress,
  599. PrtInvalidPin,
  600. PrtInvalidSource,
  601. PrtInvalidGsi,
  602. /// Produced when the PRT doesn't contain an entry for the requested address + pin
  603. PrtNoEntry,
  604. /*
  605. * Errors produced parsing Resource Descriptors.
  606. */
  607. ReservedResourceType,
  608. ResourceDescriptorTooShort,
  609. ResourceDescriptorTooLong,
  610. /*
  611. * Errors produced working with AML values.
  612. */
  613. InvalidStatusObject,
  614. InvalidShiftLeft,
  615. InvalidShiftRight,
  616. FieldRegionIsNotOpRegion,
  617. FieldInvalidAddress,
  618. FieldInvalidAccessSize,
  619. TypeCannotBeCompared(AmlType),
  620. }