Skip to contentSkip to conversation

Rust support

PATCH Superseded Miguel Ojeda 7 participants 42 messages Dec 6, 2021 – Jan 17, 2022

Subsystems (26)

v1 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Miguel Ojeda

author maintainer
#0 lore raw

cover Rust support

Rust support

This is the patch series (v2) 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 v1, plus a few extra notes and news. For the previous cover letters, please see:

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

## Infrastructure updates

There have been several improvements to the overall Rust support. The following sections cover some of these.

### Stable compiler & Rust Edition 2021

We moved from the beta Rust compiler to using stable releases, migrating each time a new one gets released. Currently we just moved to Rust 1.57.0, released last Thursday.

By upgrading the compiler, we have been able to take off the list a few unstable features we were using: const_fn_transmute, const_panic, const_unreachable_unchecked, core_panic and try_reserve. For an up-to-date list on the features and other wishlists we have, please see:

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

We will keep upgrading until we do not rely on any unstable features; at which point we may want to start declaring a minimum Rust version is supported, like it is done for e.g. GCC and Clang.

Similarly, we also migrated to the 2021 edition of the Rust language.

### Customizing core and alloc

We added a couple more "modularization" options to alloc in order to disable some features we do not need: no_rc and no_sync.

We would like to thank upstream Rust for working with us on upstreaming these so that the kernel use case is well supported (or, more precisely, the "combination" of options the kernel needs).

Upstream core has added no_fp_fmt_parse too, which we are using.

### Stricter code, docs and new lints

Following the CONFIG_WERROR discussions, we are trying to do our bit by making the option apply to Rust code and having our CI build with it enabled.

We also enabled a bunch of extra Rust compiler diagnostics and Clippy lints. We may need to disable some of them in the future if they prove too noisy or disruptive, but we think this is the best time to try them out. For instance, one of them checks that no unreachable public items are present.

One difference with respect to C here is that Rust diagnostics are slightly more natural to disable within code, which we may allow us to be more strict in the general case.

## Abstractions and driver updates

We added abstractions for sequence locks, power management callbacks, io memory (readX/writeX), irq chips & high-level flow handlers, gpio chips (including irq ones), devices, amba devices & drivers and credentials.

There is improved driver support with bus-independent infrastructure, revocable objects, revocable mutexes, efficient bit iterators, better panic diagnostics and simplified pointer wrappers.

In addition, we improved and simplified Ref (refcount_t-backed) objects and replaced all instances of Rust's Arc by it. Completely removed Arc and Rc from the alloc crate.

A new driver for PL061 gpio devices was implemented and is submitted as an RFC patch.

## Patch series status

Like we mentioned last time, 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 has just arrived in linux-next, thus the first run will happen in a day. Similarly, the preview docs for this series can be seen at:

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

From now on, we will also start submitting the patches regularly, every two weeks or so.

## Industry and academia support

In addition to the statements from Arm, Google and Microsoft from the previous cover letter, we have one from Red Hat this time:

There is interest in using Rust for kernel work that Red Hat is considering.

## Conferences, meetings and liaisons

Kangrejos, the Rust for Linux conference we announced last time, took place before LPC (made possible by Jonathan Corbet et. al. and LPC's infrastructure). Thanks everyone that joined!

https://kangrejos.com

We would also want to thank you the venues we were invited to:

- Linaro Virtual Connect 2021 Fall
- Clang Built Linux Meetup II turbo
- Linux Plumbers Conference 2021 (quite a few Rust-related talks from us and others as well!)
- Samsung Engineering Summit 2021
- Linux Foundation Live Mentorship Series

There will also be a talk in the Open Source Summit Japan this month.

We also want to thank Niko Matsakis and the Rust CTCFT (Cross Team Collaboration Fun Times) team for inviting us to present our work and our needs from Rust.

## Other related news

### rustc_codegen_gcc merged

The GCC backend for the Rust compiler (through libgccjit, although used for ahead-of-time compilation) was merged into upstream Rust:

https://github.com/rust-lang/rustc_codegen_gcc

If the backend keeps progressing, we hope to soon be able to start experimenting with compiling the Rust side of the kernel with GCC!

### Compiler Explorer improvements

This useful online tool added support for rustc_codegen_gcc. Together with GCC Rust and mrustc, the site now supports all the alternative Rust compilers. See a live example at:

    https://godbolt.org/z/6br9Ef73E

They are also adding further options for Rust we requested, e.g. MIR and macro expansion views are already live on the site.

## 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 v1:

- bjorn3 and Gary Guo for all the input on Rust compiler details and all the reviews and suggestions.

- Jonathan Corbet and the LPC organizers for lending us the Linux Plumbers Conference infrastructure so that we could have an easy time setting up Kangrejos.

- Josh Triplett for reviewing the Rust CTCFT presentation.

- Robin Randhawa for reviewing the Linaro Connect presentation.

- Viresh Kumar for his work on adding Rust bindings to libgpiod.

- Philip Herrons (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.

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

- All the Rust and LLVM contributors taking a look into codegen and other issues we have raised.

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

Please also see the acknowledgements on the previous cover letters.

Boqun Feng (1):
kallsyms: use the correct buffer size for symbols

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

Miguel Ojeda (13):
kallsyms: support "big" kernel symbols
kallsyms: increase maximum kernel symbol length to 512
rust: add C helpers
rust: add compiler_builtins crate
rust: add alloc crate
rust: add macros crate
rust: export generated symbols
scripts: add generate_rust_analyzer.py
scripts: decode_stacktrace: demangle Rust symbols
docs: add Rust documentation
Kbuild: add Rust support
samples: add Rust examples
MAINTAINERS: Rust

Wedson Almeida Filho (3):
rust: add kernel crate
[RFC] drivers: gpio: PrimeCell PL061 in Rust
[RFC] drivers: android: Binder IPC in Rust

 .gitignore                                  |    5 +
 .rustfmt.toml                               |   12 +
 Documentation/doc-guide/kernel-doc.rst      |    3 +
 Documentation/index.rst                     |    1 +
 Documentation/kbuild/kbuild.rst             |    4 +
 Documentation/process/changes.rst           |   13 +
 Documentation/rust/arch-support.rst         |   35 +
 Documentation/rust/assets/favicon-16x16.png |  Bin 0 -> 798 bytes
 Documentation/rust/assets/favicon-32x32.png |  Bin 0 -> 2076 bytes
 Documentation/rust/assets/rust-logo.png     |  Bin 0 -> 53976 bytes
 Documentation/rust/coding.rst               |   91 +
 Documentation/rust/docs.rst                 |  101 +
 Documentation/rust/index.rst                |   21 +
 Documentation/rust/quick-start.rst          |  212 ++
 MAINTAINERS                                 |   14 +
 Makefile                                    |  146 +-
 arch/arm/rust/target.json                   |   27 +
 arch/arm64/rust/target.json                 |   34 +
 arch/powerpc/rust/target.json               |   29 +
 arch/riscv/Makefile                         |    1 +
 arch/riscv/rust/rv32ima.json                |   36 +
 arch/riscv/rust/rv32imac.json               |   36 +
 arch/riscv/rust/rv64ima.json                |   36 +
 arch/riscv/rust/rv64imac.json               |   36 +
 arch/x86/rust/target.json                   |   36 +
 drivers/android/Kconfig                     |    7 +
 drivers/android/Makefile                    |    2 +
 drivers/android/allocation.rs               |  266 ++
 drivers/android/context.rs                  |   79 +
 drivers/android/defs.rs                     |   99 +
 drivers/android/node.rs                     |  476 +++
 drivers/android/process.rs                  |  964 ++++++
 drivers/android/range_alloc.rs              |  189 ++
 drivers/android/rust_binder.rs              |  114 +
 drivers/android/thread.rs                   |  871 +++++
 drivers/android/transaction.rs              |  326 ++
 drivers/gpio/Kconfig                        |    8 +
 drivers/gpio/Makefile                       |    1 +
 drivers/gpio/gpio_pl061_rust.rs             |  362 ++
 include/linux/kallsyms.h                    |    2 +-
 include/linux/spinlock.h                    |   17 +-
 include/uapi/linux/android/binder.h         |   28 +-
 init/Kconfig                                |   31 +-
 kernel/kallsyms.c                           |   26 +-
 kernel/livepatch/core.c                     |    4 +-
 kernel/printk/printk.c                      |    5 +-
 lib/Kconfig.debug                           |  144 +
 lib/vsprintf.c                              |   12 +
 rust/.gitignore                             |    7 +
 rust/Makefile                               |  353 ++
 rust/alloc/README.md                        |   32 +
 rust/alloc/alloc.rs                         |  424 +++
 rust/alloc/borrow.rs                        |  498 +++
 rust/alloc/boxed.rs                         | 1844 ++++++++++
 rust/alloc/collections/mod.rs               |  155 +
 rust/alloc/fmt.rs                           |  583 ++++
 rust/alloc/lib.rs                           |  212 ++
 rust/alloc/macros.rs                        |  126 +
 rust/alloc/raw_vec.rs                       |  612 ++++
 rust/alloc/slice.rs                         | 1275 +++++++
 rust/alloc/str.rs                           |  621 ++++
 rust/alloc/string.rs                        | 2857 ++++++++++++++++
 rust/alloc/vec/drain.rs                     |  158 +
 rust/alloc/vec/drain_filter.rs              |  145 +
 rust/alloc/vec/into_iter.rs                 |  356 ++
 rust/alloc/vec/is_zero.rs                   |  106 +
 rust/alloc/vec/mod.rs                       | 3327 +++++++++++++++++++
 rust/alloc/vec/partial_eq.rs                |   49 +
 rust/alloc/vec/set_len_on_drop.rs           |   30 +
 rust/alloc/vec/spec_extend.rs               |  172 +
 rust/bindgen_parameters                     |   13 +
 rust/build_error.rs                         |   29 +
 rust/compiler_builtins.rs                   |   57 +
 rust/exports.c                              |   16 +
 rust/helpers.c                              |  436 +++
 rust/kernel/allocator.rs                    |   65 +
 rust/kernel/amba.rs                         |  276 ++
 rust/kernel/bindings.rs                     |   47 +
 rust/kernel/bindings_helper.h               |   30 +
 rust/kernel/buffer.rs                       |   52 +
 rust/kernel/build_assert.rs                 |   80 +
 rust/kernel/c_types.rs                      |  119 +
 rust/kernel/chrdev.rs                       |  212 ++
 rust/kernel/cred.rs                         |   73 +
 rust/kernel/device.rs                       |  206 ++
 rust/kernel/driver.rs                       |  198 ++
 rust/kernel/error.rs                        |  542 +++
 rust/kernel/file.rs                         |  141 +
 rust/kernel/file_operations.rs              |  723 ++++
 rust/kernel/gpio.rs                         |  475 +++
 rust/kernel/io_buffer.rs                    |  153 +
 rust/kernel/io_mem.rs                       |  207 ++
 rust/kernel/iov_iter.rs                     |   81 +
 rust/kernel/irq.rs                          |  408 +++
 rust/kernel/lib.rs                          |  256 ++
 rust/kernel/linked_list.rs                  |  247 ++
 rust/kernel/miscdev.rs                      |  166 +
 rust/kernel/module_param.rs                 |  497 +++
 rust/kernel/of.rs                           |  101 +
 rust/kernel/pages.rs                        |  162 +
 rust/kernel/platdev.rs                      |  152 +
 rust/kernel/power.rs                        |  118 +
 rust/kernel/prelude.rs                      |   33 +
 rust/kernel/print.rs                        |  441 +++
 rust/kernel/random.rs                       |   50 +
 rust/kernel/raw_list.rs                     |  361 ++
 rust/kernel/rbtree.rs                       |  562 ++++
 rust/kernel/revocable.rs                    |  163 +
 rust/kernel/security.rs                     |   36 +
 rust/kernel/static_assert.rs                |   39 +
 rust/kernel/std_vendor.rs                   |  150 +
 rust/kernel/str.rs                          |  375 +++
 rust/kernel/sync/arc.rs                     |  500 +++
 rust/kernel/sync/condvar.rs                 |  137 +
 rust/kernel/sync/guard.rs                   |  181 +
 rust/kernel/sync/locked_by.rs               |  112 +
 rust/kernel/sync/mod.rs                     |   92 +
 rust/kernel/sync/mutex.rs                   |  111 +
 rust/kernel/sync/revocable_mutex.rs         |  184 +
 rust/kernel/sync/seqlock.rs                 |  201 ++
 rust/kernel/sync/spinlock.rs                |  180 +
 rust/kernel/sysctl.rs                       |  197 ++
 rust/kernel/task.rs                         |  182 +
 rust/kernel/types.rs                        |  486 +++
 rust/kernel/user_ptr.rs                     |  175 +
 rust/macros/helpers.rs                      |   79 +
 rust/macros/lib.rs                          |   94 +
 rust/macros/module.rs                       |  622 ++++
 samples/Kconfig                             |    2 +
 samples/Makefile                            |    1 +
 samples/rust/Kconfig                        |  113 +
 samples/rust/Makefile                       |   12 +
 samples/rust/rust_chrdev.rs                 |   50 +
 samples/rust/rust_minimal.rs                |   38 +
 samples/rust/rust_miscdev.rs                |  149 +
 samples/rust/rust_module_parameters.rs      |   72 +
 samples/rust/rust_print.rs                  |   57 +
 samples/rust/rust_random.rs                 |   61 +
 samples/rust/rust_semaphore.rs              |  174 +
 samples/rust/rust_semaphore_c.c             |  212 ++
 samples/rust/rust_stack_probing.rs          |   40 +
 samples/rust/rust_sync.rs                   |   81 +
 scripts/Makefile.build                      |   22 +
 scripts/Makefile.debug                      |   10 +
 scripts/Makefile.lib                        |   12 +
 scripts/Makefile.modfinal                   |    8 +-
 scripts/decode_stacktrace.sh                |   14 +
 scripts/generate_rust_analyzer.py           |  133 +
 scripts/is_rust_module.sh                   |   19 +
 scripts/kallsyms.c                          |   40 +-
 scripts/kconfig/confdata.c                  |   75 +
 scripts/rust-version.sh                     |   31 +
 tools/include/linux/kallsyms.h              |    2 +-
 tools/include/linux/lockdep.h               |    2 +-
 tools/lib/perf/include/perf/event.h         |    2 +-
 tools/lib/symbol/kallsyms.h                 |    2 +-
 156 files changed, 32369 insertions(+), 50 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 Documentation/rust/arch-support.rst
 create mode 100644 Documentation/rust/assets/favicon-16x16.png
 create mode 100644 Documentation/rust/assets/favicon-32x32.png
 create mode 100644 Documentation/rust/assets/rust-logo.png
 create mode 100644 Documentation/rust/coding.rst
 create mode 100644 Documentation/rust/docs.rst
 create mode 100644 Documentation/rust/index.rst
 create mode 100644 Documentation/rust/quick-start.rst
 create mode 100644 arch/arm/rust/target.json
 create mode 100644 arch/arm64/rust/target.json
 create mode 100644 arch/powerpc/rust/target.json
 create mode 100644 arch/riscv/rust/rv32ima.json
 create mode 100644 arch/riscv/rust/rv32imac.json
 create mode 100644 arch/riscv/rust/rv64ima.json
 create mode 100644 arch/riscv/rust/rv64imac.json
 create mode 100644 arch/x86/rust/target.json
 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 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/collections/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/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/bindings.rs
 create mode 100644 rust/kernel/bindings_helper.h
 create mode 100644 rust/kernel/buffer.rs
 create mode 100644 rust/kernel/build_assert.rs
 create mode 100644 rust/kernel/c_types.rs
 create mode 100644 rust/kernel/chrdev.rs
 create mode 100644 rust/kernel/cred.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/file_operations.rs
 create mode 100644 rust/kernel/gpio.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/lib.rs
 create mode 100644 rust/kernel/linked_list.rs
 create mode 100644 rust/kernel/miscdev.rs
 create mode 100644 rust/kernel/module_param.rs
 create mode 100644 rust/kernel/of.rs
 create mode 100644 rust/kernel/pages.rs
 create mode 100644 rust/kernel/platdev.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/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/mod.rs
 create mode 100644 rust/kernel/sync/mutex.rs
 create mode 100644 rust/kernel/sync/revocable_mutex.rs
 create mode 100644 rust/kernel/sync/seqlock.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/user_ptr.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 samples/rust/Kconfig
 create mode 100644 samples/rust/Makefile
 create mode 100644 samples/rust/rust_chrdev.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_print.rs
 create mode 100644 samples/rust/rust_random.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 100755 scripts/is_rust_module.sh
 create mode 100755 scripts/rust-version.sh
Signature · 1 line
2.34.0
author maintainer
#1 lore raw

PATCH 1/19 kallsyms: support "big" kernel symbols

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, and therefore we need to 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), we 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 3011bc33a5ba..80702273494a 100644
@@ -69,12 +69,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
@@ -127,7 +135,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,
@@ -141,8 +149,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 54ad86d13784..79b11bb7f07d 100644
@@ -470,12 +470,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.34.0
#2 lore raw

Re: [PATCH 01/19] kallsyms: support "big" kernel symbols

Quoted 10 lines · 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, and therefore we need to 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), we use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.

Quoted 8 lines

Who are all these people, who didn't actually do any of this implementation, and where am I who did?

Quoted 108 lines
---
 kernel/kallsyms.c  | 26 ++++++++++++++++++++++----
 scripts/kallsyms.c | 29 ++++++++++++++++++++++++++---
 2 files changed, 48 insertions(+), 7 deletions(-)
kernel/kallsyms.c +22 -4
index 3011bc33a5ba..80702273494a 100644
@@ -69,12 +69,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
@@ -127,7 +135,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,
@@ -141,8 +149,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 54ad86d13784..79b11bb7f07d 100644
@@ -470,12 +470,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.34.0
#3 lore raw

Re: [PATCH 01/19] kallsyms: support "big" kernel symbols

Quoted 3 lines · Matthew Wilcox

Who are all these people, who didn't actually do any of this implementation, and where am I who did?

In the list you said you were going to send the changes you had as a patch, but I didn't see it, did you send it? I also sent you a private email about it and never got a reply. Then Gary ended up sending the ULEB128 later on, so I picked that one up.

But, yeah, the patch should have had a Suggested-by at least. I will add you as a Co-developed-by -- no need to overreact! ;)

Cheers,
Miguel

author maintainer
#4 lore raw

PATCH 2/19 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                  | 2 +-
 tools/include/linux/kallsyms.h      | 2 +-
 tools/include/linux/lockdep.h       | 2 +-
 tools/lib/perf/include/perf/event.h | 2 +-
 tools/lib/symbol/kallsyms.h         | 2 +-
 7 files changed, 8 insertions(+), 8 deletions(-)
include/linux/kallsyms.h +1 -1
index 4176c7eca7b5..5fb17dd4b6fa 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 335d988bd811..73874e5edfda 100644
@@ -213,7 +213,7 @@ static int klp_resolve_symbols(Elf64_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(Elf64_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 +1 -1
index 79b11bb7f07d..72ba0fe4e43b 100644
@@ -27,7 +27,7 @@
 
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
 
-#define KSYM_NAME_LEN		128
+#define KSYM_NAME_LEN		512
 
 struct sym_entry {
 	unsigned long long addr;
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/include/linux/lockdep.h +1 -1
index e56997288f2b..d9c163f3ab24 100644
@@ -47,7 +47,7 @@ static inline int debug_locks_off(void)
 
 #define task_pid_nr(tsk) ((tsk)->pid)
 
-#define KSYM_NAME_LEN 128
+#define KSYM_NAME_LEN 512
 #define printk(...) dprintf(STDOUT_FILENO, __VA_ARGS__)
 #define pr_err(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
 #define pr_warn pr_err
tools/lib/perf/include/perf/event.h +1 -1
index 75ee385fb078..acc4fa065ec7 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.34.0
author maintainer
#5 lore raw

PATCH 3/19 kallsyms: use the correct buffer size for symbols

In reply to Miguel Ojeda

From: Boqun Feng <[email protected]>

The buffered name size should be larger than KSYM_NAME_LEN, otherwise we cannot tell whether the size of a symbol name is too long.

---
 scripts/kallsyms.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
scripts/kallsyms.c +6 -3
index 72ba0fe4e43b..0e37c19d84af 100644
@@ -27,6 +27,9 @@
 
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
 
+#define _stringify_1(x)	#x
+#define _stringify(x)	_stringify_1(x)
+
 #define KSYM_NAME_LEN		512
 
 struct sym_entry {
@@ -197,15 +200,15 @@ 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+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) "s\n", &addr, &type, name);
 	if (rc != 3) {
-		if (rc != EOF && fgets(name, 500, in) == NULL)
+		if (rc != EOF && fgets(name, KSYM_NAME_LEN + 1, in) == NULL)
 			fprintf(stderr, "Read error or end of file.\n");
 		return NULL;
 	}
Signature · 1 line
2.34.0
author maintainer
#6 lore raw

PATCH 4/19 rust: add C helpers

In reply to Miguel Ojeda

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

---
 rust/helpers.c | 436 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 436 insertions(+)
 create mode 100644 rust/helpers.c
rust/helpers.c new file +436 -0
new file mode 100644
index 000000000000..f3e3fb34d376
@@ -0,0 +1,436 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/bug.h>
+#include <linux/build_bug.h>
+#include <linux/uaccess.h>
+#include <linux/sched/signal.h>
+#include <linux/gfp.h>
+#include <linux/highmem.h>
+#include <linux/uio.h>
+#include <linux/errname.h>
+#include <linux/mutex.h>
+#include <linux/platform_device.h>
+#include <linux/security.h>
+#include <asm/io.h>
+#include <linux/irq.h>
+#include <linux/irqchip/chained_irq.h>
+#include <linux/irqdomain.h>
+#include <linux/amba/bus.h>
+
+__noreturn void rust_helper_BUG(void)
+{
+	BUG();
+}
+
+unsigned long rust_helper_copy_from_user(void *to, const void __user *from, unsigned long n)
+{
+	return copy_from_user(to, from, n);
+}
+
+unsigned long rust_helper_copy_to_user(void __user *to, const void *from, unsigned long n)
+{
+	return copy_to_user(to, from, n);
+}
+
+unsigned long rust_helper_clear_user(void __user *to, unsigned long n)
+{
+	return clear_user(to, n);
+}
+
+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
+
+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_init_wait(struct wait_queue_entry *wq_entry)
+{
+	init_wait(wq_entry);
+}
+EXPORT_SYMBOL_GPL(rust_helper_init_wait);
+
+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);
+
+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);
+
+/* 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.34.0
author maintainer
#7 lore raw

PATCH 5/19 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 | 57 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
 create mode 100644 rust/compiler_builtins.rs
rust/compiler_builtins.rs new file +57 -0
new file mode 100644
index 000000000000..a5a0be72591b
@@ -0,0 +1,57 @@
+// 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 floating-point 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!("`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!("`u64` division/modulo should not be used", {
+    __aeabi_uldivmod,
+    __mulodi4,
+});
Signature · 1 line
2.34.0
#8 lore raw

Re: [PATCH 05/19] rust: add `compiler_builtins` crate

Quoted 28 lines · 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 | 57 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
 create mode 100644 rust/compiler_builtins.rs
rust/compiler_builtins.rs new file +3 -0
new file mode 100644
index 000000000000..a5a0be72591b
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Our own `compiler_builtins`.

rust/compiler_builtins.rs line 13

Quoted 10 lines
rust/compiler_builtins.rs new file +10 -0
+//!
+//! 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 floating-point 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

Rather than panic at runtime, could we do some binary post processing in Kbuild with $(NM) to error the build if any of the below symbols are referenced from .o files produced by .rs sources?

If we provide definitions of these symbols, then I worry about C code that previously would have failed to link at build time when referencing these will now succeed at linking when CONFIG_RUST=y is enabled, but may panic at runtime IF we happen to hit those code paths.

Quoted 47 lines
rust/compiler_builtins.rs new file +44 -1
+//! 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!("`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!("`u64` division/modulo should not be used", {
+    __aeabi_uldivmod,
+    __mulodi4,
+});
--

2.34.0

Signature · 2 lines
Thanks,
~Nick Desaulniers
#9 lore raw

Re: [PATCH 05/19] rust: add `compiler_builtins` crate

Quoted 4 lines · Nick Desaulniers

Rather than panic at runtime, could we do some binary post processing in Kbuild with $(NM) to error the build if any of the below symbols are referenced from .o files produced by .rs sources?

To error the build, we only need to not define them; i.e. the issue is passing the build. Eventually, we should be able to avoid defining them (this is what the comment is referring to).

There are other ways around, like providing an in-tree core, but it is best to see if upstream Rust can do it.

Quoted 5 lines

If we provide definitions of these symbols, then I worry about C code that previously would have failed to link at build time when referencing these will now succeed at linking when CONFIG_RUST=y is enabled, but may panic at runtime IF we happen to hit those code paths.

It should be fine -- by the time we consider the Rust support non-experimental, we should not be defining them.

Cheers,
Miguel

author maintainer
#10 lore raw

PATCH 6/19 rust: add `alloc` crate

In reply to Miguel Ojeda

This crate is a subset of the Rust standard library alloc, with some additions on top.

This is needed because upstream support for fallible allocations is a work in progress (i.e. the try_* versions of methods which return a Result instead of panicking).

Having the library in-tree also gives us a bit more freedom to experiment with new interfaces and allows us to iterate quickly.

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

---
 rust/alloc/README.md              |   32 +
 rust/alloc/alloc.rs               |  424 ++++
 rust/alloc/borrow.rs              |  498 +++++
 rust/alloc/boxed.rs               | 1844 ++++++++++++++++
 rust/alloc/collections/mod.rs     |  155 ++
 rust/alloc/fmt.rs                 |  583 +++++
 rust/alloc/lib.rs                 |  212 ++
 rust/alloc/macros.rs              |  126 ++
 rust/alloc/raw_vec.rs             |  612 ++++++
 rust/alloc/slice.rs               | 1275 +++++++++++
 rust/alloc/str.rs                 |  621 ++++++
 rust/alloc/string.rs              | 2857 +++++++++++++++++++++++++
 rust/alloc/vec/drain.rs           |  158 ++
 rust/alloc/vec/drain_filter.rs    |  145 ++
 rust/alloc/vec/into_iter.rs       |  356 +++
 rust/alloc/vec/is_zero.rs         |  106 +
 rust/alloc/vec/mod.rs             | 3327 +++++++++++++++++++++++++++++
 rust/alloc/vec/partial_eq.rs      |   49 +
 rust/alloc/vec/set_len_on_drop.rs |   30 +
 rust/alloc/vec/spec_extend.rs     |  172 ++
 20 files changed, 13582 insertions(+)
 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/collections/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/README.md new file +32 -0
new file mode 100644
index 000000000000..a1bcc2cef0e6
@@ -0,0 +1,32 @@
+# `alloc`
+
+These source files come from the Rust standard library, hosted in
+the https://github.com/rust-lang/rust repository. 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 new file +424 -0

424 lines not on this page · raw message

rust/alloc/borrow.rs new file +498 -0

498 lines not on this page · raw message

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

1,844 lines not on this page · raw message

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

155 lines not on this page · raw message

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

47 lines not on this page · raw message

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

212 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 +612 -0

612 lines not on this page · raw message

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

1,275 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 +2857 -0

2,857 lines not on this page · raw message

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

158 lines not on this page · raw message

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

145 lines not on this page · raw message

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

356 lines not on this page · raw message

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

106 lines not on this page · raw message

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

3,327 lines not on this page · raw message

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

49 lines not on this page · raw message

rust/alloc/vec/set_len_on_drop.rs new file +30 -0
new file mode 100644
index 000000000000..448bf5076a0b

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

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

172 lines not on this page · raw message

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

Signature · 1 line
2.34.0

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

author maintainer
#11 lore raw

PATCH 7/19 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..34e589149d3e
@@ -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]
+#[no_mangle]
+#[track_caller]
+pub const fn build_error(msg: &'static str) -> ! {
+    panic!("{}", msg);
+}
+
+#[cfg(CONFIG_RUST_BUILD_ASSERT_WARN)]
+#[link_section = ".gnu.warning.build_error"]
+#[used]
+static BUILD_ERROR_WARNING: [u8; 45] = *b"call to build_error present after compilation";
Signature · 1 line
2.34.0
author maintainer
#12 lore raw

PATCH 8/19 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 v2",
    }
---
 rust/macros/helpers.rs |  79 ++++++
 rust/macros/lib.rs     |  94 +++++++
 rust/macros/module.rs  | 622 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 795 insertions(+)
 create mode 100644 rust/macros/helpers.rs
 create mode 100644 rust/macros/lib.rs
 create mode 100644 rust/macros/module.rs
rust/macros/helpers.rs new file +79 -0
new file mode 100644
index 000000000000..ad210563e5a6
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use proc_macro::{token_stream, Group, TokenTree};
+
+pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> {
+    if let Some(TokenTree::Ident(ident)) = it.next() {
+        Some(ident.to_string())
+    } else {
+        None
+    }
+}
+
+pub(crate) fn try_literal(it: &mut token_stream::IntoIter) -> Option<String> {
+    if let Some(TokenTree::Literal(literal)) = it.next() {
+        Some(literal.to_string())
+    } else {
+        None
+    }
+}
+
+pub(crate) fn try_byte_string(it: &mut token_stream::IntoIter) -> Option<String> {
+    try_literal(it).and_then(|byte_string| {
+        if byte_string.starts_with("b\"") && byte_string.ends_with('\"') {
+            Some(byte_string[2..byte_string.len() - 1].to_string())
+        } else {
+            None
+        }
+    })
+}
+
+pub(crate) fn expect_ident(it: &mut token_stream::IntoIter) -> String {
+    try_ident(it).expect("Expected Ident")
+}
+
+pub(crate) fn expect_punct(it: &mut token_stream::IntoIter) -> char {
+    if let TokenTree::Punct(punct) = it.next().expect("Reached end of token stream for Punct") {
+        punct.as_char()
+    } else {
+        panic!("Expected Punct");
+    }
+}
+
+pub(crate) fn expect_literal(it: &mut token_stream::IntoIter) -> String {
+    try_literal(it).expect("Expected Literal")
+}
+
+pub(crate) fn expect_group(it: &mut token_stream::IntoIter) -> Group {
+    if let TokenTree::Group(group) = it.next().expect("Reached end of token stream for Group") {
+        group
+    } else {
+        panic!("Expected Group");
+    }
+}
+
+pub(crate) fn expect_byte_string(it: &mut token_stream::IntoIter) -> String {
+    try_byte_string(it).expect("Expected byte string")
+}
+
+pub(crate) fn expect_end(it: &mut token_stream::IntoIter) {
+    if it.next().is_some() {
+        panic!("Expected end");
+    }
+}
+
+pub(crate) fn get_literal(it: &mut token_stream::IntoIter, expected_name: &str) -> String {
+    assert_eq!(expect_ident(it), expected_name);
+    assert_eq!(expect_punct(it), ':');
+    let literal = expect_literal(it);
+    assert_eq!(expect_punct(it), ',');
+    literal
+}
+
+pub(crate) fn get_byte_string(it: &mut token_stream::IntoIter, expected_name: &str) -> String {
+    assert_eq!(expect_ident(it), expected_name);
+    assert_eq!(expect_punct(it), ':');
+    let byte_string = expect_byte_string(it);
+    assert_eq!(expect_punct(it), ',');
+    byte_string
+}
rust/macros/lib.rs new file +94 -0

94 lines not on this page · raw message

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

622 lines not on this page · raw message

Signature · 1 line
2.34.0
author maintainer
#13 lore raw

PATCH 9/19 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.

---
 include/linux/spinlock.h            |  17 +-
 kernel/printk/printk.c              |   5 +-
 rust/kernel/allocator.rs            |  65 +++
 rust/kernel/amba.rs                 | 276 +++++++++++
 rust/kernel/bindings.rs             |  47 ++
 rust/kernel/bindings_helper.h       |  30 ++
 rust/kernel/buffer.rs               |  52 ++
 rust/kernel/build_assert.rs         |  80 +++
 rust/kernel/c_types.rs              | 119 +++++
 rust/kernel/chrdev.rs               | 212 ++++++++
 rust/kernel/cred.rs                 |  73 +++
 rust/kernel/device.rs               | 206 ++++++++
 rust/kernel/driver.rs               | 198 ++++++++
 rust/kernel/error.rs                | 542 +++++++++++++++++++++
 rust/kernel/file.rs                 | 141 ++++++
 rust/kernel/file_operations.rs      | 723 ++++++++++++++++++++++++++++
 rust/kernel/gpio.rs                 | 475 ++++++++++++++++++
 rust/kernel/io_buffer.rs            | 153 ++++++
 rust/kernel/io_mem.rs               | 207 ++++++++
 rust/kernel/iov_iter.rs             |  81 ++++
 rust/kernel/irq.rs                  | 408 ++++++++++++++++
 rust/kernel/lib.rs                  | 256 ++++++++++
 rust/kernel/linked_list.rs          | 247 ++++++++++
 rust/kernel/miscdev.rs              | 166 +++++++
 rust/kernel/module_param.rs         | 497 +++++++++++++++++++
 rust/kernel/of.rs                   | 101 ++++
 rust/kernel/pages.rs                | 162 +++++++
 rust/kernel/platdev.rs              | 152 ++++++
 rust/kernel/power.rs                | 118 +++++
 rust/kernel/prelude.rs              |  33 ++
 rust/kernel/print.rs                | 441 +++++++++++++++++
 rust/kernel/random.rs               |  50 ++
 rust/kernel/raw_list.rs             | 361 ++++++++++++++
 rust/kernel/rbtree.rs               | 562 +++++++++++++++++++++
 rust/kernel/revocable.rs            | 163 +++++++
 rust/kernel/security.rs             |  36 ++
 rust/kernel/static_assert.rs        |  39 ++
 rust/kernel/std_vendor.rs           | 150 ++++++
 rust/kernel/str.rs                  | 375 +++++++++++++++
 rust/kernel/sync/arc.rs             | 500 +++++++++++++++++++
 rust/kernel/sync/condvar.rs         | 137 ++++++
 rust/kernel/sync/guard.rs           | 181 +++++++
 rust/kernel/sync/locked_by.rs       | 112 +++++
 rust/kernel/sync/mod.rs             |  92 ++++
 rust/kernel/sync/mutex.rs           | 111 +++++
 rust/kernel/sync/revocable_mutex.rs | 184 +++++++
 rust/kernel/sync/seqlock.rs         | 201 ++++++++
 rust/kernel/sync/spinlock.rs        | 180 +++++++
 rust/kernel/sysctl.rs               | 197 ++++++++
 rust/kernel/task.rs                 | 182 +++++++
 rust/kernel/types.rs                | 486 +++++++++++++++++++
 rust/kernel/user_ptr.rs             | 175 +++++++
 52 files changed, 10750 insertions(+), 7 deletions(-)
 create mode 100644 rust/kernel/allocator.rs
 create mode 100644 rust/kernel/amba.rs
 create mode 100644 rust/kernel/bindings.rs
 create mode 100644 rust/kernel/bindings_helper.h
 create mode 100644 rust/kernel/buffer.rs
 create mode 100644 rust/kernel/build_assert.rs
 create mode 100644 rust/kernel/c_types.rs
 create mode 100644 rust/kernel/chrdev.rs
 create mode 100644 rust/kernel/cred.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/file_operations.rs
 create mode 100644 rust/kernel/gpio.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/lib.rs
 create mode 100644 rust/kernel/linked_list.rs
 create mode 100644 rust/kernel/miscdev.rs
 create mode 100644 rust/kernel/module_param.rs
 create mode 100644 rust/kernel/of.rs
 create mode 100644 rust/kernel/pages.rs
 create mode 100644 rust/kernel/platdev.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/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/mod.rs
 create mode 100644 rust/kernel/sync/mutex.rs
 create mode 100644 rust/kernel/sync/revocable_mutex.rs
 create mode 100644 rust/kernel/sync/seqlock.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/user_ptr.rs
include/linux/spinlock.h +11 -6
index b4e5ca23f840..40e467cdee2d 100644
@@ -326,12 +326,17 @@ static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock)
 
 #ifdef CONFIG_DEBUG_SPINLOCK
 
-# define spin_lock_init(lock)					\
-do {								\
-	static struct lock_class_key __key;			\
-								\
-	__raw_spin_lock_init(spinlock_check(lock),		\
-			     #lock, &__key, LD_WAIT_CONFIG);	\
+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;	\
+						\
+	__spin_lock_init(lock, #lock, &__key);	\
 } while (0)
 
 #else
kernel/printk/printk.c +4 -1
index 57b132b658e1..cbc35d586afb 100644
@@ -392,7 +392,10 @@ static struct latched_seq clear_seq = {
 /* the maximum size of a formatted record (i.e. with prefix added per line) */
 #define CONSOLE_LOG_MAX		1024
 
-/* the maximum size allowed to be reserved for a record */
+/*
+ * The maximum size allowed to be reserved for a record.
+ * Keep in sync with rust/kernel/print.rs.
+ */
 #define LOG_LINE_MAX		(CONSOLE_LOG_MAX - PREFIX_MAX)
 
 #define LOG_LEVEL(v)		((v) & 0x07)
rust/kernel/allocator.rs new file +65 -0

65 lines not on this page · raw message

rust/kernel/amba.rs new file +276 -0

276 lines not on this page · raw message

rust/kernel/bindings.rs new file +47 -0

47 lines not on this page · raw message

rust/kernel/bindings_helper.h new file +30 -0
new file mode 100644
index 000000000000..55c3f25a54eb
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#include <linux/cdev.h>
+#include <linux/errname.h>
+#include <linux/fs.h>
+#include <linux/module.h>
+#include <linux/random.h>
+#include <linux/slab.h>
+#include <linux/sysctl.h>
+#include <linux/uaccess.h>
+#include <linux/uio.h>
+#include <linux/version.h>
+#include <linux/miscdevice.h>
+#include <linux/poll.h>
+#include <linux/mm.h>
+#include <linux/file.h>
+#include <uapi/linux/android/binder.h>
+#include <linux/platform_device.h>
+#include <linux/of_platform.h>
+#include <linux/security.h>
+#include <asm/io.h>
+#include <linux/irq.h>
+#include <linux/interrupt.h>
+#include <linux/irqdomain.h>
+#include <linux/amba/bus.h>
+#include <linux/gpio/driver.h>
+
+// `bindgen` gets confused at certain things
+const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
+const gfp_t BINDINGS___GFP_ZERO = __GFP_ZERO;
rust/kernel/buffer.rs new file +52 -0

52 lines not on this page · raw message

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

80 lines not on this page · raw message

rust/kernel/c_types.rs new file +119 -0

119 lines not on this page · raw message

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

212 lines not on this page · raw message

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

73 lines not on this page · raw message

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

206 lines not on this page · raw message

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

198 lines not on this page · raw message

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

542 lines not on this page · raw message

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

141 lines not on this page · raw message

rust/kernel/file_operations.rs new file +723 -0

723 lines not on this page · raw message

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

202 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 +207 -0

207 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 +408 -0

408 lines not on this page · raw message

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

256 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 +166 -0

166 lines not on this page · raw message

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

497 lines not on this page · raw message

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

101 lines not on this page · raw message

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

162 lines not on this page · raw message

rust/kernel/platdev.rs new file +152 -0

152 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 +33 -0
new file mode 100644
index 000000000000..b602fc6db761

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

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

441 lines not on this page · raw message

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

50 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 +562 -0

562 lines not on this page · raw message

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

163 lines not on this page · raw message

rust/kernel/security.rs new file +36 -0
new file mode 100644
index 000000000000..2004d01233f4

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

rust/kernel/static_assert.rs new file +39 -0
new file mode 100644
index 000000000000..a80d8ab57564

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

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

150 lines not on this page · raw message

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

375 lines not on this page · raw message

rust/kernel/sync/arc.rs new file +500 -0

500 lines not on this page · raw message

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

137 lines not on this page · raw message

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

181 lines not on this page · raw message

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

112 lines not on this page · raw message

rust/kernel/sync/mod.rs new file +92 -0

92 lines not on this page · raw message

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

111 lines not on this page · raw message

rust/kernel/sync/revocable_mutex.rs new file +184 -0

184 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/spinlock.rs new file +180 -0

180 lines not on this page · raw message

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

197 lines not on this page · raw message

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

182 lines not on this page · raw message

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

486 lines not on this page · raw message

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

175 lines not on this page · raw message

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

Signature · 1 line
2.34.0

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

author maintainer
#14 lore raw

PATCH 10/19 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 | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
 create mode 100644 rust/exports.c
rust/exports.c new file +16 -0
new file mode 100644
index 000000000000..d7dff1b3b919
@@ -0,0 +1,16 @@
+// 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).
+
+#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_kernel_generated.h"
Signature · 1 line
2.34.0
author maintainer
#15 lore raw

PATCH 11/19 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.

---
 lib/vsprintf.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
lib/vsprintf.c +12 -0
index 58d5e567f836..bc9c05427d9a 100644
@@ -2233,6 +2233,10 @@ char *fwnode_string(char *buf, char *end, struct fwnode_handle *fwnode,
 	return widen_string(buf, buf - buf_start, end, spec);
 }
 
+#ifdef CONFIG_RUST
+char *rust_fmt_argument(char* buf, char* end, void *ptr);
+#endif
+
 /* Disable pointer hashing if requested */
 bool no_hash_pointers __ro_after_init;
 EXPORT_SYMBOL_GPL(no_hash_pointers);
@@ -2388,6 +2392,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,
@@ -2460,6 +2468,10 @@ 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);
+#ifdef CONFIG_RUST
+	case 'A':
+		return rust_fmt_argument(buf, end, ptr);
+#endif
 	case 'x':
 		return pointer_string(buf, end, ptr, spec);
 	case 'e':
Signature · 1 line
2.34.0
#16 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 27 lines · 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.

---
 lib/vsprintf.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
lib/vsprintf.c +0 -0
index 58d5e567f836..bc9c05427d9a 100644

lib/vsprintf.c char *fwnode_string(char *buf, char *end, struct fwnode_handle *fwnode, · line 2238

Quoted 6 lines
lib/vsprintf.c +3 -0
@@ -2233,6 +2233,10 @@ char *fwnode_string(char *buf, char *end, struct fwnode_handle *fwnode,
 	return widen_string(buf, buf - buf_start, end, spec);
 }
 
+#ifdef CONFIG_RUST
+char *rust_fmt_argument(char* buf, char* end, void *ptr);
+#endif

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Quoted 16 lines
lib/vsprintf.c +5 -0
+
 /* Disable pointer hashing if requested */
 bool no_hash_pointers __ro_after_init;
 EXPORT_SYMBOL_GPL(no_hash_pointers);
@@ -2388,6 +2392,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,

lib/vsprintf.c char *pointer(const char *fmt, char *buf, char *end, void *ptr, · line 2474

Quoted 7 lines
lib/vsprintf.c +4 -0
@@ -2460,6 +2468,10 @@ 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);
+#ifdef CONFIG_RUST
+	case 'A':
+		return rust_fmt_argument(buf, end, ptr);
+#endif

Same here, this should not be needed if you put it in a .h file correctly.

thanks,

greg k-h

#17 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 3 lines · Greg Kroah-Hartman

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Will do, thanks for reviewing!

Quoted 2 lines

Same here, this should not be needed if you put it in a .h file correctly.

This one is mimicking the CONFIG_BLOCK one (case 'g' a bit above) -- but we can change it, of course.

Cheers,
Miguel

#18 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 6 lines · Miguel Ojeda
Quoted 3 lines · Greg Kroah-Hartman

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Quoted 7 lines

Will do, thanks for reviewing!

Quoted 2 lines

Same here, this should not be needed if you put it in a .h file correctly.

This one is mimicking the CONFIG_BLOCK one (case 'g' a bit above) -- but we can change it, of course.

That should be changed as well :)

#19 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 7 lines · Greg Kroah-Hartman
Quoted 5 lines · Miguel Ojeda
Quoted 3 lines · Greg Kroah-Hartman

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Why not put #ifdef in .c files?

Quoted 4 lines
Quoted 4 lines

Will do, thanks for reviewing!

Quoted 2 lines

Same here, this should not be needed if you put it in a .h file correctly.

I guess IS_ENABLED could be used in the .c code, but I don't see how they could move the dispatch to rust_fmt_argument to a header without moving the definition of pointer() to a header, which they probably _cant_ do because it's noinline_for_stack.

Quoted 5 lines
Quoted 3 lines

This one is mimicking the CONFIG_BLOCK one (case 'g' a bit above) -- but we can change it, of course.

That should be changed as well :)

Isn't the point to minimize code that's unused for certain configurations?

Signature · 2 lines
Thanks,
~Nick Desaulniers
#20 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 14 lines · Nick Desaulniers
Quoted 7 lines · Greg Kroah-Hartman
Quoted 5 lines · Miguel Ojeda
Quoted 3 lines · Greg Kroah-Hartman

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Why not put #ifdef in .c files?

Quoted 2 lines
Quoted 2 lines

Will do, thanks for reviewing!

Quoted 7 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

Same here, this should not be needed if you put it in a .h file correctly.

I guess IS_ENABLED could be used in the .c code, but I don't see how they could move the dispatch to rust_fmt_argument to a header without moving the definition of pointer() to a header, which they probably _cant_ do because it's noinline_for_stack.

In the header file, you put:

#ifdef CONFIG_FOO
int foo(void);
#else
static inline int foo(void) { }
#endif

and then in your .c file, you call foo() unconditionally, and everything works beautifully.

#21 lore raw

Re: [PATCH 11/19] vsprintf: add new `%pA` format specifier

Quoted 26 lines · Matthew Wilcox
Quoted 14 lines · Nick Desaulniers
Quoted 7 lines · Greg Kroah-Hartman
Quoted 5 lines · Miguel Ojeda
Quoted 3 lines · Greg Kroah-Hartman

That should be in a .h file somewhere. Remember, don't put #ifdef in .c files please.

Why not put #ifdef in .c files?

Quoted 2 lines
Quoted 2 lines

Will do, thanks for reviewing!

Quoted 7 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

Same here, this should not be needed if you put it in a .h file correctly.

I guess IS_ENABLED could be used in the .c code, but I don't see how they could move the dispatch to rust_fmt_argument to a header without moving the definition of pointer() to a header, which they probably _cant_ do because it's noinline_for_stack.

In the header file, you put:

Quoted 9 lines

#ifdef CONFIG_FOO
int foo(void);
#else
static inline int foo(void) { }
#endif

and then in your .c file, you call foo() unconditionally, and everything works beautifully.

Ah, that is nice, thanks!

Signature · 2 lines
Thanks,
~Nick Desaulniers
author maintainer
#22 lore raw

PATCH 12/19 scripts: add `generate_rust_analyzer.py`

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 | 133 ++++++++++++++++++++++++++++++
 1 file changed, 133 insertions(+)
 create mode 100755 scripts/generate_rust_analyzer.py
scripts/generate_rust_analyzer.py new file +133 -0
new file mode 100755
index 000000000000..024f8b884c1b
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""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(
+        "kernel",
+        srctree / "rust" / "kernel" / "lib.rs",
+        ["core", "alloc", "macros", "build_error"],
+        cfg=cfg,
+    )
+    crates[-1]["env"]["OBJTREE"] = str(objtree.resolve(True))
+    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.34.0
author maintainer
#23 lore raw

PATCH 13/19 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.

---
I would like to use this patch for discussing the demangling topic.

The following discusses the different approaches we could take.

# Leave demangling to userspace

This is the easiest and less invasive approach, the one implemented by this patch.

The decode_stacktrace.sh script is already needed to map the offsets to the source code. Therefore, we could also take the chance to demangle the symbols here.

With this approach, we do not need to introduce any change in the vsprintf machinery and we minimize the risk of breaking user tools.

Note that, if we take this approach, it is likely we want to ask for a minimum version of either of the tools (since there may be users of the script that do not have recent enough toolchains).

# Demangling in kernelspace on-the-fly

That is, at backtrace print time, we demangle the Rust symbols.

The size of the code that would be needed is fairly small; around 5 KiB using the "official" library (written in Rust), e.g.:

    text    data    bss     dec      hex    filename
    7799976 1689820 2129920 11619716 b14d84 vmlinux
    7801111 1693916 2129920 11624947 b161f3 vmlinux + demangling

We can remove a few bits from the official library, e.g. punycode support that we do not need (all our identifiers will be ASCII), but it does not make a substantial difference.

The official library performs the demangling without requiring allocations. However, of course, it will increased our stack usage and complexity, specially considering a stack dump may be requested in not ideal conditions.

Furthermore, this approach (and the ones below) likely require adding a new %p specifier (or a new modifier to existing ones) if we do not want to affect non-backtrace uses of the B/S ones. Also, it is unclear whether we should write the demangled versions in an extra, different line or replace the real symbol -- we could be breaking user tools relying on parsing backtraces (e.g. our own decode_stacktrace.sh). For instance, they could be relying on having real symbols there, or may break due to e.g. spaces.

# Demangling at compile-time

This implies having kallsyms demangle all the Rust symbols.

The size of this data is around the same order of magnitude of the non-demangled ones. However, this is notably more than the demangling code (see previous point), e.g. 120 KiB (uncompressed) in a small kernel.

This approach also brings the same concerns regarding modifying the backtrace printing (see previous point).

# Demangling at compile-time and substituting symbols by hashes

One variation of the previous alternative is avoiding the mangled names inside the kernel, by hashing them. This would avoid having to support "big symbols" and would also reduce the size of the kallsyms tables, while still allowing to link modules.

However, if we do not have the real symbols around, then we do not have the possibility of providing both the mangled and demangled versions in the backtrace, which brings us back to the issues related to breaking userspace tools. There are also other places other than backtraces using "real" symbols that users may be relying on, such as /proc/*/stack.

 scripts/decode_stacktrace.sh | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
scripts/decode_stacktrace.sh +14 -0
index 5fbad61fe490..f3c7b506d440 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"
@@ -169,6 +177,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.34.0
author maintainer
#24 lore raw

PATCH 14/19 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 binary assets used for the rustdoc target and 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             |   4 +
 Documentation/process/changes.rst           |  13 ++
 Documentation/rust/arch-support.rst         |  35 ++++
 Documentation/rust/assets/favicon-16x16.png | Bin 0 -> 798 bytes
 Documentation/rust/assets/favicon-32x32.png | Bin 0 -> 2076 bytes
 Documentation/rust/assets/rust-logo.png     | Bin 0 -> 53976 bytes
 Documentation/rust/coding.rst               |  91 +++++++++
 Documentation/rust/docs.rst                 | 101 ++++++++++
 Documentation/rust/index.rst                |  21 ++
 Documentation/rust/quick-start.rst          | 212 ++++++++++++++++++++
 12 files changed, 481 insertions(+)
 create mode 100644 Documentation/rust/arch-support.rst
 create mode 100644 Documentation/rust/assets/favicon-16x16.png
 create mode 100644 Documentation/rust/assets/favicon-32x32.png
 create mode 100644 Documentation/rust/assets/rust-logo.png
 create mode 100644 Documentation/rust/coding.rst
 create mode 100644 Documentation/rust/docs.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 79aaa55d6bcf..724e2ffddff1 100644
@@ -11,6 +11,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/docs.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 54ce34fd6fbd..1b13c2445e87 100644
@@ -82,6 +82,7 @@ merged much easier.
    maintainer/index
    fault-injection/index
    livepatch/index
+   rust/index
 
 
 Kernel API documentation
Documentation/kbuild/kbuild.rst +4 -0
index 2d1fc03d346e..468a0d216c29 100644
@@ -57,6 +57,10 @@ CFLAGS_MODULE
 -------------
 Additional module specific options to use for $(CC).
 
+KRUSTFLAGS
+----------
+Additional options to the Rust compiler (for built-in and modules).
+
 LDFLAGS_MODULE
 --------------
 Additional options used for $(LD) when linking modules.
Documentation/process/changes.rst +13 -0
index b398b8576417..9f11bd5aee96 100644
@@ -26,11 +26,18 @@ running a Linux kernel.  Also, not all tools are necessary on all
 systems; obviously, if you don't have any PC Card hardware, for example,
 you probably needn't concern yourself with pcmciautils.
 
+Furthermore, note that newer versions of the Rust toolchain may or may not work
+because, for the moment, we depend on some unstable features. Thus, unless you
+know what you are doing, use the exact version listed here. Please see
+:ref:`Documentation/rust/quick-start.rst <rust_quick_start>` for details.
+
 ====================== ===============  ========================================
         Program        Minimal version       Command to check the version
 ====================== ===============  ========================================
 GNU C                  5.1              gcc --version
 Clang/LLVM (optional)  10.0.1           clang --version
+rustc (optional)       1.57.0           rustc --version
+bindgen (optional)     0.56.0           bindgen --version
 GNU make               3.81             make --version
 binutils               2.23             ld -v
 flex                   2.5.35           flex --version
@@ -329,6 +336,12 @@ Sphinx
 Please see :ref:`sphinx_install` in :ref:`Documentation/doc-guide/sphinx.rst <sphinxdoc>`
 for details about Sphinx requirements.
 
+rustdoc
+-------
+
+``rustdoc`` is used to generate Rust documentation. Please see
+:ref:`Documentation/rust/docs.rst <rust_docs>` for more information.
+
 Getting updated software
 ========================
 
Documentation/rust/arch-support.rst new file +35 -0
new file mode 100644
index 000000000000..fdcce6452623
@@ -0,0 +1,35 @@
+.. _rust_arch_support:
+
+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 (see :ref:`kbuild_llvm`).
+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.
+
+.. list-table::
+   :widths: 10 10 10
+   :header-rows: 1
+
+   * - Architecture
+     - Level of support
+     - Constraints
+   * - ``arm``
+     - Maintained
+     - ``armv6`` and compatible only, ``RUST_OPT_LEVEL >= 2``
+   * - ``arm64``
+     - Maintained
+     - None
+   * - ``powerpc``
+     - Maintained
+     - ``ppc64le`` only, ``RUST_OPT_LEVEL < 2`` requires ``CONFIG_THREAD_SHIFT=15``
+   * - ``riscv``
+     - Maintained
+     - ``riscv64`` only
+   * - ``x86``
+     - Maintained
+     - ``x86_64`` only
Documentation/rust/assets/favicon-16x16.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..d93115e8f47a939635b73ad3b3226837f83f7584
GIT binary patch
Documentation/rust/assets/favicon-32x32.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..655ccbcfc8cddde1e9c7d826a3f44c1e056b1dc8
GIT binary patch
Documentation/rust/assets/rust-logo.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..081ae80c193ba259ffc5c506ccefc4cedd915c4b
GIT binary patch
Documentation/rust/coding.rst new file +91 -0

91 lines not on this page · raw message

Documentation/rust/docs.rst new file +101 -0

101 lines not on this page · raw message

Documentation/rust/index.rst new file +21 -0
new file mode 100644
index 000000000000..906a7d698c50
@@ -0,0 +1,21 @@
+Rust
+====
+
+Documentation related to Rust within the kernel. To start using Rust
+in the kernel, please read the
+:ref:`Documentation/rust/quick-start.rst <rust_quick_start>` guide.
+
+.. toctree::
+    :maxdepth: 1
+
+    quick-start
+    coding
+    docs
+    arch-support
+
+.. only::  subproject and html
+
+   Indices
+   =======
+
+   * :ref:`genindex`
Documentation/rust/quick-start.rst new file +212 -0

212 lines not on this page · raw message

Signature · 1 line
2.34.0
#25 lore raw

Re: [PATCH 14/19] docs: add Rust documentation

Quoted 5 lines · 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.

I'm sure Documentation/rust/ will grow over time; there's certainly more that can be added and core kernel devs will have more questions over time. I'm still running into a SNAFU actually building; see
https://lore.kernel.org/lkml/CAKwvOdk9VNenJJN5HnPpGgsHT+OsRsgPGSesQgqMP2aLPWy0NQ@mail.gmail.com/.

But I read through all that was added here and didn't find anything problematic IMO. I didn't verify the png's are actually the logo...

I don't think make htmldocs produced any new warnings, though it's not exactly warning free at the moment (pre-existing before this series).

Quoted 5 lines

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 binary assets used for the rustdoc target and a few other small changes elsewhere in the documentation folder.

How is rust-logo.png being included in the docs? Is there something with RST that isn't grep'able for rust-logo.png?

Quoted 3 lines

--
2.34.0

--
Thanks,
~Nick Desaulniers

#26 lore raw

Re: [PATCH 14/19] docs: add Rust documentation

Quoted 3 lines · Nick Desaulniers

I'm sure Documentation/rust/ will grow over time; there's certainly more that can be added and core kernel devs will have more questions

Indeed -- the comment is only trying to emphasize (or explain) that this might be a difference with respect to C, i.e. that we should try to put as much of the documentation as possible closer to the code, rather than create "far" files in Documentation/rust. I will try to clarify the comment.

Quoted 2 lines

But I read through all that was added here and didn't find anything problematic IMO. I didn't verify the png's are actually the logo...

Thanks for reading through all of it!

Quoted 3 lines

I don't think make htmldocs produced any new warnings, though it's not exactly warning free at the moment (pre-existing before this series).

Yeah, I also run make htmldocs before submitting the patch series rounds. And indeed, there are quite a few warnings (20+?), but none coming from Documentation/rust that I could see.

Quoted 2 lines

How is rust-logo.png being included in the docs? Is there something with RST that isn't grep'able for rust-logo.png?

At the moment, the assets are simply copied to the output folder, in the rust/Makefile. (I should provide an SVG too or remove the reference to it, by the way).

Cheers,
Miguel

author maintainer
#27 lore raw

PATCH 15/19 Kbuild: add Rust support

In reply to 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 definition files, the version detection script and a few other bits.

In the future, we will likely want to generate the target files on the fly via a script.

---
 .gitignore                    |   5 +
 .rustfmt.toml                 |  12 ++
 Makefile                      | 146 +++++++++++++-
 arch/arm/rust/target.json     |  27 +++
 arch/arm64/rust/target.json   |  34 ++++
 arch/powerpc/rust/target.json |  29 +++
 arch/riscv/Makefile           |   1 +
 arch/riscv/rust/rv32ima.json  |  36 ++++
 arch/riscv/rust/rv32imac.json |  36 ++++
 arch/riscv/rust/rv64ima.json  |  36 ++++
 arch/riscv/rust/rv64imac.json |  36 ++++
 arch/x86/rust/target.json     |  36 ++++
 init/Kconfig                  |  31 ++-
 lib/Kconfig.debug             | 144 ++++++++++++++
 rust/.gitignore               |   7 +
 rust/Makefile                 | 353 ++++++++++++++++++++++++++++++++++
 rust/bindgen_parameters       |  13 ++
 scripts/Makefile.build        |  22 +++
 scripts/Makefile.debug        |  10 +
 scripts/Makefile.lib          |  12 ++
 scripts/Makefile.modfinal     |   8 +-
 scripts/is_rust_module.sh     |  19 ++
 scripts/kconfig/confdata.c    |  75 ++++++++
 scripts/rust-version.sh       |  31 +++
 24 files changed, 1147 insertions(+), 12 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 arch/arm/rust/target.json
 create mode 100644 arch/arm64/rust/target.json
 create mode 100644 arch/powerpc/rust/target.json
 create mode 100644 arch/riscv/rust/rv32ima.json
 create mode 100644 arch/riscv/rust/rv32imac.json
 create mode 100644 arch/riscv/rust/rv64ima.json
 create mode 100644 arch/riscv/rust/rv64imac.json
 create mode 100644 arch/x86/rust/target.json
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Makefile
 create mode 100644 rust/bindgen_parameters
 create mode 100755 scripts/is_rust_module.sh
 create mode 100755 scripts/rust-version.sh
.gitignore +5 -0
index 7afd412dadd2..48c68948f476 100644
@@ -37,6 +37,7 @@
 *.o
 *.o.*
 *.patch
+*.rmeta
 *.s
 *.so
 *.so.dbg
@@ -96,6 +97,7 @@ modules.order
 !.gitattributes
 !.gitignore
 !.mailmap
+!.rustfmt.toml
 
 #
 # Generated include files
@@ -161,3 +163,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 +138 -8

274 lines not on this page · raw message

arch/arm/rust/target.json new file +27 -0
new file mode 100644
index 000000000000..3f845b8221dc
@@ -0,0 +1,27 @@
+{
+  "arch": "arm",
+  "crt-static-respected": true,
+  "data-layout": "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64",
+  "dynamic-linking": true,
+  "env": "gnu",
+  "executables": true,
+  "features": "+strict-align,+v6",
+  "function-sections": false,
+  "has-elf-tls": true,
+  "has-rpath": true,
+  "linker-is-gnu": true,
+  "llvm-target": "arm-unknown-linux-gnueabi",
+  "max-atomic-width": 64,
+  "os": "linux",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack"
+    ]
+  },
+  "relocation-model": "static",
+  "target-family": "unix",
+  "target-mcount": "\u0001__gnu_mcount_nc",
+  "target-pointer-width": "32"
+}
arch/arm64/rust/target.json new file +34 -0
new file mode 100644
index 000000000000..09a264df26c7
@@ -0,0 +1,34 @@
+{
+  "arch": "aarch64",
+  "data-layout": "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+strict-align,+neon,+fp-armv8",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "aarch64-unknown-none",
+  "max-atomic-width": 128,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/powerpc/rust/target.json new file +29 -0
new file mode 100644
index 000000000000..2420c8e6a520
@@ -0,0 +1,29 @@
+{
+  "arch": "powerpc64",
+  "code-model": "large",
+  "cpu": "ppc64le",
+  "data-layout": "e-m:e-i64:64-n32:64",
+  "env": "gnu",
+  "features": "-altivec,-vsx,-hard-float",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "powerpc64le-elf",
+  "max-atomic-width": 64,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "target-family": "unix",
+  "target-mcount": "_mcount",
+  "target-endian": "little",
+  "target-pointer-width": "64"
+}
arch/riscv/Makefile +1 -0
index 8a107ed18b0d..0487db1e54c6 100644
@@ -52,6 +52,7 @@ riscv-march-$(CONFIG_FPU)		:= $(riscv-march-y)fd
 riscv-march-$(CONFIG_RISCV_ISA_C)	:= $(riscv-march-y)c
 KBUILD_CFLAGS += -march=$(subst fd,,$(riscv-march-y))
 KBUILD_AFLAGS += -march=$(riscv-march-y)
+KBUILD_RUST_TARGET := $(srctree)/arch/riscv/rust/$(subst fd,,$(riscv-march-y)).json
 
 KBUILD_CFLAGS += -mno-save-restore
 KBUILD_CFLAGS += -DCONFIG_PAGE_OFFSET=$(CONFIG_PAGE_OFFSET)
arch/riscv/rust/rv32ima.json new file +36 -0
new file mode 100644
index 000000000000..bcdda88c1604
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv32",
+  "code-model": "medium",
+  "cpu": "generic-rv32",
+  "data-layout": "e-m:e-p:32:32-i64:64-n32-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv32",
+  "max-atomic-width": 32,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m32"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "32",
+  "vendor": ""
+}
arch/riscv/rust/rv32imac.json new file +36 -0
new file mode 100644
index 000000000000..45873c10a5c3
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv32",
+  "code-model": "medium",
+  "cpu": "generic-rv32",
+  "data-layout": "e-m:e-p:32:32-i64:64-n32-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a,+c",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv32",
+  "max-atomic-width": 32,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m32"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "32",
+  "vendor": ""
+}
arch/riscv/rust/rv64ima.json new file +36 -0
new file mode 100644
index 000000000000..853d758c5461
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv64",
+  "code-model": "medium",
+  "cpu": "generic-rv64",
+  "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv64",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/riscv/rust/rv64imac.json new file +36 -0
new file mode 100644
index 000000000000..ce50ee8e8c93
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv64",
+  "code-model": "medium",
+  "cpu": "generic-rv64",
+  "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a,+c",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv64",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/x86/rust/target.json new file +36 -0
new file mode 100644
index 000000000000..379cf39e8941
@@ -0,0 +1,36 @@
+{
+  "arch": "x86_64",
+  "code-model": "kernel",
+  "cpu": "x86-64",
+  "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "-mmx,-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-3dnow,-3dnowa,-avx,-avx2,+soft-float",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "x86_64-elf",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": "unknown"
+}
init/Kconfig +30 -1
index 4b7bac10c72d..03d3c21e28a3 100644
@@ -60,6 +60,15 @@ config LLD_VERSION
 	default $(ld-version) if LD_IS_LLD
 	default 0
 
+config HAS_RUST
+	depends on ARM64 || CPU_32v6 || CPU_32v6K || (PPC64 && CPU_LITTLE_ENDIAN) || X86_64 || RISCV
+	def_bool $(success,$(RUSTC) --version)
+
+config RUSTC_VERSION
+	depends on HAS_RUST
+	int
+	default $(shell,$(srctree)/scripts/rust-version.sh $(RUSTC))
+
 config CC_CAN_LINK
 	bool
 	default $(success,$(srctree)/scripts/cc-can-link.sh $(CC) $(CLANG_FLAGS) $(m64-flag)) if 64BIT
@@ -142,7 +151,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,
@@ -2044,6 +2054,25 @@ config PROFILING
 	  Say Y here to enable the extended profiling support mechanisms used
 	  by profilers.
 
+config RUST
+	bool "Rust support"
+	depends on HAS_RUST
+	depends on !COMPILE_TEST
+	depends on !MODVERSIONS
+	default n
+	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.
+
 #
 # Place an empty function call at each tracepoint site. Can be
 # dynamically changed for a probe function.
lib/Kconfig.debug +144 -0

150 lines not on this page · raw message

rust/.gitignore new file +7 -0
new file mode 100644
index 000000000000..168cb26a31b9
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+
+bindings_generated.rs
+bindings_helpers_generated.rs
+exports_*_generated.h
+doc/
+test/
rust/Makefile new file +353 -0

353 lines not on this page · raw message

rust/bindgen_parameters new file +13 -0
new file mode 100644
index 000000000000..c2cc4a88234e
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0
+
+--opaque-type xregs_state
+--opaque-type desc_struct
+--opaque-type arch_lbr_state
+--opaque-type local_apic
+
+# 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/Makefile.build +22 -0
index 78656b527fe5..7adac231fafd 100644
@@ -26,6 +26,7 @@ EXTRA_CPPFLAGS :=
 EXTRA_LDFLAGS  :=
 asflags-y  :=
 ccflags-y  :=
+rustflags-y :=
 cppflags-y :=
 ldflags-y  :=
 
@@ -323,6 +324,27 @@ quiet_cmd_cc_lst_c = MKLST   $@
 $(obj)/%.lst: $(src)/%.c FORCE
 	$(call if_changed_dep,cc_lst_c)
 
+# Compile Rust sources (.rs)
+# ---------------------------------------------------------------------------
+
+# Need to use absolute path here and have symbolic links resolved;
+# otherwise rustdoc and rustc compute different hashes for the target.
+rust_cross_flags := --target=$(realpath $(KBUILD_RUST_TARGET))
+
+quiet_cmd_rustc_o_rs = $(RUSTC_OR_CLIPPY_QUIET) $(quiet_modtag) $@
+      cmd_rustc_o_rs = \
+	RUST_MODFILE=$(modfile) \
+	$(RUSTC_OR_CLIPPY) $(rust_flags) $(rust_cross_flags) \
+		-Zallow-features=allocator_api,bench_black_box,concat_idents,generic_associated_types,global_asm \
+		--extern alloc --extern kernel \
+		--crate-type rlib --out-dir $(obj) -L $(objtree)/rust/ \
+		--crate-name $(patsubst %.o,%,$(notdir $@)) $<; \
+	mv $(obj)/$(subst .o,,$(notdir $@)).d $(depfile); \
+	sed -i '/^\#/d' $(depfile)
+
+$(obj)/%.o: $(src)/%.rs FORCE
+	$(call if_changed_dep,rustc_o_rs)
+
 # Compile assembler sources (.S)
 # ---------------------------------------------------------------------------
 
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.lib +12 -0
index d1f865b8c0cb..ce6142238835 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
 # ===========================================================================
@@ -133,6 +134,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 7f39599e9fae..0518b6d3e620 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 $(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/is_rust_module.sh new file +19 -0
new file mode 100755
index 000000000000..ff24d9c16f09
@@ -0,0 +1,19 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# is_rust_module.sh MOD.ko
+#
+# Returns 0 if MOD.ko is a rust module, 1 otherwise.
+
+set -e
+module="$*"
+
+while IFS= read -r line
+do
+  # Any symbol beginning with "_R" is a v0 mangled rust symbol
+  if [[ $line =~ ^[0-9a-fA-F]+[[:space:]]+[uUtTrR][[:space:]]+_R[^[:space:]]+$ ]]; then
+    exit 0
+  fi
+done < <(nm "$module")
+
+exit 1
scripts/kconfig/confdata.c +75 -0

99 lines not on this page · raw message

scripts/rust-version.sh new file +31 -0
new file mode 100755
index 000000000000..67b6d31688e2
@@ -0,0 +1,31 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+#
+# rust-version rust-command
+#
+# Print the compiler version of `rust-command' in a 5 or 6-digit form
+# such as `14502' for rustc-1.45.2 etc.
+#
+# Returns 0 if not found (so that Kconfig does not complain)
+compiler="$*"
+
+if [ ${#compiler} -eq 0 ]; then
+	echo "Error: No compiler specified." >&2
+	printf "Usage:\n\t$0 <rust-command>\n" >&2
+	exit 1
+fi
+
+if ! command -v $compiler >/dev/null 2>&1; then
+	echo 0
+	exit 0
+fi
+
+VERSION=$($compiler --version | cut -f2 -d' ')
+
+# Cut suffix if any (e.g. `-dev`)
+VERSION=$(echo $VERSION | cut -f1 -d'-')
+
+MAJOR=$(echo $VERSION | cut -f1 -d'.')
+MINOR=$(echo $VERSION | cut -f2 -d'.')
+PATCHLEVEL=$(echo $VERSION | cut -f3 -d'.')
+printf "%d%02d%02d\\n" $MAJOR $MINOR $PATCHLEVEL
Signature · 1 line
2.34.0
#28 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

Quoted 1 line · Miguel Ojeda

... snip ...

Miguel and team,
I'm happy to see progress here! Just some quick notes after a first pass.

Testing this series applied on mainline, I see:

$ make LLVM=1 -j72 defconfig
$ grep RUST .config
CONFIG_HAS_RUST=y
CONFIG_RUSTC_VERSION=14000
# CONFIG_RUST is not set
...
$ make LLVM=1 -j72 menuconfig
# enable CONFIG_RUST
$ make LLVM=1
...
  CALL    scripts/checksyscalls.sh
error: @path is unstable - use -Z unstable-options to enable its use

error: @path is unstable - use -Z unstable-options to enable its use

$ rustc --version
rustc 1.40.0 (73528e339 2019-12-16)

Can we update some Kconfig checks to fix that?

Makefile endif · line 129

Quoted 13 lines
Makefile +7 -0
@@ -120,6 +120,13 @@ endif
 
 export KBUILD_CHECKSRC
 
+# Enable "clippy" (a linter) as part of the Rust compilation.
+#
+# Use 'make CLIPPY=1' to enable it.
+ifeq ("$(origin CLIPPY)", "command line")
+  KBUILD_CLIPPY := $(CLIPPY)
+endif
+

KBUILD_CLIPPY isn't used until ...

Quoted 45 lines
Makefile +13 -1
 # Use make M=dir or set the environment variable KBUILD_EXTMOD to specify the
 # directory of external module to build. Setting M= takes precedence.
 ifeq ("$(origin M)", "command line")
@@ -267,7 +274,7 @@ no-dot-config-targets := $(clean-targets) \
                         cscope gtags TAGS tags help% %docs check% coccicheck \
                         $(version_h) headers headers_% archheaders archscripts \
                         %asm-generic kernelversion %src-pkg dt_binding_check \
-                        outputmakefile
+                        outputmakefile rustfmt rustfmtcheck
 # Installation targets should not require compiler. Unfortunately, vdso_install
 # is an exception where build artifacts may be updated. This must be fixed.
 no-compiler-targets := $(no-dot-config-targets) install dtbs_install \
@@ -461,6 +468,12 @@ OBJDUMP            = $(CROSS_COMPILE)objdump
 READELF                = $(CROSS_COMPILE)readelf
 STRIP          = $(CROSS_COMPILE)strip
 endif
+RUSTC          = rustc
+RUSTDOC                = rustdoc
+RUSTFMT                = rustfmt
+CLIPPY_DRIVER  = clippy-driver
+BINDGEN                = bindgen
+CARGO          = cargo
 PAHOLE         = pahole
 RESOLVE_BTFIDS = $(objtree)/tools/bpf/resolve_btfids/resolve_btfids
 LEX            = flex
@@ -486,9 +499,11 @@ CHECKFLAGS     := -D__linux__ -Dlinux -D__STDC__ -Dunix -D__unix__ \
                  -Wbitwise -Wno-return-void -Wno-unknown-attribute $(CF)
 NOSTDINC_FLAGS :=
 CFLAGS_MODULE   =
+RUSTFLAGS_MODULE =
 AFLAGS_MODULE   =
 LDFLAGS_MODULE  =
 CFLAGS_KERNEL  =
+RUSTFLAGS_KERNEL =
 AFLAGS_KERNEL  =
 LDFLAGS_vmlinux =
 
@@ -517,15 +532,46 @@ KBUILD_CFLAGS   := -Wall -Wundef -Werror=strict-prototypes -Wno-trigraphs \
                   -Werror=return-type -Wno-format-security \
                   -std=gnu89
 KBUILD_CPPFLAGS := -D__KERNEL__
+KBUILD_RUST_TARGET := $(srctree)/arch/$(SRCARCH)/rust/target.json
+KBUILD_RUSTFLAGS := --emit=dep-info,obj,metadata --edition=2021 \
+                    -Cpanic=abort -Cembed-bitcode=n -Clto=n -Crpath=n \
+                    -Cforce-unwind-tables=n -Ccodegen-units=1 \

Makefile KBUILD_CFLAGS := -Wall -Wundef -Werror=strict-prototypes -Wno-trigraphs \ · line 548

Quoted 10 lines
Makefile +10 -0
+                    -Zbinary_dep_depinfo=y -Zsymbol-mangling-version=v0 \
+                    -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::float_arithmetic \
+                    -Dclippy::let_unit_value -Dclippy::mut_mut \
+                    -Dclippy::needless_bitwise_bool -Dclippy::needless_continue \
+                    -Wclippy::dbg_macro

Consider putting clippy specific flags in their own variable, and/or just adding them to KBUILD_RUSTFLAGS only when clippy is actually being used.

Quoted 7 lines
Makefile +2 -0
 KBUILD_AFLAGS_KERNEL :=
 KBUILD_CFLAGS_KERNEL :=
+KBUILD_RUSTFLAGS_KERNEL :=
 KBUILD_AFLAGS_MODULE  := -DMODULE
 KBUILD_CFLAGS_MODULE  := -DMODULE
+KBUILD_RUSTFLAGS_MODULE := --cfg MODULE
 KBUILD_LDFLAGS_MODULE :=

Makefile KBUILD_CFLAGS := -Wall -Wundef -Werror=strict-prototypes -Wno-trigraphs \ · line 565

Quoted 10 lines
Makefile +7 -0
 KBUILD_LDFLAGS :=
 CLANG_FLAGS :=
 
+ifeq ($(KBUILD_CLIPPY),1)
+       RUSTC_OR_CLIPPY_QUIET := CLIPPY
+       RUSTC_OR_CLIPPY = $(CLIPPY_DRIVER)
+else
+       RUSTC_OR_CLIPPY_QUIET := RUSTC
+       RUSTC_OR_CLIPPY = $(RUSTC)
+endif

... here. Should we sink the check for origin CLIPPY? Can we also match how we check for LLVM=1 rather than checking the variables origin? Especially since KBUILD_CLIPPY isn't exported, it seems it's not used outside of this file, IIUC?

Makefile KBUILD_CFLAGS := -Wall -Wundef -Werror=strict-prototypes -Wno-trigraphs \ · line 571

Quoted 6 lines
Makefile +6 -0
+
+ifdef RUST_LIB_SRC
+       export RUST_LIB_SRC
+endif
+
+export RUSTC_BOOTSTRAP := 1

Is this used in a different patch in the series? ^

Quoted 30 lines
Makefile +6 -3
+
 export ARCH SRCARCH CONFIG_SHELL BASH HOSTCC KBUILD_HOSTCFLAGS CROSS_COMPILE LD CC
+export RUSTC RUSTDOC RUSTFMT RUSTC_OR_CLIPPY_QUIET RUSTC_OR_CLIPPY BINDGEN CARGO
 export CPP AR NM STRIP OBJCOPY OBJDUMP READELF PAHOLE RESOLVE_BTFIDS LEX YACC AWK INSTALLKERNEL
 export PERL PYTHON3 CHECK CHECKFLAGS MAKE UTS_MACHINE HOSTCXX
 export KGZIP KBZIP2 KLZOP LZMA LZ4 XZ ZSTD
@@ -533,9 +579,10 @@ export KBUILD_HOSTCXXFLAGS KBUILD_HOSTLDFLAGS KBUILD_HOSTLDLIBS LDFLAGS_MODULE
 
 export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS KBUILD_LDFLAGS
 export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE
+export KBUILD_RUST_TARGET KBUILD_RUSTFLAGS RUSTFLAGS_KERNEL RUSTFLAGS_MODULE
 export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
-export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_LDFLAGS_MODULE
-export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL
+export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_RUSTFLAGS_MODULE KBUILD_LDFLAGS_MODULE
+export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL KBUILD_RUSTFLAGS_KERNEL
 export PAHOLE_FLAGS
 
 # Files to ignore in find ... statements
@@ -727,7 +774,7 @@ $(KCONFIG_CONFIG):
 #
 # Do not use $(call cmd,...) here. That would suppress prompts from syncconfig,
 # so you cannot notice that Kconfig is waiting for the user input.
-%/config/auto.conf %/config/auto.conf.cmd %/generated/autoconf.h: $(KCONFIG_CONFIG)
+%/config/auto.conf %/config/auto.conf.cmd %/generated/autoconf.h %/generated/rustc_cfg: $(KCONFIG_CONFIG)
        $(Q)$(kecho) "  SYNC    $@"
        $(Q)$(MAKE) -f $(srctree)/Makefile syncconfig
 else # !may-sync-config
@@ -756,11 +803,27 @@ KBUILD_CFLAGS     += $(call cc-disable-warning, address-of-packed-member)
 

Makefile KBUILD_CFLAGS += $(call cc-disable-warning, address-of-packed-member) · line 812

Quoted 10 lines
Makefile +3 -1
 ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE
 KBUILD_CFLAGS += -O2
+KBUILD_RUSTFLAGS_OPT_LEVEL_MAP := 2
 else ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE_O3
 KBUILD_CFLAGS += -O3
+KBUILD_RUSTFLAGS_OPT_LEVEL_MAP := 3
 else ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
 KBUILD_CFLAGS += -Os
-endif
+KBUILD_RUSTFLAGS_OPT_LEVEL_MAP := z

If z and s are distinct opt levels, then rustc should really be using s rather than z. IME, z has created larger images than s due to LLVM aggressively emitting libcalls, regardless of the cost of call setup. See also commit a75bb4eb9e56 ("Revert "kbuild: use -Oz instead of -Os when using clang")

Quoted 4 lines
Makefile +4 -0
+endif
+
+# Always set `debug-assertions` and `overflow-checks` because their default
+# depends on `opt-level` and `debug-assertions`, respectively.

Makefile KBUILD_CFLAGS += $(call cc-disable-warning, address-of-packed-member) · line 826

Quoted 10 lines
Makefile +10 -0
+KBUILD_RUSTFLAGS += -Cdebug-assertions=$(if $(CONFIG_RUST_DEBUG_ASSERTIONS),y,n)
+KBUILD_RUSTFLAGS += -Coverflow-checks=$(if $(CONFIG_RUST_OVERFLOW_CHECKS),y,n)
+KBUILD_RUSTFLAGS += -Copt-level=$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C),$(KBUILD_RUSTFLAGS_OPT_LEVEL_MAP))$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_0),0)$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_1),1)$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_2),2)$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_3),3)$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_S),s)$\
+       $(if $(CONFIG_RUST_OPT_LEVEL_Z),z)

I'm still not a fan of this separate configurability for optimization level differing from C.

Quoted 172 lines
Makefile +70 -3
 # Tell gcc to never replace conditional load with a non-conditional one
 ifdef CONFIG_CC_IS_GCC
@@ -791,6 +854,9 @@ KBUILD_CFLAGS += $(stackp-flags-y)
 KBUILD_CFLAGS-$(CONFIG_WERROR) += -Werror
 KBUILD_CFLAGS += $(KBUILD_CFLAGS-y) $(CONFIG_CC_IMPLICIT_FALLTHROUGH)
 
+KBUILD_RUSTFLAGS-$(CONFIG_WERROR) += -Dwarnings
+KBUILD_RUSTFLAGS += $(KBUILD_RUSTFLAGS-y)
+
 ifdef CONFIG_CC_IS_CLANG
 KBUILD_CPPFLAGS += -Qunused-arguments
 # The kernel builds with '-std=gnu89' so use of GNU extensions is acceptable.
@@ -812,6 +878,7 @@ KBUILD_CFLAGS += $(call cc-disable-warning, unused-const-variable)
 
 ifdef CONFIG_FRAME_POINTER
 KBUILD_CFLAGS  += -fno-omit-frame-pointer -fno-optimize-sibling-calls
+KBUILD_RUSTFLAGS += -Cforce-frame-pointers=y
 else
 # Some targets (ARM with Thumb2, for example), can't be built with frame
 # pointers.  For those, we don't have FUNCTION_TRACER automatically
@@ -1022,10 +1089,11 @@ include $(addprefix $(srctree)/, $(include-y))
 # Do not add $(call cc-option,...) below this line. When you build the kernel
 # from the clean source tree, the GCC plugins do not exist at this point.
 
-# Add user supplied CPPFLAGS, AFLAGS and CFLAGS as the last assignments
+# Add user supplied CPPFLAGS, AFLAGS, CFLAGS and RUSTFLAGS as the last assignments
 KBUILD_CPPFLAGS += $(KCPPFLAGS)
 KBUILD_AFLAGS   += $(KAFLAGS)
 KBUILD_CFLAGS   += $(KCFLAGS)
+KBUILD_RUSTFLAGS += $(KRUSTFLAGS)
 
 KBUILD_LDFLAGS_MODULE += --build-id=sha1
 LDFLAGS_vmlinux += --build-id=sha1
@@ -1095,6 +1163,11 @@ ifeq ($(KBUILD_EXTMOD),)
 core-y                 += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/
 core-$(CONFIG_BLOCK)   += block/
 
+# Keep this one as an `ifdef` block since its `Makefile` runs `rustc`.
+ifdef CONFIG_RUST
+core-y                 += rust/
+endif
+
 vmlinux-dirs   := $(patsubst %/,%,$(filter %/, \
                     $(core-y) $(core-m) $(drivers-y) $(drivers-m) \
                     $(libs-y) $(libs-m)))
@@ -1195,6 +1268,9 @@ archprepare: outputmakefile archheaders archscripts scripts include/config/kerne
 prepare0: archprepare
        $(Q)$(MAKE) $(build)=scripts/mod
        $(Q)$(MAKE) $(build)=.
+ifdef CONFIG_RUST
+       $(Q)$(MAKE) $(build)=rust
+endif
 
 # All the preparing..
 prepare: prepare0
@@ -1495,7 +1571,7 @@ endif # CONFIG_MODULES
 # Directories & files removed with 'make clean'
 CLEAN_FILES += include/ksym vmlinux.symvers modules-only.symvers \
               modules.builtin modules.builtin.modinfo modules.nsdeps \
-              compile_commands.json .thinlto-cache
+              compile_commands.json .thinlto-cache rust/test rust/doc
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_FILES += include/config include/generated          \
@@ -1506,7 +1582,8 @@ MRPROPER_FILES += include/config include/generated          \
                  certs/signing_key.pem certs/signing_key.x509 \
                  certs/x509.genkey \
                  vmlinux-gdb.py \
-                 *.spec
+                 *.spec \
+                 rust/*_generated.h rust/*_generated.rs rust/libmacros.so
 
 # clean - Delete most, but leave enough to build external modules
 #
@@ -1618,6 +1695,17 @@ help:
        @echo  '  kselftest-merge   - Merge all the config dependencies of'
        @echo  '                      kselftest to existing .config.'
        @echo  ''
+       @echo  'Rust targets:'
+       @echo  '  rustfmt         - Reformat all the Rust code in the kernel'
+       @echo  '  rustfmtcheck    - Checks if all the Rust code in the kernel'
+       @echo  '                    is formatted, printing a diff otherwise.'
+       @echo  '  rustdoc         - Generate Rust documentation'
+       @echo  '                    (requires kernel .config)'
+       @echo  '  rusttest        - Runs the Rust tests'
+       @echo  '                    (requires kernel .config; downloads external repos)'
+       @echo  '  rust-analyzer   - Generate rust-project.json rust-analyzer support file'
+       @echo  '                    (requires kernel .config)'
+       @echo  ''
        @$(if $(dtstree), \
                echo 'Devicetree:'; \
                echo '* dtbs             - Build device tree blobs for enabled boards'; \
@@ -1689,6 +1777,47 @@ PHONY += $(DOC_TARGETS)
 $(DOC_TARGETS):
        $(Q)$(MAKE) $(build)=Documentation $@
 
+
+# Rust targets
+# ---------------------------------------------------------------------------
+
+# Documentation target
+#
+# Using the singular to avoid running afoul of `no-dot-config-targets`.
+PHONY += rustdoc
+rustdoc: prepare0
+       $(Q)$(MAKE) $(build)=rust $@
+
+# Testing target
+PHONY += rusttest
+rusttest: prepare0
+       $(Q)$(MAKE) $(build)=rust $@
+
+# Formatting targets
+PHONY += rustfmt rustfmtcheck
+
+# We skip `rust/alloc` since we want to minimize the diff w.r.t. upstream.
+#
+# We match using absolute paths since `find` does not resolve them
+# when matching, which is a problem when e.g. `srctree` is `..`.
+# We `grep` afterwards in order to remove the directory entry itself.
+rustfmt:
+       $(Q)find $(abs_srctree) -type f -name '*.rs' \
+               -o -path $(abs_srctree)/rust/alloc -prune \
+               -o -path $(abs_objtree)/rust/test -prune \
+               | grep -Fv $(abs_srctree)/rust/alloc \
+               | grep -Fv $(abs_objtree)/rust/test \
+               | grep -Fv generated \
+               | xargs $(RUSTFMT) $(rustfmt_flags)
+
+rustfmtcheck: rustfmt_flags = --check
+rustfmtcheck: rustfmt
+
+# IDE support targets
+PHONY += rust-analyzer
+rust-analyzer: prepare0
+       $(Q)$(MAKE) $(build)=rust $@
+
 # Misc
 # ---------------------------------------------------------------------------
 
@@ -1856,6 +1985,7 @@ clean: $(clean-dirs)
        $(call cmd,rmfiles)
        @find $(if $(KBUILD_EXTMOD), $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \
                \( -name '*.[aios]' -o -name '*.ko' -o -name '.*.cmd' \
+               -o -name '*.rmeta' \
                -o -name '*.ko.*' \
                -o -name '*.dtb' -o -name '*.dtbo' -o -name '*.dtb.S' -o -name '*.dt.yaml' \
                -o -name '*.dwo' -o -name '*.lst' \
arch/arm/rust/target.json new file +17 -0
new file mode 100644
index 000000000000..3f845b8221dc
@@ -0,0 +1,27 @@
+{
+  "arch": "arm",
+  "crt-static-respected": true,
+  "data-layout": "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64",
+  "dynamic-linking": true,
+  "env": "gnu",
+  "executables": true,
+  "features": "+strict-align,+v6",
+  "function-sections": false,
+  "has-elf-tls": true,
+  "has-rpath": true,
+  "linker-is-gnu": true,
+  "llvm-target": "arm-unknown-linux-gnueabi",
+  "max-atomic-width": 64,
+  "os": "linux",
+  "position-independent-executables": true,
+  "pre-link-args": {

arch/arm/rust/target.json line 27

Quoted 10 lines
arch/arm/rust/target.json new file +10 -0
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack"
+    ]
+  },
+  "relocation-model": "static",
+  "target-family": "unix",
+  "target-mcount": "\u0001__gnu_mcount_nc",
+  "target-pointer-width": "32"
+}

oh boy. I wonder which configs change the above values? ;) Can rustc still override these via command line flags?

Quoted 372 lines
arch/arm64/rust/target.json new file +34 -0
new file mode 100644
index 000000000000..09a264df26c7
@@ -0,0 +1,34 @@
+{
+  "arch": "aarch64",
+  "data-layout": "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+strict-align,+neon,+fp-armv8",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "aarch64-unknown-none",
+  "max-atomic-width": 128,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/powerpc/rust/target.json new file +29 -0
new file mode 100644
index 000000000000..2420c8e6a520
@@ -0,0 +1,29 @@
+{
+  "arch": "powerpc64",
+  "code-model": "large",
+  "cpu": "ppc64le",
+  "data-layout": "e-m:e-i64:64-n32:64",
+  "env": "gnu",
+  "features": "-altivec,-vsx,-hard-float",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "powerpc64le-elf",
+  "max-atomic-width": 64,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "target-family": "unix",
+  "target-mcount": "_mcount",
+  "target-endian": "little",
+  "target-pointer-width": "64"
+}
arch/riscv/Makefile +1 -0
index 8a107ed18b0d..0487db1e54c6 100644
@@ -52,6 +52,7 @@ riscv-march-$(CONFIG_FPU)             := $(riscv-march-y)fd
 riscv-march-$(CONFIG_RISCV_ISA_C)      := $(riscv-march-y)c
 KBUILD_CFLAGS += -march=$(subst fd,,$(riscv-march-y))
 KBUILD_AFLAGS += -march=$(riscv-march-y)
+KBUILD_RUST_TARGET := $(srctree)/arch/riscv/rust/$(subst fd,,$(riscv-march-y)).json
 
 KBUILD_CFLAGS += -mno-save-restore
 KBUILD_CFLAGS += -DCONFIG_PAGE_OFFSET=$(CONFIG_PAGE_OFFSET)
arch/riscv/rust/rv32ima.json new file +36 -0
new file mode 100644
index 000000000000..bcdda88c1604
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv32",
+  "code-model": "medium",
+  "cpu": "generic-rv32",
+  "data-layout": "e-m:e-p:32:32-i64:64-n32-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv32",
+  "max-atomic-width": 32,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m32"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "32",
+  "vendor": ""
+}
arch/riscv/rust/rv32imac.json new file +36 -0
new file mode 100644
index 000000000000..45873c10a5c3
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv32",
+  "code-model": "medium",
+  "cpu": "generic-rv32",
+  "data-layout": "e-m:e-p:32:32-i64:64-n32-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a,+c",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv32",
+  "max-atomic-width": 32,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m32"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "32",
+  "vendor": ""
+}
arch/riscv/rust/rv64ima.json new file +36 -0
new file mode 100644
index 000000000000..853d758c5461
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv64",
+  "code-model": "medium",
+  "cpu": "generic-rv64",
+  "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv64",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/riscv/rust/rv64imac.json new file +36 -0
new file mode 100644
index 000000000000..ce50ee8e8c93
@@ -0,0 +1,36 @@
+{
+  "arch": "riscv64",
+  "code-model": "medium",
+  "cpu": "generic-rv64",
+  "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "+m,+a,+c",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "riscv64",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": ""
+}
arch/x86/rust/target.json new file +36 -0
new file mode 100644
index 000000000000..379cf39e8941
@@ -0,0 +1,36 @@
+{
+  "arch": "x86_64",
+  "code-model": "kernel",
+  "cpu": "x86-64",
+  "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128",
+  "disable-redzone": true,
+  "emit-debug-gdb-scripts": false,
+  "env": "gnu",
+  "features": "-mmx,-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-3dnow,-3dnowa,-avx,-avx2,+soft-float",
+  "frame-pointer": "always",
+  "function-sections": false,
+  "linker-flavor": "gcc",
+  "linker-is-gnu": true,
+  "llvm-target": "x86_64-elf",
+  "max-atomic-width": 64,
+  "needs-plt": true,
+  "os": "none",
+  "panic-strategy": "abort",
+  "position-independent-executables": true,
+  "pre-link-args": {
+    "gcc": [
+      "-Wl,--as-needed",
+      "-Wl,-z,noexecstack",
+      "-m64"
+    ]
+  },
+  "relocation-model": "static",
+  "relro-level": "full",
+  "stack-probes": {
+    "kind": "none"
+  },
+  "target-c-int-width": "32",
+  "target-endian": "little",
+  "target-pointer-width": "64",
+  "vendor": "unknown"
+}
init/Kconfig +30 -1
index 4b7bac10c72d..03d3c21e28a3 100644
@@ -60,6 +60,15 @@ config LLD_VERSION
        default $(ld-version) if LD_IS_LLD
        default 0
 
+config HAS_RUST
+       depends on ARM64 || CPU_32v6 || CPU_32v6K || (PPC64 && CPU_LITTLE_ENDIAN) || X86_64 || RISCV
+       def_bool $(success,$(RUSTC) --version)
+
+config RUSTC_VERSION
+       depends on HAS_RUST
+       int
+       default $(shell,$(srctree)/scripts/rust-version.sh $(RUSTC))
+
 config CC_CAN_LINK
        bool
        default $(success,$(srctree)/scripts/cc-can-link.sh $(CC) $(CLANG_FLAGS) $(m64-flag)) if 64BIT
@@ -142,7 +151,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,
@@ -2044,6 +2054,25 @@ config PROFILING
          Say Y here to enable the extended profiling support mechanisms used
          by profilers.
 
+config RUST
+       bool "Rust support"
+       depends on HAS_RUST
+       depends on !COMPILE_TEST
+       depends on !MODVERSIONS
+       default n
+       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.
+
 #
 # Place an empty function call at each tracepoint site. Can be
 # dynamically changed for a probe function.
lib/Kconfig.debug +11 -0
index 5c12bde10996..361379695f18 100644
@@ -2650,6 +2650,150 @@ config HYPERV_TESTING
 
 endmenu # "Kernel Testing and Coverage"
 
+menu "Rust hacking"
+
+config RUST_DEBUG_ASSERTIONS
+       bool "Debug assertions"
+       default n
+       depends on RUST
+       help
+         Enables rustc's `-Cdebug-assertions` codegen option.
+
+         This flag lets you turn `cfg(debug_assertions)` conditional
+         compilation on or off. This can be used to enable extra debugging

lib/Kconfig.debug config HYPERV_TESTING · line 2673

Quoted 10 lines
lib/Kconfig.debug +10 -0
+         code in development but not in production. For example, it controls
+         the behavior of the standard library's `debug_assert!` macro.
+
+         Note that this will apply to all Rust code, including `core`.
+
+         If unsure, say N.
+
+config RUST_OVERFLOW_CHECKS
+       bool "Overflow checks"
+       default y

So this is like turning on -fsanitize=signed-integer-overflow and -fsanitize=unsigned-integer-overflow by default?

lib/Kconfig.debug config HYPERV_TESTING · line 2680

Quoted 7 lines
lib/Kconfig.debug +7 -0
+       depends on RUST
+       help
+         Enables rustc's `-Coverflow-checks` codegen option.
+
+         This flag allows you to control the behavior of runtime integer
+         overflow. When overflow-checks are enabled, a panic will occur
+         on overflow.

A rust panic or a kernel panic?

Quoted 20 lines
lib/Kconfig.debug +20 -0
+
+         Note that this will apply to all Rust code, including `core`.
+
+         If unsure, say Y.
+
+choice
+       prompt "Optimization level"
+       default RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C
+       depends on RUST
+       help
+         Controls rustc's `-Copt-level` codegen option.
+
+         This flag controls the optimization level.
+
+         If unsure, say "Similar as chosen for C".
+
+config RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C
+       bool "Similar as chosen for C"
+       help
+         This choice will pick a similar optimization level as chosen in

lib/Kconfig.debug config HYPERV_TESTING · line 2710

Quoted 10 lines
lib/Kconfig.debug +10 -0
+         the "Compiler optimization level" for C:
+
+             -O2 is currently mapped to -Copt-level=2
+             -O3 is currently mapped to -Copt-level=3
+             -Os is currently mapped to -Copt-level=z
+
+         The mapping may change over time to follow the intended semantics
+         of the choice for C as sensibly as possible.
+
+         This is the default.

This should really be the only option here. I still don't see the point of allowing wacky combinations of configs where we differ from C code. The more combinations will just frustrate randconfig builds.

Quoted 197 lines
lib/Kconfig.debug +86 -0
+
+config RUST_OPT_LEVEL_0
+       bool "No optimizations (-Copt-level=0)"
+       help
+         Not recommended for most purposes. It may come in handy for debugging
+         suspected optimizer bugs, unexpected undefined behavior, etc.
+
+         Note that this level will *not* enable debug assertions nor overflow
+         checks on its own (like it happens when interacting with rustc
+         directly). Use the corresponding configuration options to control
+         that instead, orthogonally.
+
+         Note this level may cause excessive stack usage, which can lead to stack
+         overflow and subsequent crashes.
+
+config RUST_OPT_LEVEL_1
+       bool "Basic optimizations (-Copt-level=1)"
+       help
+         Useful for debugging without getting too lost, but without
+         the overhead and boilerplate of no optimizations at all.
+
+         Note this level may cause excessive stack usage, which can lead to stack
+         overflow and subsequent crashes.
+
+config RUST_OPT_LEVEL_2
+       bool "Some optimizations (-Copt-level=2)"
+       help
+         The sensible choice in most cases.
+
+config RUST_OPT_LEVEL_3
+       bool "All optimizations (-Copt-level=3)"
+       help
+         Yet more performance (hopefully).
+
+config RUST_OPT_LEVEL_S
+       bool "Optimize for size (-Copt-level=s)"
+       help
+         Smaller kernel, ideally without too much performance loss.
+
+config RUST_OPT_LEVEL_Z
+       bool "Optimize for size, no loop vectorization (-Copt-level=z)"
+       help
+         Like the previous level, but also turn off loop vectorization.
+
+endchoice
+
+choice
+       prompt "Build-time assertions"
+       default RUST_BUILD_ASSERT_ALLOW if RUST_OPT_LEVEL_0
+       default RUST_BUILD_ASSERT_DENY if !RUST_OPT_LEVEL_0
+       depends on RUST
+       help
+         Controls how are `build_error!` and `build_assert!` handled during build.
+
+         If calls to them exist in the binary, it may indicate a violated invariant
+         or that the optimizer failed to verify the invariant during compilation.
+         You can choose to abort compilation or ignore them during build and let the
+         check be carried to runtime.
+
+         If optimizations are turned off, you cannot select "Deny".
+
+         If unsure, say "Deny".
+
+config RUST_BUILD_ASSERT_ALLOW
+       bool "Allow"
+       help
+         Unoptimized calls to `build_error!` will be converted to `panic!`
+         and checked at runtime.
+
+config RUST_BUILD_ASSERT_WARN
+       bool "Warn"
+       help
+         Unoptimized calls to `build_error!` will be converted to `panic!`
+         and checked at runtime, but warnings will be generated when building.
+
+config RUST_BUILD_ASSERT_DENY
+       bool "Deny"
+       depends on !RUST_OPT_LEVEL_0
+       help
+         Unoptimized calls to `build_error!` will abort compilation.
+
+endchoice
+
+
+endmenu # "Rust"
+
 source "Documentation/Kconfig"
 
 endmenu # Kernel hacking
rust/.gitignore new file +7 -0
new file mode 100644
index 000000000000..168cb26a31b9
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+
+bindings_generated.rs
+bindings_helpers_generated.rs
+exports_*_generated.h
+doc/
+test/
rust/Makefile new file +89 -0
new file mode 100644
index 000000000000..2d08314e7031
@@ -0,0 +1,353 @@
+# SPDX-License-Identifier: GPL-2.0
+
+obj-$(CONFIG_RUST) += core.o compiler_builtins.o helpers.o
+extra-$(CONFIG_RUST) += exports_core_generated.h
+
+extra-$(CONFIG_RUST) += libmacros.so
+
+extra-$(CONFIG_RUST) += bindings_generated.rs bindings_helpers_generated.rs
+obj-$(CONFIG_RUST) += alloc.o kernel.o
+extra-$(CONFIG_RUST) += exports_alloc_generated.h exports_kernel_generated.h
+
+ifdef CONFIG_RUST_BUILD_ASSERT_DENY
+extra-$(CONFIG_RUST) += build_error.o
+else
+obj-$(CONFIG_RUST) += build_error.o
+endif
+
+obj-$(CONFIG_RUST) += exports.o
+
+ifeq ($(quiet),silent_)
+cargo_quiet=-q
+rust_test_quiet=-q
+rustdoc_test_quiet=--test-args -q
+else ifeq ($(quiet),quiet_)
+rust_test_quiet=-q
+rustdoc_test_quiet=--test-args -q
+else
+cargo_quiet=--verbose
+endif
+
+core-cfgs = \
+    --cfg no_fp_fmt_parse
+
+alloc-cfgs = \
+    --cfg no_global_oom_handling \
+    --cfg no_rc \
+    --cfg no_sync
+
+quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $<
+      cmd_rustdoc = \
+       OBJTREE=$(abspath $(objtree)) \
+       $(RUSTDOC) $(if $(rustdoc_host),,$(rust_cross_flags)) \
+               $(filter-out -Cpanic=abort, $(filter-out --emit=%, $(rust_flags))) \
+               $(rustc_target_flags) -L $(objtree)/rust \
+               --output $(objtree)/rust/doc --crate-name $(subst rustdoc-,,$@) \
+               @$(objtree)/include/generated/rustc_cfg $<
+
+rustdoc: rustdoc-core rustdoc-macros rustdoc-compiler_builtins rustdoc-alloc rustdoc-kernel
+       $(Q)cp $(srctree)/Documentation/rust/assets/* $(objtree)/rust/doc
+
+rustdoc-macros: private rustdoc_host = yes
+rustdoc-macros: private rustc_target_flags = --crate-type proc-macro \
+    --extern proc_macro
+rustdoc-macros: $(srctree)/rust/macros/lib.rs FORCE
+       $(call if_changed,rustdoc)
+
+rustdoc-compiler_builtins: $(srctree)/rust/compiler_builtins.rs rustdoc-core FORCE
+       $(call if_changed,rustdoc)
+
+# We need to allow `rustdoc::broken_intra_doc_links` because some
+# `no_global_oom_handling` functions refer to non-`no_global_oom_handling`
+# functions. Ideally `rustdoc` would have a way to distinguish broken links
+# due to things that are "configured out" vs. entirely non-existing ones.
+rustdoc-alloc: private rustc_target_flags = $(alloc-cfgs) \
+    -Arustdoc::broken_intra_doc_links
+rustdoc-alloc: $(srctree)/rust/alloc/lib.rs rustdoc-core \
+    rustdoc-compiler_builtins FORCE
+       $(call if_changed,rustdoc)
+
+rustdoc-kernel: private rustc_target_flags = --extern alloc \
+    --extern build_error \
+    --extern macros=$(objtree)/rust/libmacros.so
+rustdoc-kernel: $(srctree)/rust/kernel/lib.rs rustdoc-core \
+    rustdoc-macros rustdoc-compiler_builtins rustdoc-alloc \
+    $(objtree)/rust/libmacros.so $(objtree)/rust/bindings_generated.rs \
+    $(objtree)/rust/bindings_helpers_generated.rs FORCE
+       $(call if_changed,rustdoc)
+
+quiet_cmd_rustc_test_library = RUSTC TL $<
+      cmd_rustc_test_library = \
+       OBJTREE=$(abspath $(objtree)) \
+       $(RUSTC) $(filter-out --sysroot=%, $(filter-out -Cpanic=abort, $(filter-out --emit=%, $(rust_flags)))) \
+               $(rustc_target_flags) --crate-type $(if $(rustc_test_library_proc),proc-macro,rlib) \
+               --out-dir $(objtree)/rust/test/ --cfg testlib \
+               --sysroot $(objtree)/rust/test/sysroot \
+               -L $(objtree)/rust/test/ --crate-name $(subst rusttest-,,$(subst rusttestlib-,,$@)) $<
+
+rusttestlib-build_error: $(srctree)/rust/build_error.rs rusttest-prepare FORCE
+       $(call if_changed,rustc_test_library)

rust/Makefile line 99

Quoted 10 lines
rust/Makefile new file +10 -0
+
+rusttestlib-macros: private rustc_target_flags = --extern proc_macro
+rusttestlib-macros: private rustc_test_library_proc = yes
+rusttestlib-macros: $(srctree)/rust/macros/lib.rs rusttest-prepare FORCE
+       $(call if_changed,rustc_test_library)
+
+quiet_cmd_rustdoc_test = RUSTDOC T $<
+      cmd_rustdoc_test = \
+       OBJTREE=$(abspath $(objtree)) \
+       $(RUSTDOC) --test $(filter-out --sysroot=%, $(filter-out -Cpanic=abort, $(filter-out --emit=%, $(rust_flags)))) \

Seeing repeated filter-out rules makes me wonder if we could DRY up some of these rules with function definitions?

Quoted 30 lines
rust/Makefile new file +30 -0
+               $(rustc_target_flags) $(rustdoc_test_target_flags) \
+               --sysroot $(objtree)/rust/test/sysroot $(rustdoc_test_quiet) \
+               -L $(objtree)/rust/test \
+               --output $(objtree)/rust/doc --crate-name $(subst rusttest-,,$@) \
+               @$(objtree)/include/generated/rustc_cfg $<
+
+# We cannot use `-Zpanic-abort-tests` because some tests are dynamic,
+# so for the moment we skip `-Cpanic=abort`.
+quiet_cmd_rustc_test = RUSTC T  $<
+      cmd_rustc_test = \
+       OBJTREE=$(abspath $(objtree)) \
+       $(RUSTC) --test $(filter-out --sysroot=%, $(filter-out -Cpanic=abort, $(filter-out --emit=%, $(rust_flags)))) \
+               $(rustc_target_flags) --out-dir $(objtree)/rust/test \
+               --sysroot $(objtree)/rust/test/sysroot \
+               -L $(objtree)/rust/test/ --crate-name $(subst rusttest-,,$@) $<; \
+       $(objtree)/rust/test/$(subst rusttest-,,$@) $(rust_test_quiet) \
+               $(rustc_test_run_flags)
+
+rusttest: rusttest-macros rusttest-kernel
+
+# This prepares a custom sysroot with our custom `alloc` instead of
+# the standard one.
+#
+# This requires several hacks:
+#   - Unlike `core` and `alloc`, `std` depends on more than a dozen crates,
+#     including third-party crates that need to be downloaded, plus custom
+#     `build.rs` steps. Thus hardcoding things here is not maintainable.
+#   - `cargo` knows how to build the standard library, but it is an unstable
+#     feature so far (`-Zbuild-std`).
+#   - `cargo` only considers the use case of building the standard library

rust/Makefile line 139

Quoted 10 lines
rust/Makefile new file +10 -0
+#     to use it in a given package. Thus we need to create a dummy package
+#     and pick the generated libraries from there.
+#   - Since we only keep a subset of upstream `alloc` in-tree, we need
+#     to recreate it on the fly by putting our sources on top.
+#   - The usual ways of modifying the dependency graph in `cargo` do not seem
+#     to apply for the `-Zbuild-std` steps, thus we have to mislead it
+#     by modifying the sources in the sysroot.
+#   - To avoid messing with the user's Rust installation, we create a clone
+#     of the sysroot. However, `cargo` ignores `RUSTFLAGS` in the `-Zbuild-std`
+#     steps, thus we use a wrapper binary passed via `RUSTC` to pass the flag.

Are there links to corresponding feature requests upstream so that one day we can drop technical debt here? In particular, having to create a custom sysroot as is done here isn't particularly pretty.

I'd be curious if we could remove the dependency on cargo for rust tests.

Quoted 43 lines
rust/Makefile new file +43 -0
+#
+# In the future, we hope to avoid the whole ordeal by either:
+#   - Making the `test` crate not depend on `std` (either improving upstream
+#     or having our own custom crate).
+#   - Making the tests run in kernel space (requires the previous point).
+#   - Making `std` and friends be more like a "normal" crate, so that
+#     `-Zbuild-std` and related hacks are not needed.
+quiet_cmd_rustsysroot = RUSTSYSROOT
+      cmd_rustsysroot = \
+       rm -rf $(objtree)/rust/test; \
+       mkdir -p $(objtree)/rust/test; \
+       cp -a $(rustc_sysroot) $(objtree)/rust/test/sysroot; \
+       cp -r $(srctree)/rust/alloc/* \
+               $(objtree)/rust/test/sysroot/lib/rustlib/src/rust/library/alloc/src; \
+       echo '\#!/bin/sh' > $(objtree)/rust/test/rustc_sysroot; \
+       echo "$(RUSTC) --sysroot=$(abspath $(objtree)/rust/test/sysroot) \"\$$@\"" \
+               >> $(objtree)/rust/test/rustc_sysroot; \
+       chmod u+x $(objtree)/rust/test/rustc_sysroot; \
+       $(CARGO) -q new $(objtree)/rust/test/dummy; \
+       RUSTC=$(objtree)/rust/test/rustc_sysroot $(CARGO) $(cargo_quiet) \
+               test -Zbuild-std --target $(rustc_host_target) \
+               --manifest-path $(objtree)/rust/test/dummy/Cargo.toml; \
+       rm $(objtree)/rust/test/sysroot/lib/rustlib/$(rustc_host_target)/lib/*; \
+       cp $(objtree)/rust/test/dummy/target/$(rustc_host_target)/debug/deps/* \
+               $(objtree)/rust/test/sysroot/lib/rustlib/$(rustc_host_target)/lib
+
+rusttest-prepare: FORCE
+       $(call if_changed,rustsysroot)
+
+rusttest-macros: private rustc_target_flags = --extern proc_macro
+rusttest-macros: private rustdoc_test_target_flags = --crate-type proc-macro
+rusttest-macros: $(srctree)/rust/macros/lib.rs rusttest-prepare FORCE
+       $(call if_changed,rustc_test)
+       $(call if_changed,rustdoc_test)
+
+rusttest-kernel: private rustc_target_flags = --extern alloc \
+    --extern build_error --extern macros
+rusttest-kernel: private rustc_test_run_flags = \
+    --skip bindgen_test_layout_
+rusttest-kernel: $(srctree)/rust/kernel/lib.rs rusttest-prepare \
+    rusttestlib-build_error rusttestlib-macros FORCE
+       $(call if_changed,rustc_test)
+       $(call if_changed,rustc_test_library)

rust/Makefile line 192

Quoted 10 lines
rust/Makefile new file +10 -0
+       $(call if_changed,rustdoc_test)
+
+ifdef CONFIG_CC_IS_CLANG
+bindgen_c_flags = $(c_flags)
+else
+# bindgen relies on libclang to parse C. Ideally, bindgen would support a GCC
+# plugin backend and/or the Clang driver would be perfectly compatible with GCC.
+#
+# For the moment, here we are tweaking the flags on the fly. Some config
+# options may not work (e.g. `GCC_PLUGIN_RANDSTRUCT` if we end up using one

Do we denote the conflict in KCONFIG?

Quoted 4 lines
rust/Makefile new file +4 -0
+# of those structs).
+bindgen_skip_c_flags := -mno-fp-ret-in-387 -mpreferred-stack-boundary=% \
+       -mskip-rax-setup -mgeneral-regs-only -msign-return-address=% \
+       -mindirect-branch=thunk-extern -mindirect-branch-register -mrecord-mcount \

rust/Makefile line 206

Quoted 10 lines
rust/Makefile new file +10 -0
+       -mabi=lp64 -mstack-protector-guard% -fconserve-stack -falign-jumps=% \
+       -falign-loops=% -femit-struct-debug-baseonly \
+       -fno-ipa-cp-clone -fno-ipa-sra -fno-partial-inlining \
+       -fplugin-arg-arm_ssp_per_task_plugin-% \
+       -fno-reorder-blocks -fno-allow-store-data-races -fasan-shadow-offset=% \
+       -Wno-packed-not-aligned -Wno-format-truncation -Wno-format-overflow \
+       -Wno-stringop-truncation -Wno-unused-but-set-variable \
+       -Wno-stringop-overflow -Wno-restrict -Wno-maybe-uninitialized \
+       -Werror=designated-init -Wno-zero-length-bounds \
+       -Wno-alloc-size-larger-than --param=% --param asan-%

Why do we need to strip out all these warning flags when running bindgen? Should be just be using -w to silence all warnings from clang when invoking bindgen?

rust/Makefile line 213

Quoted 7 lines
rust/Makefile new file +7 -0
+
+# We need to keep the quotes for this one -- it comes from a `Kconfig`
+bindgen_skip_c_flags += "-Wimplicit-fallthrough=%"
+
+# PowerPC
+bindgen_skip_c_flags += -mtraceback=no -mno-pointers-to-nested-functions \
+       -mno-string -mno-strict-align

I don't understand why the PowerPC specific flags are pulled out, but the x86 specific ones (like most of the -m flags in the initial defiition of bindgen_skip_c_flags) are not.

Quoted 45 lines
rust/Makefile new file +45 -0
+
+# Derived from `scripts/Makefile.clang`
+BINDGEN_TARGET_arm     := arm-linux-gnueabi
+BINDGEN_TARGET_arm64   := aarch64-linux-gnu
+BINDGEN_TARGET_powerpc := powerpc64le-linux-gnu
+BINDGEN_TARGET_riscv   := riscv64-linux-gnu
+BINDGEN_TARGET_x86     := x86_64-linux-gnu
+BINDGEN_TARGET         := $(BINDGEN_TARGET_$(SRCARCH))
+
+bindgen_extra_c_flags = --target=$(BINDGEN_TARGET) \
+       -Wno-address-of-packed-member \
+       -Wno-gnu-variable-sized-type-not-at-end
+bindgen_c_flags = $(filter-out $(bindgen_skip_c_flags), $(c_flags)) \
+       $(bindgen_extra_c_flags)
+endif
+
+ifdef CONFIG_LTO
+bindgen_c_flags_lto = $(filter-out $(CC_FLAGS_LTO), $(bindgen_c_flags))
+else
+bindgen_c_flags_lto = $(bindgen_c_flags)
+endif
+
+# To avoid several recompilations in PowerPC, which inserts `-D_TASK_CPU`
+bindgen_c_flags_final = $(filter-out -D_TASK_CPU=%, $(bindgen_c_flags_lto))
+
+quiet_cmd_bindgen = BINDGEN $@
+      cmd_bindgen = \
+       $(BINDGEN) $< $(shell grep -v '^\#\|^$$' $(srctree)/rust/bindgen_parameters) \
+               --use-core --with-derive-default --ctypes-prefix c_types \
+               --no-debug '.*' \
+               --size_t-is-usize -o $@ -- $(bindgen_c_flags_final) -DMODULE
+
+$(objtree)/rust/bindings_generated.rs: $(srctree)/rust/kernel/bindings_helper.h \
+       $(srctree)/rust/bindgen_parameters FORCE
+       $(call if_changed_dep,bindgen)
+
+quiet_cmd_bindgen_helper = BINDGEN $@
+      cmd_bindgen_helper = \
+       $(BINDGEN) $< --blacklist-type '.*' --whitelist-var '' \
+               --whitelist-function 'rust_helper_.*' \
+               --use-core --with-derive-default --ctypes-prefix c_types \
+               --no-debug '.*' \
+               --size_t-is-usize -o $@ -- $(bindgen_c_flags_final) \
+               -I$(objtree)/rust/ -DMODULE; \
+       sed -Ei 's/pub fn rust_helper_([a-zA-Z0-9_]*)/\#[link_name="rust_helper_\1"]\n    pub fn \1/g' $@

rust/Makefile line 268

Quoted 10 lines
rust/Makefile new file +10 -0
+
+$(objtree)/rust/bindings_helpers_generated.rs: $(srctree)/rust/helpers.c FORCE
+       $(call if_changed_dep,bindgen_helper)
+
+quiet_cmd_exports = EXPORTS $@
+      cmd_exports = \
+       $(NM) -p --defined-only $< \
+               | grep -E ' (T|R|D) ' | cut -d ' ' -f 3 \
+               | xargs -Isymbol \
+               echo 'EXPORT_SYMBOL_RUST_GPL(symbol);' > $@

This doesn't accidentally export non-GPL symbols as GPL does it?

... snip ...

--
Thanks,
~Nick Desaulniers

#29 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

Quoted 23 lines · Nick Desaulniers
Quoted 1 line · Miguel Ojeda

... snip ...

Miguel and team,
I'm happy to see progress here! Just some quick notes after a first pass.

Testing this series applied on mainline, I see:

$ make LLVM=1 -j72 defconfig
$ grep RUST .config
CONFIG_HAS_RUST=y
CONFIG_RUSTC_VERSION=14000
# CONFIG_RUST is not set
...
$ make LLVM=1 -j72 menuconfig
# enable CONFIG_RUST
$ make LLVM=1
...
  CALL    scripts/checksyscalls.sh
error: @path is unstable - use -Z unstable-options to enable its use
Quoted 5 lines

error: @path is unstable - use -Z unstable-options to enable its use

$ rustc --version
rustc 1.40.0 (73528e339 2019-12-16)

Can we update some Kconfig checks to fix that?

After now reading though the Documentation/ patch:

$ rustup update
$ rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)
$ make LLVM=1 -j72
...
make[1]: *** No rule to make target
'/usr/local/google/home/ndesaulniers/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/lib.rs',
needed by 'rust/core.o'.  Stop.

Maybe I'm holding it wrong, let me reread the Documentation/ again.

I still think CONFIG_RUST shouldn't be selectable unless CONFIG_RUSTC_VERSION is either a blessed version, or above some minimal value (like we do for CONFIG_GCC_VERSION, CONFIG_LD_VERSION, CONFIG_CLANG_VERSION, LLD_VERSION, etc).

Also, it looks like I don't have bindgen installed. Anything we can do there to help the developer out, as in informing them that it's necessary perhaps via a Kconfig check? I don't think I should be able to select CONFIG_RUST if I don't have bindgen installed. (Same comment about version check probably applies, too). Installing bindgen doesn't change the error I'm observing above though.

Signature · 2 lines
Thanks,
~Nick Desaulniers
#30 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

Quoted 33 lines · Nick Desaulniers
Quoted 23 lines · Nick Desaulniers
Quoted 1 line · Miguel Ojeda

... snip ...

Miguel and team,
I'm happy to see progress here! Just some quick notes after a first pass.

Testing this series applied on mainline, I see:

$ make LLVM=1 -j72 defconfig
$ grep RUST .config
CONFIG_HAS_RUST=y
CONFIG_RUSTC_VERSION=14000
# CONFIG_RUST is not set
...
$ make LLVM=1 -j72 menuconfig
# enable CONFIG_RUST
$ make LLVM=1
...
  CALL    scripts/checksyscalls.sh
error: @path is unstable - use -Z unstable-options to enable its use
Quoted 5 lines

error: @path is unstable - use -Z unstable-options to enable its use

$ rustc --version
rustc 1.40.0 (73528e339 2019-12-16)

Can we update some Kconfig checks to fix that?

After now reading though the Documentation/ patch:

Quoted 8 lines
$ rustup update
$ rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)
$ make LLVM=1 -j72
...
make[1]: *** No rule to make target
'/usr/local/google/home/ndesaulniers/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/lib.rs',
needed by 'rust/core.o'.  Stop.

Can you run rustup component add rust-src?

When we change the compiler version, we need to install the source code for core for the new version. (We'll update the documentation to reflect that.)

Quoted 16 lines

Maybe I'm holding it wrong, let me reread the Documentation/ again.

I still think CONFIG_RUST shouldn't be selectable unless CONFIG_RUSTC_VERSION is either a blessed version, or above some minimal value (like we do for CONFIG_GCC_VERSION, CONFIG_LD_VERSION, CONFIG_CLANG_VERSION, LLD_VERSION, etc).

Also, it looks like I don't have bindgen installed. Anything we can do there to help the developer out, as in informing them that it's necessary perhaps via a Kconfig check? I don't think I should be able to select CONFIG_RUST if I don't have bindgen installed. (Same comment about version check probably applies, too). Installing bindgen doesn't change the error I'm observing above though.
--
Thanks,
~Nick Desaulniers

#31 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

Quoted 44 lines · Wedson Almeida Filho
Quoted 33 lines · Nick Desaulniers
Quoted 23 lines · Nick Desaulniers
Quoted 1 line · Miguel Ojeda

... snip ...

Miguel and team,
I'm happy to see progress here! Just some quick notes after a first pass.

Testing this series applied on mainline, I see:

$ make LLVM=1 -j72 defconfig
$ grep RUST .config
CONFIG_HAS_RUST=y
CONFIG_RUSTC_VERSION=14000
# CONFIG_RUST is not set
...
$ make LLVM=1 -j72 menuconfig
# enable CONFIG_RUST
$ make LLVM=1
...
  CALL    scripts/checksyscalls.sh
error: @path is unstable - use -Z unstable-options to enable its use
Quoted 5 lines

error: @path is unstable - use -Z unstable-options to enable its use

$ rustc --version
rustc 1.40.0 (73528e339 2019-12-16)

Can we update some Kconfig checks to fix that?

After now reading though the Documentation/ patch:

Quoted 8 lines
$ rustup update
$ rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)
$ make LLVM=1 -j72
...
make[1]: *** No rule to make target
'/usr/local/google/home/ndesaulniers/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/lib.rs',
needed by 'rust/core.o'.  Stop.
Quoted 5 lines

Can you run rustup component add rust-src?

When we change the compiler version, we need to install the source code for core for the new version. (We'll update the documentation to reflect that.)

Cool, yeah please add that to the docs. Kconfig checks should be added to make this idiot-proof; starting from everything uninstalled, I should be able to read the Kconfig dependencies in make menuconfig to understand what I'm missing. And if I'm missing anything, I shouldn't be able to select CONFIG_RUST.

I get slightly further now.

$ make LLVM=1 -j72
...
  BINDGEN rust/bindings_helpers_generated.rs
thread 'main' panicked at 'called `Result::unwrap()` on an `Err`
value: "could not run executable `/android0/llvm-project/clang`:
Permission denied (os error 13)"',
/usr/local/google/home/ndesaulniers/.cargo/registry/src/github.com-1ecc6299db9ec823/clang-sys-1.3.0/src/support.rs:196:58
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'called `Result::unwrap()` on an `Err`
value: "could not run executable `/android0/llvm-project/clang`:
Permission denied (os error 13)"',
/usr/local/google/home/ndesaulniers/.cargo/registry/src/github.com-1ecc6299db9ec823/clang-sys-1.3.0/src/support.rs:196:58
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
make[1]: *** [rust/Makefile:261: rust/bindings_helpers_generated.rs] Error 1
make[1]: *** Deleting file 'rust/bindings_helpers_generated.rs'
make[1]: *** Waiting for unfinished jobs....
make[1]: *** [rust/Makefile:248: rust/bindings_generated.rs] Error 1
make[1]: *** Deleting file 'rust/bindings_generated.rs'
make: *** [Makefile:1271: prepare0] Error 2

It looks like bindgen found part of the path to llvm-project that I have checked out to disk for when I do development on LLVM for work. So this might only be an issue if folks have a copy of clang built from source in their $PATH?

$ which clang
/android0/llvm-project/llvm/build/bin/clang

Looking at the output of make LLVM=1 -j72 V=1, I see two invocations of bindgen, and can repro if I just run the full command manually.

I don't see my path to my source code checkout of llvm-project in the command line invocation of bindgen; this might be an issue itself with bindgen.

Googling for "could not run executable" and bindgen, I find this thread with a similar failure string:
https://bugzilla.mozilla.org/show_bug.cgi?id=1363655
No hits in their issue tracker: https://github.com/rust-lang/rust-bindgen.

$ bindgen --version
bindgen 0.59.2
$ cargo install --locked --version 0.56.0 bindgen
$ bindgen --version
bindgen 0.56.0
$ make LLVM=1 -j72
# produces the same error.

I guess the error is coming not from bindgen, but a dependency of its; "clang-sys?"
https://github.com/KyleMayes/clang-sys/blob/master/src/support.rs

I've filed an issue in
https://github.com/KyleMayes/clang-sys/issues/138; let's follow up there?

Signature · 2 lines
Thanks,
~Nick Desaulniers
#32 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

In reply to Nick Desaulniers

Hi Nick,

Quoted 2 lines · Nick Desaulniers

Can we update some Kconfig checks to fix that?

Yes, I can definitely add that.

Quoted 3 lines

Consider putting clippy specific flags in their own variable, and/or just adding them to KBUILD_RUSTFLAGS only when clippy is actually being used.

This was actually the original approach, but I simplified it -- there is no need to put them on their own.

Unless, of course, what you want is shorter verbose output -- is this what you are referring to?

Quoted 4 lines

... here. Should we sink the check for origin CLIPPY? Can we also match how we check for LLVM=1 rather than checking the variables origin? Especially since KBUILD_CLIPPY isn't exported, it seems it's not used outside of this file, IIUC?

I am mimicking what we do for the checkers etc., since that is the closest to Clippy.

Quoted 1 line

Is this used in a different patch in the series? ^

RUSTC_BOOTSTRAP is used to be able to use stable releases of the compiler with unstable features (it should go away, eventually).

Quoted 5 lines

If z and s are distinct opt levels, then rustc should really be using s rather than z. IME, z has created larger images than s due to LLVM aggressively emitting libcalls, regardless of the cost of call setup. See also commit a75bb4eb9e56 ("Revert "kbuild: use -Oz instead of -Os when using clang")

Sounds good. In any case, I will check with upstream Rust if they are used (or planned to be used) for any optimization purposes even before LLVM is reached.

Quoted 2 lines

oh boy. I wonder which configs change the above values? ;) Can rustc still override these via command line flags?

No, it cannot. This is actually a topic I brought up at LPC. Ideally, we would get rustc to support similar command line flags as GCC and Clang do to customize the targets.

The good news are that it seems upstream may be open to accept flags to customize targets. They may use it as a way to stabilize parts of the custom target spec piece by piece, instead of stabilizing the custom target spec files.

We also raised the issue at the Rust CTCFT meeting a couple of weeks ago.

Quoted 2 lines

So this is like turning on -fsanitize=signed-integer-overflow and -fsanitize=unsigned-integer-overflow by default?

Not exactly -- in the Rust case, it is a (Rust) panic. So it would be closer to -fno-sanitize-recover.

Quoted 1 line

A rust panic or a kernel panic?

The former -- which currently means BUG(). However, there could perhaps be other alternatives. There was a bit of discussion about this around Kangrejos time but nothing conclusive.

Quoted 3 lines

This should really be the only option here. I still don't see the point of allowing wacky combinations of configs where we differ from C code. The more combinations will just frustrate randconfig builds.

I don't have a strong opinion -- but I have not heard from others either...

Regarding randconfig, we could restrict it, no?

Quoted 2 lines

Seeing repeated filter-out rules makes me wonder if we could DRY up some of these rules with function definitions?

Yeah, there are also some factoring out that I could do. I grew the file over time and while I am using target-specific variables to generalize a bit too, it can still be taken further.

I have some other changes planned to the build process, so I will probably take the chance to clean up a bit as well.

Quoted 5 lines

Are there links to corresponding feature requests upstream so that one day we can drop technical debt here? In particular, having to create a custom sysroot as is done here isn't particularly pretty.

I'd be curious if we could remove the dependency on cargo for rust tests.

Yes, we have brought this up to upstream, for instance in the Rust CTCFT meeting: https://rust-lang.github.io/ctcft/meetings/2021-11-22.html

In general, I track all feature requests etc. in this "live" issue (see also the linked ones from there):
https://github.com/Rust-for-Linux/linux/issues/2

Quoted 1 line

Do we denote the conflict in KCONFIG?

No, but yeah, we could. However, I am not sure if we want to denote them for something so experimental, though (another question is whether we warn the user about GCC+Rust builds in general).

Or, if we are going to be serious about GCC already (i.e. before we have actual codegen through GCC for Rust), then I would say we need a better solution to the problem (like the "check-if-correct" approach you suggested a while ago, or a proper GCC backend for bindgen).

Quoted 3 lines

Why do we need to strip out all these warning flags when running bindgen? Should be just be using -w to silence all warnings from clang when invoking bindgen?

Hmm... is there any possibility that we silence something that we care actually about? I guess we would get the same diagnostics in normal Clang/LLVM builds, so maybe it is fine. And even if not, perhaps we should just simplify anyway, given it is GCC+Rust builds we are talking about.

Quoted 3 lines

I don't understand why the PowerPC specific flags are pulled out, but the x86 specific ones (like most of the -m flags in the initial defiition of bindgen_skip_c_flags) are not.

No particular reason. When the list of archs started to grow, I decided it would be better to start splitting them out. I will clean that out.

Quoted 1 line

This doesn't accidentally export non-GPL symbols as GPL does it?

It does, but that is fine -- it is the other way around the one that would "open" the kernel unexpectedly.

Thanks a lot for the throughout review!

Cheers,
Miguel

#33 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

In reply to Miguel Ojeda
Quoted 127 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 definition files, the version detection script and a few other bits.

In the future, we will likely want to generate the target files on the fly via a script.

---
 .gitignore                    |   5 +
 .rustfmt.toml                 |  12 ++
 Makefile                      | 146 +++++++++++++-
 arch/arm/rust/target.json     |  27 +++
 arch/arm64/rust/target.json   |  34 ++++
 arch/powerpc/rust/target.json |  29 +++
 arch/riscv/Makefile           |   1 +
 arch/riscv/rust/rv32ima.json  |  36 ++++
 arch/riscv/rust/rv32imac.json |  36 ++++
 arch/riscv/rust/rv64ima.json  |  36 ++++
 arch/riscv/rust/rv64imac.json |  36 ++++
 arch/x86/rust/target.json     |  36 ++++
 init/Kconfig                  |  31 ++-
 lib/Kconfig.debug             | 144 ++++++++++++++
 rust/.gitignore               |   7 +
 rust/Makefile                 | 353 ++++++++++++++++++++++++++++++++++
 rust/bindgen_parameters       |  13 ++
 scripts/Makefile.build        |  22 +++
 scripts/Makefile.debug        |  10 +
 scripts/Makefile.lib          |  12 ++
 scripts/Makefile.modfinal     |   8 +-
 scripts/is_rust_module.sh     |  19 ++
 scripts/kconfig/confdata.c    |  75 ++++++++
 scripts/rust-version.sh       |  31 +++
 24 files changed, 1147 insertions(+), 12 deletions(-)
 create mode 100644 .rustfmt.toml
 create mode 100644 arch/arm/rust/target.json
 create mode 100644 arch/arm64/rust/target.json
 create mode 100644 arch/powerpc/rust/target.json
 create mode 100644 arch/riscv/rust/rv32ima.json
 create mode 100644 arch/riscv/rust/rv32imac.json
 create mode 100644 arch/riscv/rust/rv64ima.json
 create mode 100644 arch/riscv/rust/rv64imac.json
 create mode 100644 arch/x86/rust/target.json
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Makefile
 create mode 100644 rust/bindgen_parameters
 create mode 100755 scripts/is_rust_module.sh
 create mode 100755 scripts/rust-version.sh
.gitignore +5 -0
index 7afd412dadd2..48c68948f476 100644
@@ -37,6 +37,7 @@
 *.o
 *.o.*
 *.patch
+*.rmeta
 *.s
 *.so
 *.so.dbg
@@ -96,6 +97,7 @@ modules.order
 !.gitattributes
 !.gitignore
 !.mailmap
+!.rustfmt.toml
 
 #
 # Generated include files
@@ -161,3 +163,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 +0 -0
index 0a6ecc8bb2d2..0f20ca9bd723 100644

Makefile endif · line 128

Quoted 9 lines
Makefile +6 -0
@@ -120,6 +120,13 @@ endif
 
 export KBUILD_CHECKSRC
 
+# Enable "clippy" (a linter) as part of the Rust compilation.
+#
+# Use 'make CLIPPY=1' to enable it.
+ifeq ("$(origin CLIPPY)", "command line")
+  KBUILD_CLIPPY := $(CLIPPY)
+endif

Do you really want to support CLIPPY=1 in addition to KBUILD_CLIPPY=1 ?

(Refer to C= V= M= O=, which checks $(origin ) )

Makefile ifeq ($(KBUILD_EXTMOD),) · line 1169

Quoted 11 lines
Makefile +4 -0
 KBUILD_LDFLAGS_MODULE += --build-id=sha1
 LDFLAGS_vmlinux += --build-id=sha1
@@ -1095,6 +1163,11 @@ ifeq ($(KBUILD_EXTMOD),)
 core-y                 += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/
 core-$(CONFIG_BLOCK)   += block/
 
+# Keep this one as an `ifdef` block since its `Makefile` runs `rustc`.
+ifdef CONFIG_RUST
+core-y                 += rust/
+endif

Is there any reason why
you did not write like

  core-$(CONFIG_RUST)  += rust/

?

Quoted 25 lines
rust/.gitignore new file +7 -0
new file mode 100644
index 000000000000..168cb26a31b9
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+
+bindings_generated.rs
+bindings_helpers_generated.rs
+exports_*_generated.h
+doc/
+test/
rust/Makefile new file +6 -0
new file mode 100644
index 000000000000..2d08314e7031
@@ -0,0 +1,353 @@
+# SPDX-License-Identifier: GPL-2.0
+
+obj-$(CONFIG_RUST) += core.o compiler_builtins.o helpers.o
+extra-$(CONFIG_RUST) += exports_core_generated.h
+
+extra-$(CONFIG_RUST) += libmacros.so

rust/Makefile line 16

Quoted 10 lines
rust/Makefile new file +10 -0
+
+extra-$(CONFIG_RUST) += bindings_generated.rs bindings_helpers_generated.rs
+obj-$(CONFIG_RUST) += alloc.o kernel.o
+extra-$(CONFIG_RUST) += exports_alloc_generated.h exports_kernel_generated.h
+
+ifdef CONFIG_RUST_BUILD_ASSERT_DENY
+extra-$(CONFIG_RUST) += build_error.o
+else
+obj-$(CONFIG_RUST) += build_error.o
+endif

extra-y does nothing for 'make modules'. Is this your expected behavior?

(commit d0e628cd817f3)

Quoted 6 lines
rust/Makefile new file +6 -0
+$(objtree)/rust/build_error.o: $(srctree)/rust/build_error.rs \
+    $(objtree)/rust/compiler_builtins.o FORCE
+       $(call if_changed_dep,rustc_library)
+
+# ICE on `--extern macros`: https://github.com/rust-lang/rust/issues/56935
+$(objtree)/rust/kernel.o: private rustc_target_flags = --extern alloc \

rust/Makefile line 344

Quoted 10 lines
rust/Makefile new file +10 -0
+    --extern build_error \
+    --extern macros=$(objtree)/rust/libmacros.so
+$(objtree)/rust/kernel.o: $(srctree)/rust/kernel/lib.rs $(objtree)/rust/alloc.o \
+    $(objtree)/rust/build_error.o \
+    $(objtree)/rust/libmacros.so $(objtree)/rust/bindings_generated.rs \
+    $(objtree)/rust/bindings_helpers_generated.rs FORCE
+       $(call if_changed_dep,rustc_library)
+
+# Targets that need to expand twice
+.SECONDEXPANSION:

Why is .SECONDEXPANSION: needed ?

Signature · 2 lines
Best Regards
Masahiro Yamada
#34 lore raw

Re: [PATCH 15/19] Kbuild: add Rust support

Hi Masahiro,

Quoted 5 lines · Masahiro Yamada

Do you really want to support CLIPPY=1 in addition to KBUILD_CLIPPY=1 ?

(Refer to C= V= M= O=, which checks $(origin ) )

I implemented both because I saw the pattern used for V=, W= etc., and I thought I should follow it too. If I understand correctly, the split between KBUILD_* and the shorthands is there to avoid conflicts if the caller had set very short environment variables for some reason -- is this correct?

If you prefer only one, I think writing KBUILD_CLIPPY=1 would be too long for command line usage; so I would prefer CLIPPY=1 in that case.

Quoted 6 lines

Is there any reason why
you did not write like

  core-$(CONFIG_RUST)  += rust/

?

I have moved it inside the rust/Makefile -- please take a look at the next round I am sending in a bit.

Quoted 4 lines

extra-y does nothing for 'make modules'. Is this your expected behavior?

(commit d0e628cd817f3)

Thanks for the reference! Changed to always-y. Indeed, this is needed in make modules because we need to trigger the compilation of core.o etc. for the .rmeta files.

Quoted 1 line

Why is .SECONDEXPANSION: needed ?

It was needed at some point for the prototype more than a year ago; however, it isn't the case anymore, so I have removed it. I have also made those variables simply expanded ones.

Cheers,
Miguel

author maintainer
#35 lore raw

PATCH 16/19 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.

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                   | 113 +++++++++++++
 samples/rust/Makefile                  |  12 ++
 samples/rust/rust_chrdev.rs            |  50 ++++++
 samples/rust/rust_minimal.rs           |  38 +++++
 samples/rust/rust_miscdev.rs           | 149 +++++++++++++++++
 samples/rust/rust_module_parameters.rs |  72 +++++++++
 samples/rust/rust_print.rs             |  57 +++++++
 samples/rust/rust_random.rs            |  61 +++++++
 samples/rust/rust_semaphore.rs         | 174 ++++++++++++++++++++
 samples/rust/rust_semaphore_c.c        | 212 +++++++++++++++++++++++++
 samples/rust/rust_stack_probing.rs     |  40 +++++
 samples/rust/rust_sync.rs              |  81 ++++++++++
 14 files changed, 1062 insertions(+)
 create mode 100644 samples/rust/Kconfig
 create mode 100644 samples/rust/Makefile
 create mode 100644 samples/rust/rust_chrdev.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_print.rs
 create mode 100644 samples/rust/rust_random.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 43d2e9aa557f..a3a5166837b1 100644
@@ -241,6 +241,8 @@ config SAMPLE_WATCH_QUEUE
 	  Build example userspace program to use the new mount_notify(),
 	  sb_notify() syscalls and the KEYCTL_WATCH_KEY keyctl() function.
 
+source "samples/rust/Kconfig"
+
 endif # SAMPLES
 
 config HAVE_SAMPLE_FTRACE_DIRECT
samples/Makefile +1 -0
index 4bcd6b93bffa..d66f49a9f080 100644
@@ -32,3 +32,4 @@ obj-$(CONFIG_SAMPLE_INTEL_MEI)		+= mei/
 subdir-$(CONFIG_SAMPLE_WATCHDOG)	+= watchdog
 subdir-$(CONFIG_SAMPLE_WATCH_QUEUE)	+= watch_queue
 obj-$(CONFIG_DEBUG_KMEMLEAK_TEST)	+= kmemleak/
+obj-$(CONFIG_SAMPLES_RUST)		+= rust/
samples/rust/Kconfig new file +113 -0

113 lines not on this page · raw message

samples/rust/Makefile new file +12 -0
new file mode 100644
index 000000000000..48bc871ea1f8
@@ -0,0 +1,12 @@
+# 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
samples/rust/rust_chrdev.rs new file +50 -0

50 lines not on this page · raw message

samples/rust/rust_minimal.rs new file +38 -0
new file mode 100644
index 000000000000..3276dbe8ae94
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust minimal sample
+
+#![no_std]
+#![feature(allocator_api, global_asm)]
+
+use kernel::prelude::*;
+
+module! {
+    type: RustMinimal,
+    name: b"rust_minimal",
+    author: b"Rust for Linux Contributors",
+    description: b"Rust minimal sample",
+    license: b"GPL v2",
+}
+
+struct RustMinimal {
+    message: String,
+}
+
+impl KernelModule 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 +149 -0

149 lines not on this page · raw message

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

72 lines not on this page · raw message

samples/rust/rust_print.rs new file +57 -0

57 lines not on this page · raw message

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

61 lines not on this page · raw message

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

174 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 +40 -0
new file mode 100644
index 000000000000..4f44fade96aa
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust stack probing sample
+
+#![no_std]
+#![feature(allocator_api, global_asm)]
+#![feature(bench_black_box)]
+
+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 v2",
+}
+
+struct RustStackProbing;
+
+impl KernelModule 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 +81 -0

81 lines not on this page · raw message

Signature · 1 line
2.34.0
author maintainer
#36 lore raw

PATCH 17/19 MAINTAINERS: Rust

In reply to Miguel Ojeda

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

---
 MAINTAINERS | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
MAINTAINERS +14 -0
index 360e9aa0205d..2683d788d060 100644
@@ -16562,6 +16562,20 @@ 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:	rust/
+F:	samples/rust/
+F:	Documentation/rust/
+K:	\b(?i:rust)\b
+
 RXRPC SOCKETS (AF_RXRPC)
 M:	David Howells <[email protected]>
 M:	Marc Dionne <[email protected]>
Signature · 1 line
2.34.0
author maintainer
#37 lore raw

RFC PATCH 18/19 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 | 362 ++++++++++++++++++++++++++++++++
 3 files changed, 371 insertions(+)
 create mode 100644 drivers/gpio/gpio_pl061_rust.rs
drivers/gpio/Kconfig +8 -0
index 60d9374c72c0..8bc208ece49d 100644
@@ -471,6 +471,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 71ee9fc2ff83..5021316a5037 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 +362 -0

362 lines not on this page · raw message

Signature · 1 line
2.34.0
author maintainer
#38 lore raw

RFC PATCH 19/19 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             |   7 +
 drivers/android/Makefile            |   2 +
 drivers/android/allocation.rs       | 266 ++++++++
 drivers/android/context.rs          |  79 +++
 drivers/android/defs.rs             |  99 +++
 drivers/android/node.rs             | 476 ++++++++++++++
 drivers/android/process.rs          | 964 ++++++++++++++++++++++++++++
 drivers/android/range_alloc.rs      | 189 ++++++
 drivers/android/rust_binder.rs      | 114 ++++
 drivers/android/thread.rs           | 871 +++++++++++++++++++++++++
 drivers/android/transaction.rs      | 326 ++++++++++
 include/uapi/linux/android/binder.h |  28 +-
 12 files changed, 3408 insertions(+), 13 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 +7 -0
index 53b22e26266c..7aef7f38f988 100644
@@ -20,6 +20,13 @@ 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
+	default n
+	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 +79 -0

79 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 +964 -0

964 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 +114 -0

114 lines not on this page · raw message

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

795 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 +15 -13
index 3246f2c74696..ad619623571e 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.34.0

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

#39 lore raw

Re: [RFC PATCH 19/19] drivers: android: Binder IPC in Rust

Quoted 9 lines · 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.

Have you all tested this against the userspace binder tests? And is it up to date with the features of the in-kernel binder driver?

thanks,

greg k-h

#40 lore raw

Re: [RFC PATCH 19/19] drivers: android: Binder IPC in Rust

Quoted 5 lines · Greg Kroah-Hartman
Quoted 4 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A port to Rust of the Android Binder IPC mechanism.

Quoted 8 lines
Quoted 5 lines

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.

Have you all tested this against the userspace binder tests? And is it up to date with the features of the in-kernel binder driver?

Very little has changed here since the last submission, namely: using credentials for security callbacks, and replacing Arc with Ref (i.e., using refcount_t to manage ref-counted allocations).

As the message tries to indicate, this is submitted as an example and WIP, it doesn't have feature parity with the C version yet.

#41 lore raw

Re: [RFC PATCH 19/19] drivers: android: Binder IPC in Rust

Quoted 15 lines · Wedson Almeida Filho
Quoted 5 lines · Greg Kroah-Hartman
Quoted 4 lines · Miguel Ojeda

From: Wedson Almeida Filho <[email protected]>

A port to Rust of the Android Binder IPC mechanism.

Quoted 8 lines
Quoted 5 lines

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.

Have you all tested this against the userspace binder tests? And is it up to date with the features of the in-kernel binder driver?

Quoted 6 lines

Very little has changed here since the last submission, namely: using credentials for security callbacks, and replacing Arc with Ref (i.e., using refcount_t to manage ref-counted allocations).

As the message tries to indicate, this is submitted as an example and WIP, it doesn't have feature parity with the C version yet.

You might want to say that in the changelog text so I don't keep asking every time it gets posted :)

thanks,

greg k-h