module.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. // SPDX-License-Identifier: GPL-2.0
  2. use std::ffi::CString;
  3. use proc_macro2::{
  4. Literal,
  5. TokenStream, //
  6. };
  7. use quote::{
  8. format_ident,
  9. quote, //
  10. };
  11. use syn::{
  12. braced,
  13. bracketed,
  14. ext::IdentExt,
  15. parse::{
  16. Parse,
  17. ParseStream, //
  18. },
  19. parse_quote,
  20. punctuated::Punctuated,
  21. Error,
  22. Expr,
  23. Ident,
  24. LitStr,
  25. Path,
  26. Result,
  27. Token,
  28. Type, //
  29. };
  30. use crate::helpers::*;
  31. struct ModInfoBuilder<'a> {
  32. module: &'a str,
  33. counter: usize,
  34. ts: TokenStream,
  35. param_ts: TokenStream,
  36. }
  37. impl<'a> ModInfoBuilder<'a> {
  38. fn new(module: &'a str) -> Self {
  39. ModInfoBuilder {
  40. module,
  41. counter: 0,
  42. ts: TokenStream::new(),
  43. param_ts: TokenStream::new(),
  44. }
  45. }
  46. fn emit_base(&mut self, field: &str, content: &str, builtin: bool, param: bool) {
  47. let string = if builtin {
  48. // Built-in modules prefix their modinfo strings by `module.`.
  49. format!(
  50. "{module}.{field}={content}\0",
  51. module = self.module,
  52. field = field,
  53. content = content
  54. )
  55. } else {
  56. // Loadable modules' modinfo strings go as-is.
  57. format!("{field}={content}\0")
  58. };
  59. let length = string.len();
  60. let string = Literal::byte_string(string.as_bytes());
  61. let cfg = if builtin {
  62. quote!(#[cfg(not(MODULE))])
  63. } else {
  64. quote!(#[cfg(MODULE)])
  65. };
  66. let counter = format_ident!(
  67. "__{module}_{counter}",
  68. module = self.module.to_uppercase(),
  69. counter = self.counter
  70. );
  71. let item = quote! {
  72. #cfg
  73. #[cfg_attr(not(target_os = "macos"), link_section = ".modinfo")]
  74. #[used(compiler)]
  75. pub static #counter: [u8; #length] = *#string;
  76. };
  77. if param {
  78. self.param_ts.extend(item);
  79. } else {
  80. self.ts.extend(item);
  81. }
  82. self.counter += 1;
  83. }
  84. fn emit_only_builtin(&mut self, field: &str, content: &str, param: bool) {
  85. self.emit_base(field, content, true, param)
  86. }
  87. fn emit_only_loadable(&mut self, field: &str, content: &str, param: bool) {
  88. self.emit_base(field, content, false, param)
  89. }
  90. fn emit(&mut self, field: &str, content: &str) {
  91. self.emit_internal(field, content, false);
  92. }
  93. fn emit_internal(&mut self, field: &str, content: &str, param: bool) {
  94. self.emit_only_builtin(field, content, param);
  95. self.emit_only_loadable(field, content, param);
  96. }
  97. fn emit_param(&mut self, field: &str, param: &str, content: &str) {
  98. let content = format!("{param}:{content}", param = param, content = content);
  99. self.emit_internal(field, &content, true);
  100. }
  101. fn emit_params(&mut self, info: &ModuleInfo) {
  102. let Some(params) = &info.params else {
  103. return;
  104. };
  105. for param in params {
  106. let param_name_str = param.name.to_string();
  107. let param_type_str = param.ptype.to_string();
  108. let ops = param_ops_path(&param_type_str);
  109. // Note: The spelling of these fields is dictated by the user space
  110. // tool `modinfo`.
  111. self.emit_param("parmtype", &param_name_str, &param_type_str);
  112. self.emit_param("parm", &param_name_str, &param.description.value());
  113. let static_name = format_ident!("__{}_{}_struct", self.module, param.name);
  114. let param_name_cstr =
  115. CString::new(param_name_str).expect("name contains NUL-terminator");
  116. let param_name_cstr_with_module =
  117. CString::new(format!("{}.{}", self.module, param.name))
  118. .expect("name contains NUL-terminator");
  119. let param_name = &param.name;
  120. let param_type = &param.ptype;
  121. let param_default = &param.default;
  122. self.param_ts.extend(quote! {
  123. #[allow(non_upper_case_globals)]
  124. pub(crate) static #param_name:
  125. ::kernel::module_param::ModuleParamAccess<#param_type> =
  126. ::kernel::module_param::ModuleParamAccess::new(#param_default);
  127. const _: () = {
  128. #[allow(non_upper_case_globals)]
  129. #[link_section = "__param"]
  130. #[used(compiler)]
  131. static #static_name:
  132. ::kernel::module_param::KernelParam =
  133. ::kernel::module_param::KernelParam::new(
  134. ::kernel::bindings::kernel_param {
  135. name: kernel::str::as_char_ptr_in_const_context(
  136. if ::core::cfg!(MODULE) {
  137. #param_name_cstr
  138. } else {
  139. #param_name_cstr_with_module
  140. }
  141. ),
  142. // SAFETY: `__this_module` is constructed by the kernel at load
  143. // time and will not be freed until the module is unloaded.
  144. #[cfg(MODULE)]
  145. mod_: unsafe {
  146. core::ptr::from_ref(&::kernel::bindings::__this_module)
  147. .cast_mut()
  148. },
  149. #[cfg(not(MODULE))]
  150. mod_: ::core::ptr::null_mut(),
  151. ops: core::ptr::from_ref(&#ops),
  152. perm: 0, // Will not appear in sysfs
  153. level: -1,
  154. flags: 0,
  155. __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {
  156. arg: #param_name.as_void_ptr()
  157. },
  158. }
  159. );
  160. };
  161. });
  162. }
  163. }
  164. }
  165. fn param_ops_path(param_type: &str) -> Path {
  166. match param_type {
  167. "i8" => parse_quote!(::kernel::module_param::PARAM_OPS_I8),
  168. "u8" => parse_quote!(::kernel::module_param::PARAM_OPS_U8),
  169. "i16" => parse_quote!(::kernel::module_param::PARAM_OPS_I16),
  170. "u16" => parse_quote!(::kernel::module_param::PARAM_OPS_U16),
  171. "i32" => parse_quote!(::kernel::module_param::PARAM_OPS_I32),
  172. "u32" => parse_quote!(::kernel::module_param::PARAM_OPS_U32),
  173. "i64" => parse_quote!(::kernel::module_param::PARAM_OPS_I64),
  174. "u64" => parse_quote!(::kernel::module_param::PARAM_OPS_U64),
  175. "isize" => parse_quote!(::kernel::module_param::PARAM_OPS_ISIZE),
  176. "usize" => parse_quote!(::kernel::module_param::PARAM_OPS_USIZE),
  177. t => panic!("Unsupported parameter type {}", t),
  178. }
  179. }
  180. /// Parse fields that are required to use a specific order.
  181. ///
  182. /// As fields must follow a specific order, we *could* just parse fields one by one by peeking.
  183. /// However the error message generated when implementing that way is not very friendly.
  184. ///
  185. /// So instead we parse fields in an arbitrary order, but only enforce the ordering after parsing,
  186. /// and if the wrong order is used, the proper order is communicated to the user with error message.
  187. ///
  188. /// Usage looks like this:
  189. /// ```ignore
  190. /// parse_ordered_fields! {
  191. /// from input;
  192. ///
  193. /// // This will extract "foo: <field>" into a variable named "foo".
  194. /// // The variable will have type `Option<_>`.
  195. /// foo => <expression that parses the field>,
  196. ///
  197. /// // If you need the variable name to be different than the key name.
  198. /// // This extracts "baz: <field>" into a variable named "bar".
  199. /// // You might want this if "baz" is a keyword.
  200. /// baz as bar => <expression that parse the field>,
  201. ///
  202. /// // You can mark a key as required, and the variable will no longer be `Option`.
  203. /// // foobar will be of type `Expr` instead of `Option<Expr>`.
  204. /// foobar [required] => input.parse::<Expr>()?,
  205. /// }
  206. /// ```
  207. macro_rules! parse_ordered_fields {
  208. (@gen
  209. [$input:expr]
  210. [$([$name:ident; $key:ident; $parser:expr])*]
  211. [$([$req_name:ident; $req_key:ident])*]
  212. ) => {
  213. $(let mut $name = None;)*
  214. const EXPECTED_KEYS: &[&str] = &[$(stringify!($key),)*];
  215. const REQUIRED_KEYS: &[&str] = &[$(stringify!($req_key),)*];
  216. let span = $input.span();
  217. let mut seen_keys = Vec::new();
  218. while !$input.is_empty() {
  219. let key = $input.call(Ident::parse_any)?;
  220. if seen_keys.contains(&key) {
  221. Err(Error::new_spanned(
  222. &key,
  223. format!(r#"duplicated key "{key}". Keys can only be specified once."#),
  224. ))?
  225. }
  226. $input.parse::<Token![:]>()?;
  227. match &*key.to_string() {
  228. $(
  229. stringify!($key) => $name = Some($parser),
  230. )*
  231. _ => {
  232. Err(Error::new_spanned(
  233. &key,
  234. format!(r#"unknown key "{key}". Valid keys are: {EXPECTED_KEYS:?}."#),
  235. ))?
  236. }
  237. }
  238. $input.parse::<Token![,]>()?;
  239. seen_keys.push(key);
  240. }
  241. for key in REQUIRED_KEYS {
  242. if !seen_keys.iter().any(|e| e == key) {
  243. Err(Error::new(span, format!(r#"missing required key "{key}""#)))?
  244. }
  245. }
  246. let mut ordered_keys: Vec<&str> = Vec::new();
  247. for key in EXPECTED_KEYS {
  248. if seen_keys.iter().any(|e| e == key) {
  249. ordered_keys.push(key);
  250. }
  251. }
  252. if seen_keys != ordered_keys {
  253. Err(Error::new(
  254. span,
  255. format!(r#"keys are not ordered as expected. Order them like: {ordered_keys:?}."#),
  256. ))?
  257. }
  258. $(let $req_name = $req_name.expect("required field");)*
  259. };
  260. // Handle required fields.
  261. (@gen
  262. [$input:expr] [$($tok:tt)*] [$($req:tt)*]
  263. $key:ident as $name:ident [required] => $parser:expr,
  264. $($rest:tt)*
  265. ) => {
  266. parse_ordered_fields!(
  267. @gen [$input] [$($tok)* [$name; $key; $parser]] [$($req)* [$name; $key]] $($rest)*
  268. )
  269. };
  270. (@gen
  271. [$input:expr] [$($tok:tt)*] [$($req:tt)*]
  272. $name:ident [required] => $parser:expr,
  273. $($rest:tt)*
  274. ) => {
  275. parse_ordered_fields!(
  276. @gen [$input] [$($tok)* [$name; $name; $parser]] [$($req)* [$name; $name]] $($rest)*
  277. )
  278. };
  279. // Handle optional fields.
  280. (@gen
  281. [$input:expr] [$($tok:tt)*] [$($req:tt)*]
  282. $key:ident as $name:ident => $parser:expr,
  283. $($rest:tt)*
  284. ) => {
  285. parse_ordered_fields!(
  286. @gen [$input] [$($tok)* [$name; $key; $parser]] [$($req)*] $($rest)*
  287. )
  288. };
  289. (@gen
  290. [$input:expr] [$($tok:tt)*] [$($req:tt)*]
  291. $name:ident => $parser:expr,
  292. $($rest:tt)*
  293. ) => {
  294. parse_ordered_fields!(
  295. @gen [$input] [$($tok)* [$name; $name; $parser]] [$($req)*] $($rest)*
  296. )
  297. };
  298. (from $input:expr; $($tok:tt)*) => {
  299. parse_ordered_fields!(@gen [$input] [] [] $($tok)*)
  300. }
  301. }
  302. struct Parameter {
  303. name: Ident,
  304. ptype: Ident,
  305. default: Expr,
  306. description: LitStr,
  307. }
  308. impl Parse for Parameter {
  309. fn parse(input: ParseStream<'_>) -> Result<Self> {
  310. let name = input.parse()?;
  311. input.parse::<Token![:]>()?;
  312. let ptype = input.parse()?;
  313. let fields;
  314. braced!(fields in input);
  315. parse_ordered_fields! {
  316. from fields;
  317. default [required] => fields.parse()?,
  318. description [required] => fields.parse()?,
  319. }
  320. Ok(Self {
  321. name,
  322. ptype,
  323. default,
  324. description,
  325. })
  326. }
  327. }
  328. pub(crate) struct ModuleInfo {
  329. type_: Type,
  330. license: AsciiLitStr,
  331. name: AsciiLitStr,
  332. authors: Option<Punctuated<AsciiLitStr, Token![,]>>,
  333. description: Option<LitStr>,
  334. alias: Option<Punctuated<AsciiLitStr, Token![,]>>,
  335. firmware: Option<Punctuated<AsciiLitStr, Token![,]>>,
  336. imports_ns: Option<Punctuated<AsciiLitStr, Token![,]>>,
  337. params: Option<Punctuated<Parameter, Token![,]>>,
  338. }
  339. impl Parse for ModuleInfo {
  340. fn parse(input: ParseStream<'_>) -> Result<Self> {
  341. parse_ordered_fields!(
  342. from input;
  343. type as type_ [required] => input.parse()?,
  344. name [required] => input.parse()?,
  345. authors => {
  346. let list;
  347. bracketed!(list in input);
  348. Punctuated::parse_terminated(&list)?
  349. },
  350. description => input.parse()?,
  351. license [required] => input.parse()?,
  352. alias => {
  353. let list;
  354. bracketed!(list in input);
  355. Punctuated::parse_terminated(&list)?
  356. },
  357. firmware => {
  358. let list;
  359. bracketed!(list in input);
  360. Punctuated::parse_terminated(&list)?
  361. },
  362. imports_ns => {
  363. let list;
  364. bracketed!(list in input);
  365. Punctuated::parse_terminated(&list)?
  366. },
  367. params => {
  368. let list;
  369. braced!(list in input);
  370. Punctuated::parse_terminated(&list)?
  371. },
  372. );
  373. Ok(ModuleInfo {
  374. type_,
  375. license,
  376. name,
  377. authors,
  378. description,
  379. alias,
  380. firmware,
  381. imports_ns,
  382. params,
  383. })
  384. }
  385. }
  386. pub(crate) fn module(info: ModuleInfo) -> Result<TokenStream> {
  387. let ModuleInfo {
  388. type_,
  389. license,
  390. name,
  391. authors,
  392. description,
  393. alias,
  394. firmware,
  395. imports_ns,
  396. params: _,
  397. } = &info;
  398. // Rust does not allow hyphens in identifiers, use underscore instead.
  399. let ident = name.value().replace('-', "_");
  400. let mut modinfo = ModInfoBuilder::new(ident.as_ref());
  401. if let Some(authors) = authors {
  402. for author in authors {
  403. modinfo.emit("author", &author.value());
  404. }
  405. }
  406. if let Some(description) = description {
  407. modinfo.emit("description", &description.value());
  408. }
  409. modinfo.emit("license", &license.value());
  410. if let Some(aliases) = alias {
  411. for alias in aliases {
  412. modinfo.emit("alias", &alias.value());
  413. }
  414. }
  415. if let Some(firmware) = firmware {
  416. for fw in firmware {
  417. modinfo.emit("firmware", &fw.value());
  418. }
  419. }
  420. if let Some(imports) = imports_ns {
  421. for ns in imports {
  422. modinfo.emit("import_ns", &ns.value());
  423. }
  424. }
  425. // Built-in modules also export the `file` modinfo string.
  426. let file =
  427. std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
  428. modinfo.emit_only_builtin("file", &file, false);
  429. modinfo.emit_params(&info);
  430. let modinfo_ts = modinfo.ts;
  431. let params_ts = modinfo.param_ts;
  432. let ident_init = format_ident!("__{ident}_init");
  433. let ident_exit = format_ident!("__{ident}_exit");
  434. let ident_initcall = format_ident!("__{ident}_initcall");
  435. let initcall_section = ".initcall6.init";
  436. let global_asm = format!(
  437. r#".section "{initcall_section}", "a"
  438. __{ident}_initcall:
  439. .long __{ident}_init - .
  440. .previous
  441. "#
  442. );
  443. let name_cstr = CString::new(name.value()).expect("name contains NUL-terminator");
  444. Ok(quote! {
  445. /// The module name.
  446. ///
  447. /// Used by the printing macros, e.g. [`info!`].
  448. const __LOG_PREFIX: &[u8] = #name_cstr.to_bytes_with_nul();
  449. // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
  450. // freed until the module is unloaded.
  451. #[cfg(MODULE)]
  452. static THIS_MODULE: ::kernel::ThisModule = unsafe {
  453. extern "C" {
  454. static __this_module: ::kernel::types::Opaque<::kernel::bindings::module>;
  455. };
  456. ::kernel::ThisModule::from_ptr(__this_module.get())
  457. };
  458. #[cfg(not(MODULE))]
  459. static THIS_MODULE: ::kernel::ThisModule = unsafe {
  460. ::kernel::ThisModule::from_ptr(::core::ptr::null_mut())
  461. };
  462. /// The `LocalModule` type is the type of the module created by `module!`,
  463. /// `module_pci_driver!`, `module_platform_driver!`, etc.
  464. type LocalModule = #type_;
  465. impl ::kernel::ModuleMetadata for #type_ {
  466. const NAME: &'static ::kernel::str::CStr = #name_cstr;
  467. }
  468. // Double nested modules, since then nobody can access the public items inside.
  469. #[doc(hidden)]
  470. mod __module_init {
  471. mod __module_init {
  472. use pin_init::PinInit;
  473. /// The "Rust loadable module" mark.
  474. //
  475. // This may be best done another way later on, e.g. as a new modinfo
  476. // key or a new section. For the moment, keep it simple.
  477. #[cfg(MODULE)]
  478. #[used(compiler)]
  479. static __IS_RUST_MODULE: () = ();
  480. static mut __MOD: ::core::mem::MaybeUninit<super::super::LocalModule> =
  481. ::core::mem::MaybeUninit::uninit();
  482. // Loadable modules need to export the `{init,cleanup}_module` identifiers.
  483. /// # Safety
  484. ///
  485. /// This function must not be called after module initialization, because it may be
  486. /// freed after that completes.
  487. #[cfg(MODULE)]
  488. #[no_mangle]
  489. #[link_section = ".init.text"]
  490. pub unsafe extern "C" fn init_module() -> ::kernel::ffi::c_int {
  491. // SAFETY: This function is inaccessible to the outside due to the double
  492. // module wrapping it. It is called exactly once by the C side via its
  493. // unique name.
  494. unsafe { __init() }
  495. }
  496. #[cfg(MODULE)]
  497. #[used(compiler)]
  498. #[link_section = ".init.data"]
  499. static __UNIQUE_ID___addressable_init_module: unsafe extern "C" fn() -> i32 =
  500. init_module;
  501. #[cfg(MODULE)]
  502. #[no_mangle]
  503. #[link_section = ".exit.text"]
  504. pub extern "C" fn cleanup_module() {
  505. // SAFETY:
  506. // - This function is inaccessible to the outside due to the double
  507. // module wrapping it. It is called exactly once by the C side via its
  508. // unique name,
  509. // - furthermore it is only called after `init_module` has returned `0`
  510. // (which delegates to `__init`).
  511. unsafe { __exit() }
  512. }
  513. #[cfg(MODULE)]
  514. #[used(compiler)]
  515. #[link_section = ".exit.data"]
  516. static __UNIQUE_ID___addressable_cleanup_module: extern "C" fn() = cleanup_module;
  517. // Built-in modules are initialized through an initcall pointer
  518. // and the identifiers need to be unique.
  519. #[cfg(not(MODULE))]
  520. #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
  521. #[link_section = #initcall_section]
  522. #[used(compiler)]
  523. pub static #ident_initcall: extern "C" fn() ->
  524. ::kernel::ffi::c_int = #ident_init;
  525. #[cfg(not(MODULE))]
  526. #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
  527. ::core::arch::global_asm!(#global_asm);
  528. #[cfg(not(MODULE))]
  529. #[no_mangle]
  530. pub extern "C" fn #ident_init() -> ::kernel::ffi::c_int {
  531. // SAFETY: This function is inaccessible to the outside due to the double
  532. // module wrapping it. It is called exactly once by the C side via its
  533. // placement above in the initcall section.
  534. unsafe { __init() }
  535. }
  536. #[cfg(not(MODULE))]
  537. #[no_mangle]
  538. pub extern "C" fn #ident_exit() {
  539. // SAFETY:
  540. // - This function is inaccessible to the outside due to the double
  541. // module wrapping it. It is called exactly once by the C side via its
  542. // unique name,
  543. // - furthermore it is only called after `#ident_init` has
  544. // returned `0` (which delegates to `__init`).
  545. unsafe { __exit() }
  546. }
  547. /// # Safety
  548. ///
  549. /// This function must only be called once.
  550. unsafe fn __init() -> ::kernel::ffi::c_int {
  551. let initer = <super::super::LocalModule as ::kernel::InPlaceModule>::init(
  552. &super::super::THIS_MODULE
  553. );
  554. // SAFETY: No data race, since `__MOD` can only be accessed by this module
  555. // and there only `__init` and `__exit` access it. These functions are only
  556. // called once and `__exit` cannot be called before or during `__init`.
  557. match unsafe { initer.__pinned_init(__MOD.as_mut_ptr()) } {
  558. Ok(m) => 0,
  559. Err(e) => e.to_errno(),
  560. }
  561. }
  562. /// # Safety
  563. ///
  564. /// This function must
  565. /// - only be called once,
  566. /// - be called after `__init` has been called and returned `0`.
  567. unsafe fn __exit() {
  568. // SAFETY: No data race, since `__MOD` can only be accessed by this module
  569. // and there only `__init` and `__exit` access it. These functions are only
  570. // called once and `__init` was already called.
  571. unsafe {
  572. // Invokes `drop()` on `__MOD`, which should be used for cleanup.
  573. __MOD.assume_init_drop();
  574. }
  575. }
  576. #modinfo_ts
  577. }
  578. }
  579. mod module_parameters {
  580. #params_ts
  581. }
  582. })
  583. }