Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust: task: use safe current macro #1053

Open
wants to merge 32 commits into
base: rust-dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
aa935a1
Merge branch 'net-next-20231228' into rust-dev
fbq Dec 28, 2023
e562737
rust: upgrade to Rust 1.75.0
ojeda Dec 24, 2023
39f11a3
rust: file: add Rust abstraction for `struct file`
wedsonaf Dec 6, 2023
1d0fab6
rust: cred: add Rust abstraction for `struct cred`
wedsonaf Dec 6, 2023
dab0fe4
rust: security: add abstraction for secctx
Darksonn Dec 6, 2023
5a5888c
rust: file: add `FileDescriptorReservation`
wedsonaf Dec 6, 2023
e98a9c7
rust: file: add `Kuid` wrapper
Darksonn Dec 6, 2023
befd131
rust: file: add `DeferredFdCloser`
Darksonn Dec 6, 2023
0d01533
rust: file: add abstraction for `poll_table`
Darksonn Dec 6, 2023
ba17aad
rust: macros: add `decl_generics` to `parse_generics()`
Dec 13, 2023
884a0c6
rust: add improved version of `ForeignOwnable::borrow_mut`
Darksonn Jul 10, 2023
1fd25cc
rust: macros: allow generic parameter default values in `#[pin_data]`
Dec 13, 2023
7ca8daf
rust: Refactor the build target to allow the use of builtin targets
JamieCunliffe Oct 20, 2023
8f7e376
rust: workqueue: add `#[pin_data]` to `Work`
Dec 13, 2023
df91439
arm64: rust: Enable Rust support for AArch64
JamieCunliffe Oct 20, 2023
f3bc6f9
rust: task: add `as_raw()` to `Task`
antonio-hickey Jan 2, 2024
b54bde5
rust: task: use safe `current!` macro
antonio-hickey Jan 4, 2024
0e52e55
rust: macros: add `decl_generics` to `parse_generics()`
Dec 13, 2023
9a1d84e
rust: macros: allow generic parameter default values in `#[pin_data]`
Dec 13, 2023
b01a973
rust: workqueue: add `#[pin_data]` to `Work`
Dec 13, 2023
d02944d
rust: sync: add `CondVar::notify_sync`
Darksonn Jan 8, 2024
b13bfeb
rust: time: add msecs to jiffies conversion
Darksonn Jan 8, 2024
af3c12d
rust: sync: add `CondVar::wait_timeout`
Darksonn Jan 8, 2024
80a1985
rust: sync: update integer types in CondVar
Darksonn Jan 8, 2024
5f46355
rust: file: add Rust abstraction for `struct file`
wedsonaf Dec 6, 2023
87c2ee2
rust: cred: add Rust abstraction for `struct cred`
wedsonaf Dec 6, 2023
31608a9
rust: security: add abstraction for secctx
Darksonn Dec 6, 2023
fd6acd6
rust: file: add `FileDescriptorReservation`
wedsonaf Dec 6, 2023
8257138
rust: file: add `Kuid` wrapper
Darksonn Dec 6, 2023
a49b634
rust: file: add `DeferredFdCloser`
Darksonn Dec 6, 2023
779be36
rust: file: add abstraction for `poll_table`
Darksonn Dec 6, 2023
7822673
Merge branch 'rust-dev' into rust-dev
antonio-hickey Jan 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Documentation/process/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ you probably needn't concern yourself with pcmciautils.
====================== =============== ========================================
GNU C 5.1 gcc --version
Clang/LLVM (optional) 11.0.0 clang --version
Rust (optional) 1.73.0 rustc --version
Rust (optional) 1.75.0 rustc --version
bindgen (optional) 0.65.1 bindgen --version
GNU make 3.82 make --version
bash 4.2 bash --version
Expand Down
1 change: 1 addition & 0 deletions Documentation/rust/arch-support.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ support corresponds to ``S`` values in the ``MAINTAINERS`` file.
============ ================ ==============================================
Architecture Level of support Constraints
============ ================ ==============================================
``arm64`` Maintained Little Endian only.
``um`` Maintained ``x86_64`` only.
``x86`` Maintained ``x86_64`` only.
============ ================ ==============================================
Expand Down
13 changes: 13 additions & 0 deletions Documentation/rust/coding-guidelines.rst
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,19 @@ please take a look at the ``rustdoc`` book at:

https://doc.rust-lang.org/rustdoc/how-to-write-documentation.html

In addition, the kernel supports creating links relative to the source tree by
prefixing the link destination with ``srctree/``. For instance:

.. code-block:: rust

//! C header: [`include/linux/printk.h`](srctree/include/linux/printk.h)

or:

.. code-block:: rust

/// [`struct mutex`]: srctree/include/linux/mutex.h


Naming
------
Expand Down
24 changes: 24 additions & 0 deletions Documentation/rust/general-information.rst
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,27 @@ configuration:
#[cfg(CONFIG_X="y")] // Enabled as a built-in (`y`)
#[cfg(CONFIG_X="m")] // Enabled as a module (`m`)
#[cfg(not(CONFIG_X))] // Disabled


Testing
-------

There are the tests that come from the examples in the Rust documentation
and get transformed into KUnit tests. These can be run via KUnit. For example
via ``kunit_tool`` (``kunit.py``) on the command line::

./tools/testing/kunit/kunit.py run --make_options LLVM=1 --arch x86_64 --kconfig_add CONFIG_RUST=y

Alternatively, KUnit can run them as kernel built-in at boot. Refer to
Documentation/dev-tools/kunit/index.rst for the general KUnit documentation
and Documentation/dev-tools/kunit/architecture.rst for the details of kernel
built-in vs. command line testing.

Additionally, there are the ``#[test]`` tests. These can be run using
the ``rusttest`` Make target::

make LLVM=1 rusttest

This requires the kernel ``.config`` and downloads external repositories.
It runs the ``#[test]`` tests on the host (currently) and thus is fairly
limited in what these tests can test.
18 changes: 9 additions & 9 deletions Documentation/rust/quick-start.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,18 @@ A particular version of the Rust compiler is required. Newer versions may or
may not work because, for the moment, the kernel depends on some unstable
Rust features.

If ``rustup`` is being used, enter the checked out source code directory
and run::
If ``rustup`` is being used, enter the kernel build directory (or use
``--path=<build-dir>`` argument to the ``set`` sub-command) and run::

rustup override set $(scripts/min-tool-version.sh rustc)

This will configure your working directory to use the correct version of
``rustc`` without affecting your default toolchain. If you are not using
``rustup``, fetch a standalone installer from:
``rustc`` without affecting your default toolchain.

Note that the override applies to the current working directory (and its
sub-directories).

If you are not using ``rustup``, fetch a standalone installer from:

https://forge.rust-lang.org/infra/other-installation-methods.html#standalone

Expand Down Expand Up @@ -76,7 +80,7 @@ libclang

``libclang`` (part of LLVM) is used by ``bindgen`` to understand the C code
in the kernel, which means LLVM needs to be installed; like when the kernel
is compiled with ``CC=clang`` or ``LLVM=1``.
is compiled with ``LLVM=1``.

Linux distributions are likely to have a suitable one available, so it is
best to check that first.
Expand Down Expand Up @@ -229,10 +233,6 @@ at the moment. That is::

make LLVM=1

For architectures that do not support a full LLVM toolchain, use::

make CC=clang

Using GCC also works for some configurations, but it is very experimental at
the moment.

Expand Down
1 change: 0 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,6 @@ KBUILD_CFLAGS += -fno-strict-aliasing

KBUILD_CPPFLAGS := -D__KERNEL__
KBUILD_RUSTFLAGS := $(rust_common_flags) \
--target=$(objtree)/scripts/target.json \
-Cpanic=abort -Cembed-bitcode=n -Clto=n \
-Cforce-unwind-tables=n -Ccodegen-units=1 \
-Csymbol-mangling-version=v0 \
Expand Down
1 change: 1 addition & 0 deletions arch/arm64/Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ config ARM64
select HAVE_FUNCTION_ARG_ACCESS_API
select MMU_GATHER_RCU_TABLE_FREE
select HAVE_RSEQ
select HAVE_RUST if CPU_LITTLE_ENDIAN
select HAVE_STACKPROTECTOR
select HAVE_SYSCALL_TRACEPOINTS
select HAVE_KPROBES
Expand Down
4 changes: 4 additions & 0 deletions arch/arm64/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ KBUILD_CFLAGS += -mgeneral-regs-only \
KBUILD_CFLAGS += $(call cc-disable-warning, psabi)
KBUILD_AFLAGS += $(compat_vdso)

KBUILD_RUSTFLAGS += --target=aarch64-unknown-none -Ctarget-feature="-neon"

KBUILD_CFLAGS += $(call cc-option,-mabi=lp64)
KBUILD_AFLAGS += $(call cc-option,-mabi=lp64)

Expand All @@ -65,7 +67,9 @@ endif

ifeq ($(CONFIG_ARM64_BTI_KERNEL),y)
KBUILD_CFLAGS += -mbranch-protection=pac-ret+bti
KBUILD_RUSTFLAGS += -Zbranch-protection=bti,pac-ret
else ifeq ($(CONFIG_ARM64_PTR_AUTH_KERNEL),y)
KBUILD_RUSTFLAGS += -Zbranch-protection=pac-ret
ifeq ($(CONFIG_CC_HAS_BRANCH_PROT_PAC_RET),y)
KBUILD_CFLAGS += -mbranch-protection=pac-ret
else
Expand Down
1 change: 1 addition & 0 deletions arch/x86/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export BITS
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53383
#
KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx
KBUILD_RUSTFLAGS += --target=$(objtree)/scripts/target.json
KBUILD_RUSTFLAGS += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2

ifeq ($(CONFIG_X86_KERNEL_IBT),y)
Expand Down
14 changes: 12 additions & 2 deletions rust/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $<
$(rustc_target_flags) -L$(objtree)/$(obj) \
--output $(rustdoc_output) \
--crate-name $(subst rustdoc-,,$@) \
$(if $(rustdoc_host),,--sysroot=/dev/null) \
@$(objtree)/include/generated/rustc_cfg $<

# The `html_logo_url` and `html_favicon_url` forms of the `doc` attribute
Expand All @@ -98,7 +99,8 @@ rustdoc: rustdoc-core rustdoc-macros rustdoc-compiler_builtins \
$(Q)find $(rustdoc_output) -name '*.html' -type f -print0 | xargs -0 sed -Ei \
-e 's:rust-logo-[0-9a-f]+\.svg:logo.svg:g' \
-e 's:favicon-[0-9a-f]+\.svg:logo.svg:g' \
-e 's:<link rel="alternate icon" type="image/png" href="[/.]+/static\.files/favicon-(16x16|32x32)-[0-9a-f]+\.png">::g'
-e 's:<link rel="alternate icon" type="image/png" href="[/.]+/static\.files/favicon-(16x16|32x32)-[0-9a-f]+\.png">::g' \
-e 's:<a href="srctree/([^"]+)">:<a href="$(abs_srctree)/\1">:g'
$(Q)for f in $(rustdoc_output)/static.files/rustdoc-*.css; do \
echo ".logo-container > img { object-fit: contain; }" >> $$f; done

Expand Down Expand Up @@ -178,6 +180,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $<
--extern build_error --extern macros \
--extern bindings --extern uapi \
--no-run --crate-name kernel -Zunstable-options \
--sysroot=/dev/null \
--test-builder $(objtree)/scripts/rustdoc_test_builder \
$< $(rustdoc_test_kernel_quiet); \
$(objtree)/scripts/rustdoc_test_gen
Expand Down Expand Up @@ -294,6 +297,7 @@ bindgen_skip_c_flags := -mno-fp-ret-in-387 -mpreferred-stack-boundary=% \

# Derived from `scripts/Makefile.clang`.
BINDGEN_TARGET_x86 := x86_64-linux-gnu
BINDGEN_TARGET_arm64 := aarch64-linux-gnu
BINDGEN_TARGET := $(BINDGEN_TARGET_$(SRCARCH))

# All warnings are inhibited since GCC builds are very experimental,
Expand Down Expand Up @@ -337,6 +341,8 @@ quiet_cmd_bindgen = BINDGEN $@

$(obj)/bindings/bindings_generated.rs: private bindgen_target_flags = \
$(shell grep -Ev '^#|^$$' $(srctree)/$(src)/bindgen_parameters)
$(obj)/bindings/bindings_generated.rs: private bindgen_target_extra = ; \
sed -Ei 's/pub const RUST_CONST_HELPER_([a-zA-Z0-9_]*)/pub const \1/g' $@
$(obj)/bindings/bindings_generated.rs: $(src)/bindings/bindings_helper.h \
$(src)/bindgen_parameters FORCE
$(call if_changed_dep,bindgen)
Expand Down Expand Up @@ -402,6 +408,7 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L
--emit=metadata=$(dir $@)$(patsubst %.o,lib%.rmeta,$(notdir $@)) \
--crate-type rlib -L$(objtree)/$(obj) \
--crate-name $(patsubst %.o,%,$(notdir $@)) $< \
--sysroot=/dev/null \
$(if $(rustc_objcopy),;$(OBJCOPY) $(rustc_objcopy) $@)

rust-analyzer:
Expand All @@ -428,8 +435,11 @@ $(obj)/core.o: private skip_clippy = 1
$(obj)/core.o: private skip_flags = -Dunreachable_pub
$(obj)/core.o: private rustc_objcopy = $(foreach sym,$(redirect-intrinsics),--redefine-sym $(sym)=__rust$(sym))
$(obj)/core.o: private rustc_target_flags = $(core-cfgs)
$(obj)/core.o: $(RUST_LIB_SRC)/core/src/lib.rs scripts/target.json FORCE
$(obj)/core.o: $(RUST_LIB_SRC)/core/src/lib.rs FORCE
$(call if_changed_dep,rustc_library)
ifdef CONFIG_X86_64
$(obj)/core.o: scripts/target.json
endif

$(obj)/compiler_builtins.o: private rustc_objcopy = -w -W '__*'
$(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE
Expand Down
41 changes: 31 additions & 10 deletions rust/alloc/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,18 +345,31 @@ extern "Rust" {
fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
}

/// Abort on memory allocation error or failure.
/// Signal a memory allocation error.
///
/// Callers of memory allocation APIs wishing to abort computation
/// Callers of memory allocation APIs wishing to cease execution
/// in response to an allocation error are encouraged to call this function,
/// rather than directly invoking `panic!` or similar.
/// rather than directly invoking [`panic!`] or similar.
///
/// The default behavior of this function is to print a message to standard error
/// and abort the process.
/// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
/// This function is guaranteed to diverge (not return normally with a value), but depending on
/// global configuration, it may either panic (resulting in unwinding or aborting as per
/// configuration for all panics), or abort the process (with no unwinding).
///
/// The default behavior is:
///
/// * If the binary links against `std` (typically the case), then
/// print a message to standard error and abort the process.
/// This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
/// Future versions of Rust may panic by default instead.
///
/// * If the binary does not link against `std` (all of its crates are marked
/// [`#![no_std]`][no_std]), then call [`panic!`] with a message.
/// [The panic handler] applies as to any panic.
///
/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
#[stable(feature = "global_alloc", since = "1.28.0")]
#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
#[cfg(all(not(no_global_oom_handling), not(test)))]
Expand All @@ -366,13 +379,20 @@ pub const fn handle_alloc_error(layout: Layout) -> ! {
panic!("allocation failed");
}

#[inline]
fn rt_error(layout: Layout) -> ! {
unsafe {
__rust_alloc_error_handler(layout.size(), layout.align());
}
}

unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
#[cfg(not(feature = "panic_immediate_abort"))]
unsafe {
core::intrinsics::const_eval_select((layout,), ct_error, rt_error)
}

#[cfg(feature = "panic_immediate_abort")]
ct_error(layout)
}

// For alloc test `std::alloc::handle_alloc_error` can be used directly.
Expand All @@ -397,9 +417,10 @@ pub mod __alloc_error_handler {
if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
panic!("memory allocation of {size} bytes failed")
} else {
core::panicking::panic_nounwind_fmt(format_args!(
"memory allocation of {size} bytes failed"
))
core::panicking::panic_nounwind_fmt(
format_args!("memory allocation of {size} bytes failed"),
/* force_no_backtrace */ false,
)
}
}
}
Expand Down
20 changes: 12 additions & 8 deletions rust/alloc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ use core::marker::Tuple;
use core::marker::Unsize;
use core::mem::{self, SizedTypeProperties};
use core::ops::{
CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, DispatchFromDyn, Receiver,
};
use core::pin::Pin;
use core::ptr::{self, NonNull, Unique};
Expand Down Expand Up @@ -211,7 +211,7 @@ impl<T> Box<T> {
/// ```
/// let five = Box::new(5);
/// ```
#[cfg(all(not(no_global_oom_handling)))]
#[cfg(not(no_global_oom_handling))]
#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
Expand Down Expand Up @@ -2110,28 +2110,28 @@ impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
#[stable(feature = "pin", since = "1.33.0")]
impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}

#[unstable(feature = "generator_trait", issue = "43122")]
impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
#[unstable(feature = "coroutine_trait", issue = "43122")]
impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine<R> for Box<G, A>
where
A: 'static,
{
type Yield = G::Yield;
type Return = G::Return;

fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
G::resume(Pin::new(&mut *self), arg)
}
}

#[unstable(feature = "generator_trait", issue = "43122")]
impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
#[unstable(feature = "coroutine_trait", issue = "43122")]
impl<G: ?Sized + Coroutine<R>, R, A: Allocator> Coroutine<R> for Pin<Box<G, A>>
where
A: 'static,
{
type Yield = G::Yield;
type Return = G::Return;

fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
G::resume((*self).as_mut(), arg)
}
}
Expand Down Expand Up @@ -2448,4 +2448,8 @@ impl<T: core::error::Error> core::error::Error for Box<T> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
core::error::Error::source(&**self)
}

fn provide<'b>(&'b self, request: &mut core::error::Request<'b>) {
core::error::Error::provide(&**self, request);
}
}
Loading