linux/rust/kernel/lib.rs
Linus Torvalds 8f5b5f7811 Rust changes for v6.10
The most notable change is the drop of the 'alloc' in-tree fork. This
 is nicely reflected in the diffstat as a ~10k lines drop. In turn, this
 makes the version upgrades way simpler and smaller in the future, e.g.
 the latest one in commit 56f64b3706 ("rust: upgrade to Rust 1.78.0").
 
 More importantly, this increases the chances that a newer compiler
 version just works, which in turn means supporting several compiler
 versions is easier now. Thus we will look into finally setting a minimum
 version in the near future.
 
 Toolchain and infrastructure:
 
  - Upgrade to Rust 1.78.0.
 
    This time around, due to how the kernel and Rust schedules have
    aligned, there are two upgrades in fact. These allow us to remove one
    more unstable feature ('offset_of') from the list, among other
    improvements.
 
  - Drop 'alloc' in-tree fork of the standard library crate, which means
    all the unstable features used by 'alloc' (~30 language ones, ~60
    library ones) are not a concern anymore.
 
  - Support DWARFv5 via the '-Zdwarf-version' flag.
 
  - Support zlib and zstd debuginfo compression via the
    '-Zdebuginfo-compression' flag.
 
 'kernel' crate:
 
  - Support allocation flags ('GFP_*'), particularly in 'Box' (via
    'BoxExt'), 'Vec' (via 'VecExt'), 'Arc' and 'UniqueArc', as well as in
    the 'init' module APIs.
 
  - Remove usage of the 'allocator_api' unstable feature.
 
  - Remove 'try_' prefix in allocation APIs' names.
 
  - Add 'VecExt' (an extension trait) to be able to drop the 'alloc'
    fork.
 
  - Add the '{make,to}_{upper,lower}case()' methods to 'CStr'/'CString'.
 
  - Add the 'as_ptr' method to 'ThisModule'.
 
  - Add the 'from_raw' method to 'ArcBorrow'.
 
  - Add the 'into_unique_or_drop' method to 'Arc'.
 
  - Display column number in the 'dbg!' macro output by applying the
    equivalent change done to the standard library one.
 
  - Migrate 'Work' to '#[pin_data]' thanks to the changes in the 'macros'
    crate, which allows to remove an unsafe call in its 'new' associated
    function.
 
  - Prevent namespacing issues when using the '[try_][pin_]init!' macros
    by changing the generated name of guard variables.
 
  - Make the 'get' method in 'Opaque' const.
 
  - Implement the 'Default' trait for 'LockClassKey'.
 
  - Remove unneeded 'kernel::prelude' imports from doctests.
 
  - Remove redundant imports.
 
 'macros' crate:
 
  - Add 'decl_generics' to 'parse_generics()' to support default values,
    and use that to allow them in '#[pin_data]'.
 
 Helpers:
 
  - Trivial English grammar fix.
 
 Documentation:
 
  - Add section on Rust Kselftests to the "Testing" document.
 
  - Expand the "Abstractions vs. bindings" section of the "General
    Information" document.
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEPjU5OPd5QIZ9jqqOGXyLc2htIW0FAmZBIzoACgkQGXyLc2ht
 IW2/7hAAz5fRsx1M1b/JU3P3lc3XKUaFCmAWJX6F+sNHp8vNeFYNzVZ3ylk6Z4zB
 idkTq0Y5Rlc8ejryHiEMaY3X7Zrh0yt3G/AzKZqZx54IAPUp59BRSvG3+SJanQ7p
 Gjy+cCXweLtYjF79Au5Ejt52gV+JAwPtGLkbl1skNs0jPr4rqm+Zg4bPhE5Sr0Eh
 mh2VxcHf3rbIVhBYJTYGNpsnQYZNwfPDJ+bRudYp1BymLYOG8A328ocvU19BM63+
 6FFQBLgB3N8OS+Mw0c8AeFVNkeCw4NesmIkBMco8wm8QXyLz1zjg948LT9ogPCgB
 5eC41yAxa83uPdt8L034YNfJa+IgFleZp339QKW2+vXHks43M8IMLq9WP7GU84M1
 Axu5ekl5sR6awOk0265Zc1ghkOTQREIi0kiqtNBh9wc/qILAD2DyYoy1td9ch1Qi
 BBNxyKYaMx9z+7mhK4ksTbRb+VrdDmFPDhXOIJD5zg4yrLZOM6Mb/O+BnSD2pxa3
 6cUGwfQTv0hbBTeY4ZgdNgFu2YJ/9rqACKtULoaT0AID/d8I3fxc7J35AWnqeC/x
 nALHTa2JMkBvN03Afn0wCVuXbdLW0/9DCGnuuhYMn0DhFC/uuKicsvwfjcGSKnPN
 iaRJoRCYKjlc0AJSYHhavgyp2R9HnVM0E53PC3ubjiKz5DsaRDU=
 =j6/D
 -----END PGP SIGNATURE-----

Merge tag 'rust-6.10' of https://github.com/Rust-for-Linux/linux

Pull Rust updates from Miguel Ojeda:
 "The most notable change is the drop of the 'alloc' in-tree fork. This
  is nicely reflected in the diffstat as a ~10k lines drop. In turn,
  this makes the version upgrades way simpler and smaller in the future,
  e.g. the latest one in commit 56f64b3706 ("rust: upgrade to Rust
  1.78.0").

  More importantly, this increases the chances that a newer compiler
  version just works, which in turn means supporting several compiler
  versions is easier now. Thus we will look into finally setting a
  minimum version in the near future.

  Toolchain and infrastructure:

   - Upgrade to Rust 1.78.0

     This time around, due to how the kernel and Rust schedules have
     aligned, there are two upgrades in fact. These allow us to remove
     one more unstable feature ('offset_of') from the list, among other
     improvements

   - Drop 'alloc' in-tree fork of the standard library crate, which
     means all the unstable features used by 'alloc' (~30 language ones,
     ~60 library ones) are not a concern anymore

   - Support DWARFv5 via the '-Zdwarf-version' flag

   - Support zlib and zstd debuginfo compression via the
     '-Zdebuginfo-compression' flag

  'kernel' crate:

   - Support allocation flags ('GFP_*'), particularly in 'Box' (via
     'BoxExt'), 'Vec' (via 'VecExt'), 'Arc' and 'UniqueArc', as well as
     in the 'init' module APIs

   - Remove usage of the 'allocator_api' unstable feature

   - Remove 'try_' prefix in allocation APIs' names

   - Add 'VecExt' (an extension trait) to be able to drop the 'alloc'
     fork

   - Add the '{make,to}_{upper,lower}case()' methods to 'CStr'/'CString'

   - Add the 'as_ptr' method to 'ThisModule'

   - Add the 'from_raw' method to 'ArcBorrow'

   - Add the 'into_unique_or_drop' method to 'Arc'

   - Display column number in the 'dbg!' macro output by applying the
     equivalent change done to the standard library one

   - Migrate 'Work' to '#[pin_data]' thanks to the changes in the
     'macros' crate, which allows to remove an unsafe call in its 'new'
     associated function

   - Prevent namespacing issues when using the '[try_][pin_]init!'
     macros by changing the generated name of guard variables

   - Make the 'get' method in 'Opaque' const

   - Implement the 'Default' trait for 'LockClassKey'

   - Remove unneeded 'kernel::prelude' imports from doctests

   - Remove redundant imports

  'macros' crate:

   - Add 'decl_generics' to 'parse_generics()' to support default
     values, and use that to allow them in '#[pin_data]'

  Helpers:

   - Trivial English grammar fix

  Documentation:

   - Add section on Rust Kselftests to the 'Testing' document

   - Expand the 'Abstractions vs. bindings' section of the 'General
     Information' document"

* tag 'rust-6.10' of https://github.com/Rust-for-Linux/linux: (31 commits)
  rust: alloc: fix dangling pointer in VecExt<T>::reserve()
  rust: upgrade to Rust 1.78.0
  rust: kernel: remove redundant imports
  rust: sync: implement `Default` for `LockClassKey`
  docs: rust: extend abstraction and binding documentation
  docs: rust: Add instructions for the Rust kselftest
  rust: remove unneeded `kernel::prelude` imports from doctests
  rust: update `dbg!()` to format column number
  rust: helpers: Fix grammar in comment
  rust: init: change the generated name of guard variables
  rust: sync: add `Arc::into_unique_or_drop`
  rust: sync: add `ArcBorrow::from_raw`
  rust: types: Make Opaque::get const
  rust: kernel: remove usage of `allocator_api` unstable feature
  rust: init: update `init` module to take allocation flags
  rust: sync: update `Arc` and `UniqueArc` to take allocation flags
  rust: alloc: update `VecExt` to take allocation flags
  rust: alloc: introduce the `BoxExt` trait
  rust: alloc: introduce allocation flags
  rust: alloc: remove our fork of the `alloc` crate
  ...
2024-05-13 15:13:54 -07:00

139 lines
3.8 KiB
Rust

// SPDX-License-Identifier: GPL-2.0
//! The `kernel` crate.
//!
//! This crate contains the kernel APIs that have been ported or wrapped for
//! usage by Rust code in the kernel and is shared by all of them.
//!
//! In other words, all the rest of the Rust code in the kernel (e.g. kernel
//! modules written in Rust) depends on [`core`], [`alloc`] and this crate.
//!
//! If you need a kernel C API that is not ported or wrapped yet here, then
//! do so first instead of bypassing this crate.
#![no_std]
#![feature(coerce_unsized)]
#![feature(dispatch_from_dyn)]
#![feature(new_uninit)]
#![feature(receiver_trait)]
#![feature(unsize)]
// Ensure conditional compilation based on the kernel configuration works;
// otherwise we may silently break things like initcall handling.
#[cfg(not(CONFIG_RUST))]
compile_error!("Missing kernel configuration for conditional compilation");
// Allow proc-macros to refer to `::kernel` inside the `kernel` crate (this crate).
extern crate self as kernel;
pub mod alloc;
mod build_assert;
pub mod error;
pub mod init;
pub mod ioctl;
#[cfg(CONFIG_KUNIT)]
pub mod kunit;
#[cfg(CONFIG_NET)]
pub mod net;
pub mod prelude;
pub mod print;
mod static_assert;
#[doc(hidden)]
pub mod std_vendor;
pub mod str;
pub mod sync;
pub mod task;
pub mod time;
pub mod types;
pub mod workqueue;
#[doc(hidden)]
pub use bindings;
pub use macros;
pub use uapi;
#[doc(hidden)]
pub use build_error::build_error;
/// Prefix to appear before log messages printed from within the `kernel` crate.
const __LOG_PREFIX: &[u8] = b"rust_kernel\0";
/// The top level entrypoint to implementing a kernel module.
///
/// For any teardown or cleanup operations, your type may implement [`Drop`].
pub trait Module: Sized + Sync + Send {
/// Called at module initialization time.
///
/// Use this method to perform whatever setup or registration your module
/// should do.
///
/// Equivalent to the `module_init` macro in the C API.
fn init(module: &'static ThisModule) -> error::Result<Self>;
}
/// Equivalent to `THIS_MODULE` in the C API.
///
/// C header: [`include/linux/export.h`](srctree/include/linux/export.h)
pub struct ThisModule(*mut bindings::module);
// SAFETY: `THIS_MODULE` may be used from all threads within a module.
unsafe impl Sync for ThisModule {}
impl ThisModule {
/// Creates a [`ThisModule`] given the `THIS_MODULE` pointer.
///
/// # Safety
///
/// The pointer must be equal to the right `THIS_MODULE`.
pub const unsafe fn from_ptr(ptr: *mut bindings::module) -> ThisModule {
ThisModule(ptr)
}
/// Access the raw pointer for this module.
///
/// It is up to the user to use it correctly.
pub const fn as_ptr(&self) -> *mut bindings::module {
self.0
}
}
#[cfg(not(any(testlib, test)))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
pr_emerg!("{}\n", info);
// SAFETY: FFI call.
unsafe { bindings::BUG() };
}
/// Produces a pointer to an object from a pointer to one of its fields.
///
/// # Safety
///
/// The pointer passed to this macro, and the pointer returned by this macro, must both be in
/// bounds of the same allocation.
///
/// # Examples
///
/// ```
/// # use kernel::container_of;
/// struct Test {
/// a: u64,
/// b: u32,
/// }
///
/// let test = Test { a: 10, b: 20 };
/// let b_ptr = &test.b;
/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
/// // in-bounds of the same allocation as `b_ptr`.
/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
/// assert!(core::ptr::eq(&test, test_alias));
/// ```
#[macro_export]
macro_rules! container_of {
($ptr:expr, $type:ty, $($f:tt)*) => {{
let ptr = $ptr as *const _ as *const u8;
let offset: usize = ::core::mem::offset_of!($type, $($f)*);
ptr.sub(offset) as *const $type
}}
}