Skip to contentSkip to conversation

Rust support

PATCH Superseded Miguel Ojeda 16 participants 68 messages Aug 2, 2022 – Sep 6, 2022

Subsystems (34)

v8 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Miguel Ojeda

author maintainer
#0 lore raw

v8 cover Rust support

Rust support

This is the patch series (v8) to add support for Rust as a second language to the Linux kernel.

If you are interested in following this effort, please join us in the mailing list at:

[email protected]

and take a look at the project itself at:

https://github.com/Rust-for-Linux

As usual, special thanks go to ISRG (Internet Security Research Group) and Google for their financial support on this endeavor.

Cheers,
Miguel

--

# Rust support

This cover letter explains the major changes and updates done since the previous ones. For those, please see:

    RFC: https://lore.kernel.org/lkml/[email protected]/
    v1:  https://lore.kernel.org/lkml/[email protected]/
    v2:  https://lore.kernel.org/lkml/[email protected]/
    v3:  https://lore.kernel.org/lkml/[email protected]/
    v4:  https://lore.kernel.org/lkml/[email protected]/
    v5:  https://lore.kernel.org/lkml/[email protected]/
    v6:  https://lore.kernel.org/lkml/[email protected]/
    v7:  https://lore.kernel.org/lkml/[email protected]/

## Infrastructure updates

There have been several improvements to the overall Rust support:

- Upgraded toolchain and alloc to Rust 1.62.0 from 1.60.0. Rust 1.61.0 stabilized feature(const_fn_trait_bound) that we are using.

- Moved bindings into their own crate, bindings. This greatly improves build time when only the kernel crate changes (which previously contained the bindings).

- Disabled unused bindgen's layout test generation, which makes rust-analyzer significantly faster to run.

- bindgen can now be detected via the __BINDGEN__ macro, which we currently use to workaround an issue with the btf_type_tag attribute.

- Reimplemented concat_idents! (an unstable standard library macro) as a proc macro, which means we no longer rely on feature(concat_idents). Furthermore, the proc macro allows to refer to local variables.

- Reimplemented static_assert! in a more idiomatic way, now that core::assert!() is supported in const contexts.

- Made build_error!' work under RUST_BUILD_ASSERT_{WARN,ALLOW} for modules.

- Removed __mulodi4 panicking stub.

- Added kernel/configs/rust.config.

- Added a (temporary) self-test module for "pure" Rust tests.

- Changed .i macro expanded files to the .rsi extension and clarified that they are not intended to be compilable.

- Dropped support for compiling the Rust side with a different optimization level than the C side.

- The Linux/Tux SVG logo (recently upstreamed) is used for the generated Rust documentation, instead of the GIF one. The COPYING-logo file is bundled too.

- Other cleanups, fixes and improvements.

## Abstractions and driver updates

Some of the improvements to the abstractions and example drivers are:

- Filesystem support (fs module), including:

+ INode type (which wraps struct inode).
+ DEntry type (which wraps struct dentry).
+ Filename type (which wraps struct filename).
+ Registration type.
+ Type and Context traits.
+ SuperBlock type (which wraps struct super_block and takes advantage of typestates for its initialization).
+ File system parameters support (with a Value enum; Spec* and Constant* types, define_fs_params! macro...).
+ File system flags.
+ module_fs! macro to simplify registering kernel modules that only implement a single file system.
+ A file system sample.

- Workqueues support (workqueue module), including a Work type (which wraps struct work_struct), a Queue type (which wraps struct workqueue_struct), access to different system queues as well as macros to simplify usage, e.g.:

spawn_work_item!(workqueue::system(), || pr_info!("Hi!\n"))?;

- More asynchronous support (kasync module), including:

+ Executor support (including Task and Executor traits, a AutoStopHandle type that automatically stops the executor on drop, a spawn_task! macro that automatically defines a new lockdep lock class...).

+ A workqueue-based executor, which allows to run tasks on dedicated or shared thread pools that are managed by existing C kernel infrastructure, e.g.:

let mut handle = Executor::try_new(workqueue::system())?;

spawn_task!(handle.executor(), async {
pr_info!("First workqueue task\n");
})?;

spawn_task!(handle.executor(), async {
pr_info!("Second workqueue task\n");
})?;

handle.detach();

+ A yield_now() function that yields execution of the current task so that other ones may execute (but keeps it runnable so that it will run again as soon as the executor is available again), e.g.:

async fn example() {
pr_info!("Before yield\n");
yield_now().await;
pr_info!("After yield\n");
}

+ AsyncRevocable type (in the revocable module), which allows access to objects to be revoked without having to wait for existing users to complete. This is useful to drop futures in tasks when executors are being torn down.

+ An asynchronous TCP echo server sample.

- Introduced support for handling interrupts: [Threaded]Handler

    traits, `[Threaded]Registration` types, a `Return` enum (as the
    return value from handlers) and flags:

        struct Example;

        impl irq::Handler for Example {
            type Data = Box<u32>;

            fn handle_irq(_data: &u32) -> irq::Return {
                irq::Return::None
            }
        }

        fn request_irq(irq: u32, data: Box<u32>)
          -> Result<irq::Registration<Example>> {
            irq::Registration::try_new(
                irq, data, irq::flags::SHARED,
                fmt!("example_{irq}")
            )
        }

- Introduced the #[vtable] proc macro attribute to simplify how function pointer tables like struct file_operations are used by Rust kernel modules.

Previously, users had to call a declare_*_operations! macro which required passing the defined operations:

impl file::Operations for SomeFile {
...
declare_file_operations!(read, write, ioctl, ...);
...
}

Instead, now it is only required that they annotate the impl block with the attribute:

#[vtable]
impl file::Operations for SomeFile {
...
}

The proc macro will generate a boolean HAS_* associated constant for each method in the trait, indicating if the implementer has overridden a method.

- Added unsafe_list::List, an intrusive circular doubly-linked list, meant to be used as the basis for other linked lists.

It is also used in the workqueue-based executor to keep track of all tasks since it is cheaper than other options.

- Initial RCU support: a Guard type that represents evidence that

    the RCU read side lock is held on the current thread/CPU.

    In addition, `Revocable` now uses this new abstraction so that
    users can provide evidence of the RCU read side lock being held
    when accessing the protected object, e.g.:

        fn add_pair(value: &Revocable<(u32, u32)>) -> Option<u32> {
            let guard = rcu::read_lock();
            let pair = value.try_access_with_guard(&guard)?;
            Some(pair.0 + pair.1)
        }

- Added StaticRef which allows the creation of "reference-counted" globals; i.e. allows to define static variables that can be used when Ref<T> or RefBorrow<'_, T> are expected.

This, in turn, allows to have functions that return shared resources (e.g. a global workqueue) without allocations (the shared object is statically allocated).

- Added Task::spawn() function to create and automatically run

    kernel threads easily, e.g.:

        for i in 0..10 {
            Task::spawn(fmt!("test{i}"), threadfn).unwrap();
        }

- Added Task::wake_up() method.

- Converted Task to use ARef to unify the usage of all ref-counted C structures.

- Initial support for delays/sleeps (delay module) with a basic coarse_sleep() function that wraps the C side msleep() and takes advantage of the Duration standard library type:

coarse_sleep(Duration::from_millis(20));

- Added file flags (to further reduce bindings::* usage), e.g.:

        let blocking = (file.flags() & file::flags::O_NONBLOCK) == 0;

- Added gpio_chip_register! and gpio_irq_chip_register! macros which automatically define the required lock classes.

- Removal of bindings::lock_class_key from drivers. This gets us closer to eventually make bindings private to the kernel crate.

- Moved usage of ManuallyDrop to MaybeUninit in Revocable, which was unsound.

- Other cleanups, fixes and improvements.

## Patch series updates

The patch series has been reorganized a bit since last time:

- The include/linux/ changes for the C helpers have been moved into their own small patches, which can be taken independently as prerequisite patches if needed.

- Now that the bindings are in their own bindings crate, they also get their own patch.

- There is a new patch that adds the kernel/configs/rust.config.

- One of the kallsyms patches has been split into three smaller ones.

- Cleaned up some "exceeds 100 columns" checkpatch.pl warnings. With this final cleanup, the remaining warnings (of all kinds) are either false positives, or cannot be changed without diverging with upstream alloc or would make things look worse.

## Patch series status

The Rust support is still to be considered experimental. However, support is good enough that kernel developers can start working on the Rust abstractions for subsystems and write drivers and other modules.

The current series will appear in the next linux-next, as usual. Similarly, the preview docs for this series can be seen at:

https://rust-for-linux.github.io/docs/kernel/

As usual, please see the following link for the live list of unstable Rust features we are using:

https://github.com/Rust-for-Linux/linux/issues/2

## Conferences, meetings and liaisons

Join us in LPC 2022 (Linux Plumbers Conference) for the Rust MC (microconference)! The schedule is available at:

    https://lpc.events/event/16/sessions/150/

We will be talking about GCC Rust (the Rust frontend for GCC), rustc_codegen_gcc (the GCC backend for rustc), Rust for Linux, the Rust NVMe driver, the integration of Rust with the Kernel Testing Service and Rust in the Kernel (via eBPF).

In addition, I would like to personally thank Google and ISRG (Internet Security Research Group) for sponsoring Kangrejos, the Rust for Linux workshop:

https://kangrejos.com

Furthermore, we would like to thank the venues we were invited to:

- Linux Foundation Live Mentorship Series
- Open Source Summit North America
- Huawei Global Software Technology Summit

## Related news

The GCC Steering Committee accepted the contribution of the Rust frontend (GCC Rust). Its first released version (experimental, disabled by default) should appear in GCC 13. The first round of patches has been posted to the gcc-patches mailing list.

rustc_codegen_gcc (the GCC backend for rustc) has seen enough progress on SIMD support to compile stdarch. In addition, more prerequisite patches are making their way into GCC.

## Acknowledgements

The signatures in the main commits correspond to the people that wrote code that has ended up in them at the present time. For details on contributions to code and discussions, please see our repository:

https://github.com/Rust-for-Linux/linux

However, we would like to give credit to everyone that has contributed in one way or another to the Rust for Linux project. Since the previous cover letter:

- Nick Desaulniers, Joe Perches, Masahiro Yamada and Jarkko Sakkinen for their reviews of some of the v7 patches.

- Daniel Latypov, Brendan Higgins and Shuah Khan for picking up the KUnit prerequisite patch.

- As usual, Björn Roy Baron (bjorn3) and Gary Guo for all the input on Rust compiler details, reviews and suggestions.

- Andreas Hindborg for working on the NVMe driver, as well as adding atomic allocations for Box and allowing to use GFP flags for KernelAllocator.

- Li Hongyu for working on a virtio abstraction.

- Boqun Feng for working on adding an alloc alignment test.

- Andreas Reindl for working on adding missing SAFETY comments.

- Anhad Singh for working on adding the new_with_flags method

    to `Pages`.

- Finn Behrens for working on making it possible to compile the kernel on macOS with Rust enabled.

- Roel Kluin for working on code refactorings.

- Wei Liu for taking the time to answer questions from newcomers in Zulip.

- Philip Li, Yujie Liu et al. for continuing their work on adding Rust support to the Intel 0DAY/LKP kernel test robot.

- Philip Herron and Arthur Cohen (and his supporters Open Source Security and Embecosm) et al. for their ongoing work on GCC Rust.

- Antoni Boucher (and his supporters) et al. for their ongoing work on rustc_codegen_gcc.

- Emilio Cobos Álvarez et. al. for their work on bindgen, including on issues that affect the kernel.

- Mats Larsen, Marc Poulhiès et al. for their ongoing work on improving Rust support in Compiler Explorer.

- Many folks that have reported issues, tested the project, helped spread the word, joined discussions and contributed in other ways!

Please see also the acknowledgements on the previous cover letters.

Boqun Feng (2):
kallsyms: use sizeof instead of hardcoded size
kallsyms: avoid hardcoding buffer size

Gary Guo (2):
rust: add build_error crate
vsprintf: add new %pA format specifier

Miguel Ojeda (19):
kallsyms: add static relationship between KSYM_NAME_LEN{,_BUFFER}
kallsyms: support "big" kernel symbols
kallsyms: increase maximum kernel symbol length to 512
rust: add C helpers
rust: add compiler_builtins crate
rust: import upstream alloc crate
rust: adapt alloc crate to the kernel
rust: add macros crate
rust: add bindings crate
rust: export generated symbols
scripts: checkpatch: diagnose uses of %pA in the C side as errors
scripts: checkpatch: enable language-independent checks for Rust
scripts: add rustdoc_test_{builder,gen}.py scripts
scripts: add generate_rust_analyzer.py scripts
scripts: decode_stacktrace: demangle Rust symbols
docs: add Rust documentation
Kbuild: add Rust support
samples: add Rust examples
MAINTAINERS: Rust

Wedson Almeida Filho (8):
workqueue: introduce __INIT_WORK_WITH_KEY locking/spinlock: introduce __spin_lock_init locking/spinlock: introduce _raw_spin_lock_init
rust: add kernel crate's sync module
rust: add kernel crate
configs: add rust config
[RFC] drivers: gpio: PrimeCell PL061 in Rust [RFC] drivers: android: Binder IPC in Rust

 .gitignore                                   |    6 +
 .rustfmt.toml                                |   12 +
 Documentation/core-api/printk-formats.rst    |   10 +
 Documentation/doc-guide/kernel-doc.rst       |    3 +
 Documentation/index.rst                      |    1 +
 Documentation/kbuild/kbuild.rst              |   17 +
 Documentation/kbuild/makefiles.rst           |   50 +-
 Documentation/process/changes.rst            |   41 +
 Documentation/rust/arch-support.rst          |   23 +
 Documentation/rust/coding-guidelines.rst     |  216 ++
 Documentation/rust/general-information.rst   |   79 +
 Documentation/rust/index.rst                 |   22 +
 Documentation/rust/quick-start.rst           |  232 ++
 MAINTAINERS                                  |   15 +
 Makefile                                     |  172 +-
 arch/Kconfig                                 |    6 +
 arch/arm/Kconfig                             |    1 +
 arch/arm64/Kconfig                           |    1 +
 arch/powerpc/Kconfig                         |    1 +
 arch/riscv/Kconfig                           |    1 +
 arch/riscv/Makefile                          |    5 +
 arch/um/Kconfig                              |    1 +
 arch/x86/Kconfig                             |    1 +
 arch/x86/Makefile                            |   10 +
 drivers/android/Kconfig                      |    6 +
 drivers/android/Makefile                     |    2 +
 drivers/android/allocation.rs                |  266 ++
 drivers/android/context.rs                   |   80 +
 drivers/android/defs.rs                      |   99 +
 drivers/android/node.rs                      |  476 +++
 drivers/android/process.rs                   |  961 +++++
 drivers/android/range_alloc.rs               |  189 +
 drivers/android/rust_binder.rs               |  106 +
 drivers/android/thread.rs                    |  871 +++++
 drivers/android/transaction.rs               |  326 ++
 drivers/gpio/Kconfig                         |    8 +
 drivers/gpio/Makefile                        |    1 +
 drivers/gpio/gpio_pl061_rust.rs              |  367 ++
 include/linux/compiler_types.h               |    6 +-
 include/linux/kallsyms.h                     |    2 +-
 include/linux/spinlock.h                     |   17 +-
 include/linux/workqueue.h                    |   21 +-
 include/uapi/linux/android/binder.h          |   30 +-
 init/Kconfig                                 |   46 +-
 kernel/configs/rust.config                   |    1 +
 kernel/kallsyms.c                            |   26 +-
 kernel/livepatch/core.c                      |    4 +-
 lib/Kconfig.debug                            |   82 +
 lib/vsprintf.c                               |   13 +
 rust/.gitignore                              |   10 +
 rust/Makefile                                |  415 +++
 rust/alloc/README.md                         |   33 +
 rust/alloc/alloc.rs                          |  440 +++
 rust/alloc/borrow.rs                         |  498 +++
 rust/alloc/boxed.rs                          | 2026 +++++++++++
 rust/alloc/boxed/thin.rs                     |  219 ++
 rust/alloc/collections/mod.rs                |  156 +
 rust/alloc/ffi/c_str.rs                      | 1203 ++++++
 rust/alloc/ffi/mod.rs                        |   93 +
 rust/alloc/fmt.rs                            |  614 ++++
 rust/alloc/lib.rs                            |  239 ++
 rust/alloc/macros.rs                         |  128 +
 rust/alloc/raw_vec.rs                        |  567 +++
 rust/alloc/slice.rs                          | 1295 +++++++
 rust/alloc/str.rs                            |  641 ++++
 rust/alloc/string.rs                         | 2944 +++++++++++++++
 rust/alloc/vec/drain.rs                      |  186 +
 rust/alloc/vec/drain_filter.rs               |  145 +
 rust/alloc/vec/into_iter.rs                  |  365 ++
 rust/alloc/vec/is_zero.rs                    |  120 +
 rust/alloc/vec/mod.rs                        | 3420 ++++++++++++++++++
 rust/alloc/vec/partial_eq.rs                 |   49 +
 rust/alloc/vec/set_len_on_drop.rs            |   30 +
 rust/alloc/vec/spec_extend.rs                |  174 +
 rust/bindgen_parameters                      |   21 +
 rust/bindings/bindings_helper.h              |   49 +
 rust/bindings/lib.rs                         |   57 +
 rust/build_error.rs                          |   29 +
 rust/compiler_builtins.rs                    |   79 +
 rust/exports.c                               |   21 +
 rust/helpers.c                               |  679 ++++
 rust/kernel/allocator.rs                     |   64 +
 rust/kernel/amba.rs                          |  261 ++
 rust/kernel/build_assert.rs                  |   83 +
 rust/kernel/chrdev.rs                        |  206 ++
 rust/kernel/clk.rs                           |   79 +
 rust/kernel/cred.rs                          |   46 +
 rust/kernel/delay.rs                         |  104 +
 rust/kernel/device.rs                        |  527 +++
 rust/kernel/driver.rs                        |  442 +++
 rust/kernel/error.rs                         |  564 +++
 rust/kernel/file.rs                          |  887 +++++
 rust/kernel/fs.rs                            |  846 +++++
 rust/kernel/fs/param.rs                      |  553 +++
 rust/kernel/gpio.rs                          |  505 +++
 rust/kernel/hwrng.rs                         |  210 ++
 rust/kernel/io_buffer.rs                     |  153 +
 rust/kernel/io_mem.rs                        |  278 ++
 rust/kernel/iov_iter.rs                      |   81 +
 rust/kernel/irq.rs                           |  681 ++++
 rust/kernel/kasync.rs                        |   50 +
 rust/kernel/kasync/executor.rs               |  154 +
 rust/kernel/kasync/executor/workqueue.rs     |  291 ++
 rust/kernel/kasync/net.rs                    |  322 ++
 rust/kernel/kunit.rs                         |   91 +
 rust/kernel/lib.rs                           |  267 ++
 rust/kernel/linked_list.rs                   |  247 ++
 rust/kernel/miscdev.rs                       |  290 ++
 rust/kernel/mm.rs                            |  149 +
 rust/kernel/module_param.rs                  |  499 +++
 rust/kernel/net.rs                           |  392 ++
 rust/kernel/net/filter.rs                    |  447 +++
 rust/kernel/of.rs                            |   63 +
 rust/kernel/pages.rs                         |  144 +
 rust/kernel/platform.rs                      |  223 ++
 rust/kernel/power.rs                         |  118 +
 rust/kernel/prelude.rs                       |   36 +
 rust/kernel/print.rs                         |  406 +++
 rust/kernel/random.rs                        |   42 +
 rust/kernel/raw_list.rs                      |  361 ++
 rust/kernel/rbtree.rs                        |  563 +++
 rust/kernel/revocable.rs                     |  425 +++
 rust/kernel/security.rs                      |   38 +
 rust/kernel/static_assert.rs                 |   34 +
 rust/kernel/std_vendor.rs                    |  161 +
 rust/kernel/str.rs                           |  597 +++
 rust/kernel/sync.rs                          |  169 +
 rust/kernel/sync/arc.rs                      |  582 +++
 rust/kernel/sync/condvar.rs                  |  140 +
 rust/kernel/sync/guard.rs                    |  159 +
 rust/kernel/sync/locked_by.rs                |  111 +
 rust/kernel/sync/mutex.rs                    |  149 +
 rust/kernel/sync/nowait.rs                   |  188 +
 rust/kernel/sync/rcu.rs                      |   52 +
 rust/kernel/sync/revocable.rs                |  246 ++
 rust/kernel/sync/rwsem.rs                    |  196 +
 rust/kernel/sync/seqlock.rs                  |  201 +
 rust/kernel/sync/smutex.rs                   |  290 ++
 rust/kernel/sync/spinlock.rs                 |  357 ++
 rust/kernel/sysctl.rs                        |  199 +
 rust/kernel/task.rs                          |  239 ++
 rust/kernel/types.rs                         |  705 ++++
 rust/kernel/unsafe_list.rs                   |  680 ++++
 rust/kernel/user_ptr.rs                      |  175 +
 rust/kernel/workqueue.rs                     |  512 +++
 rust/macros/concat_idents.rs                 |   23 +
 rust/macros/helpers.rs                       |   79 +
 rust/macros/lib.rs                           |  191 +
 rust/macros/module.rs                        |  655 ++++
 rust/macros/vtable.rs                        |   95 +
 samples/Kconfig                              |    2 +
 samples/Makefile                             |    1 +
 samples/rust/Kconfig                         |  165 +
 samples/rust/Makefile                        |   19 +
 samples/rust/hostprogs/.gitignore            |    3 +
 samples/rust/hostprogs/Makefile              |    5 +
 samples/rust/hostprogs/a.rs                  |    7 +
 samples/rust/hostprogs/b.rs                  |    5 +
 samples/rust/hostprogs/single.rs             |   12 +
 samples/rust/rust_chrdev.rs                  |   49 +
 samples/rust/rust_echo_server.rs             |   60 +
 samples/rust/rust_fs.rs                      |   59 +
 samples/rust/rust_minimal.rs                 |   35 +
 samples/rust/rust_miscdev.rs                 |  142 +
 samples/rust/rust_module_parameters.rs       |   69 +
 samples/rust/rust_netfilter.rs               |   54 +
 samples/rust/rust_platform.rs                |   22 +
 samples/rust/rust_print.rs                   |   54 +
 samples/rust/rust_random.rs                  |   60 +
 samples/rust/rust_selftests.rs               |   99 +
 samples/rust/rust_semaphore.rs               |  170 +
 samples/rust/rust_semaphore_c.c              |  212 ++
 samples/rust/rust_stack_probing.rs           |   36 +
 samples/rust/rust_sync.rs                    |   93 +
 scripts/.gitignore                           |    1 +
 scripts/Kconfig.include                      |    6 +-
 scripts/Makefile                             |    3 +
 scripts/Makefile.build                       |   60 +
 scripts/Makefile.debug                       |   10 +
 scripts/Makefile.host                        |   34 +-
 scripts/Makefile.lib                         |   12 +
 scripts/Makefile.modfinal                    |    8 +-
 scripts/cc-version.sh                        |   12 +-
 scripts/checkpatch.pl                        |   12 +-
 scripts/decode_stacktrace.sh                 |   14 +
 scripts/generate_rust_analyzer.py            |  141 +
 scripts/generate_rust_target.rs              |  232 ++
 scripts/is_rust_module.sh                    |   16 +
 scripts/kallsyms.c                           |   47 +-
 scripts/kconfig/confdata.c                   |   75 +
 scripts/min-tool-version.sh                  |    6 +
 scripts/rust-is-available-bindgen-libclang.h |    2 +
 scripts/rust-is-available.sh                 |  160 +
 scripts/rustdoc_test_builder.py              |   59 +
 scripts/rustdoc_test_gen.py                  |  164 +
 tools/include/linux/kallsyms.h               |    2 +-
 tools/lib/perf/include/perf/event.h          |    2 +-
 tools/lib/symbol/kallsyms.h                  |    2 +-
 198 files changed, 43688 insertions(+), 75 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 Documentation/rust/arch-support.rst
 create mode 100644 Documentation/rust/coding-guidelines.rst
 create mode 100644 Documentation/rust/general-information.rst
 create mode 100644 Documentation/rust/index.rst
 create mode 100644 Documentation/rust/quick-start.rst
 create mode 100644 drivers/android/allocation.rs
 create mode 100644 drivers/android/context.rs
 create mode 100644 drivers/android/defs.rs
 create mode 100644 drivers/android/node.rs
 create mode 100644 drivers/android/process.rs
 create mode 100644 drivers/android/range_alloc.rs
 create mode 100644 drivers/android/rust_binder.rs
 create mode 100644 drivers/android/thread.rs
 create mode 100644 drivers/android/transaction.rs
 create mode 100644 drivers/gpio/gpio_pl061_rust.rs
 create mode 100644 kernel/configs/rust.config
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Makefile
 create mode 100644 rust/alloc/README.md
 create mode 100644 rust/alloc/alloc.rs
 create mode 100644 rust/alloc/borrow.rs
 create mode 100644 rust/alloc/boxed.rs
 create mode 100644 rust/alloc/boxed/thin.rs
 create mode 100644 rust/alloc/collections/mod.rs
 create mode 100644 rust/alloc/ffi/c_str.rs
 create mode 100644 rust/alloc/ffi/mod.rs
 create mode 100644 rust/alloc/fmt.rs
 create mode 100644 rust/alloc/lib.rs
 create mode 100644 rust/alloc/macros.rs
 create mode 100644 rust/alloc/raw_vec.rs
 create mode 100644 rust/alloc/slice.rs
 create mode 100644 rust/alloc/str.rs
 create mode 100644 rust/alloc/string.rs
 create mode 100644 rust/alloc/vec/drain.rs
 create mode 100644 rust/alloc/vec/drain_filter.rs
 create mode 100644 rust/alloc/vec/into_iter.rs
 create mode 100644 rust/alloc/vec/is_zero.rs
 create mode 100644 rust/alloc/vec/mod.rs
 create mode 100644 rust/alloc/vec/partial_eq.rs
 create mode 100644 rust/alloc/vec/set_len_on_drop.rs
 create mode 100644 rust/alloc/vec/spec_extend.rs
 create mode 100644 rust/bindgen_parameters
 create mode 100644 rust/bindings/bindings_helper.h
 create mode 100644 rust/bindings/lib.rs
 create mode 100644 rust/build_error.rs
 create mode 100644 rust/compiler_builtins.rs
 create mode 100644 rust/exports.c
 create mode 100644 rust/helpers.c
 create mode 100644 rust/kernel/allocator.rs
 create mode 100644 rust/kernel/amba.rs
 create mode 100644 rust/kernel/build_assert.rs
 create mode 100644 rust/kernel/chrdev.rs
 create mode 100644 rust/kernel/clk.rs
 create mode 100644 rust/kernel/cred.rs
 create mode 100644 rust/kernel/delay.rs
 create mode 100644 rust/kernel/device.rs
 create mode 100644 rust/kernel/driver.rs
 create mode 100644 rust/kernel/error.rs
 create mode 100644 rust/kernel/file.rs
 create mode 100644 rust/kernel/fs.rs
 create mode 100644 rust/kernel/fs/param.rs
 create mode 100644 rust/kernel/gpio.rs
 create mode 100644 rust/kernel/hwrng.rs
 create mode 100644 rust/kernel/io_buffer.rs
 create mode 100644 rust/kernel/io_mem.rs
 create mode 100644 rust/kernel/iov_iter.rs
 create mode 100644 rust/kernel/irq.rs
 create mode 100644 rust/kernel/kasync.rs
 create mode 100644 rust/kernel/kasync/executor.rs
 create mode 100644 rust/kernel/kasync/executor/workqueue.rs
 create mode 100644 rust/kernel/kasync/net.rs
 create mode 100644 rust/kernel/kunit.rs
 create mode 100644 rust/kernel/lib.rs
 create mode 100644 rust/kernel/linked_list.rs
 create mode 100644 rust/kernel/miscdev.rs
 create mode 100644 rust/kernel/mm.rs
 create mode 100644 rust/kernel/module_param.rs
 create mode 100644 rust/kernel/net.rs
 create mode 100644 rust/kernel/net/filter.rs
 create mode 100644 rust/kernel/of.rs
 create mode 100644 rust/kernel/pages.rs
 create mode 100644 rust/kernel/platform.rs
 create mode 100644 rust/kernel/power.rs
 create mode 100644 rust/kernel/prelude.rs
 create mode 100644 rust/kernel/print.rs
 create mode 100644 rust/kernel/random.rs
 create mode 100644 rust/kernel/raw_list.rs
 create mode 100644 rust/kernel/rbtree.rs
 create mode 100644 rust/kernel/revocable.rs
 create mode 100644 rust/kernel/security.rs
 create mode 100644 rust/kernel/static_assert.rs
 create mode 100644 rust/kernel/std_vendor.rs
 create mode 100644 rust/kernel/str.rs
 create mode 100644 rust/kernel/sync.rs
 create mode 100644 rust/kernel/sync/arc.rs
 create mode 100644 rust/kernel/sync/condvar.rs
 create mode 100644 rust/kernel/sync/guard.rs
 create mode 100644 rust/kernel/sync/locked_by.rs
 create mode 100644 rust/kernel/sync/mutex.rs
 create mode 100644 rust/kernel/sync/nowait.rs
 create mode 100644 rust/kernel/sync/rcu.rs
 create mode 100644 rust/kernel/sync/revocable.rs
 create mode 100644 rust/kernel/sync/rwsem.rs
 create mode 100644 rust/kernel/sync/seqlock.rs
 create mode 100644 rust/kernel/sync/smutex.rs
 create mode 100644 rust/kernel/sync/spinlock.rs
 create mode 100644 rust/kernel/sysctl.rs
 create mode 100644 rust/kernel/task.rs
 create mode 100644 rust/kernel/types.rs
 create mode 100644 rust/kernel/unsafe_list.rs
 create mode 100644 rust/kernel/user_ptr.rs
 create mode 100644 rust/kernel/workqueue.rs
 create mode 100644 rust/macros/concat_idents.rs
 create mode 100644 rust/macros/helpers.rs
 create mode 100644 rust/macros/lib.rs
 create mode 100644 rust/macros/module.rs
 create mode 100644 rust/macros/vtable.rs
 create mode 100644 samples/rust/Kconfig
 create mode 100644 samples/rust/Makefile
 create mode 100644 samples/rust/hostprogs/.gitignore
 create mode 100644 samples/rust/hostprogs/Makefile
 create mode 100644 samples/rust/hostprogs/a.rs
 create mode 100644 samples/rust/hostprogs/b.rs
 create mode 100644 samples/rust/hostprogs/single.rs
 create mode 100644 samples/rust/rust_chrdev.rs
 create mode 100644 samples/rust/rust_echo_server.rs
 create mode 100644 samples/rust/rust_fs.rs
 create mode 100644 samples/rust/rust_minimal.rs
 create mode 100644 samples/rust/rust_miscdev.rs
 create mode 100644 samples/rust/rust_module_parameters.rs
 create mode 100644 samples/rust/rust_netfilter.rs
 create mode 100644 samples/rust/rust_platform.rs
 create mode 100644 samples/rust/rust_print.rs
 create mode 100644 samples/rust/rust_random.rs
 create mode 100644 samples/rust/rust_selftests.rs
 create mode 100644 samples/rust/rust_semaphore.rs
 create mode 100644 samples/rust/rust_semaphore_c.c
 create mode 100644 samples/rust/rust_stack_probing.rs
 create mode 100644 samples/rust/rust_sync.rs
 create mode 100755 scripts/generate_rust_analyzer.py
 create mode 100644 scripts/generate_rust_target.rs
 create mode 100755 scripts/is_rust_module.sh
 create mode 100644 scripts/rust-is-available-bindgen-libclang.h
 create mode 100755 scripts/rust-is-available.sh
 create mode 100755 scripts/rustdoc_test_builder.py
 create mode 100755 scripts/rustdoc_test_gen.py

base-commit: 3d7cb6b04c3f3115719235cc6866b10326de34cd

Signature · 1 line
2.37.1
author maintainer
#38 lore raw

PATCH v8 27/31 Kbuild: add Rust support

Having all the new files in place, we now enable Rust support in the build system, including Kconfig entries related to Rust, the Rust configuration printer, the target specification generation script, the version detection script and a few other bits.

---
 .gitignore                                   |   6 +
 .rustfmt.toml                                |  12 +
 Makefile                                     | 172 +++++++-
 arch/Kconfig                                 |   6 +
 arch/arm/Kconfig                             |   1 +
 arch/arm64/Kconfig                           |   1 +
 arch/powerpc/Kconfig                         |   1 +
 arch/riscv/Kconfig                           |   1 +
 arch/riscv/Makefile                          |   5 +
 arch/um/Kconfig                              |   1 +
 arch/x86/Kconfig                             |   1 +
 arch/x86/Makefile                            |  10 +
 include/linux/compiler_types.h               |   6 +-
 init/Kconfig                                 |  46 +-
 lib/Kconfig.debug                            |  82 ++++
 rust/.gitignore                              |  10 +
 rust/Makefile                                | 415 +++++++++++++++++++
 rust/bindgen_parameters                      |  21 +
 scripts/.gitignore                           |   1 +
 scripts/Kconfig.include                      |   6 +-
 scripts/Makefile                             |   3 +
 scripts/Makefile.build                       |  60 +++
 scripts/Makefile.debug                       |  10 +
 scripts/Makefile.host                        |  34 +-
 scripts/Makefile.lib                         |  12 +
 scripts/Makefile.modfinal                    |   8 +-
 scripts/cc-version.sh                        |  12 +-
 scripts/generate_rust_target.rs              | 232 +++++++++++
 scripts/is_rust_module.sh                    |  16 +
 scripts/kconfig/confdata.c                   |  75 ++++
 scripts/min-tool-version.sh                  |   6 +
 scripts/rust-is-available-bindgen-libclang.h |   2 +
 scripts/rust-is-available.sh                 | 160 +++++++
 33 files changed, 1408 insertions(+), 26 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Makefile
 create mode 100644 rust/bindgen_parameters
 create mode 100644 scripts/generate_rust_target.rs
 create mode 100755 scripts/is_rust_module.sh
 create mode 100644 scripts/rust-is-available-bindgen-libclang.h
 create mode 100755 scripts/rust-is-available.sh
.gitignore +6 -0
index 265959544978..5da004814678 100644
@@ -37,6 +37,8 @@
 *.o
 *.o.*
 *.patch
+*.rmeta
+*.rsi
 *.s
 *.so
 *.so.dbg
@@ -97,6 +99,7 @@ modules.order
 !.gitattributes
 !.gitignore
 !.mailmap
+!.rustfmt.toml
 
 #
 # Generated include files
@@ -162,3 +165,6 @@ x509.genkey
 
 # Documentation toolchain
 sphinx_*/
+
+# Rust analyzer configuration
+/rust-project.json
.rustfmt.toml new file +12 -0
new file mode 100644
index 000000000000..3de5cc497465
@@ -0,0 +1,12 @@
+edition = "2021"
+newline_style = "Unix"
+
+# Unstable options that help catching some mistakes in formatting and that we may want to enable
+# when they become stable.
+#
+# They are kept here since they are useful to run from time to time.
+#format_code_in_doc_comments = true
+#reorder_impl_items = true
+#comment_width = 100
+#wrap_comments = true
+#normalize_comments = true
Makefile +163 -9

342 lines not on this page · raw message

arch/Kconfig +6 -0
index 71b9272acb28..d5038cf8dd49 100644
@@ -353,6 +353,12 @@ config HAVE_RSEQ
 	  This symbol should be selected by an architecture if it
 	  supports an implementation of restartable sequences.
 
+config HAVE_RUST
+	bool
+	help
+	  This symbol should be selected by an architecture if it
+	  supports Rust.
+
 config HAVE_FUNCTION_ARG_ACCESS_API
 	bool
 	help
arch/arm/Kconfig +1 -0
index 7630ba9cb6cc..147655a4fc27 100644
@@ -116,6 +116,7 @@ config ARM
 	select MMU_GATHER_RCU_TABLE_FREE if SMP && ARM_LPAE
 	select HAVE_REGS_AND_STACK_ACCESS_API
 	select HAVE_RSEQ
+	select HAVE_RUST if CPU_32v6 || CPU_32v6K
 	select HAVE_STACKPROTECTOR
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_UID16
arch/arm64/Kconfig +1 -0
index 1652a9800ebe..aaeb70358979 100644
@@ -201,6 +201,7 @@ config ARM64
 	select HAVE_FUNCTION_ARG_ACCESS_API
 	select MMU_GATHER_RCU_TABLE_FREE
 	select HAVE_RSEQ
+	select HAVE_RUST
 	select HAVE_STACKPROTECTOR
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_KPROBES
arch/powerpc/Kconfig +1 -0
index 4d8f26c1399b..edab3cc9edf5 100644
@@ -243,6 +243,7 @@ config PPC
 	select HAVE_REGS_AND_STACK_ACCESS_API
 	select HAVE_RELIABLE_STACKTRACE
 	select HAVE_RSEQ
+	select HAVE_RUST			if PPC64 && CPU_LITTLE_ENDIAN
 	select HAVE_SETUP_PER_CPU_AREA		if PPC64
 	select HAVE_SOFTIRQ_ON_OWN_STACK
 	select HAVE_STACKPROTECTOR		if PPC32 && $(cc-option,-mstack-protector-guard=tls -mstack-protector-guard-reg=r2)
arch/riscv/Kconfig +1 -0
index fcbb81feb7ad..5b53b41528f6 100644
@@ -104,6 +104,7 @@ config RISCV
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RUST if 64BIT
 	select HAVE_FUNCTION_ARG_ACCESS_API
 	select HAVE_STACKPROTECTOR
 	select HAVE_SYSCALL_TRACEPOINTS
arch/riscv/Makefile +5 -0
index 81029d40a672..24ebe042406e 100644
@@ -26,6 +26,8 @@ ifeq ($(CONFIG_ARCH_RV64I),y)
 	KBUILD_CFLAGS += -mabi=lp64
 	KBUILD_AFLAGS += -mabi=lp64
 
+	KBUILD_RUSTFLAGS += -Ctarget-cpu=generic-rv64
+
 	KBUILD_LDFLAGS += -melf64lriscv
 else
 	BITS := 32
@@ -33,6 +35,9 @@ else
 
 	KBUILD_CFLAGS += -mabi=ilp32
 	KBUILD_AFLAGS += -mabi=ilp32
+
+	KBUILD_RUSTFLAGS += -Ctarget-cpu=generic-rv32
+
 	KBUILD_LDFLAGS += -melf32lriscv
 endif
 
arch/um/Kconfig +1 -0
index 4ec22e156a2e..6dc06a7bf8b7 100644
@@ -25,6 +25,7 @@ config UML
 	select TRACE_IRQFLAGS_SUPPORT
 	select TTY # Needed for line.c
 	select HAVE_ARCH_VMAP_STACK
+	select HAVE_RUST			if X86_64
 
 config MMU
 	bool
arch/x86/Kconfig +1 -0
index 52a7f91527fe..4d5a3f256cbc 100644
@@ -258,6 +258,7 @@ config X86
 	select HAVE_STATIC_CALL_INLINE		if HAVE_OBJTOOL
 	select HAVE_PREEMPT_DYNAMIC_CALL
 	select HAVE_RSEQ
+	select HAVE_RUST			if X86_64
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_UACCESS_VALIDATION		if HAVE_OBJTOOL
 	select HAVE_UNSTABLE_SCHED_CLOCK
arch/x86/Makefile +10 -0
index 7854685c5f25..bab595003f07 100644
@@ -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 += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2
 
 ifeq ($(CONFIG_X86_KERNEL_IBT),y)
 #
@@ -155,8 +156,17 @@ else
         cflags-$(CONFIG_GENERIC_CPU)	+= -mtune=generic
         KBUILD_CFLAGS += $(cflags-y)
 
+        rustflags-$(CONFIG_MK8)		+= -Ctarget-cpu=k8
+        rustflags-$(CONFIG_MPSC)	+= -Ctarget-cpu=nocona
+        rustflags-$(CONFIG_MCORE2)	+= -Ctarget-cpu=core2
+        rustflags-$(CONFIG_MATOM)	+= -Ctarget-cpu=atom
+        rustflags-$(CONFIG_GENERIC_CPU)	+= -Ztune-cpu=generic
+        KBUILD_RUSTFLAGS += $(rustflags-y)
+
         KBUILD_CFLAGS += -mno-red-zone
         KBUILD_CFLAGS += -mcmodel=kernel
+        KBUILD_RUSTFLAGS += -Cno-redzone=y
+        KBUILD_RUSTFLAGS += -Ccode-model=kernel
 endif
 
 #
include/linux/compiler_types.h +5 -1
index 4f2a819fd60a..50b3f6b9502e 100644
@@ -4,8 +4,12 @@
 
 #ifndef __ASSEMBLY__
 
+/*
+ * Skipped when running bindgen due to a libclang issue;
+ * see https://github.com/rust-lang/rust-bindgen/issues/2244.
+ */
 #if defined(CONFIG_DEBUG_INFO_BTF) && defined(CONFIG_PAHOLE_HAS_BTF_TAG) && \
-	__has_attribute(btf_type_tag)
+	__has_attribute(btf_type_tag) && !defined(__BINDGEN__)
 # define BTF_TYPE_TAG(value) __attribute__((btf_type_tag(#value)))
 #else
 # define BTF_TYPE_TAG(value) /* nothing */
init/Kconfig +45 -1

64 lines not on this page · raw message

lib/Kconfig.debug +82 -0

88 lines not on this page · raw message

rust/.gitignore new file +10 -0
new file mode 100644
index 000000000000..89b602d91109
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+
+target.json
+bindings_generated.rs
+bindings_helpers_generated.rs
+exports_*_generated.h
+doctests_kernel_generated.rs
+doctests_kernel_generated_kunit.c
+doc/
+test/
rust/Makefile new file +415 -0

415 lines not on this page · raw message

rust/bindgen_parameters new file +21 -0
new file mode 100644
index 000000000000..be4963bf7203
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0
+
+--opaque-type xregs_state
+--opaque-type desc_struct
+--opaque-type arch_lbr_state
+--opaque-type local_apic
+
+# Packed type cannot transitively contain a `#[repr(align)]` type.
+--opaque-type x86_msi_data
+--opaque-type x86_msi_addr_lo
+
+# `try` is a reserved keyword since Rust 2018; solved in `bindgen` v0.59.2,
+# commit 2aed6b021680 ("context: Escape the try keyword properly").
+--opaque-type kunit_try_catch
+
+# If SMP is disabled, `arch_spinlock_t` is defined as a ZST which triggers a Rust
+# warning. We don't need to peek into it anyway.
+--opaque-type spinlock
+
+# `seccomp`'s comment gets understood as a doctest
+--no-doc-comments
scripts/.gitignore +1 -0
index eed308bef604..b7aec8eb1bd4 100644
@@ -1,6 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 /asn1_compiler
 /bin2c
+/generate_rust_target
 /insert-sys-cert
 /kallsyms
 /module.lds
scripts/Kconfig.include +3 -3
index 0496efd6e117..83e850321eb6 100644
@@ -36,12 +36,12 @@ ld-option = $(success,$(LD) -v $(1))
 as-instr = $(success,printf "%b\n" "$(1)" | $(CC) $(CLANG_FLAGS) -c -x assembler -o /dev/null -)
 
 # check if $(CC) and $(LD) exist
-$(error-if,$(failure,command -v $(CC)),compiler '$(CC)' not found)
+$(error-if,$(failure,command -v $(CC)),C compiler '$(CC)' not found)
 $(error-if,$(failure,command -v $(LD)),linker '$(LD)' not found)
 
-# Get the compiler name, version, and error out if it is not supported.
+# Get the C compiler name, version, and error out if it is not supported.
 cc-info := $(shell,$(srctree)/scripts/cc-version.sh $(CC))
-$(error-if,$(success,test -z "$(cc-info)"),Sorry$(comma) this compiler is not supported.)
+$(error-if,$(success,test -z "$(cc-info)"),Sorry$(comma) this C compiler is not supported.)
 cc-name := $(shell,set -- $(cc-info) && echo $1)
 cc-version := $(shell,set -- $(cc-info) && echo $2)
 
scripts/Makefile +3 -0
index f084f08ed176..1575af84d557 100644
@@ -10,6 +10,9 @@ hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT)		+= sorttable
 hostprogs-always-$(CONFIG_ASN1)				+= asn1_compiler
 hostprogs-always-$(CONFIG_MODULE_SIG_FORMAT)		+= sign-file
 hostprogs-always-$(CONFIG_SYSTEM_EXTRA_CERTIFICATE)	+= insert-sys-cert
+hostprogs-always-$(CONFIG_RUST)				+= generate_rust_target
+
+generate_rust_target-rust := y
 
 HOSTCFLAGS_sorttable.o = -I$(srctree)/tools/include
 HOSTLDLIBS_sorttable = -lpthread
scripts/Makefile.build +60 -0

72 lines not on this page · raw message

scripts/Makefile.debug +10 -0
index 9f39b0130551..fe87389d52c0 100644
@@ -1,4 +1,5 @@
 DEBUG_CFLAGS	:=
+DEBUG_RUSTFLAGS	:=
 
 ifdef CONFIG_DEBUG_INFO_SPLIT
 DEBUG_CFLAGS	+= -gsplit-dwarf
@@ -10,6 +11,12 @@ ifndef CONFIG_AS_IS_LLVM
 KBUILD_AFLAGS	+= -Wa,-gdwarf-2
 endif
 
+ifdef CONFIG_DEBUG_INFO_REDUCED
+DEBUG_RUSTFLAGS += -Cdebuginfo=1
+else
+DEBUG_RUSTFLAGS += -Cdebuginfo=2
+endif
+
 ifndef CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT
 dwarf-version-$(CONFIG_DEBUG_INFO_DWARF4) := 4
 dwarf-version-$(CONFIG_DEBUG_INFO_DWARF5) := 5
@@ -31,3 +38,6 @@ endif
 
 KBUILD_CFLAGS += $(DEBUG_CFLAGS)
 export DEBUG_CFLAGS
+
+KBUILD_RUSTFLAGS += $(DEBUG_RUSTFLAGS)
+export DEBUG_RUSTFLAGS
scripts/Makefile.host +31 -3
index 278b4d6ac945..da133780b751 100644
@@ -22,6 +22,8 @@ $(obj)/%.tab.c $(obj)/%.tab.h: $(src)/%.y FORCE
 # to preprocess a data file.
 #
 # Both C and C++ are supported, but preferred language is C for such utilities.
+# Rust is also supported, but it may only be used in scenarios where a Rust
+# toolchain is required to be available (e.g. when  `CONFIG_RUST` is enabled).
 #
 # Sample syntax (see Documentation/kbuild/makefiles.rst for reference)
 # hostprogs := bin2hex
@@ -37,15 +39,20 @@ $(obj)/%.tab.c $(obj)/%.tab.h: $(src)/%.y FORCE
 # qconf-objs      := menu.o
 # Will compile qconf as a C++ program, and menu as a C program.
 # They are linked as C++ code to the executable qconf
+#
+# hostprogs   := target
+# target-rust := y
+# Will compile `target` as a Rust program, using `target.rs` as the crate root.
+# The crate may consist of several source files.
 
 # C code
 # Executables compiled from a single .c file
 host-csingle	:= $(foreach m,$(hostprogs), \
-			$(if $($(m)-objs)$($(m)-cxxobjs),,$(m)))
+			$(if $($(m)-objs)$($(m)-cxxobjs)$($(m)-rust),,$(m)))
 
 # C executables linked based on several .o files
 host-cmulti	:= $(foreach m,$(hostprogs),\
-		   $(if $($(m)-cxxobjs),,$(if $($(m)-objs),$(m))))
+		   $(if $($(m)-cxxobjs)$($(m)-rust),,$(if $($(m)-objs),$(m))))
 
 # Object (.o) files compiled from .c files
 host-cobjs	:= $(sort $(foreach m,$(hostprogs),$($(m)-objs)))
@@ -58,11 +65,17 @@ host-cxxmulti	:= $(foreach m,$(hostprogs),$(if $($(m)-cxxobjs),$(m)))
 # C++ Object (.o) files compiled from .cc files
 host-cxxobjs	:= $(sort $(foreach m,$(host-cxxmulti),$($(m)-cxxobjs)))
 
+# Rust code
+# Executables compiled from a single Rust crate (which may consist of
+# one or more .rs files)
+host-rust	:= $(foreach m,$(hostprogs),$(if $($(m)-rust),$(m)))
+
 host-csingle	:= $(addprefix $(obj)/,$(host-csingle))
 host-cmulti	:= $(addprefix $(obj)/,$(host-cmulti))
 host-cobjs	:= $(addprefix $(obj)/,$(host-cobjs))
 host-cxxmulti	:= $(addprefix $(obj)/,$(host-cxxmulti))
 host-cxxobjs	:= $(addprefix $(obj)/,$(host-cxxobjs))
+host-rust	:= $(addprefix $(obj)/,$(host-rust))
 
 #####
 # Handle options to gcc. Support building with separate output directory
@@ -71,6 +84,8 @@ _hostc_flags   = $(KBUILD_HOSTCFLAGS)   $(HOST_EXTRACFLAGS)   \
                  $(HOSTCFLAGS_$(target-stem).o)
 _hostcxx_flags = $(KBUILD_HOSTCXXFLAGS) $(HOST_EXTRACXXFLAGS) \
                  $(HOSTCXXFLAGS_$(target-stem).o)
+_hostrust_flags = $(KBUILD_HOSTRUSTFLAGS) $(HOST_EXTRARUSTFLAGS) \
+                  $(HOSTRUSTFLAGS_$(target-stem))
 
 # $(objtree)/$(obj) for including generated headers from checkin source files
 ifeq ($(KBUILD_EXTMOD),)
@@ -82,6 +97,7 @@ endif
 
 hostc_flags    = -Wp,-MMD,$(depfile) $(_hostc_flags)
 hostcxx_flags  = -Wp,-MMD,$(depfile) $(_hostcxx_flags)
+hostrust_flags = $(_hostrust_flags)
 
 #####
 # Compile programs on the host
@@ -128,5 +144,17 @@ quiet_cmd_host-cxxobjs	= HOSTCXX $@
 $(host-cxxobjs): $(obj)/%.o: $(src)/%.cc FORCE
 	$(call if_changed_dep,host-cxxobjs)
 
+# Create executable from a single Rust crate (which may consist of
+# one or more `.rs` files)
+# host-rust -> Executable
+quiet_cmd_host-rust	= HOSTRUSTC $@
+      cmd_host-rust	= \
+	$(HOSTRUSTC) $(hostrust_flags) --emit=dep-info,link \
+		--out-dir=$(obj)/ $<; \
+	mv $(obj)/$(target-stem).d $(depfile); \
+	sed -i '/^\#/d' $(depfile)
+$(host-rust): $(obj)/%: $(src)/%.rs FORCE
+	$(call if_changed_dep,host-rust)
+
 targets += $(host-csingle) $(host-cmulti) $(host-cobjs) \
-	   $(host-cxxmulti) $(host-cxxobjs)
+	   $(host-cxxmulti) $(host-cxxobjs) $(host-rust)
scripts/Makefile.lib +12 -0
index 3fb6a99e78c4..c88b98b5dc44 100644
@@ -8,6 +8,7 @@ ldflags-y  += $(EXTRA_LDFLAGS)
 # flags that take effect in current and sub directories
 KBUILD_AFLAGS += $(subdir-asflags-y)
 KBUILD_CFLAGS += $(subdir-ccflags-y)
+KBUILD_RUSTFLAGS += $(subdir-rustflags-y)
 
 # Figure out what we need to build from the various variables
 # ===========================================================================
@@ -128,6 +129,10 @@ _c_flags       = $(filter-out $(CFLAGS_REMOVE_$(target-stem).o), \
                      $(filter-out $(ccflags-remove-y), \
                          $(KBUILD_CPPFLAGS) $(KBUILD_CFLAGS) $(ccflags-y)) \
                      $(CFLAGS_$(target-stem).o))
+_rust_flags    = $(filter-out $(RUSTFLAGS_REMOVE_$(target-stem).o), \
+                     $(filter-out $(rustflags-remove-y), \
+                         $(KBUILD_RUSTFLAGS) $(rustflags-y)) \
+                     $(RUSTFLAGS_$(target-stem).o))
 _a_flags       = $(filter-out $(AFLAGS_REMOVE_$(target-stem).o), \
                      $(filter-out $(asflags-remove-y), \
                          $(KBUILD_CPPFLAGS) $(KBUILD_AFLAGS) $(asflags-y)) \
@@ -202,6 +207,11 @@ modkern_cflags =                                          \
 		$(KBUILD_CFLAGS_MODULE) $(CFLAGS_MODULE), \
 		$(KBUILD_CFLAGS_KERNEL) $(CFLAGS_KERNEL) $(modfile_flags))
 
+modkern_rustflags =                                              \
+	$(if $(part-of-module),                                   \
+		$(KBUILD_RUSTFLAGS_MODULE) $(RUSTFLAGS_MODULE), \
+		$(KBUILD_RUSTFLAGS_KERNEL) $(RUSTFLAGS_KERNEL))
+
 modkern_aflags = $(if $(part-of-module),				\
 			$(KBUILD_AFLAGS_MODULE) $(AFLAGS_MODULE),	\
 			$(KBUILD_AFLAGS_KERNEL) $(AFLAGS_KERNEL))
@@ -211,6 +221,8 @@ c_flags        = -Wp,-MMD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE)     \
 		 $(_c_flags) $(modkern_cflags)                           \
 		 $(basename_flags) $(modname_flags)
 
+rust_flags     = $(_rust_flags) $(modkern_rustflags) @$(objtree)/include/generated/rustc_cfg
+
 a_flags        = -Wp,-MMD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE)     \
 		 $(_a_flags) $(modkern_aflags)
 
scripts/Makefile.modfinal +5 -3
index 35100e981f4a..9a1fa6aa30fe 100644
@@ -39,11 +39,13 @@ quiet_cmd_ld_ko_o = LD [M]  $@
 
 quiet_cmd_btf_ko = BTF [M] $@
       cmd_btf_ko = 							\
-	if [ -f vmlinux ]; then						\
+	if [ ! -f vmlinux ]; then					\
+		printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \
+	elif [ -n "$(CONFIG_RUST)" ] && $(srctree)/scripts/is_rust_module.sh $@; then 		\
+		printf "Skipping BTF generation for %s because it's a Rust module\n" $@ 1>&2; \
+	else								\
 		LLVM_OBJCOPY="$(OBJCOPY)" $(PAHOLE) -J $(PAHOLE_FLAGS) --btf_base vmlinux $@; \
 		$(RESOLVE_BTFIDS) -b vmlinux $@; 			\
-	else								\
-		printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \
 	fi;
 
 # Same as newer-prereqs, but allows to exclude specified extra dependencies
scripts/cc-version.sh +6 -6
index f1952c522466..2401c86fcf53 100755
@@ -1,13 +1,13 @@
 #!/bin/sh
 # SPDX-License-Identifier: GPL-2.0
 #
-# Print the compiler name and its version in a 5 or 6-digit form.
+# Print the C compiler name and its version in a 5 or 6-digit form.
 # Also, perform the minimum version check.
 
 set -e
 
-# Print the compiler name and some version components.
-get_compiler_info()
+# Print the C compiler name and some version components.
+get_c_compiler_info()
 {
 	cat <<- EOF | "$@" -E -P -x c - 2>/dev/null
 	#if defined(__clang__)
@@ -32,7 +32,7 @@ get_canonical_version()
 
 # $@ instead of $1 because multiple words might be given, e.g. CC="ccache gcc".
 orig_args="$@"
-set -- $(get_compiler_info "$@")
+set -- $(get_c_compiler_info "$@")
 
 name=$1
 
@@ -52,7 +52,7 @@ ICC)
 	min_version=$($min_tool_version icc)
 	;;
 *)
-	echo "$orig_args: unknown compiler" >&2
+	echo "$orig_args: unknown C compiler" >&2
 	exit 1
 	;;
 esac
@@ -62,7 +62,7 @@ min_cversion=$(get_canonical_version $min_version)
 
 if [ "$cversion" -lt "$min_cversion" ]; then
 	echo >&2 "***"
-	echo >&2 "*** Compiler is too old."
+	echo >&2 "*** C compiler is too old."
 	echo >&2 "***   Your $name version:    $version"
 	echo >&2 "***   Minimum $name version: $min_version"
 	echo >&2 "***"
scripts/generate_rust_target.rs new file +232 -0

232 lines not on this page · raw message

scripts/is_rust_module.sh new file +16 -0
new file mode 100755
index 000000000000..28b3831a7593
@@ -0,0 +1,16 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+#
+# is_rust_module.sh module.ko
+#
+# Returns `0` if `module.ko` is a Rust module, `1` otherwise.
+
+set -e
+
+# Using the `16_` prefix ensures other symbols with the same substring
+# are not picked up (even if it would be unlikely). The last part is
+# used just in case LLVM decides to use the `.` suffix.
+#
+# In the future, checking for the `.comment` section may be another
+# option, see https://github.com/rust-lang/rust/pull/97550.
+${NM} "$*" | grep -qE '^[0-9a-fA-F]+ r _R[^[:space:]]+16___IS_RUST_MODULE[^[:space:]]*$'
scripts/kconfig/confdata.c +75 -0

99 lines not on this page · raw message

scripts/min-tool-version.sh +6 -0
index 250925aab101..b6593eac5003 100755
@@ -30,6 +30,12 @@ llvm)
 		echo 11.0.0
 	fi
 	;;
+rustc)
+	echo 1.62.0
+	;;
+bindgen)
+	echo 0.56.0
+	;;
 *)
 	echo "$1: unknown tool" >&2
 	exit 1
scripts/rust-is-available-bindgen-libclang.h new file +2 -0
new file mode 100644
index 000000000000..0ef6db10d674
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#pragma message("clang version " __clang_version__)
scripts/rust-is-available.sh new file +160 -0

160 lines not on this page · raw message

Signature · 7 lines
2.37.1


_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
author maintainer
#1 lore raw

PATCH v8 1/31 kallsyms: use `sizeof` instead of hardcoded size

In reply to Miguel Ojeda

From: Boqun Feng <[email protected]>

This removes one place where the 500 constant is hardcoded.

---
 scripts/kallsyms.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/kallsyms.c +1 -1
index f18e6dfc68c5..52f5488c61bc 100644
@@ -206,7 +206,7 @@ static struct sym_entry *read_symbol(FILE *in)
 
 	rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
 	if (rc != 3) {
-		if (rc != EOF && fgets(name, 500, in) == NULL)
+		if (rc != EOF && fgets(name, sizeof(name), in) == NULL)
 			fprintf(stderr, "Read error or end of file.\n");
 		return NULL;
 	}
Signature · 1 line
2.37.1
author maintainer
#2 lore raw

PATCH v8 2/31 kallsyms: avoid hardcoding buffer size

In reply to Miguel Ojeda

From: Boqun Feng <[email protected]>

This introduces KSYM_NAME_LEN_BUFFER in place of the previously hardcoded size of the input buffer.

It will also make it easier to update the size in a single place in a later patch.

---
 scripts/kallsyms.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
scripts/kallsyms.c +8 -2
index 52f5488c61bc..f3c5a2623f71 100644
@@ -27,8 +27,14 @@
 
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
 
+#define _stringify_1(x)	#x
+#define _stringify(x)	_stringify_1(x)
+
 #define KSYM_NAME_LEN		128
 
+/* A substantially bigger size than the current maximum. */
+#define KSYM_NAME_LEN_BUFFER	499
+
 struct sym_entry {
 	unsigned long long addr;
 	unsigned int len;
@@ -198,13 +204,13 @@ static void check_symbol_range(const char *sym, unsigned long long addr,
 
 static struct sym_entry *read_symbol(FILE *in)
 {
-	char name[500], type;
+	char name[KSYM_NAME_LEN_BUFFER+1], type;
 	unsigned long long addr;
 	unsigned int len;
 	struct sym_entry *sym;
 	int rc;
 
-	rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
+	rc = fscanf(in, "%llx %c %" _stringify(KSYM_NAME_LEN_BUFFER) "s\n", &addr, &type, name);
 	if (rc != 3) {
 		if (rc != EOF && fgets(name, sizeof(name), in) == NULL)
 			fprintf(stderr, "Read error or end of file.\n");
Signature · 1 line
2.37.1
author maintainer
#5 lore raw

PATCH v8 3/31 kallsyms: add static relationship between `KSYM_NAME_LEN{,_BUFFER}`

In reply to Miguel Ojeda

This adds a static assert to ensure KSYM_NAME_LEN_BUFFER gets updated when KSYM_NAME_LEN changes.

The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).

---
 scripts/kallsyms.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
scripts/kallsyms.c +5 -1
index f3c5a2623f71..f543b1c4f99f 100644
@@ -33,7 +33,11 @@
 #define KSYM_NAME_LEN		128
 
 /* A substantially bigger size than the current maximum. */
-#define KSYM_NAME_LEN_BUFFER	499
+#define KSYM_NAME_LEN_BUFFER	512
+_Static_assert(
+	KSYM_NAME_LEN_BUFFER == KSYM_NAME_LEN * 4,
+	"Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN"
+);
 
 struct sym_entry {
 	unsigned long long addr;
Signature · 1 line
2.37.1
author maintainer
#6 lore raw

PATCH v8 4/31 kallsyms: support "big" kernel symbols

In reply to Miguel Ojeda

Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc.

Increasing to 255 is not enough in some cases, therefore introduce longer lengths to the symbol table.

In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.

---
 kernel/kallsyms.c  | 26 ++++++++++++++++++++++----
 scripts/kallsyms.c | 29 ++++++++++++++++++++++++++---
 2 files changed, 48 insertions(+), 7 deletions(-)
kernel/kallsyms.c +22 -4
index fbdf8d3279ac..87e2b1638115 100644
@@ -70,12 +70,20 @@ static unsigned int kallsyms_expand_symbol(unsigned int off,
 	data = &kallsyms_names[off];
 	len = *data;
 	data++;
+	off++;
+
+	/* If MSB is 1, it is a "big" symbol, so needs an additional byte. */
+	if ((len & 0x80) != 0) {
+		len = (len & 0x7F) | (*data << 7);
+		data++;
+		off++;
+	}
 
 	/*
 	 * Update the offset to return the offset for the next symbol on
 	 * the compressed stream.
 	 */
-	off += len + 1;
+	off += len;
 
 	/*
 	 * For every byte on the compressed symbol data, copy the table
@@ -128,7 +136,7 @@ static char kallsyms_get_symbol_type(unsigned int off)
 static unsigned int get_symbol_offset(unsigned long pos)
 {
 	const u8 *name;
-	int i;
+	int i, len;
 
 	/*
 	 * Use the closest marker we have. We have markers every 256 positions,
@@ -142,8 +150,18 @@ static unsigned int get_symbol_offset(unsigned long pos)
 	 * so we just need to add the len to the current pointer for every
 	 * symbol we wish to skip.
 	 */
-	for (i = 0; i < (pos & 0xFF); i++)
-		name = name + (*name) + 1;
+	for (i = 0; i < (pos & 0xFF); i++) {
+		len = *name;
+
+		/*
+		 * If MSB is 1, it is a "big" symbol, so we need to look into
+		 * the next byte (and skip it, too).
+		 */
+		if ((len & 0x80) != 0)
+			len = ((len & 0x7F) | (name[1] << 7)) + 1;
+
+		name = name + len + 1;
+	}
 
 	return name - kallsyms_names;
 }
scripts/kallsyms.c +26 -3
index f543b1c4f99f..9da3b7767e9d 100644
@@ -481,12 +481,35 @@ static void write_src(void)
 		if ((i & 0xFF) == 0)
 			markers[i >> 8] = off;
 
-		printf("\t.byte 0x%02x", table[i]->len);
+		/* There cannot be any symbol of length zero. */
+		if (table[i]->len == 0) {
+			fprintf(stderr, "kallsyms failure: "
+				"unexpected zero symbol length\n");
+			exit(EXIT_FAILURE);
+		}
+
+		/* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
+		if (table[i]->len > 0x3FFF) {
+			fprintf(stderr, "kallsyms failure: "
+				"unexpected huge symbol length\n");
+			exit(EXIT_FAILURE);
+		}
+
+		/* Encode length with ULEB128. */
+		if (table[i]->len <= 0x7F) {
+			/* Most symbols use a single byte for the length. */
+			printf("\t.byte 0x%02x", table[i]->len);
+			off += table[i]->len + 1;
+		} else {
+			/* "Big" symbols use two bytes. */
+			printf("\t.byte 0x%02x, 0x%02x",
+				(table[i]->len & 0x7F) | 0x80,
+				(table[i]->len >> 7) & 0x7F);
+			off += table[i]->len + 2;
+		}
 		for (k = 0; k < table[i]->len; k++)
 			printf(", 0x%02x", table[i]->sym[k]);
 		printf("\n");
-
-		off += table[i]->len + 1;
 	}
 	printf("\n");
 
Signature · 1 line
2.37.1
author maintainer
#7 lore raw

PATCH v8 5/31 kallsyms: increase maximum kernel symbol length to 512

In reply to Miguel Ojeda

Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc. For instance, the following code:

    pub mod my_module {
        pub struct MyType;
        pub struct MyGenericType<T>(T);

        pub trait MyTrait {
            fn my_method() -> u32;
        }

        impl MyTrait for MyGenericType<MyType> {
            fn my_method() -> u32 {
                42
            }
        }
    }

generates a symbol of length 96 when using the upcoming v0 mangling scheme:

_RNvXNtCshGpAVYOtgW1_7example9my_moduleINtB2_13MyGenericTypeNtB2_6MyTypeENtB2_7MyTrait9my_method

At the moment, Rust symbols may reach up to 300 in length. Setting 512 as the maximum seems like a reasonable choice to keep some headroom.

---
 include/linux/kallsyms.h            | 2 +-
 kernel/livepatch/core.c             | 4 ++--
 scripts/kallsyms.c                  | 4 ++--
 tools/include/linux/kallsyms.h      | 2 +-
 tools/lib/perf/include/perf/event.h | 2 +-
 tools/lib/symbol/kallsyms.h         | 2 +-
 6 files changed, 8 insertions(+), 8 deletions(-)
include/linux/kallsyms.h +1 -1
index ad39636e0c3f..649faac31ddb 100644
@@ -15,7 +15,7 @@
 
 #include <asm/sections.h>
 
-#define KSYM_NAME_LEN 128
+#define KSYM_NAME_LEN 512
 #define KSYM_SYMBOL_LEN (sizeof("%s+%#lx/%#lx [%s %s]") + \
 			(KSYM_NAME_LEN - 1) + \
 			2*(BITS_PER_LONG*3/10) + (MODULE_NAME_LEN - 1) + \
kernel/livepatch/core.c +2 -2
index bc475e62279d..ec06ce59d728 100644
@@ -213,7 +213,7 @@ static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,
 	 * we use the smallest/strictest upper bound possible (56, based on
 	 * the current definition of MODULE_NAME_LEN) to prevent overflows.
 	 */
-	BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 128);
+	BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 512);
 
 	relas = (Elf_Rela *) relasec->sh_addr;
 	/* For each rela in this klp relocation section */
@@ -227,7 +227,7 @@ static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,
 
 		/* Format: .klp.sym.sym_objname.sym_name,sympos */
 		cnt = sscanf(strtab + sym->st_name,
-			     ".klp.sym.%55[^.].%127[^,],%lu",
+			     ".klp.sym.%55[^.].%511[^,],%lu",
 			     sym_objname, sym_name, &sympos);
 		if (cnt != 3) {
 			pr_err("symbol %s has an incorrectly formatted name\n",
scripts/kallsyms.c +2 -2
index 9da3b7767e9d..3b64dda7e4cc 100644
@@ -30,10 +30,10 @@
 #define _stringify_1(x)	#x
 #define _stringify(x)	_stringify_1(x)
 
-#define KSYM_NAME_LEN		128
+#define KSYM_NAME_LEN		512
 
 /* A substantially bigger size than the current maximum. */
-#define KSYM_NAME_LEN_BUFFER	512
+#define KSYM_NAME_LEN_BUFFER	2048
 _Static_assert(
 	KSYM_NAME_LEN_BUFFER == KSYM_NAME_LEN * 4,
 	"Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN"
tools/include/linux/kallsyms.h +1 -1
index efb6c3f5f2a9..5a37ccbec54f 100644
@@ -6,7 +6,7 @@
 #include <stdio.h>
 #include <unistd.h>
 
-#define KSYM_NAME_LEN 128
+#define KSYM_NAME_LEN 512
 
 struct module;
 
tools/lib/perf/include/perf/event.h +1 -1
index e7758707cadd..116a80c31675 100644
@@ -95,7 +95,7 @@ struct perf_record_throttle {
 };
 
 #ifndef KSYM_NAME_LEN
-#define KSYM_NAME_LEN 256
+#define KSYM_NAME_LEN 512
 #endif
 
 struct perf_record_ksymbol {
tools/lib/symbol/kallsyms.h +1 -1
index 72ab9870454b..542f9b059c3b 100644
@@ -7,7 +7,7 @@
 #include <linux/types.h>
 
 #ifndef KSYM_NAME_LEN
-#define KSYM_NAME_LEN 256
+#define KSYM_NAME_LEN 512
 #endif
 
 static inline u8 kallsyms2elf_binding(char type)
Signature · 1 line
2.37.1
author maintainer
#8 lore raw

PATCH v8 6/31 workqueue: introduce `__INIT_WORK_WITH_KEY`

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call __INIT_WORK with a passed key, rather than define one in place.

In order to do that, this moves the initialization code from the __INIT_WORK macro into a new __INIT_WORK_WITH_KEY macro which takes the key as an extra parameter.

---
 include/linux/workqueue.h | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)
include/linux/workqueue.h +14 -7
index 62e75dd40d9a..06c24805e666 100644
@@ -221,24 +221,31 @@ static inline unsigned int work_static(struct work_struct *work) { return 0; }
  * to generate better code.
  */
 #ifdef CONFIG_LOCKDEP
+#define __INIT_WORK_WITH_KEY(_work, _func, _onstack, _key)		\
+	do {								\
+		__init_work((_work), _onstack);				\
+		(_work)->data = (atomic_long_t) WORK_DATA_INIT();	\
+		lockdep_init_map(&(_work)->lockdep_map, "(work_completion)"#_work, _key, 0); \
+		INIT_LIST_HEAD(&(_work)->entry);			\
+		(_work)->func = (_func);				\
+	} while (0)
+
 #define __INIT_WORK(_work, _func, _onstack)				\
 	do {								\
 		static struct lock_class_key __key;			\
-									\
-		__init_work((_work), _onstack);				\
-		(_work)->data = (atomic_long_t) WORK_DATA_INIT();	\
-		lockdep_init_map(&(_work)->lockdep_map, "(work_completion)"#_work, &__key, 0); \
-		INIT_LIST_HEAD(&(_work)->entry);			\
-		(_work)->func = (_func);				\
+		__INIT_WORK_WITH_KEY(_work, _func, _onstack, &__key);	\
 	} while (0)
 #else
-#define __INIT_WORK(_work, _func, _onstack)				\
+#define __INIT_WORK_WITH_KEY(_work, _func, _onstack, _key)		\
 	do {								\
 		__init_work((_work), _onstack);				\
 		(_work)->data = (atomic_long_t) WORK_DATA_INIT();	\
 		INIT_LIST_HEAD(&(_work)->entry);			\
 		(_work)->func = (_func);				\
 	} while (0)
+
+#define __INIT_WORK(_work, _func, _onstack)				\
+	__INIT_WORK_WITH_KEY(_work, _func, _onstack, NULL)
 #endif
 
 #define INIT_WORK(_work, _func)						\
Signature · 1 line
2.37.1
author maintainer
#11 lore raw

PATCH v8 7/31 locking/spinlock: introduce `__spin_lock_init`

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call spin_lock_init with a passed key, rather than define one in place.

In order to do that, this changes the spin_lock_init macro to call a new __spin_lock_init function which takes the key as an extra parameter.

---
 include/linux/spinlock.h | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
include/linux/spinlock.h +7 -2
index 5c0c5174155d..ad1c91884ed8 100644
@@ -326,12 +326,17 @@ static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock)
 
 #ifdef CONFIG_DEBUG_SPINLOCK
 
+static inline void __spin_lock_init(spinlock_t *lock, const char *name,
+				    struct lock_class_key *key)
+{
+	__raw_spin_lock_init(spinlock_check(lock), name, key, LD_WAIT_CONFIG);
+}
+
 # define spin_lock_init(lock)					\
 do {								\
 	static struct lock_class_key __key;			\
 								\
-	__raw_spin_lock_init(spinlock_check(lock),		\
-			     #lock, &__key, LD_WAIT_CONFIG);	\
+	__spin_lock_init(lock, #lock, &__key);			\
 } while (0)
 
 #else
Signature · 1 line
2.37.1
author maintainer
#13 lore raw

PATCH v8 8/31 locking/spinlock: introduce `_raw_spin_lock_init`

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call raw_spin_lock_init with a passed key, rather than define one in place.

In order to do that, this changes the raw_spin_lock_init macro to call a new _raw_spin_lock_init function which takes the key as an extra parameter.

---
 include/linux/spinlock.h | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
include/linux/spinlock.h +7 -1
index ad1c91884ed8..27df5380c1e4 100644
@@ -99,11 +99,17 @@
   extern void __raw_spin_lock_init(raw_spinlock_t *lock, const char *name,
 				   struct lock_class_key *key, short inner);
 
+static inline void _raw_spin_lock_init(raw_spinlock_t *lock, const char *name,
+				       struct lock_class_key *key)
+{
+	__raw_spin_lock_init(lock, name, key, LD_WAIT_SPIN);
+}
+
 # define raw_spin_lock_init(lock)					\
 do {									\
 	static struct lock_class_key __key;				\
 									\
-	__raw_spin_lock_init((lock), #lock, &__key, LD_WAIT_SPIN);	\
+	_raw_spin_lock_init((lock), #lock, &__key);			\
 } while (0)
 
 #else
Signature · 1 line
2.37.1
author maintainer
#15 lore raw

PATCH v8 9/31 rust: add C helpers

In reply to Miguel Ojeda

This source file contains forwarders to C macros and inlined functions.

---
 rust/helpers.c | 679 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 679 insertions(+)
 create mode 100644 rust/helpers.c
rust/helpers.c new file +679 -0
new file mode 100644
index 000000000000..bf790f46c763
@@ -0,0 +1,679 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Non-trivial C macros cannot be used in Rust. Similarly, inlined C functions
+ * cannot be called either. This file explicitly creates functions ("helpers")
+ * that wrap those so that they can be called from Rust.
+ *
+ * Even though Rust kernel modules should never use directly the bindings, some
+ * of these helpers need to be exported because Rust generics and inlined
+ * functions may not get their code generated in the crate where they are
+ * defined. Other helpers, called from non-inline functions, may not be
+ * exported, in principle. However, in general, the Rust compiler does not
+ * guarantee codegen will be performed for a non-inline function either.
+ * Therefore, this file exports all the helpers. In the future, this may be
+ * revisited to reduce the number of exports after the compiler is informed
+ * about the places codegen is required.
+ *
+ * All symbols are exported as GPL-only to guarantee no GPL-only feature is
+ * accidentally exposed.
+ */
+
+#include <linux/amba/bus.h>
+#include <linux/bug.h>
+#include <linux/build_bug.h>
+#include <linux/clk.h>
+#include <linux/errname.h>
+#include <linux/fs_parser.h>
+#include <linux/gfp.h>
+#include <linux/highmem.h>
+#include <linux/io.h>
+#include <linux/irqchip/chained_irq.h>
+#include <linux/irqdomain.h>
+#include <linux/irq.h>
+#include <linux/mutex.h>
+#include <linux/netdevice.h>
+#include <linux/of_device.h>
+#include <linux/platform_device.h>
+#include <linux/sched/signal.h>
+#include <linux/security.h>
+#include <linux/skbuff.h>
+#include <linux/uaccess.h>
+#include <linux/uio.h>
+
+__noreturn void rust_helper_BUG(void)
+{
+	BUG();
+}
+EXPORT_SYMBOL_GPL(rust_helper_BUG);
+
+void rust_helper_clk_disable_unprepare(struct clk *clk)
+{
+	return clk_disable_unprepare(clk);
+}
+EXPORT_SYMBOL_GPL(rust_helper_clk_disable_unprepare);
+
+int rust_helper_clk_prepare_enable(struct clk *clk)
+{
+	return clk_prepare_enable(clk);
+}
+EXPORT_SYMBOL_GPL(rust_helper_clk_prepare_enable);
+
+unsigned long rust_helper_copy_from_user(void *to, const void __user *from, unsigned long n)
+{
+	return copy_from_user(to, from, n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_from_user);
+
+unsigned long rust_helper_copy_to_user(void __user *to, const void *from, unsigned long n)
+{
+	return copy_to_user(to, from, n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_to_user);
+
+unsigned long rust_helper_clear_user(void __user *to, unsigned long n)
+{
+	return clear_user(to, n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_clear_user);
+
+void __iomem *rust_helper_ioremap(resource_size_t offset, unsigned long size)
+{
+	return ioremap(offset, size);
+}
+EXPORT_SYMBOL_GPL(rust_helper_ioremap);
+
+u8 rust_helper_readb(const volatile void __iomem *addr)
+{
+	return readb(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readb);
+
+u16 rust_helper_readw(const volatile void __iomem *addr)
+{
+	return readw(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readw);
+
+u32 rust_helper_readl(const volatile void __iomem *addr)
+{
+	return readl(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readl);
+
+#ifdef CONFIG_64BIT
+u64 rust_helper_readq(const volatile void __iomem *addr)
+{
+	return readq(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readq);
+#endif
+
+void rust_helper_writeb(u8 value, volatile void __iomem *addr)
+{
+	writeb(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writeb);
+
+void rust_helper_writew(u16 value, volatile void __iomem *addr)
+{
+	writew(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writew);
+
+void rust_helper_writel(u32 value, volatile void __iomem *addr)
+{
+	writel(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writel);
+
+#ifdef CONFIG_64BIT
+void rust_helper_writeq(u64 value, volatile void __iomem *addr)
+{
+	writeq(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writeq);
+#endif
+
+u8 rust_helper_readb_relaxed(const volatile void __iomem *addr)
+{
+	return readb_relaxed(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readb_relaxed);
+
+u16 rust_helper_readw_relaxed(const volatile void __iomem *addr)
+{
+	return readw_relaxed(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readw_relaxed);
+
+u32 rust_helper_readl_relaxed(const volatile void __iomem *addr)
+{
+	return readl_relaxed(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readl_relaxed);
+
+#ifdef CONFIG_64BIT
+u64 rust_helper_readq_relaxed(const volatile void __iomem *addr)
+{
+	return readq_relaxed(addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_readq_relaxed);
+#endif
+
+void rust_helper_writeb_relaxed(u8 value, volatile void __iomem *addr)
+{
+	writeb_relaxed(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writeb_relaxed);
+
+void rust_helper_writew_relaxed(u16 value, volatile void __iomem *addr)
+{
+	writew_relaxed(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writew_relaxed);
+
+void rust_helper_writel_relaxed(u32 value, volatile void __iomem *addr)
+{
+	writel_relaxed(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writel_relaxed);
+
+#ifdef CONFIG_64BIT
+void rust_helper_writeq_relaxed(u64 value, volatile void __iomem *addr)
+{
+	writeq_relaxed(value, addr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_writeq_relaxed);
+#endif
+
+void rust_helper_memcpy_fromio(void *to, const volatile void __iomem *from, long count)
+{
+	memcpy_fromio(to, from, count);
+}
+EXPORT_SYMBOL_GPL(rust_helper_memcpy_fromio);
+
+void rust_helper___spin_lock_init(spinlock_t *lock, const char *name,
+				  struct lock_class_key *key)
+{
+#ifdef CONFIG_DEBUG_SPINLOCK
+	__spin_lock_init(lock, name, key);
+#else
+	spin_lock_init(lock);
+#endif
+}
+EXPORT_SYMBOL_GPL(rust_helper___spin_lock_init);
+
+void rust_helper_spin_lock(spinlock_t *lock)
+{
+	spin_lock(lock);
+}
+EXPORT_SYMBOL_GPL(rust_helper_spin_lock);
+
+void rust_helper_spin_unlock(spinlock_t *lock)
+{
+	spin_unlock(lock);
+}
+EXPORT_SYMBOL_GPL(rust_helper_spin_unlock);
+
+unsigned long rust_helper_spin_lock_irqsave(spinlock_t *lock)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(lock, flags);
+
+	return flags;
+}
+EXPORT_SYMBOL_GPL(rust_helper_spin_lock_irqsave);
+
+void rust_helper_spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags)
+{
+	spin_unlock_irqrestore(lock, flags);
+}
+EXPORT_SYMBOL_GPL(rust_helper_spin_unlock_irqrestore);
+
+void rust_helper__raw_spin_lock_init(raw_spinlock_t *lock, const char *name,
+				     struct lock_class_key *key)
+{
+#ifdef CONFIG_DEBUG_SPINLOCK
+	_raw_spin_lock_init(lock, name, key);
+#else
+	raw_spin_lock_init(lock);
+#endif
+}
+EXPORT_SYMBOL_GPL(rust_helper__raw_spin_lock_init);
+
+void rust_helper_raw_spin_lock(raw_spinlock_t *lock)
+{
+	raw_spin_lock(lock);
+}
+EXPORT_SYMBOL_GPL(rust_helper_raw_spin_lock);
+
+void rust_helper_raw_spin_unlock(raw_spinlock_t *lock)
+{
+	raw_spin_unlock(lock);
+}
+EXPORT_SYMBOL_GPL(rust_helper_raw_spin_unlock);
+
+unsigned long rust_helper_raw_spin_lock_irqsave(raw_spinlock_t *lock)
+{
+	unsigned long flags;
+
+	raw_spin_lock_irqsave(lock, flags);
+
+	return flags;
+}
+EXPORT_SYMBOL_GPL(rust_helper_raw_spin_lock_irqsave);
+
+void rust_helper_raw_spin_unlock_irqrestore(raw_spinlock_t *lock,
+					    unsigned long flags)
+{
+	raw_spin_unlock_irqrestore(lock, flags);
+}
+EXPORT_SYMBOL_GPL(rust_helper_raw_spin_unlock_irqrestore);
+
+void rust_helper_init_wait(struct wait_queue_entry *wq_entry)
+{
+	init_wait(wq_entry);
+}
+EXPORT_SYMBOL_GPL(rust_helper_init_wait);
+
+void rust_helper_init_waitqueue_func_entry(struct wait_queue_entry *wq_entry,
+					   wait_queue_func_t func)
+{
+	init_waitqueue_func_entry(wq_entry, func);
+}
+EXPORT_SYMBOL_GPL(rust_helper_init_waitqueue_func_entry);
+
+int rust_helper_signal_pending(struct task_struct *t)
+{
+	return signal_pending(t);
+}
+EXPORT_SYMBOL_GPL(rust_helper_signal_pending);
+
+struct page *rust_helper_alloc_pages(gfp_t gfp_mask, unsigned int order)
+{
+	return alloc_pages(gfp_mask, order);
+}
+EXPORT_SYMBOL_GPL(rust_helper_alloc_pages);
+
+void *rust_helper_kmap(struct page *page)
+{
+	return kmap(page);
+}
+EXPORT_SYMBOL_GPL(rust_helper_kmap);
+
+void rust_helper_kunmap(struct page *page)
+{
+	return kunmap(page);
+}
+EXPORT_SYMBOL_GPL(rust_helper_kunmap);
+
+int rust_helper_cond_resched(void)
+{
+	return cond_resched();
+}
+EXPORT_SYMBOL_GPL(rust_helper_cond_resched);
+
+size_t rust_helper_copy_from_iter(void *addr, size_t bytes, struct iov_iter *i)
+{
+	return copy_from_iter(addr, bytes, i);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_from_iter);
+
+size_t rust_helper_copy_to_iter(const void *addr, size_t bytes, struct iov_iter *i)
+{
+	return copy_to_iter(addr, bytes, i);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_to_iter);
+
+bool rust_helper_IS_ERR(__force const void *ptr)
+{
+	return IS_ERR(ptr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_IS_ERR);
+
+long rust_helper_PTR_ERR(__force const void *ptr)
+{
+	return PTR_ERR(ptr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_PTR_ERR);
+
+const char *rust_helper_errname(int err)
+{
+	return errname(err);
+}
+EXPORT_SYMBOL_GPL(rust_helper_errname);
+
+void rust_helper_mutex_lock(struct mutex *lock)
+{
+	mutex_lock(lock);
+}
+EXPORT_SYMBOL_GPL(rust_helper_mutex_lock);
+
+void rust_helper_amba_set_drvdata(struct amba_device *dev, void *data)
+{
+	amba_set_drvdata(dev, data);
+}
+EXPORT_SYMBOL_GPL(rust_helper_amba_set_drvdata);
+
+void *rust_helper_amba_get_drvdata(struct amba_device *dev)
+{
+	return amba_get_drvdata(dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_amba_get_drvdata);
+
+void *
+rust_helper_platform_get_drvdata(const struct platform_device *pdev)
+{
+	return platform_get_drvdata(pdev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_platform_get_drvdata);
+
+void
+rust_helper_platform_set_drvdata(struct platform_device *pdev,
+				 void *data)
+{
+	return platform_set_drvdata(pdev, data);
+}
+EXPORT_SYMBOL_GPL(rust_helper_platform_set_drvdata);
+
+refcount_t rust_helper_REFCOUNT_INIT(int n)
+{
+	return (refcount_t)REFCOUNT_INIT(n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_REFCOUNT_INIT);
+
+void rust_helper_refcount_inc(refcount_t *r)
+{
+	refcount_inc(r);
+}
+EXPORT_SYMBOL_GPL(rust_helper_refcount_inc);
+
+bool rust_helper_refcount_dec_and_test(refcount_t *r)
+{
+	return refcount_dec_and_test(r);
+}
+EXPORT_SYMBOL_GPL(rust_helper_refcount_dec_and_test);
+
+void rust_helper_rb_link_node(struct rb_node *node, struct rb_node *parent,
+			      struct rb_node **rb_link)
+{
+	rb_link_node(node, parent, rb_link);
+}
+EXPORT_SYMBOL_GPL(rust_helper_rb_link_node);
+
+struct task_struct *rust_helper_get_current(void)
+{
+	return current;
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_current);
+
+void rust_helper_get_task_struct(struct task_struct *t)
+{
+	get_task_struct(t);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_task_struct);
+
+void rust_helper_put_task_struct(struct task_struct *t)
+{
+	put_task_struct(t);
+}
+EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
+
+int rust_helper_security_binder_set_context_mgr(const struct cred *mgr)
+{
+	return security_binder_set_context_mgr(mgr);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_binder_set_context_mgr);
+
+int rust_helper_security_binder_transaction(const struct cred *from,
+					    const struct cred *to)
+{
+	return security_binder_transaction(from, to);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_binder_transaction);
+
+int rust_helper_security_binder_transfer_binder(const struct cred *from,
+						const struct cred *to)
+{
+	return security_binder_transfer_binder(from, to);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_binder_transfer_binder);
+
+int rust_helper_security_binder_transfer_file(const struct cred *from,
+					      const struct cred *to,
+					      struct file *file)
+{
+	return security_binder_transfer_file(from, to, file);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_binder_transfer_file);
+
+struct file *rust_helper_get_file(struct file *f)
+{
+	return get_file(f);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_file);
+
+void rust_helper_rcu_read_lock(void)
+{
+	rcu_read_lock();
+}
+EXPORT_SYMBOL_GPL(rust_helper_rcu_read_lock);
+
+void rust_helper_rcu_read_unlock(void)
+{
+	rcu_read_unlock();
+}
+EXPORT_SYMBOL_GPL(rust_helper_rcu_read_unlock);
+
+void rust_helper_synchronize_rcu(void)
+{
+	synchronize_rcu();
+}
+EXPORT_SYMBOL_GPL(rust_helper_synchronize_rcu);
+
+void *rust_helper_dev_get_drvdata(struct device *dev)
+{
+	return dev_get_drvdata(dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dev_get_drvdata);
+
+const char *rust_helper_dev_name(const struct device *dev)
+{
+	return dev_name(dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dev_name);
+
+void rust_helper___seqcount_init(seqcount_t *s, const char *name,
+				 struct lock_class_key *key)
+{
+	__seqcount_init(s, name, key);
+}
+EXPORT_SYMBOL_GPL(rust_helper___seqcount_init);
+
+unsigned rust_helper_read_seqcount_begin(seqcount_t *s)
+{
+	return read_seqcount_begin(s);
+}
+EXPORT_SYMBOL_GPL(rust_helper_read_seqcount_begin);
+
+int rust_helper_read_seqcount_retry(seqcount_t *s, unsigned start)
+{
+	return read_seqcount_retry(s, start);
+}
+EXPORT_SYMBOL_GPL(rust_helper_read_seqcount_retry);
+
+void rust_helper_write_seqcount_begin(seqcount_t *s)
+{
+	do_write_seqcount_begin(s);
+}
+EXPORT_SYMBOL_GPL(rust_helper_write_seqcount_begin);
+
+void rust_helper_write_seqcount_end(seqcount_t *s)
+{
+	do_write_seqcount_end(s);
+}
+EXPORT_SYMBOL_GPL(rust_helper_write_seqcount_end);
+
+void rust_helper_irq_set_handler_locked(struct irq_data *data,
+					irq_flow_handler_t handler)
+{
+	irq_set_handler_locked(data, handler);
+}
+EXPORT_SYMBOL_GPL(rust_helper_irq_set_handler_locked);
+
+void *rust_helper_irq_data_get_irq_chip_data(struct irq_data *d)
+{
+	return irq_data_get_irq_chip_data(d);
+}
+EXPORT_SYMBOL_GPL(rust_helper_irq_data_get_irq_chip_data);
+
+struct irq_chip *rust_helper_irq_desc_get_chip(struct irq_desc *desc)
+{
+	return irq_desc_get_chip(desc);
+}
+EXPORT_SYMBOL_GPL(rust_helper_irq_desc_get_chip);
+
+void *rust_helper_irq_desc_get_handler_data(struct irq_desc *desc)
+{
+	return irq_desc_get_handler_data(desc);
+}
+EXPORT_SYMBOL_GPL(rust_helper_irq_desc_get_handler_data);
+
+void rust_helper_chained_irq_enter(struct irq_chip *chip,
+				   struct irq_desc *desc)
+{
+	chained_irq_enter(chip, desc);
+}
+EXPORT_SYMBOL_GPL(rust_helper_chained_irq_enter);
+
+void rust_helper_chained_irq_exit(struct irq_chip *chip,
+				   struct irq_desc *desc)
+{
+	chained_irq_exit(chip, desc);
+}
+EXPORT_SYMBOL_GPL(rust_helper_chained_irq_exit);
+
+const struct cred *rust_helper_get_cred(const struct cred *cred)
+{
+	return get_cred(cred);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_cred);
+
+void rust_helper_put_cred(const struct cred *cred)
+{
+	put_cred(cred);
+}
+EXPORT_SYMBOL_GPL(rust_helper_put_cred);
+
+const struct of_device_id *rust_helper_of_match_device(
+		const struct of_device_id *matches, const struct device *dev)
+{
+	return of_match_device(matches, dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_of_match_device);
+
+void rust_helper_init_completion(struct completion *c)
+{
+	init_completion(c);
+}
+EXPORT_SYMBOL_GPL(rust_helper_init_completion);
+
+struct sk_buff *rust_helper_skb_get(struct sk_buff *skb)
+{
+	return skb_get(skb);
+}
+EXPORT_SYMBOL_GPL(rust_helper_skb_get);
+
+unsigned int rust_helper_skb_headlen(const struct sk_buff *skb)
+{
+	return skb_headlen(skb);
+}
+EXPORT_SYMBOL_GPL(rust_helper_skb_headlen);
+
+void rust_helper_dev_hold(struct net_device *dev)
+{
+	return dev_hold(dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dev_hold);
+
+void rust_helper_dev_put(struct net_device *dev)
+{
+	return dev_put(dev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dev_put);
+
+struct net *rust_helper_get_net(struct net *net)
+{
+	return get_net(net);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_net);
+
+void rust_helper_put_net(struct net *net)
+{
+	return put_net(net);
+}
+EXPORT_SYMBOL_GPL(rust_helper_put_net);
+
+unsigned int rust_helper_NF_QUEUE_NR(unsigned int n)
+{
+	return NF_QUEUE_NR(n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_NF_QUEUE_NR);
+
+void rust_helper___INIT_WORK_WITH_KEY(struct work_struct *work,
+		work_func_t func, bool on_stack, struct lock_class_key *key)
+{
+	__INIT_WORK_WITH_KEY(work, func, on_stack, key);
+}
+EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK_WITH_KEY);
+
+struct dentry *rust_helper_dget(struct dentry *dentry)
+{
+	return dget(dentry);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dget);
+
+void rust_helper_lockdep_register_key(struct lock_class_key *key)
+{
+	lockdep_register_key(key);
+}
+EXPORT_SYMBOL_GPL(rust_helper_lockdep_register_key);
+
+void rust_helper_lockdep_unregister_key(struct lock_class_key *key)
+{
+	lockdep_unregister_key(key);
+}
+EXPORT_SYMBOL_GPL(rust_helper_lockdep_unregister_key);
+
+int rust_helper_fs_parse(struct fs_context *fc,
+		const struct fs_parameter_spec *desc,
+		struct fs_parameter *param,
+		struct fs_parse_result *result)
+{
+	return fs_parse(fc, desc, param, result);
+}
+EXPORT_SYMBOL_GPL(rust_helper_fs_parse);
+
+/*
+ * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
+ * as the Rust `usize` type, so we can use it in contexts where Rust
+ * expects a `usize` like slice (array) indices. `usize` is defined to be
+ * the same as C's `uintptr_t` type (can hold any pointer) but not
+ * necessarily the same as `size_t` (can hold the size of any single
+ * object). Most modern platforms use the same concrete integer type for
+ * both of them, but in case we find ourselves on a platform where
+ * that's not true, fail early instead of risking ABI or
+ * integer-overflow issues.
+ *
+ * If your platform fails this assertion, it means that you are in
+ * danger of integer-overflow bugs (even if you attempt to remove
+ * `--size_t-is-usize`). It may be easiest to change the kernel ABI on
+ * your platform such that `size_t` matches `uintptr_t` (i.e., to increase
+ * `size_t`, because `uintptr_t` has to be at least as big as `size_t`).
+ */
+static_assert(
+	sizeof(size_t) == sizeof(uintptr_t) &&
+	__alignof__(size_t) == __alignof__(uintptr_t),
+	"Rust code expects C `size_t` to match Rust `usize`"
+);
Signature · 1 line
2.37.1
author maintainer
#16 lore raw

PATCH v8 10/31 rust: add `compiler_builtins` crate

In reply to Miguel Ojeda

Rust provides compiler_builtins as a port of LLVM's compiler-rt. Since we do not need the vast majority of them, we avoid the dependency by providing our own crate.

---
 rust/compiler_builtins.rs | 79 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 79 insertions(+)
 create mode 100644 rust/compiler_builtins.rs
rust/compiler_builtins.rs new file +79 -0
new file mode 100644
index 000000000000..e57011b7c3da
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Our own `compiler_builtins`.
+//!
+//! Rust provides [`compiler_builtins`] as a port of LLVM's [`compiler-rt`].
+//! Since we do not need the vast majority of them, we avoid the dependency
+//! by providing this file.
+//!
+//! At the moment, some builtins are required that should not be. For instance,
+//! [`core`] has 128-bit integers functionality which we should not be compiling
+//! in. We will work with upstream [`core`] to provide feature flags to disable
+//! the parts we do not need. For the moment, we define them to [`panic!`] at
+//! runtime for simplicity to catch mistakes, instead of performing surgery
+//! on `core.o`.
+//!
+//! In any case, all these symbols are weakened to ensure we do not override
+//! those that may be provided by the rest of the kernel.
+//!
+//! [`compiler_builtins`]: https://github.com/rust-lang/compiler-builtins
+//! [`compiler-rt`]: https://compiler-rt.llvm.org/
+
+#![feature(compiler_builtins)]
+#![compiler_builtins]
+#![no_builtins]
+#![no_std]
+
+macro_rules! define_panicking_intrinsics(
+    ($reason: tt, { $($ident: ident, )* }) => {
+        $(
+            #[doc(hidden)]
+            #[no_mangle]
+            pub extern "C" fn $ident() {
+                panic!($reason);
+            }
+        )*
+    }
+);
+
+define_panicking_intrinsics!("`f32` should not be used", {
+    __eqsf2,
+    __gesf2,
+    __lesf2,
+    __nesf2,
+    __unordsf2,
+});
+
+define_panicking_intrinsics!("`f64` should not be used", {
+    __unorddf2,
+});
+
+define_panicking_intrinsics!("`i128` should not be used", {
+    __ashrti3,
+    __muloti4,
+    __multi3,
+});
+
+define_panicking_intrinsics!("`u128` should not be used", {
+    __ashlti3,
+    __lshrti3,
+    __udivmodti4,
+    __udivti3,
+    __umodti3,
+});
+
+#[cfg(target_arch = "arm")]
+define_panicking_intrinsics!("`f32` should not be used", {
+    __aeabi_fcmpeq,
+    __aeabi_fcmpun,
+});
+
+#[cfg(target_arch = "arm")]
+define_panicking_intrinsics!("`f64` should not be used", {
+    __aeabi_dcmpun,
+});
+
+#[cfg(target_arch = "arm")]
+define_panicking_intrinsics!("`u64` division/modulo should not be used", {
+    __aeabi_uldivmod,
+});
Signature · 1 line
2.37.1
author maintainer
#17 lore raw

PATCH v8 11/31 rust: import upstream `alloc` crate

In reply to Miguel Ojeda

This is a subset of the Rust standard library alloc crate, version 1.62.0, licensed under "Apache-2.0 OR MIT", from:

    https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src

The files are copied as-is, with no modifications whatsoever (not even adding the SPDX identifiers).

For copyright details, please see:

    https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT

The next patch modifies these files as needed for use within the kernel. This patch split allows reviewers to double-check the import and to clearly see the differences introduced.

Vendoring alloc, at least for the moment, allows us to have fallible allocations support (i.e. the try_* versions of methods which return a Result instead of panicking) early on. It also gives a bit more freedom to experiment with new interfaces and to iterate quickly.

Eventually, the goal is to have everything the kernel needs in upstream alloc and drop it from the kernel tree.

For a summary of work on alloc happening upstream, please see:

    https://github.com/Rust-for-Linux/linux/issues/408
---
 rust/alloc/alloc.rs               |  438 ++++
 rust/alloc/borrow.rs              |  496 +++++
 rust/alloc/boxed.rs               | 2024 +++++++++++++++++++
 rust/alloc/boxed/thin.rs          |  215 ++
 rust/alloc/collections/mod.rs     |  154 ++
 rust/alloc/ffi/c_str.rs           | 1201 +++++++++++
 rust/alloc/ffi/mod.rs             |   91 +
 rust/alloc/fmt.rs                 |  612 ++++++
 rust/alloc/lib.rs                 |  236 +++
 rust/alloc/macros.rs              |  126 ++
 rust/alloc/raw_vec.rs             |  518 +++++
 rust/alloc/slice.rs               | 1202 +++++++++++
 rust/alloc/str.rs                 |  621 ++++++
 rust/alloc/string.rs              | 2942 +++++++++++++++++++++++++++
 rust/alloc/vec/drain.rs           |  184 ++
 rust/alloc/vec/drain_filter.rs    |  143 ++
 rust/alloc/vec/into_iter.rs       |  362 ++++
 rust/alloc/vec/is_zero.rs         |  118 ++
 rust/alloc/vec/mod.rs             | 3115 +++++++++++++++++++++++++++++
 rust/alloc/vec/partial_eq.rs      |   47 +
 rust/alloc/vec/set_len_on_drop.rs |   28 +
 rust/alloc/vec/spec_extend.rs     |   87 +
 22 files changed, 14960 insertions(+)
 create mode 100644 rust/alloc/alloc.rs
 create mode 100644 rust/alloc/borrow.rs
 create mode 100644 rust/alloc/boxed.rs
 create mode 100644 rust/alloc/boxed/thin.rs
 create mode 100644 rust/alloc/collections/mod.rs
 create mode 100644 rust/alloc/ffi/c_str.rs
 create mode 100644 rust/alloc/ffi/mod.rs
 create mode 100644 rust/alloc/fmt.rs
 create mode 100644 rust/alloc/lib.rs
 create mode 100644 rust/alloc/macros.rs
 create mode 100644 rust/alloc/raw_vec.rs
 create mode 100644 rust/alloc/slice.rs
 create mode 100644 rust/alloc/str.rs
 create mode 100644 rust/alloc/string.rs
 create mode 100644 rust/alloc/vec/drain.rs
 create mode 100644 rust/alloc/vec/drain_filter.rs
 create mode 100644 rust/alloc/vec/into_iter.rs
 create mode 100644 rust/alloc/vec/is_zero.rs
 create mode 100644 rust/alloc/vec/mod.rs
 create mode 100644 rust/alloc/vec/partial_eq.rs
 create mode 100644 rust/alloc/vec/set_len_on_drop.rs
 create mode 100644 rust/alloc/vec/spec_extend.rs
rust/alloc/alloc.rs new file +438 -0
new file mode 100644
index 000000000000..6162b5c6d4c9
@@ -0,0 +1,438 @@
+//! Memory allocation APIs
+
+#![stable(feature = "alloc_module", since = "1.28.0")]
+
+#[cfg(not(test))]
+use core::intrinsics;
+use core::intrinsics::{min_align_of_val, size_of_val};
+
+use core::ptr::Unique;
+#[cfg(not(test))]
+use core::ptr::{self, NonNull};
+
+#[stable(feature = "alloc_module", since = "1.28.0")]
+#[doc(inline)]
+pub use core::alloc::*;
+
+use core::marker::Destruct;
+
+#[cfg(test)]
+mod tests;
+
+extern "Rust" {
+    // These are the magic symbols to call the global allocator.  rustc generates
+    // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
+    // (the code expanding that attribute macro generates those functions), or to call
+    // the default implementations in libstd (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
+    // otherwise.
+    // The rustc fork of LLVM also special-cases these function names to be able to optimize them
+    // like `malloc`, `realloc`, and `free`, respectively.
+    #[rustc_allocator]
+    #[rustc_allocator_nounwind]
+    fn __rust_alloc(size: usize, align: usize) -> *mut u8;
+    #[rustc_allocator_nounwind]
+    fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
+    #[rustc_allocator_nounwind]
+    fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
+    #[rustc_allocator_nounwind]
+    fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
+}
+
+/// The global memory allocator.
+///
+/// This type implements the [`Allocator`] trait by forwarding calls
+/// to the allocator registered with the `#[global_allocator]` attribute
+/// if there is one, or the `std` crate’s default.
+///
+/// Note: while this type is unstable, the functionality it provides can be
+/// accessed through the [free functions in `alloc`](self#functions).
+#[unstable(feature = "allocator_api", issue = "32838")]
+#[derive(Copy, Clone, Default, Debug)]
+#[cfg(not(test))]
+pub struct Global;
+
+#[cfg(test)]
+pub use std::alloc::Global;
+
+/// Allocate memory with the global allocator.
+///
+/// This function forwards calls to the [`GlobalAlloc::alloc`] method
+/// of the allocator registered with the `#[global_allocator]` attribute
+/// if there is one, or the `std` crate’s default.
+///
+/// This function is expected to be deprecated in favor of the `alloc` method
+/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
+///
+/// # Safety
+///
+/// See [`GlobalAlloc::alloc`].
+///
+/// # Examples
+///
+/// ```
+/// use std::alloc::{alloc, dealloc, Layout};
+///
+/// unsafe {
+///     let layout = Layout::new::<u16>();
+///     let ptr = alloc(layout);
+///
+///     *(ptr as *mut u16) = 42;
+///     assert_eq!(*(ptr as *mut u16), 42);
+///
+///     dealloc(ptr, layout);
+/// }
+/// ```
+#[stable(feature = "global_alloc", since = "1.28.0")]
+#[must_use = "losing the pointer will leak memory"]
+#[inline]
+pub unsafe fn alloc(layout: Layout) -> *mut u8 {
+    unsafe { __rust_alloc(layout.size(), layout.align()) }
+}
+
+/// Deallocate memory with the global allocator.
+///
+/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
+/// of the allocator registered with the `#[global_allocator]` attribute
+/// if there is one, or the `std` crate’s default.
+///
+/// This function is expected to be deprecated in favor of the `dealloc` method
+/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
+///
+/// # Safety
+///
+/// See [`GlobalAlloc::dealloc`].
+#[stable(feature = "global_alloc", since = "1.28.0")]
+#[inline]
+pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
+    unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
+}
+
+/// Reallocate memory with the global allocator.
+///
+/// This function forwards calls to the [`GlobalAlloc::realloc`] method
+/// of the allocator registered with the `#[global_allocator]` attribute
+/// if there is one, or the `std` crate’s default.
+///
+/// This function is expected to be deprecated in favor of the `realloc` method
+/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
+///
+/// # Safety
+///
+/// See [`GlobalAlloc::realloc`].
+#[stable(feature = "global_alloc", since = "1.28.0")]
+#[must_use = "losing the pointer will leak memory"]
+#[inline]
+pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
+    unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
+}
+
+/// Allocate zero-initialized memory with the global allocator.
+///
+/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
+/// of the allocator registered with the `#[global_allocator]` attribute
+/// if there is one, or the `std` crate’s default.
+///
+/// This function is expected to be deprecated in favor of the `alloc_zeroed` method
+/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
+///
+/// # Safety
+///
+/// See [`GlobalAlloc::alloc_zeroed`].
+///
+/// # Examples
+///
+/// ```
+/// use std::alloc::{alloc_zeroed, dealloc, Layout};
+///
+/// unsafe {
+///     let layout = Layout::new::<u16>();
+///     let ptr = alloc_zeroed(layout);
+///
+///     assert_eq!(*(ptr as *mut u16), 0);
+///
+///     dealloc(ptr, layout);
+/// }
+/// ```
+#[stable(feature = "global_alloc", since = "1.28.0")]
+#[must_use = "losing the pointer will leak memory"]
+#[inline]
+pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
+    unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
+}
+
+#[cfg(not(test))]
+impl Global {
+    #[inline]
+    fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
+        match layout.size() {
+            0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
+            // SAFETY: `layout` is non-zero in size,
+            size => unsafe {
+                let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
+                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
+                Ok(NonNull::slice_from_raw_parts(ptr, size))
+            },
+        }
+    }
+
+    // SAFETY: Same as `Allocator::grow`
+    #[inline]
+    unsafe fn grow_impl(
+        &self,
+        ptr: NonNull<u8>,
+        old_layout: Layout,
+        new_layout: Layout,
+        zeroed: bool,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        debug_assert!(
+            new_layout.size() >= old_layout.size(),
+            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
+        );
+
+        match old_layout.size() {
+            0 => self.alloc_impl(new_layout, zeroed),
+
+            // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
+            // as required by safety conditions. Other conditions must be upheld by the caller
+            old_size if old_layout.align() == new_layout.align() => unsafe {
+                let new_size = new_layout.size();
+
+                // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
+                intrinsics::assume(new_size >= old_layout.size());
+
+                let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
+                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
+                if zeroed {
+                    raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
+                }
+                Ok(NonNull::slice_from_raw_parts(ptr, new_size))
+            },
+
+            // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
+            // both the old and new memory allocation are valid for reads and writes for `old_size`
+            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
+            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
+            // for `dealloc` must be upheld by the caller.
+            old_size => unsafe {
+                let new_ptr = self.alloc_impl(new_layout, zeroed)?;
+                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
+                self.deallocate(ptr, old_layout);
+                Ok(new_ptr)
+            },
+        }
+    }
+}
+
+#[unstable(feature = "allocator_api", issue = "32838")]
+#[cfg(not(test))]
+unsafe impl Allocator for Global {
+    #[inline]
+    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
+        self.alloc_impl(layout, false)
+    }
+
+    #[inline]
+    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
+        self.alloc_impl(layout, true)
+    }
+
+    #[inline]
+    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
+        if layout.size() != 0 {
+            // SAFETY: `layout` is non-zero in size,
+            // other conditions must be upheld by the caller
+            unsafe { dealloc(ptr.as_ptr(), layout) }
+        }
+    }
+
+    #[inline]
+    unsafe fn grow(
+        &self,
+        ptr: NonNull<u8>,
+        old_layout: Layout,
+        new_layout: Layout,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: all conditions must be upheld by the caller
+        unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
+    }
+
+    #[inline]
+    unsafe fn grow_zeroed(
+        &self,
+        ptr: NonNull<u8>,
+        old_layout: Layout,
+        new_layout: Layout,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: all conditions must be upheld by the caller
+        unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
+    }
+
+    #[inline]
+    unsafe fn shrink(
+        &self,
+        ptr: NonNull<u8>,
+        old_layout: Layout,
+        new_layout: Layout,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        debug_assert!(
+            new_layout.size() <= old_layout.size(),
+            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
+        );
+
+        match new_layout.size() {
+            // SAFETY: conditions must be upheld by the caller
+            0 => unsafe {
+                self.deallocate(ptr, old_layout);
+                Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
+            },
+
+            // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
+            new_size if old_layout.align() == new_layout.align() => unsafe {
+                // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
+                intrinsics::assume(new_size <= old_layout.size());
+
+                let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
+                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
+                Ok(NonNull::slice_from_raw_parts(ptr, new_size))
+            },
+
+            // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
+            // both the old and new memory allocation are valid for reads and writes for `new_size`
+            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
+            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
+            // for `dealloc` must be upheld by the caller.
+            new_size => unsafe {
+                let new_ptr = self.allocate(new_layout)?;
+                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
+                self.deallocate(ptr, old_layout);
+                Ok(new_ptr)
+            },
+        }
+    }
+}
+
+/// The allocator for unique pointers.
+#[cfg(all(not(no_global_oom_handling), not(test)))]
+#[lang = "exchange_malloc"]
+#[inline]
+unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
+    let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
+    match Global.allocate(layout) {
+        Ok(ptr) => ptr.as_mut_ptr(),
+        Err(_) => handle_alloc_error(layout),
+    }
+}
+
+#[cfg_attr(not(test), lang = "box_free")]
+#[inline]
+#[rustc_const_unstable(feature = "const_box", issue = "92521")]
+// This signature has to be the same as `Box`, otherwise an ICE will happen.
+// When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
+// well.
+// For example if `Box` is changed to  `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
+// this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
+pub(crate) const unsafe fn box_free<T: ?Sized, A: ~const Allocator + ~const Destruct>(
+    ptr: Unique<T>,
+    alloc: A,
+) {
+    unsafe {
+        let size = size_of_val(ptr.as_ref());
+        let align = min_align_of_val(ptr.as_ref());
+        let layout = Layout::from_size_align_unchecked(size, align);
+        alloc.deallocate(From::from(ptr.cast()), layout)
+    }
+}
+
+// # Allocation error handler
+
+#[cfg(not(no_global_oom_handling))]
+extern "Rust" {
+    // This is the magic symbol to call the global alloc error handler.  rustc generates
+    // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
+    // default implementations below (`__rdl_oom`) otherwise.
+    fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
+}
+
+/// Abort on memory allocation error or failure.
+///
+/// Callers of memory allocation APIs wishing to abort computation
+/// in response to an allocation error are encouraged to call this function,
+/// 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`].
+///
+/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
+/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
+#[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)))]
+#[cold]
+pub const fn handle_alloc_error(layout: Layout) -> ! {
+    const fn ct_error(_: Layout) -> ! {
+        panic!("allocation failed");
+    }
+
+    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) }
+}
+
+// For alloc test `std::alloc::handle_alloc_error` can be used directly.
+#[cfg(all(not(no_global_oom_handling), test))]
+pub use std::alloc::handle_alloc_error;
+
+#[cfg(all(not(no_global_oom_handling), not(test)))]
+#[doc(hidden)]
+#[allow(unused_attributes)]
+#[unstable(feature = "alloc_internals", issue = "none")]
+pub mod __alloc_error_handler {
+    use crate::alloc::Layout;
+
+    // called via generated `__rust_alloc_error_handler`
+
+    // if there is no `#[alloc_error_handler]`
+    #[rustc_std_internal_symbol]
+    pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! {
+        panic!("memory allocation of {size} bytes failed")
+    }
+
+    // if there is an `#[alloc_error_handler]`
+    #[rustc_std_internal_symbol]
+    pub unsafe extern "C-unwind" fn __rg_oom(size: usize, align: usize) -> ! {
+        let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
+        extern "Rust" {
+            #[lang = "oom"]
+            fn oom_impl(layout: Layout) -> !;
+        }
+        unsafe { oom_impl(layout) }
+    }
+}
+
+/// Specialize clones into pre-allocated, uninitialized memory.
+/// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
+pub(crate) trait WriteCloneIntoRaw: Sized {
+    unsafe fn write_clone_into_raw(&self, target: *mut Self);
+}
+
+impl<T: Clone> WriteCloneIntoRaw for T {
+    #[inline]
+    default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
+        // Having allocated *first* may allow the optimizer to create
+        // the cloned value in-place, skipping the local and move.
+        unsafe { target.write(self.clone()) };
+    }
+}
+
+impl<T: Copy> WriteCloneIntoRaw for T {
+    #[inline]
+    unsafe fn write_clone_into_raw(&self, target: *mut Self) {
+        // We can always copy in-place, without ever involving a local value.
+        unsafe { target.copy_from_nonoverlapping(self, 1) };
+    }
+}
rust/alloc/borrow.rs new file +496 -0

496 lines not on this page · raw message

rust/alloc/boxed.rs new file +2024 -0

2,024 lines not on this page · raw message

rust/alloc/boxed/thin.rs new file +215 -0

42 lines not on this page · raw message

rust/alloc/collections/mod.rs new file +154 -0

154 lines not on this page · raw message

rust/alloc/ffi/c_str.rs new file +1201 -0

1,201 lines not on this page · raw message

rust/alloc/ffi/mod.rs new file +91 -0

91 lines not on this page · raw message

rust/alloc/fmt.rs new file +612 -0

612 lines not on this page · raw message

rust/alloc/lib.rs new file +236 -0

236 lines not on this page · raw message

rust/alloc/macros.rs new file +126 -0

126 lines not on this page · raw message

rust/alloc/raw_vec.rs new file +518 -0

518 lines not on this page · raw message

rust/alloc/slice.rs new file +1202 -0

1,202 lines not on this page · raw message

rust/alloc/str.rs new file +621 -0

621 lines not on this page · raw message

rust/alloc/string.rs new file +2942 -0

2,942 lines not on this page · raw message

rust/alloc/vec/drain.rs new file +184 -0

184 lines not on this page · raw message

rust/alloc/vec/drain_filter.rs new file +143 -0

143 lines not on this page · raw message

rust/alloc/vec/into_iter.rs new file +362 -0

362 lines not on this page · raw message

rust/alloc/vec/is_zero.rs new file +118 -0

118 lines not on this page · raw message

rust/alloc/vec/mod.rs new file +3115 -0

3,115 lines not on this page · raw message

rust/alloc/vec/partial_eq.rs new file +47 -0

47 lines not on this page · raw message

rust/alloc/vec/set_len_on_drop.rs new file +28 -0
new file mode 100644
index 000000000000..8b66bc812129

Lines of this file are not shown. View the raw message.

rust/alloc/vec/spec_extend.rs new file +87 -0

87 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.37.1

Part of the diff is not shown here. View the raw message.

author maintainer
#18 lore raw

PATCH v8 12/31 rust: adapt `alloc` crate to the kernel

In reply to Miguel Ojeda

This customizes the subset of the Rust standard library alloc that was just imported as-is, mainly by:

- Adding SPDX license identifiers.

- Skipping rc and sync modules via new cfgs.

- Skipping the vec! macro.

- Addding fallible (try_*) versions of existing infallible methods (i.e. returning a Result instead of panicking).

Since the standard library requires stable/unstable attributes, these additions are annotated with:

#[stable(feature = "kernel", since = "1.0.0")]

Using "kernel" as the feature allows to have the additions clearly marked. The "1.0.0" version is just a placeholder.

---
 rust/alloc/README.md              |  33 ++++
 rust/alloc/alloc.rs               |   2 +
 rust/alloc/borrow.rs              |   2 +
 rust/alloc/boxed.rs               |   2 +
 rust/alloc/boxed/thin.rs          |   6 +-
 rust/alloc/collections/mod.rs     |   2 +
 rust/alloc/ffi/c_str.rs           |   2 +
 rust/alloc/ffi/mod.rs             |   2 +
 rust/alloc/fmt.rs                 |   2 +
 rust/alloc/lib.rs                 |   5 +-
 rust/alloc/macros.rs              |   2 +
 rust/alloc/raw_vec.rs             |  51 ++++-
 rust/alloc/slice.rs               |  95 ++++++++-
 rust/alloc/str.rs                 |  20 ++
 rust/alloc/string.rs              |   6 +-
 rust/alloc/vec/drain.rs           |   2 +
 rust/alloc/vec/drain_filter.rs    |   2 +
 rust/alloc/vec/into_iter.rs       |   3 +
 rust/alloc/vec/is_zero.rs         |   2 +
 rust/alloc/vec/mod.rs             | 311 +++++++++++++++++++++++++++++-
 rust/alloc/vec/partial_eq.rs      |   2 +
 rust/alloc/vec/set_len_on_drop.rs |   2 +
 rust/alloc/vec/spec_extend.rs     |  87 +++++++++
 23 files changed, 634 insertions(+), 9 deletions(-)
 create mode 100644 rust/alloc/README.md
rust/alloc/README.md new file +33 -0
new file mode 100644
index 000000000000..c89c753720b5
@@ -0,0 +1,33 @@
+# `alloc`
+
+These source files come from the Rust standard library, hosted in
+the <https://github.com/rust-lang/rust> repository, licensed under
+"Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
+see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>.
+
+Please note that these files should be kept as close as possible to
+upstream. In general, only additions should be performed (e.g. new
+methods). Eventually, changes should make it into upstream so that,
+at some point, this fork can be dropped from the kernel tree.
+
+
+## Rationale
+
+On one hand, kernel folks wanted to keep `alloc` in-tree to have more
+freedom in both workflow and actual features if actually needed
+(e.g. receiver types if we ended up using them), which is reasonable.
+
+On the other hand, Rust folks wanted to keep `alloc` as close as
+upstream as possible and avoid as much divergence as possible, which
+is also reasonable.
+
+We agreed on a middle-ground: we would keep a subset of `alloc`
+in-tree that would be as small and as close as possible to upstream.
+Then, upstream can start adding the functions that we add to `alloc`
+etc., until we reach a point where the kernel already knows exactly
+what it needs in `alloc` and all the new methods are merged into
+upstream, so that we can drop `alloc` from the kernel tree and go back
+to using the upstream one.
+
+By doing this, the kernel can go a bit faster now, and Rust can
+slowly incorporate and discuss the changes as needed.
rust/alloc/alloc.rs +2 -0
index 6162b5c6d4c9..ca224a541770 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! Memory allocation APIs
 
 #![stable(feature = "alloc_module", since = "1.28.0")]
rust/alloc/borrow.rs +2 -0
index cb4e438f8bea..ca8e3dfa7004 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! A module for working with borrowed data.
 
 #![stable(feature = "rust1", since = "1.0.0")]
rust/alloc/boxed.rs +2 -0
index c07536f0d0ce..8fd296421dec 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! A pointer type for heap allocation.
 //!
 //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
rust/alloc/boxed/thin.rs +5 -1
index 390030fa2b21..9135203114fc 100644
@@ -1,9 +1,13 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 // Based on
 // https://github.com/matthieu-m/rfc2580/blob/b58d1d3cba0d4b5e859d3617ea2d0943aaa31329/examples/thin.rs
 // by matthieu-m
 use crate::alloc::{self, Layout, LayoutError};
 use core::fmt::{self, Debug, Display, Formatter};
-use core::marker::{PhantomData, Unsize};
+use core::marker::PhantomData;
+#[cfg(not(no_global_oom_handling))]
+use core::marker::Unsize;
 use core::mem;
 use core::ops::{Deref, DerefMut};
 use core::ptr::Pointee;
rust/alloc/collections/mod.rs +2 -0
index 628a5b155673..1eec265b28f8 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! Collection types.
 
 #![stable(feature = "rust1", since = "1.0.0")]
rust/alloc/ffi/c_str.rs +2 -0
index 172a008e89a0..5e2f4073771a 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 #[cfg(test)]
 mod tests;
 
rust/alloc/ffi/mod.rs +2 -0
index eed2851c1539..56d429785339 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! Utilities related to FFI bindings.
 //!
 //! This module provides utilities to handle data across non-Rust
rust/alloc/fmt.rs +2 -0
index 73b75ea4d83d..b9c4d2926d23 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! Utilities for formatting and printing `String`s.
 //!
 //! This module contains the runtime support for the [`format!`] syntax extension.
rust/alloc/lib.rs +4 -1
index fd21b3671182..03d2ce1df814 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! # The Rust core allocation and collections library
 //!
 //! This library provides smart pointers and collections for managing
@@ -217,11 +219,12 @@ pub mod collections;
 #[cfg(not(no_global_oom_handling))]
 pub mod ffi;
 pub mod fmt;
+#[cfg(not(no_rc))]
 pub mod rc;
 pub mod slice;
 pub mod str;
 pub mod string;
-#[cfg(target_has_atomic = "ptr")]
+#[cfg(all(not(no_sync), target_has_atomic = "ptr"))]
 pub mod sync;
 #[cfg(all(not(no_global_oom_handling), target_has_atomic = "ptr"))]
 pub mod task;
rust/alloc/macros.rs +2 -0
index 093b02113c3a..fa7bacfd5847 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 /// Creates a [`Vec`] containing the arguments.
 ///
 /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
rust/alloc/raw_vec.rs +50 -1

87 lines not on this page · raw message

rust/alloc/slice.rs +94 -1

144 lines not on this page · raw message

rust/alloc/str.rs +20 -0
index 0eaa26398635..4e3aec690fdb 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! Unicode string slices.
 //!
 //! *[See also the `str` primitive type](str).*
@@ -36,6 +38,7 @@ use core::unicode::conversions;
 
 use crate::borrow::ToOwned;
 use crate::boxed::Box;
+use crate::collections::TryReserveError;
 use crate::slice::{Concat, Join, SliceIndex};
 use crate::string::String;
 use crate::vec::Vec;
@@ -598,6 +601,23 @@ impl str {
         // make_ascii_lowercase() preserves the UTF-8 invariant.
         unsafe { String::from_utf8_unchecked(bytes) }
     }
+
+    /// Tries to create a `String`.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// let s: &str = "a";
+    /// let ss: String = s.try_to_owned().unwrap();
+    /// ```
+    #[rustc_allow_incoherent_impl]
+    #[inline]
+    #[stable(feature = "kernel", since = "1.0.0")]
+    pub fn try_to_owned(&self) -> Result<String, TryReserveError> {
+        unsafe { Ok(String::from_utf8_unchecked(self.as_bytes().try_to_vec()?)) }
+    }
 }
 
 /// Converts a boxed slice of bytes to a boxed string slice without checking
rust/alloc/string.rs +4 -2
index 2272c5b7330d..2ba7f30a7503 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 //! A UTF-8–encoded, growable string.
 //!
 //! This module contains the [`String`] type, the [`ToString`] trait for
@@ -47,8 +49,8 @@ use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
 use core::fmt;
 use core::hash;
 #[cfg(not(no_global_oom_handling))]
-use core::iter::FromIterator;
-use core::iter::{from_fn, FusedIterator};
+use core::iter::{from_fn, FromIterator};
+use core::iter::FusedIterator;
 #[cfg(not(no_global_oom_handling))]
 use core::ops::Add;
 #[cfg(not(no_global_oom_handling))]
rust/alloc/vec/drain.rs +2 -0
index 5cdee0bd4da4..b6a5f98e4fcd 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 use crate::alloc::{Allocator, Global};
 use core::fmt;
 use core::iter::{FusedIterator, TrustedLen};
rust/alloc/vec/drain_filter.rs +2 -0
index 3c37c92ae44b..b04fce041622 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 use crate::alloc::{Allocator, Global};
 use core::ptr::{self};
 use core::slice::{self};
rust/alloc/vec/into_iter.rs +3 -0
index 9b84a1d9b4b6..09cfee0ae631 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 #[cfg(not(no_global_oom_handling))]
 use super::AsVecIntoIter;
 use crate::alloc::{Allocator, Global};
@@ -9,6 +11,7 @@ use core::iter::{
 };
 use core::marker::PhantomData;
 use core::mem::{self, ManuallyDrop};
+#[cfg(not(no_global_oom_handling))]
 use core::ops::Deref;
 use core::ptr::{self, NonNull};
 use core::slice::{self};
rust/alloc/vec/is_zero.rs +2 -0
index edf270db81d4..377f3d172777 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 use crate::boxed::Box;
 
 #[rustc_specialization_trait]
rust/alloc/vec/mod.rs +308 -3

388 lines not on this page · raw message

rust/alloc/vec/partial_eq.rs +2 -0
index b0cf72577a1b..10ad4e492287 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 use crate::alloc::Allocator;
 #[cfg(not(no_global_oom_handling))]
 use crate::borrow::Cow;
rust/alloc/vec/set_len_on_drop.rs +2 -0
index 8b66bc812129..448bf5076a0b 100644
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
 //
 // The idea is: The length field in SetLenOnDrop is a local variable
rust/alloc/vec/spec_extend.rs +87 -0

128 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#19 lore raw

PATCH v8 13/31 rust: add `build_error` crate

In reply to Miguel Ojeda

From: Gary Guo <[email protected]>

The build_error crate provides the build_error function which is then used to provide the build_error! and the build_assert! macros.

build_assert! is intended to be used when static_assert! cannot be used, e.g. when the condition refers to generic parameters or parameters of an inline function.

---
 rust/build_error.rs | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
 create mode 100644 rust/build_error.rs
rust/build_error.rs new file +29 -0
new file mode 100644
index 000000000000..bbd3a05440b2
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Build-time error.
+//!
+//! This crate provides a function `build_error`, which will panic in
+//! compile-time if executed in const context, and will cause a build error
+//! if not executed at compile time and the optimizer does not optimise away the
+//! call.
+//!
+//! It is used by `build_assert!` in the kernel crate, allowing checking of
+//! conditions that could be checked statically, but could not be enforced in
+//! Rust yet (e.g. perform some checks in const functions, but those
+//! functions could still be called in the runtime).
+
+#![no_std]
+
+/// Panics if executed in const context, or triggers a build error if not.
+#[inline(never)]
+#[cold]
+#[export_name = "rust_build_error"]
+#[track_caller]
+pub const fn build_error(msg: &'static str) -> ! {
+    panic!("{}", msg);
+}
+
+#[cfg(CONFIG_RUST_BUILD_ASSERT_WARN)]
+#[link_section = ".gnu.warning.rust_build_error"]
+#[used]
+static BUILD_ERROR_WARNING: [u8; 45] = *b"call to build_error present after compilation";
Signature · 1 line
2.37.1
author maintainer
#20 lore raw

PATCH v8 14/31 rust: add `macros` crate

In reply to Miguel Ojeda

This crate contains all the procedural macros ("proc macros") shared by all the kernel.

Procedural macros allow to create syntax extensions. They run at compile-time and can consume as well as produce Rust syntax.

For instance, the module! macro that is used by Rust modules is implemented here. It allows to easily declare the equivalent information to the MODULE_* macros in C modules, e.g.:

module! {
type: RustMinimal,
name: b"rust_minimal",
author: b"Rust for Linux Contributors",
description: b"Rust minimal sample",
license: b"GPL",
}

---
 rust/macros/concat_idents.rs |  23 ++
 rust/macros/helpers.rs       |  79 +++++
 rust/macros/lib.rs           | 191 ++++++++++
 rust/macros/module.rs        | 655 +++++++++++++++++++++++++++++++++++
 rust/macros/vtable.rs        |  95 +++++
 5 files changed, 1043 insertions(+)
 create mode 100644 rust/macros/concat_idents.rs
 create mode 100644 rust/macros/helpers.rs
 create mode 100644 rust/macros/lib.rs
 create mode 100644 rust/macros/module.rs
 create mode 100644 rust/macros/vtable.rs
rust/macros/concat_idents.rs new file +23 -0
new file mode 100644
index 000000000000..3b5a9dd70e8a
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use proc_macro::{token_stream, Ident, TokenStream, TokenTree};
+
+use crate::helpers::expect_punct;
+
+fn expect_ident(it: &mut token_stream::IntoIter) -> Ident {
+    if let Some(TokenTree::Ident(ident)) = it.next() {
+        ident
+    } else {
+        panic!("Expected Ident")
+    }
+}
+
+pub(crate) fn concat_idents(ts: TokenStream) -> TokenStream {
+    let mut it = ts.into_iter();
+    let a = expect_ident(&mut it);
+    assert_eq!(expect_punct(&mut it), ',');
+    let b = expect_ident(&mut it);
+    assert!(it.next().is_none(), "only two idents can be concatenated");
+    let res = Ident::new(&(a.to_string() + &b.to_string()), b.span());
+    TokenStream::from_iter([TokenTree::Ident(res)])
+}
rust/macros/helpers.rs new file +79 -0

79 lines not on this page · raw message

rust/macros/lib.rs new file +191 -0

191 lines not on this page · raw message

rust/macros/module.rs new file +655 -0

655 lines not on this page · raw message

rust/macros/vtable.rs new file +95 -0

95 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#21 lore raw

PATCH v8 15/31 rust: add `bindings` crate

In reply to Miguel Ojeda

This crate contains the bindings to the C side of the kernel.

Calling C (in general, FFI) is assumed to be unsafe in Rust and, in many cases, this is accurate. For instance, virtually all C functions that take a pointer are unsafe since, typically, it will be dereferenced at some point (and in most cases there is no way for the callee to check its validity beforehand).

Since one of the goals of using Rust in the kernel is precisely to avoid unsafe code in "leaf" kernel modules (e.g. drivers), these bindings should not be used directly by them.

Instead, these bindings need to be wrapped into safe abstractions. These abstractions provide a safe API that kernel modules can use. In this way, unsafe code in kernel modules is minimized.

---
 rust/bindings/bindings_helper.h | 49 ++++++++++++++++++++++++++++
 rust/bindings/lib.rs            | 57 +++++++++++++++++++++++++++++++++
 2 files changed, 106 insertions(+)
 create mode 100644 rust/bindings/bindings_helper.h
 create mode 100644 rust/bindings/lib.rs
rust/bindings/bindings_helper.h new file +49 -0
new file mode 100644
index 000000000000..284793085d55
@@ -0,0 +1,49 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Header that contains the code (mostly headers) for which Rust bindings
+ * will be automatically generated by `bindgen`.
+ *
+ * Sorted alphabetically.
+ */
+
+#include <kunit/test.h>
+#include <linux/amba/bus.h>
+#include <linux/cdev.h>
+#include <linux/clk.h>
+#include <linux/errname.h>
+#include <linux/file.h>
+#include <linux/fs.h>
+#include <linux/fs_parser.h>
+#include <linux/gpio/driver.h>
+#include <linux/hw_random.h>
+#include <linux/interrupt.h>
+#include <linux/io.h>
+#include <linux/irqdomain.h>
+#include <linux/irq.h>
+#include <linux/miscdevice.h>
+#include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/netfilter_arp.h>
+#include <linux/netfilter.h>
+#include <linux/netfilter_ipv4.h>
+#include <linux/netfilter_ipv6.h>
+#include <linux/of_platform.h>
+#include <linux/platform_device.h>
+#include <linux/poll.h>
+#include <linux/random.h>
+#include <linux/security.h>
+#include <linux/slab.h>
+#include <linux/sysctl.h>
+#include <linux/uaccess.h>
+#include <linux/uio.h>
+#include <uapi/linux/android/binder.h>
+
+/* `bindgen` gets confused at certain things. */
+const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
+const gfp_t BINDINGS___GFP_ZERO = __GFP_ZERO;
+const __poll_t BINDINGS_EPOLLIN = EPOLLIN;
+const __poll_t BINDINGS_EPOLLOUT = EPOLLOUT;
+const __poll_t BINDINGS_EPOLLERR = EPOLLERR;
+const __poll_t BINDINGS_EPOLLHUP = EPOLLHUP;
+
+const loff_t BINDINGS_MAX_LFS_FILESIZE = MAX_LFS_FILESIZE;
rust/bindings/lib.rs new file +57 -0

57 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#22 lore raw

PATCH v8 16/31 rust: add `kernel` crate's `sync` module

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

This module contains the kernel APIs related to synchronisation that have been ported or wrapped for usage by Rust code in the kernel and is shared by all of them.

---
 rust/kernel/sync.rs           | 161 ++++++++++
 rust/kernel/sync/arc.rs       | 582 ++++++++++++++++++++++++++++++++++
 rust/kernel/sync/condvar.rs   | 140 ++++++++
 rust/kernel/sync/guard.rs     | 159 ++++++++++
 rust/kernel/sync/locked_by.rs | 111 +++++++
 rust/kernel/sync/mutex.rs     | 149 +++++++++
 rust/kernel/sync/nowait.rs    | 188 +++++++++++
 rust/kernel/sync/rcu.rs       |  52 +++
 rust/kernel/sync/revocable.rs | 246 ++++++++++++++
 rust/kernel/sync/rwsem.rs     | 196 ++++++++++++
 rust/kernel/sync/seqlock.rs   | 201 ++++++++++++
 rust/kernel/sync/smutex.rs    | 290 +++++++++++++++++
 rust/kernel/sync/spinlock.rs  | 357 +++++++++++++++++++++
 13 files changed, 2832 insertions(+)
 create mode 100644 rust/kernel/sync.rs
 create mode 100644 rust/kernel/sync/arc.rs
 create mode 100644 rust/kernel/sync/condvar.rs
 create mode 100644 rust/kernel/sync/guard.rs
 create mode 100644 rust/kernel/sync/locked_by.rs
 create mode 100644 rust/kernel/sync/mutex.rs
 create mode 100644 rust/kernel/sync/nowait.rs
 create mode 100644 rust/kernel/sync/rcu.rs
 create mode 100644 rust/kernel/sync/revocable.rs
 create mode 100644 rust/kernel/sync/rwsem.rs
 create mode 100644 rust/kernel/sync/seqlock.rs
 create mode 100644 rust/kernel/sync/smutex.rs
 create mode 100644 rust/kernel/sync/spinlock.rs
rust/kernel/sync.rs new file +161 -0
new file mode 100644
index 000000000000..dbf705d573e6
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Synchronisation primitives.
+//!
+//! This module contains the kernel APIs related to synchronisation that have been ported or
+//! wrapped for usage by Rust code in the kernel and is shared by all of them.
+//!
+//! # Examples
+//!
+//! ```
+//! # use kernel::mutex_init;
+//! # use kernel::sync::Mutex;
+//! # use alloc::boxed::Box;
+//! # use core::pin::Pin;
+//! // SAFETY: `init` is called below.
+//! let mut data = Pin::from(Box::try_new(unsafe { Mutex::new(10) }).unwrap());
+//! mutex_init!(data.as_mut(), "test::data");
+//!
+//! assert_eq!(*data.lock(), 10);
+//! *data.lock() = 20;
+//! assert_eq!(*data.lock(), 20);
+//! ```
+
+use crate::{bindings, str::CStr};
+use core::pin::Pin;
+
+mod arc;
+mod condvar;
+mod guard;
+mod locked_by;
+mod mutex;
+mod nowait;
+mod revocable;
+mod rwsem;
+mod seqlock;
+pub mod smutex;
+mod spinlock;
+
+pub use arc::{Ref, RefBorrow, UniqueRef};
+pub use condvar::CondVar;
+pub use guard::{Guard, Lock, LockFactory, LockInfo, LockIniter, ReadLock, WriteLock};
+pub use locked_by::LockedBy;
+pub use mutex::{Mutex, RevocableMutex, RevocableMutexGuard};
+pub use nowait::{NoWaitLock, NoWaitLockGuard};
+pub use revocable::{Revocable, RevocableGuard};
+pub use rwsem::{RevocableRwSemaphore, RevocableRwSemaphoreGuard, RwSemaphore};
+pub use seqlock::{SeqLock, SeqLockReadGuard};
+pub use spinlock::{RawSpinLock, SpinLock};
+
+/// Safely initialises an object that has an `init` function that takes a name and a lock class as
+/// arguments, examples of these are [`Mutex`] and [`SpinLock`]. Each of them also provides a more
+/// specialised name that uses this macro.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! init_with_lockdep {
+    ($obj:expr, $name:expr) => {{
+        static mut CLASS1: core::mem::MaybeUninit<$crate::bindings::lock_class_key> =
+            core::mem::MaybeUninit::uninit();
+        static mut CLASS2: core::mem::MaybeUninit<$crate::bindings::lock_class_key> =
+            core::mem::MaybeUninit::uninit();
+        let obj = $obj;
+        let name = $crate::c_str!($name);
+        // SAFETY: `CLASS1` and `CLASS2` are never used by Rust code directly; the C portion of the
+        // kernel may change it though.
+        #[allow(unused_unsafe)]
+        unsafe {
+            $crate::sync::NeedsLockClass::init(obj, name, CLASS1.as_mut_ptr(), CLASS2.as_mut_ptr())
+        };
+    }};
+}
+
+/// A trait for types that need a lock class during initialisation.
+///
+/// Implementers of this trait benefit from the [`init_with_lockdep`] macro that generates a new
+/// class for each initialisation call site.
+pub trait NeedsLockClass {
+    /// Initialises the type instance so that it can be safely used.
+    ///
+    /// Callers are encouraged to use the [`init_with_lockdep`] macro as it automatically creates a
+    /// new lock class on each usage.
+    ///
+    /// # Safety
+    ///
+    /// `key1` and `key2` must point to valid memory locations and remain valid until `self` is
+    /// dropped.
+    unsafe fn init(
+        self: Pin<&mut Self>,
+        name: &'static CStr,
+        key1: *mut bindings::lock_class_key,
+        key2: *mut bindings::lock_class_key,
+    );
+}
+
+/// Automatically initialises static instances of synchronisation primitives.
+///
+/// The syntax resembles that of regular static variables, except that the value assigned is that
+/// of the protected type (if one exists). In the examples below, all primitives except for
+/// [`CondVar`] require the inner value to be supplied.
+///
+/// # Examples
+///
+/// ```ignore
+/// # use kernel::{init_static_sync, sync::{CondVar, Mutex, RevocableMutex, SpinLock}};
+/// struct Test {
+///     a: u32,
+///     b: u32,
+/// }
+///
+/// init_static_sync! {
+///     static A: Mutex<Test> = Test { a: 10, b: 20 };
+///
+///     /// Documentation for `B`.
+///     pub static B: Mutex<u32> = 0;
+///
+///     pub(crate) static C: SpinLock<Test> = Test { a: 10, b: 20 };
+///     static D: CondVar;
+///
+///     static E: RevocableMutex<Test> = Test { a: 30, b: 40 };
+/// }
+/// ```
+#[macro_export]
+macro_rules! init_static_sync {
+    ($($(#[$outer:meta])* $v:vis static $id:ident : $t:ty $(= $value:expr)?;)*) => {
+        $(
+            $(#[$outer])*
+            $v static $id: $t = {
+                #[link_section = ".init_array"]
+                #[used]
+                static TMP: extern "C" fn() = {
+                    extern "C" fn constructor() {
+                        // SAFETY: This locally-defined function is only called from a constructor,
+                        // which guarantees that `$id` is not accessible from other threads
+                        // concurrently.
+                        #[allow(clippy::cast_ref_to_mut)]
+                        let mutable = unsafe { &mut *(&$id as *const _ as *mut $t) };
+                        // SAFETY: It's a shared static, so it cannot move.
+                        let pinned = unsafe { core::pin::Pin::new_unchecked(mutable) };
+                        $crate::init_with_lockdep!(pinned, stringify!($id));
+                    }
+                    constructor
+                };
+                $crate::init_static_sync!(@call_new $t, $($value)?)
+            };
+        )*
+    };
+    (@call_new $t:ty, $value:expr) => {{
+        let v = $value;
+        // SAFETY: the initialisation function is called by the constructor above.
+        unsafe { <$t>::new(v) }
+    }};
+    (@call_new $t:ty,) => {
+        // SAFETY: the initialisation function is called by the constructor above.
+        unsafe { <$t>::new() }
+    };
+}
+
+/// Reschedules the caller's task if needed.
+pub fn cond_resched() -> bool {
+    // SAFETY: No arguments, reschedules `current` if needed.
+    unsafe { bindings::cond_resched() != 0 }
+}
rust/kernel/sync/arc.rs new file +582 -0

582 lines not on this page · raw message

rust/kernel/sync/condvar.rs new file +140 -0

140 lines not on this page · raw message

rust/kernel/sync/guard.rs new file +159 -0

159 lines not on this page · raw message

rust/kernel/sync/locked_by.rs new file +111 -0

111 lines not on this page · raw message

rust/kernel/sync/mutex.rs new file +149 -0

149 lines not on this page · raw message

rust/kernel/sync/nowait.rs new file +188 -0

188 lines not on this page · raw message

rust/kernel/sync/rcu.rs new file +52 -0

52 lines not on this page · raw message

rust/kernel/sync/revocable.rs new file +246 -0

246 lines not on this page · raw message

rust/kernel/sync/rwsem.rs new file +196 -0

196 lines not on this page · raw message

rust/kernel/sync/seqlock.rs new file +201 -0

201 lines not on this page · raw message

rust/kernel/sync/smutex.rs new file +290 -0

290 lines not on this page · raw message

rust/kernel/sync/spinlock.rs new file +357 -0

357 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#23 lore raw

PATCH v8 17/31 rust: add `kernel` crate

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

The kernel crate currently includes all the abstractions that wrap kernel features written in C.

These abstractions call the C side of the kernel via the generated bindings with the bindgen tool. Modules developed in Rust should never call the bindings themselves.

In the future, as the abstractions grow in number, we may need to split this crate into several, possibly following a similar subdivision in subsystems as the kernel itself and/or moving the code to the actual subsystems.

---
 rust/kernel/allocator.rs                 |  64 ++
 rust/kernel/amba.rs                      | 261 +++++++
 rust/kernel/build_assert.rs              |  83 +++
 rust/kernel/chrdev.rs                    | 206 ++++++
 rust/kernel/clk.rs                       |  79 ++
 rust/kernel/cred.rs                      |  46 ++
 rust/kernel/delay.rs                     | 104 +++
 rust/kernel/device.rs                    | 527 ++++++++++++++
 rust/kernel/driver.rs                    | 442 +++++++++++
 rust/kernel/error.rs                     | 564 ++++++++++++++
 rust/kernel/file.rs                      | 887 +++++++++++++++++++++++
 rust/kernel/fs.rs                        | 846 +++++++++++++++++++++
 rust/kernel/fs/param.rs                  | 553 ++++++++++++++
 rust/kernel/gpio.rs                      | 505 +++++++++++++
 rust/kernel/hwrng.rs                     | 210 ++++++
 rust/kernel/io_buffer.rs                 | 153 ++++
 rust/kernel/io_mem.rs                    | 278 +++++++
 rust/kernel/iov_iter.rs                  |  81 +++
 rust/kernel/irq.rs                       | 681 +++++++++++++++++
 rust/kernel/kasync.rs                    |  50 ++
 rust/kernel/kasync/executor.rs           | 154 ++++
 rust/kernel/kasync/executor/workqueue.rs | 291 ++++++++
 rust/kernel/kasync/net.rs                | 322 ++++++++
 rust/kernel/kunit.rs                     |  91 +++
 rust/kernel/lib.rs                       | 267 +++++++
 rust/kernel/linked_list.rs               | 247 +++++++
 rust/kernel/miscdev.rs                   | 290 ++++++++
 rust/kernel/mm.rs                        | 149 ++++
 rust/kernel/module_param.rs              | 499 +++++++++++++
 rust/kernel/net.rs                       | 392 ++++++++++
 rust/kernel/net/filter.rs                | 447 ++++++++++++
 rust/kernel/of.rs                        |  63 ++
 rust/kernel/pages.rs                     | 144 ++++
 rust/kernel/platform.rs                  | 223 ++++++
 rust/kernel/power.rs                     | 118 +++
 rust/kernel/prelude.rs                   |  36 +
 rust/kernel/print.rs                     | 406 +++++++++++
 rust/kernel/random.rs                    |  42 ++
 rust/kernel/raw_list.rs                  | 361 +++++++++
 rust/kernel/rbtree.rs                    | 563 ++++++++++++++
 rust/kernel/revocable.rs                 | 425 +++++++++++
 rust/kernel/security.rs                  |  38 +
 rust/kernel/static_assert.rs             |  34 +
 rust/kernel/std_vendor.rs                | 161 ++++
 rust/kernel/str.rs                       | 597 +++++++++++++++
 rust/kernel/sync.rs                      |  48 +-
 rust/kernel/sysctl.rs                    | 199 +++++
 rust/kernel/task.rs                      | 239 ++++++
 rust/kernel/types.rs                     | 705 ++++++++++++++++++
 rust/kernel/unsafe_list.rs               | 680 +++++++++++++++++
 rust/kernel/user_ptr.rs                  | 175 +++++
 rust/kernel/workqueue.rs                 | 512 +++++++++++++
 52 files changed, 15518 insertions(+), 20 deletions(-)
 create mode 100644 rust/kernel/allocator.rs
 create mode 100644 rust/kernel/amba.rs
 create mode 100644 rust/kernel/build_assert.rs
 create mode 100644 rust/kernel/chrdev.rs
 create mode 100644 rust/kernel/clk.rs
 create mode 100644 rust/kernel/cred.rs
 create mode 100644 rust/kernel/delay.rs
 create mode 100644 rust/kernel/device.rs
 create mode 100644 rust/kernel/driver.rs
 create mode 100644 rust/kernel/error.rs
 create mode 100644 rust/kernel/file.rs
 create mode 100644 rust/kernel/fs.rs
 create mode 100644 rust/kernel/fs/param.rs
 create mode 100644 rust/kernel/gpio.rs
 create mode 100644 rust/kernel/hwrng.rs
 create mode 100644 rust/kernel/io_buffer.rs
 create mode 100644 rust/kernel/io_mem.rs
 create mode 100644 rust/kernel/iov_iter.rs
 create mode 100644 rust/kernel/irq.rs
 create mode 100644 rust/kernel/kasync.rs
 create mode 100644 rust/kernel/kasync/executor.rs
 create mode 100644 rust/kernel/kasync/executor/workqueue.rs
 create mode 100644 rust/kernel/kasync/net.rs
 create mode 100644 rust/kernel/kunit.rs
 create mode 100644 rust/kernel/lib.rs
 create mode 100644 rust/kernel/linked_list.rs
 create mode 100644 rust/kernel/miscdev.rs
 create mode 100644 rust/kernel/mm.rs
 create mode 100644 rust/kernel/module_param.rs
 create mode 100644 rust/kernel/net.rs
 create mode 100644 rust/kernel/net/filter.rs
 create mode 100644 rust/kernel/of.rs
 create mode 100644 rust/kernel/pages.rs
 create mode 100644 rust/kernel/platform.rs
 create mode 100644 rust/kernel/power.rs
 create mode 100644 rust/kernel/prelude.rs
 create mode 100644 rust/kernel/print.rs
 create mode 100644 rust/kernel/random.rs
 create mode 100644 rust/kernel/raw_list.rs
 create mode 100644 rust/kernel/rbtree.rs
 create mode 100644 rust/kernel/revocable.rs
 create mode 100644 rust/kernel/security.rs
 create mode 100644 rust/kernel/static_assert.rs
 create mode 100644 rust/kernel/std_vendor.rs
 create mode 100644 rust/kernel/str.rs
 create mode 100644 rust/kernel/sysctl.rs
 create mode 100644 rust/kernel/task.rs
 create mode 100644 rust/kernel/types.rs
 create mode 100644 rust/kernel/unsafe_list.rs
 create mode 100644 rust/kernel/user_ptr.rs
 create mode 100644 rust/kernel/workqueue.rs
rust/kernel/allocator.rs new file +64 -0
new file mode 100644
index 000000000000..397a3dd57a9b
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Allocator support.
+
+use core::alloc::{GlobalAlloc, Layout};
+use core::ptr;
+
+use crate::bindings;
+
+struct KernelAllocator;
+
+unsafe impl GlobalAlloc for KernelAllocator {
+    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+        // `krealloc()` is used instead of `kmalloc()` because the latter is
+        // an inline function and cannot be bound to as a result.
+        unsafe { bindings::krealloc(ptr::null(), layout.size(), bindings::GFP_KERNEL) as *mut u8 }
+    }
+
+    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
+        unsafe {
+            bindings::kfree(ptr as *const core::ffi::c_void);
+        }
+    }
+}
+
+#[global_allocator]
+static ALLOCATOR: KernelAllocator = KernelAllocator;
+
+// `rustc` only generates these for some crate types. Even then, we would need
+// to extract the object file that has them from the archive. For the moment,
+// let's generate them ourselves instead.
+//
+// Note that `#[no_mangle]` implies exported too, nowadays.
+#[no_mangle]
+fn __rust_alloc(size: usize, _align: usize) -> *mut u8 {
+    unsafe { bindings::krealloc(core::ptr::null(), size, bindings::GFP_KERNEL) as *mut u8 }
+}
+
+#[no_mangle]
+fn __rust_dealloc(ptr: *mut u8, _size: usize, _align: usize) {
+    unsafe { bindings::kfree(ptr as *const core::ffi::c_void) };
+}
+
+#[no_mangle]
+fn __rust_realloc(ptr: *mut u8, _old_size: usize, _align: usize, new_size: usize) -> *mut u8 {
+    unsafe {
+        bindings::krealloc(
+            ptr as *const core::ffi::c_void,
+            new_size,
+            bindings::GFP_KERNEL,
+        ) as *mut u8
+    }
+}
+
+#[no_mangle]
+fn __rust_alloc_zeroed(size: usize, _align: usize) -> *mut u8 {
+    unsafe {
+        bindings::krealloc(
+            core::ptr::null(),
+            size,
+            bindings::GFP_KERNEL | bindings::__GFP_ZERO,
+        ) as *mut u8
+    }
+}
rust/kernel/amba.rs new file +261 -0

261 lines not on this page · raw message

rust/kernel/build_assert.rs new file +83 -0

83 lines not on this page · raw message

rust/kernel/chrdev.rs new file +206 -0

206 lines not on this page · raw message

rust/kernel/clk.rs new file +79 -0

79 lines not on this page · raw message

rust/kernel/cred.rs new file +46 -0

46 lines not on this page · raw message

rust/kernel/delay.rs new file +104 -0

104 lines not on this page · raw message

rust/kernel/device.rs new file +527 -0

527 lines not on this page · raw message

rust/kernel/driver.rs new file +442 -0

442 lines not on this page · raw message

rust/kernel/error.rs new file +564 -0

564 lines not on this page · raw message

rust/kernel/file.rs new file +887 -0

624 lines not on this page · raw message

rust/kernel/fs.rs new file +846 -0

846 lines not on this page · raw message

rust/kernel/fs/param.rs new file +553 -0

553 lines not on this page · raw message

rust/kernel/gpio.rs new file +505 -0

505 lines not on this page · raw message

rust/kernel/hwrng.rs new file +210 -0

210 lines not on this page · raw message

rust/kernel/io_buffer.rs new file +153 -0

153 lines not on this page · raw message

rust/kernel/io_mem.rs new file +278 -0

278 lines not on this page · raw message

rust/kernel/iov_iter.rs new file +81 -0

81 lines not on this page · raw message

rust/kernel/irq.rs new file +681 -0

681 lines not on this page · raw message

rust/kernel/kasync.rs new file +50 -0

50 lines not on this page · raw message

rust/kernel/kasync/executor.rs new file +154 -0

154 lines not on this page · raw message

rust/kernel/kasync/executor/workqueue.rs new file +291 -0

291 lines not on this page · raw message

rust/kernel/kasync/net.rs new file +322 -0

322 lines not on this page · raw message

rust/kernel/kunit.rs new file +91 -0

91 lines not on this page · raw message

rust/kernel/lib.rs new file +267 -0

267 lines not on this page · raw message

rust/kernel/linked_list.rs new file +247 -0

247 lines not on this page · raw message

rust/kernel/miscdev.rs new file +290 -0

290 lines not on this page · raw message

rust/kernel/mm.rs new file +149 -0

149 lines not on this page · raw message

rust/kernel/module_param.rs new file +499 -0

499 lines not on this page · raw message

rust/kernel/net.rs new file +392 -0

392 lines not on this page · raw message

rust/kernel/net/filter.rs new file +447 -0

447 lines not on this page · raw message

rust/kernel/of.rs new file +63 -0

63 lines not on this page · raw message

rust/kernel/pages.rs new file +144 -0

144 lines not on this page · raw message

rust/kernel/platform.rs new file +223 -0

223 lines not on this page · raw message

rust/kernel/power.rs new file +118 -0

118 lines not on this page · raw message

rust/kernel/prelude.rs new file +36 -0
new file mode 100644
index 000000000000..26f8af9e16ab

Lines of this file are not shown. View the raw message.

rust/kernel/print.rs new file +406 -0

406 lines not on this page · raw message

rust/kernel/random.rs new file +42 -0

42 lines not on this page · raw message

rust/kernel/raw_list.rs new file +361 -0

361 lines not on this page · raw message

rust/kernel/rbtree.rs new file +563 -0

563 lines not on this page · raw message

rust/kernel/revocable.rs new file +425 -0

425 lines not on this page · raw message

rust/kernel/security.rs new file +38 -0
new file mode 100644
index 000000000000..0a33363289d3

Lines of this file are not shown. View the raw message.

rust/kernel/static_assert.rs new file +34 -0
new file mode 100644
index 000000000000..3115ee0ba8e9

Lines of this file are not shown. View the raw message.

rust/kernel/std_vendor.rs new file +161 -0

161 lines not on this page · raw message

rust/kernel/str.rs new file +597 -0

597 lines not on this page · raw message

rust/kernel/sync.rs +28 -20

48 lines not on this page · raw message

rust/kernel/sysctl.rs new file +199 -0

199 lines not on this page · raw message

rust/kernel/task.rs new file +239 -0

239 lines not on this page · raw message

rust/kernel/types.rs new file +705 -0

705 lines not on this page · raw message

rust/kernel/unsafe_list.rs new file +680 -0

680 lines not on this page · raw message

rust/kernel/user_ptr.rs new file +175 -0

175 lines not on this page · raw message

rust/kernel/workqueue.rs new file +512 -0

512 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.37.1

Part of the diff is not shown here. View the raw message.

author maintainer
#30 lore raw

PATCH v8 19/31 vsprintf: add new `%pA` format specifier

In reply to Miguel Ojeda

From: Gary Guo <[email protected]>

This patch adds a format specifier %pA to vsprintf which formats a pointer as core::fmt::Arguments. Doing so allows us to directly format to the internal buffer of printf, so we do not have to use a temporary buffer on the stack to pre-assemble the message on the Rust side.

This specifier is intended only to be used from Rust and not for C, so checkpatch.pl is intentionally unchanged to catch any misuse.

---
 Documentation/core-api/printk-formats.rst | 10 ++++++++++
 lib/vsprintf.c                            | 13 +++++++++++++
 2 files changed, 23 insertions(+)
Documentation/core-api/printk-formats.rst +10 -0
index 5e89497ba314..dbe1aacc79d0 100644
@@ -625,6 +625,16 @@ Examples::
 	%p4cc	Y10  little-endian (0x20303159)
 	%p4cc	NV12 big-endian (0xb231564e)
 
+Rust
+----
+
+::
+
+	%pA
+
+Only intended to be used from Rust code to format ``core::fmt::Arguments``.
+Do *not* use it from C.
+
 Thanks
 ======
 
lib/vsprintf.c +13 -0
index 3c1853a9d1c0..c414a8d9f1ea 100644
@@ -2246,6 +2246,9 @@ int __init no_hash_pointers_enable(char *str)
 }
 early_param("no_hash_pointers", no_hash_pointers_enable);
 
+/* Used for Rust formatting ('%pA'). */
+char *rust_fmt_argument(char *buf, char *end, void *ptr);
+
 /*
  * Show a '%p' thing.  A kernel extension is that the '%p' is followed
  * by an extra set of alphanumeric characters that are extended format
@@ -2372,6 +2375,10 @@ early_param("no_hash_pointers", no_hash_pointers_enable);
  *
  * Note: The default behaviour (unadorned %p) is to hash the address,
  * rendering it useful as a unique identifier.
+ *
+ * There is also a '%pA' format specifier, but it is only intended to be used
+ * from Rust code to format core::fmt::Arguments. Do *not* use it from C.
+ * See rust/kernel/print.rs for details.
  */
 static noinline_for_stack
 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
@@ -2444,6 +2451,12 @@ char *pointer(const char *fmt, char *buf, char *end, void *ptr,
 		return device_node_string(buf, end, ptr, spec, fmt + 1);
 	case 'f':
 		return fwnode_string(buf, end, ptr, spec, fmt + 1);
+	case 'A':
+		if (!IS_ENABLED(CONFIG_RUST)) {
+			WARN_ONCE(1, "Please remove %%pA from non-Rust code\n");
+			return error_string(buf, end, "(%pA?)", spec);
+		}
+		return rust_fmt_argument(buf, end, ptr);
 	case 'x':
 		return pointer_string(buf, end, ptr, spec);
 	case 'e':
Signature · 1 line
2.37.1
author maintainer
#29 lore raw

PATCH v8 18/31 rust: export generated symbols

In reply to Miguel Ojeda

All symbols are reexported reusing the EXPORT_SYMBOL_GPL macro from C. The lists of symbols are generated on the fly.

There are three main sets of symbols to distinguish:

- The ones from the core and alloc crates (from the Rust standard library). The code is licensed as Apache/MIT.

- The ones from our abstractions in the kernel crate.

- The helpers (already exported since they are not generated).

We export everything as GPL. This ensures we do not mistakenly expose GPL kernel symbols/features as non-GPL, even indirectly.

---
 rust/exports.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
 create mode 100644 rust/exports.c
rust/exports.c new file +21 -0
new file mode 100644
index 000000000000..bb7cc64cecd0
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A hack to export Rust symbols for loadable modules without having to redo
+ * the entire `include/linux/export.h` logic in Rust.
+ *
+ * This requires the Rust's new/future `v0` mangling scheme because the default
+ * one ("legacy") uses invalid characters for C identifiers (thus we cannot use
+ * the `EXPORT_SYMBOL_*` macros).
+ *
+ * All symbols are exported as GPL-only to guarantee no GPL-only feature is
+ * accidentally exposed.
+ */
+
+#include <linux/module.h>
+
+#define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym)
+
+#include "exports_core_generated.h"
+#include "exports_alloc_generated.h"
+#include "exports_bindings_generated.h"
+#include "exports_kernel_generated.h"
Signature · 1 line
2.37.1
author maintainer
#31 lore raw

PATCH v8 20/31 scripts: checkpatch: diagnose uses of `%pA` in the C side as errors

In reply to Miguel Ojeda

The %pA format specifier is only intended to be used from Rust.

checkpatch.pl already gives a warning for invalid specificers:

WARNING: Invalid vsprintf pointer extension '%pA'

This makes it an error and introduces an explanatory message:

ERROR: Invalid vsprintf pointer extension '%pA' - '%pA' is only intended to be used from Rust code

---
 scripts/checkpatch.pl | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
scripts/checkpatch.pl +6 -2
index 503e8abbb2c1..23799e8013b3 100755
@@ -6782,15 +6782,19 @@ sub process {
 				}
 				if ($bad_specifier ne "") {
 					my $stat_real = get_stat_real($linenr, $lc);
+					my $msg_level = \&WARN;
 					my $ext_type = "Invalid";
 					my $use = "";
 					if ($bad_specifier =~ /p[Ff]/) {
 						$use = " - use %pS instead";
 						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
+					} elsif ($bad_specifier =~ /pA/) {
+						$use =  " - '%pA' is only intended to be used from Rust code";
+						$msg_level = \&ERROR;
 					}
 
-					WARN("VSPRINTF_POINTER_EXTENSION",
-					     "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
+					&{$msg_level}("VSPRINTF_POINTER_EXTENSION",
+						      "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
 				}
 			}
 		}
Signature · 1 line
2.37.1
author maintainer
#32 lore raw

PATCH v8 21/31 scripts: checkpatch: enable language-independent checks for Rust

In reply to Miguel Ojeda

Include Rust in the "source code files" category, so that the language-independent tests are checked for Rust too, and teach checkpatch about the comment style for Rust files.

This enables the malformed SPDX check, the misplaced SPDX license tag check, the long line checks, the lines without a newline check and the embedded filename check.

---
 scripts/checkpatch.pl | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/checkpatch.pl +2 -2
index 23799e8013b3..bd0025d77bcf 100755
@@ -3615,7 +3615,7 @@ sub process {
 				my $comment = "";
 				if ($realfile =~ /\.(h|s|S)$/) {
 					$comment = '/*';
-				} elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
+				} elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
 					$comment = '//';
 				} elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
 					$comment = '#';
@@ -3663,7 +3663,7 @@ sub process {
 		}
 
 # check we are in a valid source file if not then ignore this hunk
-		next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
+		next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
 
 # check for using SPDX-License-Identifier on the wrong line number
 		if ($realline != $checklicenseline &&
Signature · 1 line
2.37.1
author maintainer
#33 lore raw

PATCH v8 22/31 scripts: add `rustdoc_test_{builder,gen}.py` scripts

In reply to Miguel Ojeda

Rust documentation tests are typically examples of usage of any item (e.g. function, struct, module...). They are very convenient because they are just written alongside the documentation, e.g.:

    /// Sums two numbers.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(mymod::f(10, 20), 30);
    /// ```
    pub fn f(a: i32, b: i32) -> i32 {
        a + b
    }

These scripts are used to transform Rust documentation tests into KUnit tests, so that they can be run in-kernel. In turn, this allows us to run tests that use kernel APIs.

In particular, the test builder receives rustdoc-generated tests, parses them and stores the result. Then, the test generator takes the saved results and generates a KUnit suite where each original documentation test is a test case.

For the moment, this is only done for the kernel crate, but the plan is to generalize it for other crates and modules.

---
 scripts/rustdoc_test_builder.py |  59 ++++++++++++
 scripts/rustdoc_test_gen.py     | 164 ++++++++++++++++++++++++++++++++
 2 files changed, 223 insertions(+)
 create mode 100755 scripts/rustdoc_test_builder.py
 create mode 100755 scripts/rustdoc_test_gen.py
scripts/rustdoc_test_builder.py new file +59 -0
new file mode 100755
index 000000000000..d9b47a5c54fc
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+"""rustdoc_test_builder - Test builder for `rustdoc`-generated tests.
+"""
+
+import json
+import pathlib
+import re
+import sys
+
+RUST_DIR = pathlib.Path("rust")
+TESTS_DIR = RUST_DIR / "test" / "doctests" / "kernel"
+
+# `[^\s]*` removes the prefix (e.g. `_doctest_main_`) plus any
+# leading path (for `O=` builds).
+MAIN_RE = re.compile(
+    r"^"
+    r"fn main\(\) { "
+    r"#\[allow\(non_snake_case\)\] "
+    r"fn ([^\s]*rust_kernel_([a-zA-Z0-9_]+))\(\) {"
+    r"$"
+)
+
+def main():
+    found_main = False
+    test_header = ""
+    test_body = ""
+    for line in sys.stdin.readlines():
+        main_match = MAIN_RE.match(line)
+        if main_match:
+            if found_main:
+                raise Exception("More than one `main` line found.")
+            found_main = True
+            function_name = main_match.group(1)
+            test_name = f"rust_kernel_doctest_{main_match.group(2)}"
+            continue
+
+        if found_main:
+            test_body += line
+        else:
+            test_header += line
+
+    if not found_main:
+        raise Exception("No `main` line found.")
+
+    call_line = f"}} {function_name}() }}"
+    if not test_body.endswith(call_line):
+        raise Exception("Unexpected end of test body.")
+    test_body = test_body[:-len(call_line)]
+
+    with open(TESTS_DIR / f"{test_name}.json", "w") as fd:
+        json.dump({
+            "name": test_name,
+            "header": test_header,
+            "body": test_body,
+        }, fd, sort_keys=True, indent=4)
+
+if __name__ == "__main__":
+    main()
scripts/rustdoc_test_gen.py new file +164 -0

164 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#34 lore raw

PATCH v8 23/31 scripts: add `generate_rust_analyzer.py` scripts

In reply to Miguel Ojeda

The generate_rust_analyzer.py script generates the configuration file (rust-project.json) for rust-analyzer.

rust-analyzer is a modular compiler frontend for the Rust language. It provides an LSP server which can be used in editors such as VS Code, Emacs or Vim.

---
 scripts/generate_rust_analyzer.py | 141 ++++++++++++++++++++++++++++++
 1 file changed, 141 insertions(+)
 create mode 100755 scripts/generate_rust_analyzer.py
scripts/generate_rust_analyzer.py new file +141 -0
new file mode 100755
index 000000000000..ecc7ea9a4dcf
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+"""generate_rust_analyzer - Generates the `rust-project.json` file for `rust-analyzer`.
+"""
+
+import argparse
+import json
+import logging
+import pathlib
+import sys
+
+def generate_crates(srctree, objtree, sysroot_src):
+    # Generate the configuration list.
+    cfg = []
+    with open(objtree / "include" / "generated" / "rustc_cfg") as fd:
+        for line in fd:
+            line = line.replace("--cfg=", "")
+            line = line.replace("\n", "")
+            cfg.append(line)
+
+    # Now fill the crates list -- dependencies need to come first.
+    #
+    # Avoid O(n^2) iterations by keeping a map of indexes.
+    crates = []
+    crates_indexes = {}
+
+    def append_crate(display_name, root_module, deps, cfg=[], is_workspace_member=True, is_proc_macro=False):
+        crates_indexes[display_name] = len(crates)
+        crates.append({
+            "display_name": display_name,
+            "root_module": str(root_module),
+            "is_workspace_member": is_workspace_member,
+            "is_proc_macro": is_proc_macro,
+            "deps": [{"crate": crates_indexes[dep], "name": dep} for dep in deps],
+            "cfg": cfg,
+            "edition": "2021",
+            "env": {
+                "RUST_MODFILE": "This is only for rust-analyzer"
+            }
+        })
+
+    # First, the ones in `rust/` since they are a bit special.
+    append_crate(
+        "core",
+        sysroot_src / "core" / "src" / "lib.rs",
+        [],
+        is_workspace_member=False,
+    )
+
+    append_crate(
+        "compiler_builtins",
+        srctree / "rust" / "compiler_builtins.rs",
+        [],
+    )
+
+    append_crate(
+        "alloc",
+        srctree / "rust" / "alloc" / "lib.rs",
+        ["core", "compiler_builtins"],
+    )
+
+    append_crate(
+        "macros",
+        srctree / "rust" / "macros" / "lib.rs",
+        [],
+        is_proc_macro=True,
+    )
+    crates[-1]["proc_macro_dylib_path"] = "rust/libmacros.so"
+
+    append_crate(
+        "build_error",
+        srctree / "rust" / "build_error.rs",
+        ["core", "compiler_builtins"],
+    )
+
+    append_crate(
+        "bindings",
+        srctree / "rust"/ "bindings" / "lib.rs",
+        ["core"],
+        cfg=cfg,
+    )
+    crates[-1]["env"]["OBJTREE"] = str(objtree.resolve(True))
+
+    append_crate(
+        "kernel",
+        srctree / "rust" / "kernel" / "lib.rs",
+        ["core", "alloc", "macros", "build_error", "bindings"],
+        cfg=cfg,
+    )
+    crates[-1]["source"] = {
+        "include_dirs": [
+            str(srctree / "rust" / "kernel"),
+            str(objtree / "rust")
+        ],
+        "exclude_dirs": [],
+    }
+
+    # Then, the rest outside of `rust/`.
+    #
+    # We explicitly mention the top-level folders we want to cover.
+    for folder in ("samples", "drivers"):
+        for path in (srctree / folder).rglob("*.rs"):
+            logging.info("Checking %s", path)
+            name = path.name.replace(".rs", "")
+
+            # Skip those that are not crate roots.
+            if f"{name}.o" not in open(path.parent / "Makefile").read():
+                continue
+
+            logging.info("Adding %s", name)
+            append_crate(
+                name,
+                path,
+                ["core", "alloc", "kernel"],
+                cfg=cfg,
+            )
+
+    return crates
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--verbose', '-v', action='store_true')
+    parser.add_argument("srctree", type=pathlib.Path)
+    parser.add_argument("objtree", type=pathlib.Path)
+    parser.add_argument("sysroot_src", type=pathlib.Path)
+    args = parser.parse_args()
+
+    logging.basicConfig(
+        format="[%(asctime)s] [%(levelname)s] %(message)s",
+        level=logging.INFO if args.verbose else logging.WARNING
+    )
+
+    rust_project = {
+        "crates": generate_crates(args.srctree, args.objtree, args.sysroot_src),
+        "sysroot_src": str(args.sysroot_src),
+    }
+
+    json.dump(rust_project, sys.stdout, sort_keys=True, indent=4)
+
+if __name__ == "__main__":
+    main()
Signature · 1 line
2.37.1
author maintainer
#35 lore raw

PATCH v8 24/31 scripts: decode_stacktrace: demangle Rust symbols

In reply to Miguel Ojeda

Recent versions of both Binutils (c++filt) and LLVM (llvm-cxxfilt) provide Rust v0 mangling support.

---
 scripts/decode_stacktrace.sh | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
scripts/decode_stacktrace.sh +14 -0
index 7075e26ab2c4..564c5632e1a2 100755
@@ -8,6 +8,14 @@ usage() {
 	echo "	$0 -r <release> | <vmlinux> [<base path>|auto] [<modules path>]"
 }
 
+# Try to find a Rust demangler
+if type llvm-cxxfilt >/dev/null 2>&1 ; then
+	cppfilt=llvm-cxxfilt
+elif type c++filt >/dev/null 2>&1 ; then
+	cppfilt=c++filt
+	cppfilt_opts=-i
+fi
+
 if [[ $1 == "-r" ]] ; then
 	vmlinux=""
 	basepath="auto"
@@ -180,6 +188,12 @@ parse_symbol() {
 	# In the case of inlines, move everything to same line
 	code=${code//$'\n'/' '}
 
+	# Demangle if the name looks like a Rust symbol and if
+	# we got a Rust demangler
+	if [[ $name =~ ^_R && $cppfilt != "" ]] ; then
+		name=$("$cppfilt" "$cppfilt_opts" "$name")
+	fi
+
 	# Replace old address with pretty line numbers
 	symbol="$segment$name ($code)"
 }
Signature · 1 line
2.37.1
author maintainer
#36 lore raw

PATCH v8 25/31 configs: add `rust` config

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

This allows us to enable Rust while creating a configuration file, for example, we can run make defconfig rust.config from the command line to create the default configuration plus enable Rust.

---
 kernel/configs/rust.config | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 kernel/configs/rust.config
kernel/configs/rust.config new file +1 -0
new file mode 100644
index 000000000000..38a7c5362c9c
@@ -0,0 +1 @@
+CONFIG_RUST=y
Signature · 1 line
2.37.1
author maintainer
#37 lore raw

PATCH v8 26/31 docs: add Rust documentation

In reply to Miguel Ojeda

Most of the documentation for Rust is written within the source code itself, as it is idiomatic for Rust projects. This applies to both the shared infrastructure at rust/ as well as any other Rust module (e.g. drivers) written across the kernel.

However, these documents contain general information that does not fit particularly well in the source code, like the Quick Start guide.

It also contains a few other small changes elsewhere in the documentation folder.

---
 Documentation/doc-guide/kernel-doc.rst     |   3 +
 Documentation/index.rst                    |   1 +
 Documentation/kbuild/kbuild.rst            |  17 ++
 Documentation/kbuild/makefiles.rst         |  50 ++++-
 Documentation/process/changes.rst          |  41 ++++
 Documentation/rust/arch-support.rst        |  23 ++
 Documentation/rust/coding-guidelines.rst   | 216 +++++++++++++++++++
 Documentation/rust/general-information.rst |  79 +++++++
 Documentation/rust/index.rst               |  22 ++
 Documentation/rust/quick-start.rst         | 232 +++++++++++++++++++++
 10 files changed, 680 insertions(+), 4 deletions(-)
 create mode 100644 Documentation/rust/arch-support.rst
 create mode 100644 Documentation/rust/coding-guidelines.rst
 create mode 100644 Documentation/rust/general-information.rst
 create mode 100644 Documentation/rust/index.rst
 create mode 100644 Documentation/rust/quick-start.rst
Documentation/doc-guide/kernel-doc.rst +3 -0
index a7cb2afd7990..9b868d9eb20f 100644
@@ -12,6 +12,9 @@ when it is embedded in source files.
    reasons. The kernel source contains tens of thousands of kernel-doc
    comments. Please stick to the style described here.
 
+.. note:: kernel-doc does not cover Rust code: please see
+   Documentation/rust/general-information.rst instead.
+
 The kernel-doc structure is extracted from the comments, and proper
 `Sphinx C Domain`_ function and type descriptions with anchors are
 generated from them. The descriptions are filtered for special kernel-doc
Documentation/index.rst +1 -0
index 67036a05b771..35d90903242a 100644
@@ -82,6 +82,7 @@ merged much easier.
    maintainer/index
    fault-injection/index
    livepatch/index
+   rust/index
 
 
 Kernel API documentation
Documentation/kbuild/kbuild.rst +17 -0
index ef19b9c13523..08f575e6236c 100644
@@ -48,6 +48,10 @@ KCFLAGS
 -------
 Additional options to the C compiler (for built-in and modules).
 
+KRUSTFLAGS
+----------
+Additional options to the Rust compiler (for built-in and modules).
+
 CFLAGS_KERNEL
 -------------
 Additional options for $(CC) when used to compile
@@ -57,6 +61,15 @@ CFLAGS_MODULE
 -------------
 Additional module specific options to use for $(CC).
 
+RUSTFLAGS_KERNEL
+----------------
+Additional options for $(RUSTC) when used to compile
+code that is compiled as built-in.
+
+RUSTFLAGS_MODULE
+----------------
+Additional module specific options to use for $(RUSTC).
+
 LDFLAGS_MODULE
 --------------
 Additional options used for $(LD) when linking modules.
@@ -69,6 +82,10 @@ HOSTCXXFLAGS
 ------------
 Additional flags to be passed to $(HOSTCXX) when building host programs.
 
+HOSTRUSTFLAGS
+-------------
+Additional flags to be passed to $(HOSTRUSTC) when building host programs.
+
 HOSTLDFLAGS
 -----------
 Additional flags to be passed when linking host programs.
Documentation/kbuild/makefiles.rst +46 -4

80 lines not on this page · raw message

Documentation/process/changes.rst +41 -0

65 lines not on this page · raw message

Documentation/rust/arch-support.rst new file +23 -0
new file mode 100644
index 000000000000..bcc92cae11d9
@@ -0,0 +1,23 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Arch Support
+============
+
+Currently, the Rust compiler (``rustc``) uses LLVM for code generation,
+which limits the supported architectures that can be targeted. In addition,
+support for building the kernel with LLVM/Clang varies (please see
+Documentation/kbuild/llvm.rst). This support is needed for ``bindgen``
+which uses ``libclang``.
+
+Below is a general summary of architectures that currently work. Level of
+support corresponds to ``S`` values in the ``MAINTAINERS`` file.
+
+============  ================  ==============================================
+Architecture  Level of support  Constraints
+============  ================  ==============================================
+``arm``       Maintained        ``armv6`` and compatible only.
+``arm64``     Maintained        None.
+``powerpc``   Maintained        ``ppc64le`` only.
+``riscv``     Maintained        ``riscv64`` only.
+``x86``       Maintained        ``x86_64`` only.
+============  ================  ==============================================
Documentation/rust/coding-guidelines.rst new file +216 -0

216 lines not on this page · raw message

Documentation/rust/general-information.rst new file +79 -0

79 lines not on this page · raw message

Documentation/rust/index.rst new file +22 -0
new file mode 100644
index 000000000000..4ae8c66b94fa
@@ -0,0 +1,22 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Rust
+====
+
+Documentation related to Rust within the kernel. To start using Rust
+in the kernel, please read the quick-start.rst guide.
+
+.. toctree::
+    :maxdepth: 1
+
+    quick-start
+    general-information
+    coding-guidelines
+    arch-support
+
+.. only::  subproject and html
+
+   Indices
+   =======
+
+   * :ref:`genindex`
Documentation/rust/quick-start.rst new file +232 -0

232 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#54 lore raw

PATCH v8 29/31 MAINTAINERS: Rust

In reply to Miguel Ojeda

Miguel, Alex and Wedson will be maintaining the Rust support.

---
 MAINTAINERS | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
MAINTAINERS +15 -0
index 64379c699903..a4f90593b59c 100644
@@ -17477,6 +17477,21 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/infiniband/ulp/rtrs/
 
+RUST
+M:	Miguel Ojeda <[email protected]>
+M:	Alex Gaynor <[email protected]>
+M:	Wedson Almeida Filho <[email protected]>
+L:	[email protected]
+S:	Supported
+W:	https://github.com/Rust-for-Linux/linux
+B:	https://github.com/Rust-for-Linux/linux/issues
+T:	git https://github.com/Rust-for-Linux/linux.git rust-next
+F:	Documentation/rust/
+F:	rust/
+F:	samples/rust/
+F:	scripts/*rust*
+K:	\b(?i:rust)\b
+
 RXRPC SOCKETS (AF_RXRPC)
 M:	David Howells <[email protected]>
 M:	Marc Dionne <[email protected]>
Signature · 1 line
2.37.1
author maintainer
#47 lore raw

PATCH v8 28/31 samples: add Rust examples

In reply to Miguel Ojeda

A set of Rust modules that showcase how Rust modules look like and how to use the abstracted kernel features, as well as an example of a Rust host program with several modules.

These samples also double as tests in the CI.

The semaphore sample comes with a C version for comparison.

---
 samples/Kconfig                        |   2 +
 samples/Makefile                       |   1 +
 samples/rust/Kconfig                   | 165 +++++++++++++++++++
 samples/rust/Makefile                  |  19 +++
 samples/rust/hostprogs/.gitignore      |   3 +
 samples/rust/hostprogs/Makefile        |   5 +
 samples/rust/hostprogs/a.rs            |   7 +
 samples/rust/hostprogs/b.rs            |   5 +
 samples/rust/hostprogs/single.rs       |  12 ++
 samples/rust/rust_chrdev.rs            |  49 ++++++
 samples/rust/rust_echo_server.rs       |  60 +++++++
 samples/rust/rust_fs.rs                |  59 +++++++
 samples/rust/rust_minimal.rs           |  35 ++++
 samples/rust/rust_miscdev.rs           | 142 +++++++++++++++++
 samples/rust/rust_module_parameters.rs |  69 ++++++++
 samples/rust/rust_netfilter.rs         |  54 +++++++
 samples/rust/rust_platform.rs          |  22 +++
 samples/rust/rust_print.rs             |  54 +++++++
 samples/rust/rust_random.rs            |  60 +++++++
 samples/rust/rust_selftests.rs         |  99 ++++++++++++
 samples/rust/rust_semaphore.rs         | 170 ++++++++++++++++++++
 samples/rust/rust_semaphore_c.c        | 212 +++++++++++++++++++++++++
 samples/rust/rust_stack_probing.rs     |  36 +++++
 samples/rust/rust_sync.rs              |  93 +++++++++++
 24 files changed, 1433 insertions(+)
 create mode 100644 samples/rust/Kconfig
 create mode 100644 samples/rust/Makefile
 create mode 100644 samples/rust/hostprogs/.gitignore
 create mode 100644 samples/rust/hostprogs/Makefile
 create mode 100644 samples/rust/hostprogs/a.rs
 create mode 100644 samples/rust/hostprogs/b.rs
 create mode 100644 samples/rust/hostprogs/single.rs
 create mode 100644 samples/rust/rust_chrdev.rs
 create mode 100644 samples/rust/rust_echo_server.rs
 create mode 100644 samples/rust/rust_fs.rs
 create mode 100644 samples/rust/rust_minimal.rs
 create mode 100644 samples/rust/rust_miscdev.rs
 create mode 100644 samples/rust/rust_module_parameters.rs
 create mode 100644 samples/rust/rust_netfilter.rs
 create mode 100644 samples/rust/rust_platform.rs
 create mode 100644 samples/rust/rust_print.rs
 create mode 100644 samples/rust/rust_random.rs
 create mode 100644 samples/rust/rust_selftests.rs
 create mode 100644 samples/rust/rust_semaphore.rs
 create mode 100644 samples/rust/rust_semaphore_c.c
 create mode 100644 samples/rust/rust_stack_probing.rs
 create mode 100644 samples/rust/rust_sync.rs
samples/Kconfig +2 -0
index 470ee3baf2e1..0d81c00289ee 100644
@@ -263,6 +263,8 @@ config SAMPLE_CORESIGHT_SYSCFG
 	  This demonstrates how a user may create their own CoreSight
 	  configurations and easily load them into the system at runtime.
 
+source "samples/rust/Kconfig"
+
 endif # SAMPLES
 
 config HAVE_SAMPLE_FTRACE_DIRECT
samples/Makefile +1 -0
index 701e912ab5af..9832ef3f8fcb 100644
@@ -35,3 +35,4 @@ subdir-$(CONFIG_SAMPLE_WATCH_QUEUE)	+= watch_queue
 obj-$(CONFIG_DEBUG_KMEMLEAK_TEST)	+= kmemleak/
 obj-$(CONFIG_SAMPLE_CORESIGHT_SYSCFG)	+= coresight/
 obj-$(CONFIG_SAMPLE_FPROBE)		+= fprobe/
+obj-$(CONFIG_SAMPLES_RUST)		+= rust/
samples/rust/Kconfig new file +165 -0

165 lines not on this page · raw message

samples/rust/Makefile new file +19 -0
new file mode 100644
index 000000000000..420bcefeb082
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: GPL-2.0
+
+obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
+obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
+obj-$(CONFIG_SAMPLE_RUST_MODULE_PARAMETERS)	+= rust_module_parameters.o
+obj-$(CONFIG_SAMPLE_RUST_SYNC)			+= rust_sync.o
+obj-$(CONFIG_SAMPLE_RUST_CHRDEV)		+= rust_chrdev.o
+obj-$(CONFIG_SAMPLE_RUST_MISCDEV)		+= rust_miscdev.o
+obj-$(CONFIG_SAMPLE_RUST_STACK_PROBING)		+= rust_stack_probing.o
+obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE)		+= rust_semaphore.o
+obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE_C)		+= rust_semaphore_c.o
+obj-$(CONFIG_SAMPLE_RUST_RANDOM)		+= rust_random.o
+obj-$(CONFIG_SAMPLE_RUST_PLATFORM)		+= rust_platform.o
+obj-$(CONFIG_SAMPLE_RUST_NETFILTER)		+= rust_netfilter.o
+obj-$(CONFIG_SAMPLE_RUST_ECHO_SERVER)		+= rust_echo_server.o
+obj-$(CONFIG_SAMPLE_RUST_FS)			+= rust_fs.o
+obj-$(CONFIG_SAMPLE_RUST_SELFTESTS)		+= rust_selftests.o
+
+subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS)		+= hostprogs
samples/rust/hostprogs/.gitignore new file +3 -0
new file mode 100644
index 000000000000..a6c173da5048
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0
+
+single
samples/rust/hostprogs/Makefile new file +5 -0
new file mode 100644
index 000000000000..8ddcbd7416db
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+
+hostprogs-always-y := single
+
+single-rust := y
samples/rust/hostprogs/a.rs new file +7 -0
new file mode 100644
index 000000000000..f7a4a3d0f4e0
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust single host program sample: module `a`.
+
+pub(crate) fn f(x: i32) {
+    println!("The number is {}.", x);
+}
samples/rust/hostprogs/b.rs new file +5 -0
new file mode 100644
index 000000000000..c1675890648f
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust single host program sample: module `b`.
+
+pub(crate) const CONSTANT: i32 = 42;
samples/rust/hostprogs/single.rs new file +12 -0
new file mode 100644
index 000000000000..8c48a119339a
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust single host program sample.
+
+mod a;
+mod b;
+
+fn main() {
+    println!("Hello world!");
+
+    a::f(b::CONSTANT);
+}
samples/rust/rust_chrdev.rs new file +49 -0

49 lines not on this page · raw message

samples/rust/rust_echo_server.rs new file +60 -0

60 lines not on this page · raw message

samples/rust/rust_fs.rs new file +59 -0

59 lines not on this page · raw message

samples/rust/rust_minimal.rs new file +35 -0
new file mode 100644
index 000000000000..6e1a926c6f62
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust minimal sample.
+
+use kernel::prelude::*;
+
+module! {
+    type: RustMinimal,
+    name: b"rust_minimal",
+    author: b"Rust for Linux Contributors",
+    description: b"Rust minimal sample",
+    license: b"GPL",
+}
+
+struct RustMinimal {
+    message: String,
+}
+
+impl kernel::Module for RustMinimal {
+    fn init(_name: &'static CStr, _module: &'static ThisModule) -> Result<Self> {
+        pr_info!("Rust minimal sample (init)\n");
+        pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
+
+        Ok(RustMinimal {
+            message: "on the heap!".try_to_owned()?,
+        })
+    }
+}
+
+impl Drop for RustMinimal {
+    fn drop(&mut self) {
+        pr_info!("My message is {}\n", self.message);
+        pr_info!("Rust minimal sample (exit)\n");
+    }
+}
samples/rust/rust_miscdev.rs new file +142 -0

142 lines not on this page · raw message

samples/rust/rust_module_parameters.rs new file +69 -0

69 lines not on this page · raw message

samples/rust/rust_netfilter.rs new file +54 -0

54 lines not on this page · raw message

samples/rust/rust_platform.rs new file +22 -0
new file mode 100644
index 000000000000..f62784676919
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust platform device driver sample.
+
+use kernel::{module_platform_driver, of, platform, prelude::*};
+
+module_platform_driver! {
+    type: Driver,
+    name: b"rust_platform",
+    license: b"GPL",
+}
+
+struct Driver;
+impl platform::Driver for Driver {
+    kernel::define_of_id_table! {(), [
+        (of::DeviceId::Compatible(b"rust,sample"), None),
+    ]}
+
+    fn probe(_dev: &mut platform::Device, _id_info: Option<&Self::IdInfo>) -> Result {
+        Ok(())
+    }
+}
samples/rust/rust_print.rs new file +54 -0

54 lines not on this page · raw message

samples/rust/rust_random.rs new file +60 -0

60 lines not on this page · raw message

samples/rust/rust_selftests.rs new file +99 -0

99 lines not on this page · raw message

samples/rust/rust_semaphore.rs new file +170 -0

170 lines not on this page · raw message

samples/rust/rust_semaphore_c.c new file +212 -0

212 lines not on this page · raw message

samples/rust/rust_stack_probing.rs new file +36 -0
new file mode 100644
index 000000000000..1448fe8e1b56
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust stack probing sample.
+
+use kernel::prelude::*;
+
+module! {
+    type: RustStackProbing,
+    name: b"rust_stack_probing",
+    author: b"Rust for Linux Contributors",
+    description: b"Rust stack probing sample",
+    license: b"GPL",
+}
+
+struct RustStackProbing;
+
+impl kernel::Module for RustStackProbing {
+    fn init(_name: &'static CStr, _module: &'static ThisModule) -> Result<Self> {
+        pr_info!("Rust stack probing sample (init)\n");
+
+        // Including this large variable on the stack will trigger
+        // stack probing on the supported archs.
+        // This will verify that stack probing does not lead to
+        // any errors if we need to link `__rust_probestack`.
+        let x: [u64; 514] = core::hint::black_box([5; 514]);
+        pr_info!("Large array has length: {}\n", x.len());
+
+        Ok(RustStackProbing)
+    }
+}
+
+impl Drop for RustStackProbing {
+    fn drop(&mut self) {
+        pr_info!("Rust stack probing sample (exit)\n");
+    }
+}
samples/rust/rust_sync.rs new file +93 -0

93 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#59 lore raw

RFC PATCH v8 30/31 drivers: gpio: PrimeCell PL061 in Rust

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A port to Rust of the PrimeCell PL061 GPIO driver.

This module is a work in progress and will be sent for review later on, as well as separately from the Rust support.

However, it is included to show how an actual working module written in Rust may look like.

---
 drivers/gpio/Kconfig            |   8 +
 drivers/gpio/Makefile           |   1 +
 drivers/gpio/gpio_pl061_rust.rs | 367 ++++++++++++++++++++++++++++++++
 3 files changed, 376 insertions(+)
 create mode 100644 drivers/gpio/gpio_pl061_rust.rs
drivers/gpio/Kconfig +8 -0
index b01961999ced..bf942f8e9a60 100644
@@ -482,6 +482,14 @@ config GPIO_PL061
 	help
 	  Say yes here to support the PrimeCell PL061 GPIO device.
 
+config GPIO_PL061_RUST
+	tristate "PrimeCell PL061 GPIO support written in Rust"
+	depends on ARM_AMBA && RUST
+	select IRQ_DOMAIN
+	select GPIOLIB_IRQCHIP
+	help
+	  Say yes here to support the PrimeCell PL061 GPIO device
+
 config GPIO_PMIC_EIC_SPRD
 	tristate "Spreadtrum PMIC EIC support"
 	depends on MFD_SC27XX_PMIC || COMPILE_TEST
drivers/gpio/Makefile +1 -0
index 14352f6dfe8e..30141fec12be 100644
@@ -118,6 +118,7 @@ obj-$(CONFIG_GPIO_PCIE_IDIO_24)		+= gpio-pcie-idio-24.o
 obj-$(CONFIG_GPIO_PCI_IDIO_16)		+= gpio-pci-idio-16.o
 obj-$(CONFIG_GPIO_PISOSR)		+= gpio-pisosr.o
 obj-$(CONFIG_GPIO_PL061)		+= gpio-pl061.o
+obj-$(CONFIG_GPIO_PL061_RUST)		+= gpio_pl061_rust.o
 obj-$(CONFIG_GPIO_PMIC_EIC_SPRD)	+= gpio-pmic-eic-sprd.o
 obj-$(CONFIG_GPIO_PXA)			+= gpio-pxa.o
 obj-$(CONFIG_GPIO_RASPBERRYPI_EXP)	+= gpio-raspberrypi-exp.o
drivers/gpio/gpio_pl061_rust.rs new file +367 -0

367 lines not on this page · raw message

Signature · 1 line
2.37.1
author maintainer
#60 lore raw

RFC PATCH v8 31/31 drivers: android: Binder IPC in Rust

In reply to Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A port to Rust of the Android Binder IPC mechanism.

This module is a work in progress and will be sent for review later on, as well as separately from the Rust support.

However, it is included to show how an actual working module written in Rust may look like.

---
 drivers/android/Kconfig             |   6 +
 drivers/android/Makefile            |   2 +
 drivers/android/allocation.rs       | 266 ++++++++
 drivers/android/context.rs          |  80 +++
 drivers/android/defs.rs             |  99 +++
 drivers/android/node.rs             | 476 ++++++++++++++
 drivers/android/process.rs          | 961 ++++++++++++++++++++++++++++
 drivers/android/range_alloc.rs      | 189 ++++++
 drivers/android/rust_binder.rs      | 106 +++
 drivers/android/thread.rs           | 871 +++++++++++++++++++++++++
 drivers/android/transaction.rs      | 326 ++++++++++
 include/uapi/linux/android/binder.h |  30 +-
 12 files changed, 3398 insertions(+), 14 deletions(-)
 create mode 100644 drivers/android/allocation.rs
 create mode 100644 drivers/android/context.rs
 create mode 100644 drivers/android/defs.rs
 create mode 100644 drivers/android/node.rs
 create mode 100644 drivers/android/process.rs
 create mode 100644 drivers/android/range_alloc.rs
 create mode 100644 drivers/android/rust_binder.rs
 create mode 100644 drivers/android/thread.rs
 create mode 100644 drivers/android/transaction.rs
drivers/android/Kconfig +6 -0
index 53b22e26266c..bc10eebd3ad3 100644
@@ -20,6 +20,12 @@ config ANDROID_BINDER_IPC
 	  Android process, using Binder to identify, invoke and pass arguments
 	  between said processes.
 
+config ANDROID_BINDER_IPC_RUST
+	bool "Android Binder IPC Driver in Rust"
+	depends on MMU && RUST
+	help
+	  Implementation of the Binder IPC in Rust.
+
 config ANDROID_BINDERFS
 	bool "Android Binderfs filesystem"
 	depends on ANDROID_BINDER_IPC
drivers/android/Makefile +2 -0
index c9d3d0c99c25..c428f2ce2f05 100644
@@ -4,3 +4,5 @@ ccflags-y += -I$(src)			# needed for trace events
 obj-$(CONFIG_ANDROID_BINDERFS)		+= binderfs.o
 obj-$(CONFIG_ANDROID_BINDER_IPC)	+= binder.o binder_alloc.o
 obj-$(CONFIG_ANDROID_BINDER_IPC_SELFTEST) += binder_alloc_selftest.o
+
+obj-$(CONFIG_ANDROID_BINDER_IPC_RUST) += rust_binder.o
drivers/android/allocation.rs new file +266 -0

266 lines not on this page · raw message

drivers/android/context.rs new file +80 -0

80 lines not on this page · raw message

drivers/android/defs.rs new file +99 -0

99 lines not on this page · raw message

drivers/android/node.rs new file +476 -0

476 lines not on this page · raw message

drivers/android/process.rs new file +961 -0

961 lines not on this page · raw message

drivers/android/range_alloc.rs new file +189 -0

189 lines not on this page · raw message

drivers/android/rust_binder.rs new file +106 -0

106 lines not on this page · raw message

drivers/android/thread.rs new file +871 -0

806 lines not on this page · raw message

drivers/android/transaction.rs new file +326 -0

326 lines not on this page · raw message

include/uapi/linux/android/binder.h +16 -14
index 986333cf5bbe..a3bd993c5c9a 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.37.1

Part of the diff is not shown here. View the raw message.

#55 lore raw

Re: [PATCH v8 29/31] MAINTAINERS: Rust

In reply to Miguel Ojeda
Quoted 17 lines · Miguel Ojeda

Miguel, Alex and Wedson will be maintaining the Rust support.

---
 MAINTAINERS | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
MAINTAINERS +0 -0
index 64379c699903..a4f90593b59c 100644

MAINTAINERS L: [email protected] · line 17483

Quoted 7 lines
MAINTAINERS +4 -0
@@ -17477,6 +17477,21 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/infiniband/ulp/rtrs/
 
+RUST
+M:	Miguel Ojeda <[email protected]>
+M:	Alex Gaynor <[email protected]>
+M:	Wedson Almeida Filho <[email protected]>

May I join the party and become a reviewer?

R: Boqun Feng <[email protected]>

Also given their activities on GitHub, I'd like to encourge Björn Roy Baron and Gary Guo to become reviewers as well. Of course, they need to be aware of the possible upcoming email volume and sign up themselves ;-)

More eyes (especially from Rust language experts) are helpful ;-)

Regards,
Boqun

Quoted 18 lines
MAINTAINERS +11 -0
+L:	[email protected]
+S:	Supported
+W:	https://github.com/Rust-for-Linux/linux
+B:	https://github.com/Rust-for-Linux/linux/issues
+T:	git https://github.com/Rust-for-Linux/linux.git rust-next
+F:	Documentation/rust/
+F:	rust/
+F:	samples/rust/
+F:	scripts/*rust*
+K:	\b(?i:rust)\b
+
 RXRPC SOCKETS (AF_RXRPC)
 M:	David Howells <[email protected]>
 M:	Marc Dionne <[email protected]>
Signature · 1 line
2.37.1
#56 lore raw

Re: [PATCH v8 29/31] MAINTAINERS: Rust

Quoted 4 lines · Boqun Feng

May I join the party and become a reviewer?

R: Boqun Feng <[email protected]>

Of course! Thanks!

Quoted 6 lines

Also given their activities on GitHub, I'd like to encourge Björn Roy Baron and Gary Guo to become reviewers as well. Of course, they need to be aware of the possible upcoming email volume and sign up themselves ;-)

More eyes (especially from Rust language experts) are helpful ;-)

Indeed, they would be most welcome to join :)

Cheers,
Miguel

#3 lore raw

RE: [PATCH v8 02/31] kallsyms: avoid hardcoding buffer size

In reply to Miguel Ojeda

From: Miguel Ojeda

Quoted 39 lines

Sent: 02 August 2022 02:50

From: Boqun Feng <[email protected]>

This introduces KSYM_NAME_LEN_BUFFER in place of the previously hardcoded size of the input buffer.

It will also make it easier to update the size in a single place in a later patch.

---
 scripts/kallsyms.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
scripts/kallsyms.c +6 -0
index 52f5488c61bc..f3c5a2623f71 100644
@@ -27,8 +27,14 @@
 
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
 
+#define _stringify_1(x)	#x
+#define _stringify(x)	_stringify_1(x)
+
 #define KSYM_NAME_LEN		128
 
+/* A substantially bigger size than the current maximum. */
+#define KSYM_NAME_LEN_BUFFER	499
+
 struct sym_entry {
 	unsigned long long addr;
 	unsigned int len;
@@ -198,13 +204,13 @@ static void check_symbol_range(const char *sym, unsigned long long addr,
 
 static struct sym_entry *read_symbol(FILE *in)

scripts/kallsyms.c static void check_symbol_range(const char *sym, unsigned long long addr, · line 213

Quoted 10 lines
scripts/kallsyms.c +2 -2
 {
-	char name[500], type;
+	char name[KSYM_NAME_LEN_BUFFER+1], type;
 	unsigned long long addr;
 	unsigned int len;
 	struct sym_entry *sym;
 	int rc;
 
-	rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
+	rc = fscanf(in, "%llx %c %" _stringify(KSYM_NAME_LEN_BUFFER) "s\n", &addr, &type, name);

Think I'd use "%*s" - simpler.
Although I normally completely avoid scanf() - too easy to get wrong.

David

Quoted 5 lines
scripts/kallsyms.c +0 -1
 	if (rc != 3) {
 		if (rc != EOF && fgets(name, sizeof(name), in) == NULL)
 			fprintf(stderr, "Read error or end of file.\n");
--

2.37.1

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)

#4 lore raw

Re: [PATCH v8 02/31] kallsyms: avoid hardcoding buffer size

Quoted 8 lines · David Laight

From: Miguel Ojeda

scripts/kallsyms.c static void check_symbol_range(const char *sym, unsigned long long addr, · line 213

Quoted 4 lines

Sent: 02 August 2022 02:50

scripts/kallsyms.c +1 -1
-	rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
+	rc = fscanf(in, "%llx %c %" _stringify(KSYM_NAME_LEN_BUFFER) "s\n", &addr, &type, name);

Think I'd use "%*s" - simpler.
Although I normally completely avoid scanf() - too easy to get wrong.

Indeed, and your suggestion is a perfect example: for scanf, * doesn't mean "there's an int argument specifying the 'precision'", quite the contrary. man fscanf:

• An optional '*' assignment-suppression character: scanf()
reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is re‐ quired, and this specification is not included in the count of successful assignments returned by scanf().

Rasmus

#61 lore raw
In reply to Miguel Ojeda
Quoted 4 lines · Miguel Ojeda

Some of the improvements to the abstractions and example drivers are:

- Filesystem support (fs module), including:

Quoted 13 lines

+ INode type (which wraps struct inode).
+ DEntry type (which wraps struct dentry).
+ Filename type (which wraps struct filename).
+ Registration type.
+ Type and Context traits.
+ SuperBlock type (which wraps struct super_block and takes advantage of typestates for its initialization).
+ File system parameters support (with a Value enum; Spec* and Constant* types, define_fs_params! macro...).
+ File system flags.
+ module_fs! macro to simplify registering kernel modules that only implement a single file system.
+ A file system sample.

None of this (afaict) has been discussed on linux-fsdevel. And I may have missed somethiing, but I don't see the fs module in this series of patches. Could linux-fsdevel be cc'd on the development of Rust support for filesystems in the future?

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#24 lore raw

Re: [PATCH v8 17/31] rust: add `kernel` crate

In reply to Miguel Ojeda
Quoted 115 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

The kernel crate currently includes all the abstractions that wrap kernel features written in C.

These abstractions call the C side of the kernel via the generated bindings with the bindgen tool. Modules developed in Rust should never call the bindings themselves.

In the future, as the abstractions grow in number, we may need to split this crate into several, possibly following a similar subdivision in subsystems as the kernel itself and/or moving the code to the actual subsystems.

---
 rust/kernel/allocator.rs                 |  64 ++
 rust/kernel/amba.rs                      | 261 +++++++
 rust/kernel/build_assert.rs              |  83 +++
 rust/kernel/chrdev.rs                    | 206 ++++++
 rust/kernel/clk.rs                       |  79 ++
 rust/kernel/cred.rs                      |  46 ++
 rust/kernel/delay.rs                     | 104 +++
 rust/kernel/device.rs                    | 527 ++++++++++++++
 rust/kernel/driver.rs                    | 442 +++++++++++
 rust/kernel/error.rs                     | 564 ++++++++++++++
 rust/kernel/file.rs                      | 887 +++++++++++++++++++++++
 rust/kernel/fs.rs                        | 846 +++++++++++++++++++++
 rust/kernel/fs/param.rs                  | 553 ++++++++++++++
 rust/kernel/gpio.rs                      | 505 +++++++++++++
 rust/kernel/hwrng.rs                     | 210 ++++++
 rust/kernel/io_buffer.rs                 | 153 ++++
 rust/kernel/io_mem.rs                    | 278 +++++++
 rust/kernel/iov_iter.rs                  |  81 +++
 rust/kernel/irq.rs                       | 681 +++++++++++++++++
 rust/kernel/kasync.rs                    |  50 ++
 rust/kernel/kasync/executor.rs           | 154 ++++
 rust/kernel/kasync/executor/workqueue.rs | 291 ++++++++
 rust/kernel/kasync/net.rs                | 322 ++++++++
 rust/kernel/kunit.rs                     |  91 +++
 rust/kernel/lib.rs                       | 267 +++++++
 rust/kernel/linked_list.rs               | 247 +++++++
 rust/kernel/miscdev.rs                   | 290 ++++++++
 rust/kernel/mm.rs                        | 149 ++++
 rust/kernel/module_param.rs              | 499 +++++++++++++
 rust/kernel/net.rs                       | 392 ++++++++++
 rust/kernel/net/filter.rs                | 447 ++++++++++++
 rust/kernel/of.rs                        |  63 ++
 rust/kernel/pages.rs                     | 144 ++++
 rust/kernel/platform.rs                  | 223 ++++++
 rust/kernel/power.rs                     | 118 +++
 rust/kernel/prelude.rs                   |  36 +
 rust/kernel/print.rs                     | 406 +++++++++++
 rust/kernel/random.rs                    |  42 ++
 rust/kernel/raw_list.rs                  | 361 +++++++++
 rust/kernel/rbtree.rs                    | 563 ++++++++++++++
 rust/kernel/revocable.rs                 | 425 +++++++++++
 rust/kernel/security.rs                  |  38 +
 rust/kernel/static_assert.rs             |  34 +
 rust/kernel/std_vendor.rs                | 161 ++++
 rust/kernel/str.rs                       | 597 +++++++++++++++
Quoted 8 lines
 rust/kernel/sync.rs                      |  48 +-
 rust/kernel/sysctl.rs                    | 199 +++++
 rust/kernel/task.rs                      | 239 ++++++
 rust/kernel/types.rs                     | 705 ++++++++++++++++++
 rust/kernel/unsafe_list.rs               | 680 +++++++++++++++++
 rust/kernel/user_ptr.rs                  | 175 +++++
 rust/kernel/workqueue.rs                 | 512 +++++++++++++
 52 files changed, 15518 insertions(+), 20 deletions(-)

This is huge for a single commit, and pretty much impossible to review as-is.

Any chance you can turn this into a series of commits, that starts with the basics and builds on top of that? Right now you are mixing many many different subsystems all at once into one commit, guaranteeing that no one can review the whole thing properly :(

thanks,

greg k-h

#62 lore raw
In reply to Matthew Wilcox

Hi Willy,

Quoted 5 lines · Matthew Wilcox

None of this (afaict) has been discussed on linux-fsdevel. And I may have missed somethiing, but I don't see the fs module in this series of patches. Could linux-fsdevel be cc'd on the development of Rust support for filesystems in the future?

In order to provide example drivers and kernel modules, we need to have some safe abstractions for them, thus we are adding some as we need them.

More importantly, the abstractions also serve as a showcase of how they may be written in the future if Rust support is merged.

This does not mean these abstractions are a final design or that we plan to develop them independently of subsystem maintainers. In fact, we would prefer the opposite: in the future, when the support is merged and more people start having more experience with Rust, we hope that the respective kernel maintainers start developing and maintaining the abstractions themselves.

But we have to start somewhere, and at least provide enough examples to serve as guidance and to show that it is actually possible to write abstractions that restrict the amount of unsafe code.

And, of course, if you are already interested in developing them, that would be actually great and we would love your input and/or that you join us.

As for the fs module, I see in lore 2 patches didn't make it through, but I didn't get a bounce (I do get bounces for the rust-for-linux ML, but I was told that was fine as long as LKML got them). Sorry about that... I will ask what to do.

Meanwhile, you can see the patches in this branch:

https://github.com/Rust-for-Linux/linux.git rust-next

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#65 lore raw
In reply to Miguel Ojeda
Quoted 23 lines · Miguel Ojeda

Hi Willy,

Quoted 5 lines · Matthew Wilcox

None of this (afaict) has been discussed on linux-fsdevel. And I may have missed somethiing, but I don't see the fs module in this series of patches. Could linux-fsdevel be cc'd on the development of Rust support for filesystems in the future?

In order to provide example drivers and kernel modules, we need to have some safe abstractions for them, thus we are adding some as we need them.

More importantly, the abstractions also serve as a showcase of how they may be written in the future if Rust support is merged.

This does not mean these abstractions are a final design or that we plan to develop them independently of subsystem maintainers. In fact, we would prefer the opposite: in the future, when the support is merged and more people start having more experience with Rust, we hope that the respective kernel maintainers start developing and maintaining the abstractions themselves.

Quoted 7 lines

But we have to start somewhere, and at least provide enough examples to serve as guidance and to show that it is actually possible to write abstractions that restrict the amount of unsafe code.

And, of course, if you are already interested in developing them, that would be actually great and we would love your input and/or that you join us.

No objections to any of this. I love the idea of being able to write filesystems in Rust. I just think it would go more smoothly if linux-fsdevel were involved more closely so people at least have the option of being able to follow design decisions, and hopefully influence them. That goes both ways, of course; I hardly think our current operations structures are the optimum way to implement a filesystem, and having fresh eyes say things like "But that shouldn't be part of the address_space_operations" can impel better abstractions.

Quoted 4 lines

As for the fs module, I see in lore 2 patches didn't make it through, but I didn't get a bounce (I do get bounces for the rust-for-linux ML, but I was told that was fine as long as LKML got them). Sorry about that... I will ask what to do.

The obvious answer is to split out the 'fs module' into its own patch ;-) I presume it was part of the kernel crate which would have been either patch 17 or 11 in that series?

Quoted 6 lines

Meanwhile, you can see the patches in this branch:

https://github.com/Rust-for-Linux/linux.git rust-next

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#48 lore raw

Re: [PATCH v8 28/31] samples: add Rust examples

In reply to Miguel Ojeda

samples/rust/rust_semaphore.rs line 34

Quoted 7 lines
samples/rust/rust_semaphore.rs new file +7 -0
+module! {
+    type: RustSemaphore,
+    name: b"rust_semaphore",
+    author: b"Rust for Linux Contributors",
+    description: b"Rust semaphore sample",
+    license: b"GPL",
+}

A minor neat, but ain't it possible to use &str here in order to drop this ugly binary string prefix?

#64 lore raw
In reply to Christoph Hellwig
Quoted 4 lines · Christoph Hellwig

handwaiving and pointing to git trees is not how Linux development works. Please make sure all the patches go to the relevant lists and maintainers first, and actually do have ACKs.

Which hand-waving? In fact, we were requested to do it like this.

As for the Cc's, if any ML wants to be Cc'd for an abstraction we create, even if no C code is modified on their side, I am more than happy to Cc them. I can even do that by default, but not everyone may want to hear about the Rust side just yet, so I have not been doing it so far.

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#25 lore raw

Re: [PATCH v8 17/31] rust: add `kernel` crate

In reply to Greg Kroah-Hartman

Hi Greg,

Quoted 8 lines · Greg Kroah-Hartman

This is huge for a single commit, and pretty much impossible to review as-is.

Any chance you can turn this into a series of commits, that starts with the basics and builds on top of that? Right now you are mixing many many different subsystems all at once into one commit, guaranteeing that no one can review the whole thing properly :(

Yeah, of course, I am happy to do that -- I did it for the sync module, but stopped splitting further since I understood you wanted it this way from what you told me on February.

Cheers,
Miguel

#26 lore raw

Re: [PATCH v8 17/31] rust: add `kernel` crate

Quoted 8 lines · Miguel Ojeda

Hi Greg,

Quoted 4 lines · Greg Kroah-Hartman

This is huge for a single commit, and pretty much impossible to review as-is.

Quoted 8 lines
Quoted 4 lines

Any chance you can turn this into a series of commits, that starts with the basics and builds on top of that? Right now you are mixing many many different subsystems all at once into one commit, guaranteeing that no one can review the whole thing properly :(

Yeah, of course, I am happy to do that -- I did it for the sync module, but stopped splitting further since I understood you wanted it this way from what you told me on February.

I did? Maybe I didn't realize we would end up with 15k lines of code from different parts of the kernel like amba bus and filesystem apis all in a single commit. If so, my fault, but as other parts of this discussion show, it is going to be required to get the subsystem maintainers to be able to review the interfaces to their code in order to get any further.

thanks,

greg k-h

maintainer
#57 lore raw

Re: [PATCH v8 29/31] MAINTAINERS: Rust

In reply to Boqun Feng
Quoted 28 lines · On Mon, 1 Aug 2022 19:25:55 -0700 Boqun Feng <[email protected]> wrote:
Quoted 17 lines · Miguel Ojeda

Miguel, Alex and Wedson will be maintaining the Rust support.

---
 MAINTAINERS | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
MAINTAINERS +0 -0
index 64379c699903..a4f90593b59c 100644

MAINTAINERS L: [email protected] · line 17483

Quoted 7 lines
MAINTAINERS +4 -0
@@ -17477,6 +17477,21 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/infiniband/ulp/rtrs/
 
+RUST
+M:	Miguel Ojeda <[email protected]>
+M:	Alex Gaynor <[email protected]>
+M:	Wedson Almeida Filho <[email protected]>  

May I join the party and become a reviewer?

Quoted 4 lines

R: Boqun Feng <[email protected]>

Also given their activities on GitHub, I'd like to encourge Björn Roy Baron and Gary Guo to become reviewers as well.

Sure! I am happy to help reviewing.

R: Gary Guo <[email protected]>

Quoted 2 lines

Of course, they need to be aware of the possible upcoming email volume and sign up themselves ;-)

I've got inbox rules that should sort these items, hopefully :)

Best,
Gary

#27 lore raw

Re: [PATCH v8 17/31] rust: add `kernel` crate

In reply to Greg Kroah-Hartman
Quoted 7 lines · Greg Kroah-Hartman

I did? Maybe I didn't realize we would end up with 15k lines of code from different parts of the kernel like amba bus and filesystem apis all in a single commit. If so, my fault, but as other parts of this discussion show, it is going to be required to get the subsystem maintainers to be able to review the interfaces to their code in order to get any further.

No worries at all! Probably a misunderstanding on my side too.

I am more than happy to spit it into quite a few patches, and it will also help with the C-d-b's.

As for reviewing -- since we keep adding abstractions and new features to show how things may work, we would be chasing new reviews all the time. Would it be better to drop some of those for the moment and get the "core" in first?

That way we can merge each subsystem part by part later, send it to the proper MLs as smaller patches, get maintainers on board, etc. etc., and it would be more manageable for everyone.

Cheers,
Miguel

#66 lore raw
In reply to Matthew Wilcox
Quoted 9 lines · Matthew Wilcox

No objections to any of this. I love the idea of being able to write filesystems in Rust. I just think it would go more smoothly if linux-fsdevel were involved more closely so people at least have the option of being able to follow design decisions, and hopefully influence them. That goes both ways, of course; I hardly think our current operations structures are the optimum way to implement a filesystem, and having fresh eyes say things like "But that shouldn't be part of the address_space_operations" can impel better abstractions.

I will send the patches to fsdevel then!

As for following development closely and design decisions, we have been doing it in GitHub so far pre-merge, so the easiest until the merge (for us) would be to ping you there. We can also send you copies of the fs related patches too if you would like that. I would highly recommend joining the monthly informal calls too.

(I appreciate the kind answer, by the way!)

Quoted 3 lines

The obvious answer is to split out the 'fs module' into its own patch ;-) I presume it was part of the kernel crate which would have been either patch 17 or 11 in that series?

Yeah, patch 17, exactly (patch 11 is the alloc import). I have asked Konstantin privately about them.

In any case, I will split the patches further for v9 which should help.

Meanwhile, you can also see the fs module here, if you are curious:

https://github.com/Rust-for-Linux/linux/blob/rust-next/rust/kernel/fs.rs
https://github.com/Rust-for-Linux/linux/blob/rust-next/rust/kernel/fs/param.rs

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#67 lore raw
Quoted 3 lines · Miguel Ojeda

Yeah, patch 17, exactly (patch 11 is the alloc import). I have asked Konstantin privately about them.

The patches are showing up now in lore -- not sure if it was just a delay (which would be consistent with the lack of bounce) or somebody did something (thank you if so!).

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#49 lore raw

Re: [PATCH v8 28/31] samples: add Rust examples

In reply to Konstantin Shelekhin
Quoted 10 lines · Konstantin Shelekhin

samples/rust/rust_semaphore.rs line 34

Quoted 7 lines
samples/rust/rust_semaphore.rs new file +7 -0
+module! {
+    type: RustSemaphore,
+    name: b"rust_semaphore",
+    author: b"Rust for Linux Contributors",
+    description: b"Rust semaphore sample",
+    license: b"GPL",
+}

A minor neat, but ain't it possible to use &str here in order to drop this ugly binary string prefix?

Their types are different. One is for u8. The other is for UTF-8.

Thanks,
Wei.

#28 lore raw

Re: [PATCH v8 17/31] rust: add `kernel` crate

In reply to Miguel Ojeda
Quoted 12 lines · Miguel Ojeda
Quoted 7 lines · Greg Kroah-Hartman

I did? Maybe I didn't realize we would end up with 15k lines of code from different parts of the kernel like amba bus and filesystem apis all in a single commit. If so, my fault, but as other parts of this discussion show, it is going to be required to get the subsystem maintainers to be able to review the interfaces to their code in order to get any further.

No worries at all! Probably a misunderstanding on my side too.

Quoted 7 lines

I am more than happy to spit it into quite a few patches, and it will also help with the C-d-b's.

As for reviewing -- since we keep adding abstractions and new features to show how things may work, we would be chasing new reviews all the time. Would it be better to drop some of those for the moment and get the "core" in first?

Yes, it would be good to drop almost all of these for now, anything you do not have an in-tree user for, should not be present in anything you submit upstream.

Quoted 3 lines

That way we can merge each subsystem part by part later, send it to the proper MLs as smaller patches, get maintainers on board, etc. etc., and it would be more manageable for everyone.

Yes, that would be the normal review process.

thanks,

greg k-h

#50 lore raw

Re: [PATCH v8 28/31] samples: add Rust examples

In reply to Wei Liu
Quoted 1 line

Their types are different. One is for u8. The other is for UTF-8.

Yes, but:

+#[derive(Debug, Default)]
+struct ModuleInfo {

  +    type_: String,
  +    license: String,
  +    name: String,
  +    author: Option<String>,
  +    description: Option<String>,
  +    alias: Option<String>,
  +    params: Option<Group>,

+}

[...]

+impl ModuleInfo {
+ fn parse(it: &mut token_stream::IntoIter) -> Self {
+ match key.as_str() {

  +                "type" => info.type_ = expect_ident(it),
  +                "name" => info.name = expect_byte_string(it),
  +                "author" => info.author = Some(expect_byte_string(it)),
  +                "description" => info.description = Some(expect_byte_string(it)),
  +                "license" => info.license = expect_byte_string(it),
  +                "alias" => info.alias = Some(expect_byte_string(it)),
  +                "alias_rtnl_link" => {
  +                    info.alias = Some(format!("rtnl-link-{}", expect_byte_string(it)))
  +                }
  +                "params" => info.params = Some(expect_group(it)),
  +                _ => panic!(

+ "Unknown key \"{}\". Valid keys are: {:?}.",
+ key, EXPECTED_KEYS
+ ),
+ }

In the the end all module parameters are String, so why not use &str in the API?

Acked-by on v8 7/31
#12 lore raw

Re: [PATCH v8 07/31] locking/spinlock: introduce `__spin_lock_init`

In reply to Miguel Ojeda
Quoted 10 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call spin_lock_init with a passed key, rather than define one in place.

In order to do that, this changes the spin_lock_init macro to call a new __spin_lock_init function which takes the key as an extra parameter.

Quoted 5 lines

Peter, Will & Waiman, could you take a look at this patch and patch #8?

These two are needed because currently there is no way to convert a C macro to a Rust macro, a C macro can be called as a function on Rust side, but that's not quite for generating a static key of lockdep. As a result, __spin_lock_init() needs to be exposed.

I think these are tiny and harmless, but looking forwards to your insight ;-)

Regards,
Boqun

Quoted 32 lines
---
 include/linux/spinlock.h | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
include/linux/spinlock.h +7 -2
index 5c0c5174155d..ad1c91884ed8 100644
@@ -326,12 +326,17 @@ static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock)
 
 #ifdef CONFIG_DEBUG_SPINLOCK
 
+static inline void __spin_lock_init(spinlock_t *lock, const char *name,
+				    struct lock_class_key *key)
+{
+	__raw_spin_lock_init(spinlock_check(lock), name, key, LD_WAIT_CONFIG);
+}
+
 # define spin_lock_init(lock)					\
 do {								\
 	static struct lock_class_key __key;			\
 								\
-	__raw_spin_lock_init(spinlock_check(lock),		\
-			     #lock, &__key, LD_WAIT_CONFIG);	\
+	__spin_lock_init(lock, #lock, &__key);			\
 } while (0)
 
 #else
Signature · 1 line
2.37.1
Acked-by on v8 8/31
#14 lore raw

Re: [PATCH v8 08/31] locking/spinlock: introduce `_raw_spin_lock_init`

In reply to Miguel Ojeda
Quoted 10 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call raw_spin_lock_init with a passed key, rather than define one in place.

In order to do that, this changes the raw_spin_lock_init macro to call a new _raw_spin_lock_init function which takes the key as an extra parameter.

Quoted 5 lines

Regards,
Boqun

Quoted 31 lines
---
 include/linux/spinlock.h | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
include/linux/spinlock.h +7 -1
index ad1c91884ed8..27df5380c1e4 100644
@@ -99,11 +99,17 @@
   extern void __raw_spin_lock_init(raw_spinlock_t *lock, const char *name,
 				   struct lock_class_key *key, short inner);
 
+static inline void _raw_spin_lock_init(raw_spinlock_t *lock, const char *name,
+				       struct lock_class_key *key)
+{
+	__raw_spin_lock_init(lock, name, key, LD_WAIT_SPIN);
+}
+
 # define raw_spin_lock_init(lock)					\
 do {									\
 	static struct lock_class_key __key;				\
 									\
-	__raw_spin_lock_init((lock), #lock, &__key, LD_WAIT_SPIN);	\
+	_raw_spin_lock_init((lock), #lock, &__key);			\
 } while (0)
 
 #else
Signature · 1 line
2.37.1
reviewer
#58 lore raw

Re: [PATCH v8 29/31] MAINTAINERS: Rust

In reply to Boqun Feng
Quoted 43 lines · Boqun Feng
Quoted 20 lines · Miguel Ojeda

Miguel, Alex and Wedson will be maintaining the Rust support.

---
MAINTAINERS | 15 +++++++++++++++

1 file changed, 15 insertions(+)
MAINTAINERS +0 -0
index 64379c699903..a4f90593b59c 100644
@@ -17477,6 +17477,21 @@ L: [email protected]

S: Maintained
F: drivers/infiniband/ulp/rtrs/

MAINTAINERS

Quoted 4 lines
MAINTAINERS +4 -0
+RUST
+M: Miguel Ojeda [email protected]
+M: Alex Gaynor [email protected]
+M: Wedson Almeida Filho [email protected]

May I join the party and become a reviewer?

R: Boqun Feng [email protected]

Also given their activities on GitHub, I'd like to encourge Björn Roy Baron and Gary Guo to become reviewers as well. Of course, they need to be aware of the possible upcoming email volume and sign up themselves ;-)

More eyes (especially from Rust language experts) are helpful ;-)

Regards,
Boqun

Quoted 16 lines
Quoted 11 lines
MAINTAINERS +11 -0
+L: [email protected]
+S: Supported
+W: https://github.com/Rust-for-Linux/linux
+B: https://github.com/Rust-for-Linux/linux/issues
+T: git https://github.com/Rust-for-Linux/linux.git rust-next
+F: Documentation/rust/
+F: rust/
+F: samples/rust/
+F: scripts/rust
+K: \b(?i:rust)\b
+
Quoted 5 lines

RXRPC SOCKETS (AF_RXRPC)
M: David Howells [email protected]
M: Marc Dionne [email protected]
--
2.37.1

I've already told this Miguel in private, but I did like to join as reviewer:

R: Björn Roy Baron <[email protected]>

Cheers,
Bjorn

#52 lore raw

Re: [PATCH v8 28/31] samples: add Rust examples

Quoted 10 lines · Miguel Ojeda

«Внимание! Данное письмо от внешнего адресата!»

Quoted 3 lines · Konstantin Shelekhin

A minor neat, but ain't it possible to use &str here in order to drop this ugly binary string prefix?

Yeah, we would like to remove those at some point -- please see
https://github.com/Rust-for-Linux/linux/issues/252.

Cool, thanks. I suggest it for the next patchset iteration, since it's already has a GH issue.

#53 lore raw

Re: [PATCH v8 28/31] samples: add Rust examples

Quoted 3 lines · Konstantin Shelekhin

Cool, thanks. I suggest it for the next patchset iteration, since it's already has a GH issue.

Gary implemented a subset of string literals to cover this without having to vendor extra external code in
https://github.com/Rust-for-Linux/linux/pull/858:

    module! {
        type: RustNetfilter,
        name: "rust_netfilter",
        author: "Rust for Linux Contributors",
        description: "Rust netfilter sample",
        license: "GPL",
    }

It will be there in v10.

Cheers,
Miguel

maintainer Acked-by on v8 6/31
#9 lore raw

Re: [PATCH v8 06/31] workqueue: introduce `__INIT_WORK_WITH_KEY`

In reply to Miguel Ojeda
Quoted 9 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A Rust helper (introduced in a later patch) needs to call __INIT_WORK with a passed key, rather than define one in place.

In order to do that, this moves the initialization code from the __INIT_WORK macro into a new __INIT_WORK_WITH_KEY macro which takes the key as an extra parameter.

Quoted 5 lines

Please feel free to route the patch with the rest of the series or let me know if you want through the wq tree.

Thanks.

Signature · 1 line
tejun
#10 lore raw

Re: [PATCH v8 06/31] workqueue: introduce `__INIT_WORK_WITH_KEY`

Hi Tejun,

Quoted 5 lines · Tejun Heo

Please feel free to route the patch with the rest of the series or let me know if you want through the wq tree.

Since for v9 [1] I had to trim the patch series, this patch is not in the series anymore, so I think this one should ideally go through the wq tree later on when we send it together with the Rust abstractions for it after the core support is merged.

Thanks a lot!

[1] https://lore.kernel.org/lkml/[email protected]/

Cheers,
Miguel

#39 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

In reply to Miguel Ojeda
Quoted 6 lines · Miguel Ojeda
Makefile +5 -0
+# These flags apply to all Rust code in the tree, including the kernel and
+# host programs.
+export rust_common_flags := --edition=2021 \
+                           -Zbinary_dep_depinfo=y \
+                           -Dunsafe_op_in_unsafe_fn -Drust_2018_idioms \

Makefile KBUILD_USERHOSTCFLAGS := -Wall -Wmissing-prototypes -Wstrict-prototypes \ · line 471

Quoted 10 lines
Makefile +10 -0
+                           -Dunreachable_pub -Dnon_ascii_idents \
+                           -Wmissing_docs \
+                           -Drustdoc::missing_crate_level_docs \
+                           -Dclippy::correctness -Dclippy::style \
+                           -Dclippy::suspicious -Dclippy::complexity \
+                           -Dclippy::perf \
+                           -Dclippy::let_unit_value -Dclippy::mut_mut \
+                           -Dclippy::needless_bitwise_bool \
+                           -Dclippy::needless_continue \
+                           -Wclippy::dbg_macro

Hi Miguel,

I tried enabling rust support in the gcc builds I provide at
https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/arm64/12.1.0/
to make this more accessible, but it appears that the command line options here are not portable:

/home/arnd/cross/x86_64/gcc-12.1.0+rust-nolibc/x86_64-linux/bin/x86_64-linux-gccrs
--edition=2021 -Zbinary_dep_depinfo=y -Dunsafe_op_in_unsafe_fn -Drust_2018_idioms -Dunreachable_pub -Dnon_ascii_idents -Wmissing_docs -Drustdoc::missing_crate_level_docs -Dclippy::correctness -Dclippy::style -Dclippy::suspicious -Dclippy::complexity -Dclippy::perf -Dclippy::let_unit_value -Dclippy::mut_mut -Dclippy::needless_bitwise_bool -Dclippy::needless_continue -Wclippy::dbg_macro -O -Cstrip=debuginfo -Zallow-features= --emit=dep-info,link --out-dir=scripts/ /git/arm-soc/scripts/generate_rust_target.rs; mv scripts/generate_rust_target.d scripts/.generate_rust_target.d; sed -i '/^#/d' scripts/.generate_rust_target.d
x86_64-linux-gccrs: error: unrecognized command-line option '--edition=2021'; did you mean '-frust-edition=2021'?
x86_64-linux-gccrs: error: unrecognized command-line option '-Zbinary_dep_depinfo=y'
x86_64-linux-gccrs: error: unrecognized command-line option '-Wmissing_docs'; did you mean '-Wmissing-braces'?
x86_64-linux-gccrs: error: unrecognized command-line option '-Wclippy::dbg_macro'
x86_64-linux-gccrs: error: unrecognized command-line option '-Cstrip=debuginfo'
x86_64-linux-gccrs: error: unrecognized command-line option '-Zallow-features='
x86_64-linux-gccrs: error: unrecognized command-line option '--emit=dep-info,link'
x86_64-linux-gccrs: error: unrecognized command-line option '--out-dir=scripts/' make[3]: *** [/git/arm-soc/scripts/Makefile.host:157:
scripts/generate_rust_target] Error 1

I guess nobody has tried this so far. Would you think that fixing this is only a matter for fixing the build system to pass the correct flags depending on the compiler, or is this broken in a more fundamental way?

Arnd

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#40 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

Hi Arnd,

Quoted 5 lines · Arnd Bergmann

Hi Miguel,

I tried enabling rust support in the gcc builds I provide at
https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/arm64/12.1.0/

Thanks for giving it a go!

Quoted 4 lines

to make this more accessible, but it appears that the command line options here are not portable:

/home/arnd/cross/x86_64/gcc-12.1.0+rust-nolibc/x86_64-linux/bin/x86_64-linux-gccrs

So you mean with GCC Rust, right? (i.e. we have "GCC builds" working, via compiling the Rust side with LLVM and linking with the GCC C side, but it is not intended for production or to be supported, even if we cover it in our CI, test it boots and loads modules etc.).

Indeed, gccrs does not support rustc flags yet. I am not sure if the GCC Rust team will eventually provide a driver for those like clang does for e.g. cl -- I would hope they do, since many projects would benefit from it, but maybe they plan to start simply by modifying Cargo to call them as they need instead.

If they don't support it, we will have to map the flags on our side -- it should not be a big problem. However, see below...

Quoted 3 lines

I guess nobody has tried this so far. Would you think that fixing this is only a matter for fixing the build system to pass the correct flags depending on the compiler, or is this broken in a more fundamental way?

If you meant GCC Rust, then it is a bit too early for the compiler. As far as I now, they are working on compiling the core crate and supporting more stable language features. They are also researching the integration of the borrow checker, though we wouldn't need that for "only" compiling the kernel.

Now, if they decided to focus on supporting Rust for Linux early on (which would be great), they would still need to work on the delta between what what they target now and what we use (which includes both stable and some unstable features), plus I assume infrastructure bits like the platform (target spec) support, the flags / rustc driver (though I would be happy to do as much as possible on our side to help), etc.

(We privately talked about possible timelines for all that if they were to focus on Rust for Linux etc., but I let them comment or not on that... Cc'ing them! :)

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#41 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

Quoted 10 lines · Miguel Ojeda
Quoted 3 lines · Arnd Bergmann

I tried enabling rust support in the gcc builds I provide at
https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/arm64/12.1.0/

Thanks for giving it a go!

Quoted 3 lines

to make this more accessible, but it appears that the command line options here are not portable:

Quoted 6 lines
Quoted 1 line

/home/arnd/cross/x86_64/gcc-12.1.0+rust-nolibc/x86_64-linux/bin/x86_64-linux-gccrs

So you mean with GCC Rust, right? (i.e. we have "GCC builds" working, via compiling the Rust side with LLVM and linking with the GCC C side, but it is not intended for production or to be supported, even if we cover it in our CI, test it boots and loads modules etc.).

Yes, I meant GCC rust, with the contents of
https://gcc.gnu.org/git/?p=gcc.git;a=shortlog;h=refs/heads/devel/rust/master
merged into the gcc-12.1.0 release tag.

Quoted 18 lines
Quoted 3 lines

I guess nobody has tried this so far. Would you think that fixing this is only a matter for fixing the build system to pass the correct flags depending on the compiler, or is this broken in a more fundamental way?

If you meant GCC Rust, then it is a bit too early for the compiler. As far as I now, they are working on compiling the core crate and supporting more stable language features. They are also researching the integration of the borrow checker, though we wouldn't need that for "only" compiling the kernel.

Now, if they decided to focus on supporting Rust for Linux early on (which would be great), they would still need to work on the delta between what what they target now and what we use (which includes both stable and some unstable features), plus I assume infrastructure bits like the platform (target spec) support, the flags / rustc driver (though I would be happy to do as much as possible on our side to help), etc.

Quoted 3 lines

(We privately talked about possible timelines for all that if they were to focus on Rust for Linux etc., but I let them comment or not on that... Cc'ing them! :)

Thanks for the explanation. My hope was that building the kernel would actually be easier here than building the more complicated rust user space.

The gcc cross-compilers on kernel.org are similarly easy to build for all architectures the kernel supports because the complexity is usually in picking a working libc for the more obscure architectures, so I was naively thinking that this would work for building the rust support across all architectures in Linux.

I tried one more step and just removed the unsupported command line flags to see what would happen, but that did not get me any further:

/home/arnd/cross/x86_64/gcc-12.1.0+rust-nolibc/x86_64-linux/bin/x86_64-linux-gccrs -frust-edition=2021 -Dunsafe_op_in_unsafe_fn -Drust_2018_idioms -Dunreachable_pub -Dnon_ascii_idents -Drustdoc::missing_crate_level_docs -Dclippy::correctness -Dclippy::style -Dclippy::suspicious -Dclippy::complexity -Dclippy::perf -Dclippy::let_unit_value -Dclippy::mut_mut -Dclippy::needless_bitwise_bool -Dclippy::needless_continue -O /git/arm-soc/scripts/generate_rust_target.rs; mv scripts/generate_rust_target.d scripts/.generate_rust_target.d; sed -i '/^#/d' scripts/.generate_rust_target.d
rust1: internal compiler error: Segmentation fault
0x7f37ee04b51f ??? ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0 0x7f37ee032fcf __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
0x7f37ee03307c __libc_start_main_impl
../csu/libc-start.c:409
Please submit a full bug report, with preprocessed source (by using -freport-bug).
Please include the complete backtrace with any bug report.
See <https://gcc.gnu.org/bugs/> for instructions.

Arnd

#43 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

In reply to Miguel Ojeda
Quoted 23 lines · Miguel Ojeda

Hi Arnd,

Quoted 4 lines · On Wed, Aug 17, 2022 at 4:40 PM Arnd Bergmann [email protected] wrote:

Hi Miguel,

I tried enabling rust support in the gcc builds I provide at
https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/arm64/12.1.0/

Thanks for giving it a go!

Quoted 4 lines

to make this more accessible, but it appears that the command line options here are not portable:

/home/arnd/cross/x86_64/gcc-12.1.0+rust-nolibc/x86_64-linux/bin/x86_64-linux-gccrs

So you mean with GCC Rust, right? (i.e. we have "GCC builds" working, via compiling the Rust side with LLVM and linking with the GCC C side, but it is not intended for production or to be supported, even if we cover it in our CI, test it boots and loads modules etc.).

Quoted 5 lines

Indeed, gccrs does not support rustc flags yet. I am not sure if the GCC Rust team will eventually provide a driver for those like clang does for e.g. cl -- I would hope they do, since many projects would benefit from it, but maybe they plan to start simply by modifying Cargo to call them as they need instead.

There is already a prototype of such a driver. It can be found at https://github.com/Rust-GCC/cargo-gccrs. Unlike what the name suggests it is not cargo specific. It consists of two binaries. The first calls cargo, but tells it to use the second binary instead of a real rustc. This second part then translates all arguments to what gccrs expects. It is possible to directly invoke this second binary. For now it probably won't work for rust-for-linux though as it doesn't have all arguments that are used by rust-for-linux implemented.

Quoted 23 lines

If they don't support it, we will have to map the flags on our side -- it should not be a big problem. However, see below...

Quoted 3 lines

I guess nobody has tried this so far. Would you think that fixing this is only a matter for fixing the build system to pass the correct flags depending on the compiler, or is this broken in a more fundamental way?

If you meant GCC Rust, then it is a bit too early for the compiler. As far as I now, they are working on compiling the core crate and supporting more stable language features. They are also researching the integration of the borrow checker, though we wouldn't need that for "only" compiling the kernel.

Now, if they decided to focus on supporting Rust for Linux early on (which would be great), they would still need to work on the delta between what what they target now and what we use (which includes both stable and some unstable features), plus I assume infrastructure bits like the platform (target spec) support, the flags / rustc driver (though I would be happy to do as much as possible on our side to help), etc.

Quoted 6 lines

(We privately talked about possible timelines for all that if they were to focus on Rust for Linux etc., but I let them comment or not on that... Cc'ing them! :)

Cheers,
Miguel

As alternative to GCC Rust there is also github.com/rust-lang/rustc_codegen_gcc/ which uses libgccjit as backend for the official rust compiler rather than writing a full Rust frontend for GCC from scratch. With a bit of patching to force it to be used, I was able to compile all Rust samples with GCC using rustc_codegen_gcc. However it gives warnings of the following kind:

ld.lld: warning: rust/built-in.a(core.o):(.data.rel.local) is being placed in '.data.rel.local'

And hangs very early in the boot process. If I enable early logging, it prints up to "Booting the kernel." and then does nothing. This is probably because support for setting a different relocation model is not yet implemented. I opened https://github.com/rust-lang/rustc_codegen_gcc/issues/205 for this.

There may be other issues, but rustc_codegen_gcc is probably going to be the easiest route towards a LLVM free rust-for-linux build. By the way note that rust-bindgen which we use for generating rust bindings from C headers depends on LLVM. See https://github.com/rust-lang/rust-bindgen/issues/1949.

Cheers,
Bjorn

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#44 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

Quoted 2 lines · Björn Roy Baron

There is already a prototype of such a driver. It can be found at https://github.com/Rust-GCC/cargo-gccrs. Unlike what the name suggests it is not cargo specific. It consists of two binaries. The first calls cargo, but tells it to use the second binary instead of a real rustc. This second part then translates all arguments to what gccrs expects. It is possible to directly invoke this second binary. For now it probably won't work for rust-for-linux though as it doesn't have all arguments that are used by rust-for-linux implemented.

I spoke with them about this a few weeks ago, but I thought it was best to leave it up to the GCC Rust folks to detail how they will proceed if they already know.

Quoted 5 lines

As alternative to GCC Rust there is also github.com/rust-lang/rustc_codegen_gcc/ which uses libgccjit as backend for the official rust compiler rather than writing a full Rust frontend for GCC from scratch. With a bit of patching to force it to be used, I was able to compile all Rust samples with GCC using rustc_codegen_gcc. However it gives warnings of the following kind:

ld.lld: warning: rust/built-in.a(core.o):(.data.rel.local) is being placed in '.data.rel.local'

And hangs very early in the boot process. If I enable early logging, it prints up to "Booting the kernel." and then does nothing. This is probably because support for setting a different relocation model is not yet implemented. I opened https://github.com/rust-lang/rustc_codegen_gcc/issues/205 for this.

Thanks Björn for giving it a go!

Arnd maintains a set of cross-GCC binaries for kernel developers, so I assumed he was mainly interested in including GCC Rust there -- I didn't mean to leave rustc_codegen_gcc aside! :) In fact, a few weeks ago I also spoke with Antoni (Cc'd too!) about whether he would be interested in getting it to work with Rust for Linux soon, whether and how we could help him, etc.

In any case, both GCC Rust and rustc_codegen_gcc will be present in Kangrejos and LPC (Rust MC), so hopefully we will discuss the details face-to-face!

Quoted 1 line

There may be other issues, but rustc_codegen_gcc is probably going to be the easiest route towards a LLVM free rust-for-linux build. By the way note that rust-bindgen which we use for generating rust bindings from C headers depends on LLVM. See https://github.com/rust-lang/rust-bindgen/issues/1949.

Yeah, rustc_codegen_gcc is possibly going to happen sooner than GCC Rust for the kernel.

As for bindgen, it is indeed a pain point. There are several possibilities we have been considering (GCC backend in bindgen, an equivalent tool in GCC, something based on other parsers, something else entirely, "just checking the results" approaches, even convincing upstream Rust that C header support would be amazing for Rust uptake... ;-). Ideally we would get funding to have somebody working on the problem, but we will see.

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#42 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

In reply to Arnd Bergmann
Quoted 2 lines · Arnd Bergmann

Thanks for the explanation. My hope was that building the kernel

Don't mention it!

Quoted 2 lines

would actually be easier here than building the more complicated rust user space.

Yeah, the kernel is complicated for them in different ways, so I assume they will decide which bits to tackle first... Hopefully I will succeed in my attempts to convince them to focus a bit on the kernel at least ;)

Quoted 3 lines

I tried one more step and just removed the unsupported command line flags to see what would happen, but that did not get me any further:

Thanks!

It looks like it failed when compiling the target spec generator, which is a Rust host program. If they were to attempt the GCC Rust support early on, we could make things easier for them by not compiling host programs with gccrs.

By the way, feel free to remove all the -D flags ("denying") when playing with it since they are related to diagnostics (making lints errors that can still be bypassed if needed), in case the crash is about handling those.

Cheers,
Miguel

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#45 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

In reply to Miguel Ojeda
Quoted 130 lines · Miguel Ojeda

Having all the new files in place, we now enable Rust support in the build system, including Kconfig entries related to Rust, the Rust configuration printer, the target specification generation script, the version detection script and a few other bits.

---
 .gitignore                                   |   6 +
 .rustfmt.toml                                |  12 +
 Makefile                                     | 172 +++++++-
 arch/Kconfig                                 |   6 +
 arch/arm/Kconfig                             |   1 +
 arch/arm64/Kconfig                           |   1 +
 arch/powerpc/Kconfig                         |   1 +
 arch/riscv/Kconfig                           |   1 +
 arch/riscv/Makefile                          |   5 +
 arch/um/Kconfig                              |   1 +
 arch/x86/Kconfig                             |   1 +
 arch/x86/Makefile                            |  10 +
 include/linux/compiler_types.h               |   6 +-
 init/Kconfig                                 |  46 +-
 lib/Kconfig.debug                            |  82 ++++
 rust/.gitignore                              |  10 +
 rust/Makefile                                | 415 +++++++++++++++++++
 rust/bindgen_parameters                      |  21 +
 scripts/.gitignore                           |   1 +
 scripts/Kconfig.include                      |   6 +-
 scripts/Makefile                             |   3 +
 scripts/Makefile.build                       |  60 +++
 scripts/Makefile.debug                       |  10 +
 scripts/Makefile.host                        |  34 +-
 scripts/Makefile.lib                         |  12 +
 scripts/Makefile.modfinal                    |   8 +-
 scripts/cc-version.sh                        |  12 +-
 scripts/generate_rust_target.rs              | 232 +++++++++++
 scripts/is_rust_module.sh                    |  16 +
 scripts/kconfig/confdata.c                   |  75 ++++
 scripts/min-tool-version.sh                  |   6 +
 scripts/rust-is-available-bindgen-libclang.h |   2 +
 scripts/rust-is-available.sh                 | 160 +++++++
 33 files changed, 1408 insertions(+), 26 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Makefile
 create mode 100644 rust/bindgen_parameters
 create mode 100644 scripts/generate_rust_target.rs
 create mode 100755 scripts/is_rust_module.sh
 create mode 100644 scripts/rust-is-available-bindgen-libclang.h
 create mode 100755 scripts/rust-is-available.sh
init/Kconfig +24 -1
@@ -151,7 +162,8 @@ config WERROR
        default COMPILE_TEST
        help
          A kernel build should not cause any compiler warnings, and this
-         enables the '-Werror' flag to enforce that rule by default.
+         enables the '-Werror' (for C) and '-Dwarnings' (for Rust) flags
+         to enforce that rule by default.
 
          However, if you have a new (or very old) compiler with odd and
          unusual warnings, or you have some architecture with problems,
@@ -1898,6 +1910,38 @@ config PROFILING
          Say Y here to enable the extended profiling support mechanisms used
          by profilers.
 
+config RUST
+       bool "Rust support"
+       depends on HAVE_RUST
+       depends on RUST_IS_AVAILABLE
+       depends on !MODVERSIONS
+       depends on !GCC_PLUGINS
+       depends on !RANDSTRUCT
+       depends on !DEBUG_INFO_BTF
+       select CONSTRUCTORS
+       help
+         Enables Rust support in the kernel.
+
+         This allows other Rust-related options, like drivers written in Rust,
+         to be selected.
+
+         It is also required to be able to load external kernel modules
+         written in Rust.
+
+         See Documentation/rust/ for more information.
+
+         If unsure, say N.
+

init/Kconfig config PROFILING · line 1944

Quoted 10 lines
init/Kconfig +10 -0
+config RUSTC_VERSION_TEXT
+       string
+       depends on RUST
+       default $(shell,command -v $(RUSTC) >/dev/null 2>&1 && $(RUSTC) --version || echo n)
+
+config BINDGEN_VERSION_TEXT
+       string
+       depends on RUST
+       default $(shell,command -v $(BINDGEN) >/dev/null 2>&1 && $(BINDGEN) --version || echo n)
+

Where are these config options used?

I grep'ed but no hit.

masahiro@zoe:~/ref/linux-next$ git grep RUSTC_VERSION_TEXT
init/Kconfig:config RUSTC_VERSION_TEXT
masahiro@zoe:~/ref/linux-next$ git grep BINDGEN_VERSION_TEXT
init/Kconfig:config BINDGEN_VERSION_TEXT
Quoted 3 lines
(quoted diff) +0 -1
--

2.37.1

--
Best Regards
Masahiro Yamada

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um

#46 lore raw

Re: [PATCH v8 27/31] Kbuild: add Rust support

Quoted 7 lines · Masahiro Yamada
Quoted 6 lines · Miguel Ojeda

Having all the new files in place, we now enable Rust support in the build system, including Kconfig entries related to Rust, the Rust configuration printer, the target specification generation script, the version detection script and a few other bits.

...

Quoted 14 lines

init/Kconfig config PROFILING · line 1944

Quoted 11 lines
init/Kconfig +11 -0
+
+config RUSTC_VERSION_TEXT
+       string
+       depends on RUST
+       default $(shell,command -v $(RUSTC) >/dev/null 2>&1 && $(RUSTC) --version || echo n)
+
+config BINDGEN_VERSION_TEXT
+       string
+       depends on RUST
+       default $(shell,command -v $(BINDGEN) >/dev/null 2>&1 && $(BINDGEN) --version || echo n)
+

Where are these config options used?

Quoted 6 lines

I grep'ed but no hit.

masahiro@zoe:~/ref/linux-next$ git grep RUSTC_VERSION_TEXT
init/Kconfig:config RUSTC_VERSION_TEXT
masahiro@zoe:~/ref/linux-next$ git grep BINDGEN_VERSION_TEXT
init/Kconfig:config BINDGEN_VERSION_TEXT

That came up before in a review by Nick:

Quoted 6 lines · Miguel
Quoted 1 line · Nick

Are these two kconfigs used anywhere?

Not for the moment, but it could still be useful when getting .config reports (and we could add it to LINUX_COMPILER etc. in the future).

https://lore.kernel.org/all/CANiq72n2bU3LSGu-4v66nif_95EVq--z2X_F2V7JBPU8v=h8EA@mail.gmail.com/

cheers

_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um