lib.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! The `kernel` crate.
  3. //!
  4. //! This crate contains the kernel APIs that have been ported or wrapped for
  5. //! usage by Rust code in the kernel and is shared by all of them.
  6. //!
  7. //! In other words, all the rest of the Rust code in the kernel (e.g. kernel
  8. //! modules written in Rust) depends on [`core`], [`alloc`] and this crate.
  9. //!
  10. //! If you need a kernel C API that is not ported or wrapped yet here, then
  11. //! do so first instead of bypassing this crate.
  12. #![no_std]
  13. #![feature(core_ffi_c)]
  14. // Ensure conditional compilation based on the kernel configuration works;
  15. // otherwise we may silently break things like initcall handling.
  16. #[cfg(not(CONFIG_RUST))]
  17. compile_error!("Missing kernel configuration for conditional compilation");
  18. #[cfg(not(test))]
  19. #[cfg(not(testlib))]
  20. mod allocator;
  21. pub mod error;
  22. pub mod prelude;
  23. pub mod print;
  24. pub mod str;
  25. #[doc(hidden)]
  26. pub use bindings;
  27. pub use macros;
  28. /// Prefix to appear before log messages printed from within the `kernel` crate.
  29. const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
  30. /// The top level entrypoint to implementing a kernel module.
  31. ///
  32. /// For any teardown or cleanup operations, your type may implement [`Drop`].
  33. pub trait Module: Sized + Sync {
  34. /// Called at module initialization time.
  35. ///
  36. /// Use this method to perform whatever setup or registration your module
  37. /// should do.
  38. ///
  39. /// Equivalent to the `module_init` macro in the C API.
  40. fn init(module: &'static ThisModule) -> error::Result<Self>;
  41. }
  42. /// Equivalent to `THIS_MODULE` in the C API.
  43. ///
  44. /// C header: `include/linux/export.h`
  45. pub struct ThisModule(*mut bindings::module);
  46. // SAFETY: `THIS_MODULE` may be used from all threads within a module.
  47. unsafe impl Sync for ThisModule {}
  48. impl ThisModule {
  49. /// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
  50. ///
  51. /// # Safety
  52. ///
  53. /// The pointer must be equal to the right `THIS_MODULE`.
  54. pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
  55. ThisModule(ptr)
  56. }
  57. }
  58. #[cfg(not(any(testlib, test)))]
  59. #[panic_handler]
  60. fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
  61. pr_emerg!("{}\n", info);
  62. // SAFETY: FFI call.
  63. unsafe { bindings::BUG() };
  64. // Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`
  65. // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
  66. loop {}
  67. }