Rust block device driver API and null block driver
Subsystems (4)
cover Rust block device driver API and null block driver
From: Andreas Hindborg <[email protected]>
Hi All!
This is the second version of the Rust block device driver API and the Rust null block driver. The context and motivation can be seen in cover letter of the RFC v1 [1]. If more context is required, a talk about this effort was recorded at LPC [2]. I hope to be able to discuss this series at LSF this year [3].
The series is still in RFC state, as many dependencies have not yet been merged.
Changes from v1:
- Improved request lifetime tracking
- Changed rust null block driver name to rnull
- Added timer completion support to rnull
- Added softirq completion support to rnull
- Moved to xarray for memory backing
- Adopted the folio abstraction where applicable
- Added SAFETY comments to all unsafe blocks
- Improved documentation and added examples
- Fixed up vtable default method behavior
- Dropped unsafe from vtable builder
- Fixed a safety issue in RawWriter
- Dropped the TagSetRef abstraction
- Renamed Bio::iter -> Bio::raw_iter
- Updated core::fmt::Display for Bio for readability
- Simplified BioIterator::next
- Documented and refactored bvec_iter functions
- Moved cache alignment out of Lock
- Added MAINTAINER entry
Thanks for all the input on v1!
Performance
===========
Rather than include an abundance of performance numbers in this letter, I would refer to [4] for a comparison of performance to the C null block driver. In general across all of the benchmark configurations, the mean of the difference is -2.5%, with individual configurations showing [-10%;30%] difference in IO/s.
Request lifetime modeling
=========================
While implementing timer completion, it became clear that the request lifetime modeling applied in the v1 RFC was not adequate. With that modeling, combined with the timer callback feature, a developer would be able to write safe Rust code that violates the Rust invariants for references, thus leading to undefined behavior. A similar situation would happen in the completion path when developers write code to convert from a completion id to a &Request.
To make these situations safe, and thus free from undefined behavior, the Request type now applies reference counting. The logic piggybacks on the atomic_t ref field of the C struct request. In order to make this work, the Rust code has to be able to free requests when the refcount reaches zero. Therefore, the series exposes (EXPORT_SYMBOL_GPL) the internal blk-mq symbol __blk_mq_free_request.
I am curious what the community thinks of this approach and whether it is OK to expose this symbol so that Rust can call it.
One consequence of these changes is that requests that are processed by a Rust block device driver, are freed at a different place in the completion path, than requests processed by C drivers. Requests processed by C drivers are typically freed and recycled inline during the call to blk_mq_complete_request. The requests processed by a Rust driver will be recycled when the RequestRef is dropped, which is usually at some time after the request has been completed.
There does not seem to be any statistically significant effect on performance for the rust null block implementation due to this change.
Dependencies
============
This series is based on the branch rnull-deps-v6.8 of [5]. This tree is based on the upstream v6.8 tag and has been prepared with dependencies for this series:
- [17] rust: add CacheAligned for easy cache line alignment of values
- [16] rust: xarray: add mutable access through Guard
- [15] rust: hrtimer: introduce hrtimer support
- [14] rust: add Opaque::try_ffi_init
- [13] rust: make ARef repr transparent
- [12] rust: folio: add with_slice_into_page()
- [11] rust: page: add from_raw()
- [10] rust: page: add with_slice_into_page()
- [ 9] IM: implement ForeignOwnable for Pin
- [ 8] IM: add module_params macro
- [ 7] rust: xarray: fix example
- [ 6] LIST: rust: xarray: Add an abstraction for XArray
- [ 5] LIST: rust: types: add FOREIGN_ALIGN to ForeignOwnable
- [ 4] LIST: rust: lock: implement IrqSaveBackend for SpinLock
- [ 3] LIST: rust: lock: add support for Lock::lock_irqsave
- [ 2] LIST: rust: add improved version of ForeignOwnable::borrow_mut
- [ 1] LIST: rust: folio: introduce basic support for folios
- [ 0] LIST: rust: add abstraction for struct page
Dependencies 0-6 are patches that have appeared on the list but are not yet merged. Dependencies 8-9 are imports from the rust branch [6,7] that have not yet been submitted. Dependencies 10-17 I will submit independently in the near future.
If the upstream maintainers agree, then when the dependencies are merged, I will eventually start submitting PRs to Jens. I fully commit to maintain this code as indicated in the MAINTAINERS entry.
Best regards,
Andreas Hindborg
[1] https://lore.kernel.org/rust-for-linux/[email protected]
[2] https://lpc.events/event/17/contributions/1425
[3] https://lore.kernel.org/rust-for-linux/[email protected]
[4] https://rust-for-linux.com/null-block-driver
[5] git https://github.com/metaspace/linux.git rnull-deps-v6.8
[6] git https://github.com/rust-for-Linux/linux.git rust
[7] https://rust-for-linux.com/branches#rust
Andreas Hindborg (5):
rust: block: introduce kernel::block::mq module
rust: block: introduce kernel::block::bio module
rust: block: allow hrtimer::Timer in RequestData
rust: block: add rnull, Rust null_blk implementation
MAINTAINERS: add entry for Rust block device driver API
MAINTAINERS | 14 ++ block/blk-mq.c | 3 +- drivers/block/Kconfig | 4 + drivers/block/Makefile | 3 + drivers/block/rnull.rs | 323 +++++++++++++++++++++++++++ include/linux/blk-mq.h | 1 + rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 46 ++++ rust/kernel/block.rs | 6 + rust/kernel/block/bio.rs | 112 ++++++++++ rust/kernel/block/bio/vec.rs | 279 +++++++++++++++++++++++ rust/kernel/block/mq.rs | 131 +++++++++++ rust/kernel/block/mq/gen_disk.rs | 174 +++++++++++++++ rust/kernel/block/mq/operations.rs | 346 +++++++++++++++++++++++++++++ rust/kernel/block/mq/raw_writer.rs | 60 +++++ rust/kernel/block/mq/request.rs | 269 ++++++++++++++++++++++ rust/kernel/block/mq/tag_set.rs | 117 ++++++++++ rust/kernel/error.rs | 5 + rust/kernel/lib.rs | 1 + scripts/Makefile.build | 2 +- 20 files changed, 1896 insertions(+), 2 deletions(-) create mode 100644 drivers/block/rnull.rs create mode 100644 rust/kernel/block.rs create mode 100644 rust/kernel/block/bio.rs create mode 100644 rust/kernel/block/bio/vec.rs create mode 100644 rust/kernel/block/mq.rs create mode 100644 rust/kernel/block/mq/gen_disk.rs create mode 100644 rust/kernel/block/mq/operations.rs create mode 100644 rust/kernel/block/mq/raw_writer.rs create mode 100644 rust/kernel/block/mq/request.rs create mode 100644 rust/kernel/block/mq/tag_set.rs
base-commit: e8f897f4afef0031fe618a8e94127a0934896aba
prerequisite-patch-id: 299c2cc48c45c8149e7cb18c6146a0308e5d0a44
prerequisite-patch-id: 5153ee1c410dbdf22a6fd40667712943b4b89a97
prerequisite-patch-id: 4d025bab9bc9741aedecc5327ad18f88f9105271
prerequisite-patch-id: a5e932c86fa6c68234764aa3d7f314e5b534b1d9
prerequisite-patch-id: aef3042976c4c678b7aa96154fc280f9061ebaf7
prerequisite-patch-id: 8bf108ad0af2a3ec89acb8d99ee1b49ca2f51c69
prerequisite-patch-id: a803b221c3232db3258406a4075558e85acefd09
prerequisite-patch-id: 5e9cbcd0dc56a83353f0e4a3b5d4e8d5b51f3160
prerequisite-patch-id: 28bae4a7fe83b36afed9892515a6dde1ea51e98a
prerequisite-patch-id: 5b5ea2a21b37afb05fdf655396a6f74d83bb99c4
prerequisite-patch-id: dc53b6ce21f74726d5d13988398c2954da07bcb6
prerequisite-patch-id: b86d2b14f1770c1d4756ca10b93efaada643e560
prerequisite-patch-id: 6a155859eb9a18afcd22a5bda3350d45d92e2fc7
prerequisite-patch-id: c8ca075008f50d3cf1781c1ea1130a8ee735e7d2
prerequisite-patch-id: b000cd190fe80dea3f4dd9172ecf8787f23b72be
prerequisite-patch-id: b72f1fc3bd44b60911d9d91ecc5a45812a75eba3
prerequisite-patch-id: 167c7770e124b9afa44bead742f90a57ac73f2d7
prerequisite-patch-id: cc24a3135b4f258f4b1ea83ac91c2be4ffe31772
Signature · 1 line
2.44.0
RFC PATCH 1/5 rust: block: introduce `kernel::block::mq` module
From: Andreas Hindborg <[email protected]>
Add initial abstractions for working with blk-mq.
This patch is a maintained, refactored subset of code originally published by Wedson Almeida Filho <[email protected]> [1].
--- block/blk-mq.c | 3 +- include/linux/blk-mq.h | 1 + rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 45 ++++ rust/kernel/block.rs | 5 + rust/kernel/block/mq.rs | 131 +++++++++++ rust/kernel/block/mq/gen_disk.rs | 174 +++++++++++++++ rust/kernel/block/mq/operations.rs | 346 +++++++++++++++++++++++++++++ rust/kernel/block/mq/raw_writer.rs | 60 +++++ rust/kernel/block/mq/request.rs | 182 +++++++++++++++ rust/kernel/block/mq/tag_set.rs | 117 ++++++++++ rust/kernel/error.rs | 5 + rust/kernel/lib.rs | 1 + 13 files changed, 1071 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/block.rs create mode 100644 rust/kernel/block/mq.rs create mode 100644 rust/kernel/block/mq/gen_disk.rs create mode 100644 rust/kernel/block/mq/operations.rs create mode 100644 rust/kernel/block/mq/raw_writer.rs create mode 100644 rust/kernel/block/mq/request.rs create mode 100644 rust/kernel/block/mq/tag_set.rs
block/blk-mq.c +2 -1
@@ -702,7 +702,7 @@ static void blk_mq_finish_request(struct request *rq) } } -static void __blk_mq_free_request (struct request *rq) +void __blk_mq_free_request (struct request *rq) {struct request_queue *q = rq->q;struct blk_mq_ctx *ctx = rq->mq_ctx;
@@ -722,6 +722,7 @@ static void __blk_mq_free_request(struct request *rq)blk_mq_sched_restart (hctx);blk_queue_exit (q); } +EXPORT_SYMBOL_GPL (__blk_mq_free_request);void blk_mq_free_request (struct request *rq) {
include/linux/blk-mq.h +1 -0
@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags);void blk_mq_free_tag_set (struct blk_mq_tag_set *set); +void __blk_mq_free_request (struct request *rq);void blk_mq_free_request (struct request *rq);int blk_rq_poll (struct request *rq,struct io_comp_batch *iob,unsigned int poll_flags);
rust/bindings/bindings_helper.h +2 -0
@@ -7,6 +7,8 @@*/ #include <kunit/test.h> +#include <linux/blk_types.h> +#include <linux/blk-mq.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/mdio.h>
rust/helpers.c +45 -0
63 lines not on this page · raw message
rust/kernel/block.rs new file +5 -0
@@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Types for working with the block layer + +pub mod mq;
rust/kernel/block/mq.rs new file +131 -0
131 lines not on this page · raw message
rust/kernel/block/mq/gen_disk.rs new file +174 -0
174 lines not on this page · raw message
rust/kernel/block/mq/operations.rs new file +346 -0
346 lines not on this page · raw message
rust/kernel/block/mq/raw_writer.rs new file +60 -0
60 lines not on this page · raw message
rust/kernel/block/mq/request.rs new file +182 -0
182 lines not on this page · raw message
rust/kernel/block/mq/tag_set.rs new file +117 -0
117 lines not on this page · raw message
rust/kernel/error.rs +5 -0
@@ -130,6 +130,11 @@ pub fn to_errno(self) -> core::ffi::c_int { self.0 } +pub (crate )fn to_blk_status (self) -> bindings::blk_status_t { +// SAFETY: `self.0` is a valid error due to its invariant. +unsafe { bindings::errno_to_blk_status (self.0 ) } + } +/// Returns the error encoded as a pointer. #[allow(dead_code)] pub (crate )fn to_ptr <T >(self) -> *mut T {
rust/kernel/lib.rs +1 -0
@@ -34,6 +34,7 @@#[cfg(not(test))] #[cfg(not(testlib))] mod allocator; +pub mod block;mod build_assert;mod cache_aligned;pub mod error;
Signature · 1 line
2.44.0
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 48 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
Add initial abstractions for working with blk-mq.
This patch is a maintained, refactored subset of code originally published by Wedson Almeida Filho <[email protected]> [1].
Cc Wedson Almeida Filho <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>--- block/blk-mq.c | 3 +- include/linux/blk-mq.h | 1 + rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 45 ++++ rust/kernel/block.rs | 5 + rust/kernel/block/mq.rs | 131 +++++++++++ rust/kernel/block/mq/gen_disk.rs | 174 +++++++++++++++ rust/kernel/block/mq/operations.rs | 346 +++++++++++++++++++++++++++++ rust/kernel/block/mq/raw_writer.rs | 60 +++++ rust/kernel/block/mq/request.rs | 182 +++++++++++++++ rust/kernel/block/mq/tag_set.rs | 117 ++++++++++ rust/kernel/error.rs | 5 + rust/kernel/lib.rs | 1 + 13 files changed, 1071 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/block.rs create mode 100644 rust/kernel/block/mq.rs create mode 100644 rust/kernel/block/mq/gen_disk.rs create mode 100644 rust/kernel/block/mq/operations.rs create mode 100644 rust/kernel/block/mq/raw_writer.rs create mode 100644 rust/kernel/block/mq/request.rs create mode 100644 rust/kernel/block/mq/tag_set.rsblock/blk-mq.c +1
-1@@ -702,7 +702,7 @@ static void blk_mq_finish_request(struct request *rq) } } -static void __blk_mq_free_request (struct request *rq) +void __blk_mq_free_request (struct request *rq) {struct request_queue *q = rq->q;struct blk_mq_ctx *ctx = rq->mq_ctx;
block/blk-mq.c static void __blk_mq_free_request(struct request *rq) · line 726
Quoted 5 lines
block/blk-mq.c +1
-0@@ -722,6 +722,7 @@ static void __blk_mq_free_request(struct request *rq)blk_mq_sched_restart (hctx);blk_queue_exit (q); } +EXPORT_SYMBOL_GPL (__blk_mq_free_request);
Note that for an EXPORT_SYMBOL_GPL() symbol, you can just add the corresponding header file in rust/bindings/bindings_helper.h:
+#include <linux/blk-mq.h>
and you will be able to call it from Rust via:
bindings::__blk_mq_free_request()
in other words, rust_helper_blk_mq_free_request_internal() is probably not necessary.
Regards,
Boqun
Quoted 34 lines
block/blk-mq.c +0
-0void blk_mq_free_request (struct request *rq) {include/linux/blk-mq.h +1
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags);void blk_mq_free_tag_set (struct blk_mq_tag_set *set); +void __blk_mq_free_request (struct request *rq);void blk_mq_free_request (struct request *rq);int blk_rq_poll (struct request *rq,struct io_comp_batch *iob,unsigned int poll_flags);rust/bindings/bindings_helper.h +2
-0@@ -7,6 +7,8 @@*/ #include <kunit/test.h> +#include <linux/blk_types.h> +#include <linux/blk-mq.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/mdio.h> rust/helpers.c +0
-0@@ -21,6 +21,9 @@*/
[...]
Quoted 7 lines
rust/helpers.c +7
-0+ +void rust_helper_blk_mq_free_request_internal (struct request *req) +{ +__blk_mq_free_request (req); +} +EXPORT_SYMBOL_GPL (rust_helper_blk_mq_free_request_internal); +
[...]
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 58 lines · Boqun Feng
Quoted 48 lines · Andreas Hindborg
From: Andreas Hindborg <[email protected]>
Add initial abstractions for working with blk-mq.
This patch is a maintained, refactored subset of code originally published by Wedson Almeida Filho <[email protected]> [1].
Cc Wedson Almeida Filho <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>--- block/blk-mq.c | 3 +- include/linux/blk-mq.h | 1 + rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 45 ++++ rust/kernel/block.rs | 5 + rust/kernel/block/mq.rs | 131 +++++++++++ rust/kernel/block/mq/gen_disk.rs | 174 +++++++++++++++ rust/kernel/block/mq/operations.rs | 346 +++++++++++++++++++++++++++++ rust/kernel/block/mq/raw_writer.rs | 60 +++++ rust/kernel/block/mq/request.rs | 182 +++++++++++++++ rust/kernel/block/mq/tag_set.rs | 117 ++++++++++ rust/kernel/error.rs | 5 + rust/kernel/lib.rs | 1 + 13 files changed, 1071 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/block.rs create mode 100644 rust/kernel/block/mq.rs create mode 100644 rust/kernel/block/mq/gen_disk.rs create mode 100644 rust/kernel/block/mq/operations.rs create mode 100644 rust/kernel/block/mq/raw_writer.rs create mode 100644 rust/kernel/block/mq/request.rs create mode 100644 rust/kernel/block/mq/tag_set.rsblock/blk-mq.c +1
-1@@ -702,7 +702,7 @@ static void blk_mq_finish_request(struct request *rq) } } -static void __blk_mq_free_request (struct request *rq) +void __blk_mq_free_request (struct request *rq) {struct request_queue *q = rq->q;struct blk_mq_ctx *ctx = rq->mq_ctx;block/blk-mq.c static void __blk_mq_free_request(struct request *rq) · line 726
Quoted 5 lines
block/blk-mq.c +1
-0@@ -722,6 +722,7 @@ static void __blk_mq_free_request(struct request *rq)blk_mq_sched_restart (hctx);blk_queue_exit (q); } +EXPORT_SYMBOL_GPL (__blk_mq_free_request);Note that for an
EXPORT_SYMBOL_GPL()symbol, you can just add the corresponding header file inrust/bindings/bindings_helper.h:
Quoted 8 lines
+#include <
linux/blk-mq.h>and you will be able to call it from Rust via:
bindings::__blk_mq_free_request()in other words,
rust_helper_blk_mq_free_request_internal()is probably not necessary.
Yes, good point. Another option suggested by Miguel is that __blk_mq_free_request need not be exported at all. We can make it non-static and then call it from rust_helper_blk_mq_free_request_internal(). Then only the latter will be in the kernel image symbol table, which might be better in terms of not exposing __blk_mq_free_request() directly.
BR Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 7 lines · Andreas Hindborg
Yes, good point. Another option suggested by Miguel is that
__blk_mq_free_requestneed not be exported at all. We can make it non-static and then call it fromrust_helper_blk_mq_free_request_internal(). Then only the latter will be in the kernel image symbol table, which might be better in terms of not exposing__blk_mq_free_request()directly.
The helper is not needed, i.e. what I meant was to make it non-static and add it to include/linux/blk-mq.h.
Cheers,
Miguel
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 11 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
Yes, good point. Another option suggested by Miguel is that
__blk_mq_free_requestneed not be exported at all. We can make it non-static and then call it fromrust_helper_blk_mq_free_request_internal(). Then only the latter will be in the kernel image symbol table, which might be better in terms of not exposing__blk_mq_free_request()directly.The helper is not needed, i.e. what I meant was to make it non-static and add it to
include/linux/blk-mq.h.
The way the current code compiles, <kernel::block::mq::Request as kernel::types::AlwaysRefCounted>::dec_ref is inlined into the rnull module. A relocation for rust_helper_blk_mq_free_request_internal appears in rnull_mod.ko. I didn't test it yet, but if __blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?
BR Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 14 lines · Andreas Hindborg
Quoted 11 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
Yes, good point. Another option suggested by Miguel is that
__blk_mq_free_requestneed not be exported at all. We can make it non-static and then call it fromrust_helper_blk_mq_free_request_internal(). Then only the latter will be in the kernel image symbol table, which might be better in terms of not exposing__blk_mq_free_request()directly.The helper is not needed, i.e. what I meant was to make it non-static and add it to
include/linux/blk-mq.h.
Quoted 7 lines
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?
I just tested what you suggested Miguel, and I get a link error for __blk_mq_free_request being undefined when the module is linked. This is even though the code that calls this function lives in the kernel crate, because it is inlined.
BR Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
In reply to Andreas HindborgQuoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
In any case, if we really want to avoid exporting the original symbol (perhaps so that "only Rust" can use it -- or someone trying hard to bypass things on purpose), then we could still avoid the helper and instead write a non-generic kernel-private Rust function instead.
Cheers,
Miguel
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 5 lines · Miguel Ojeda
In any case, if we really want to avoid exporting the original symbol (perhaps so that "only Rust" can use it -- or someone trying hard to bypass things on purpose), then we could still avoid the helper and instead write a non-generic
kernel-private Rust function instead.
The advantages would be that we get the export done automatically and that we could write in Rust, e.g. with restricted visibility.
But we could need #[inline(never)] (or ideally #[used] if it could go on functions) or #[no_mangle] (but we would lose the mangling).
Anyway, the simplest is to export the original symbol, but we could consider to provide support one way or another for this kind of "helpers" (i.e. leaving the current helpers as those for macros and inline functions), so that it is clear what symbols are only exported for Rust use (and not other C code).
Cheers,
Miguel
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
In reply to Miguel OjedaQuoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?
Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
unsigned int set_flags);
void blk_mq_free_tag_set(struct blk_mq_tag_set *set);
+void __blk_mq_free_request(struct request *rq);
void blk_mq_free_request(struct request *rq);
int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
unsigned int poll_flags);
Quoted 4 lines
In any case, if we really want to avoid exporting the original symbol (perhaps so that "only Rust" can use it -- or someone trying hard to bypass things on purpose), then we could still avoid the helper and instead write a non-generic
kernel-private Rust function instead.
Let's see what the block layer experts say first. Perhaps it is OK to expose this symbol like this or maybe it can be made more generic somehow.
Jens, Ming, Keith, do you have any comments?
Best regards,
Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 20 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 7 lines
(quoted diff) +1
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set); +void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);
Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
Thanks,
Ming
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 24 lines · Ming Lei
Quoted 23 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
(quoted diff) +0
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set);
Quoted 7 lines
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 4 lines
(quoted diff) +1
-0+void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
It is not the rust null block driver that calls this symbol directly. It is called by the Rust block device driver API. But because of inlining, the symbol is referenced from the loadable object.
The reason we have to call this symbol directly is to ensure proper lifetime of the struct request. For example in C, when a driver converts a tag to a request, the developer makes sure to only ask for requests which are outstanding in the driver. In Rust, for the API to be sound, we must ensure that the developer cannot write safe code that obtains a reference to a request that is not owned by the driver.
A similar issue exists in the null block driver when timer completions are enabled. If the request is cancelled and the timer fires after the request has been recycled, there is a problem because the timer holds a reference to the request private data area.
To that end, I use the atomic_t ref field of the C struct request and implement the AlwaysRefCounted Rust trait for the request type. This is a smart pointer that owns a reference to the pointee. In this way, the request is not freed and recycled until the smart pointer is dropped. But if the smart pointer holds the last reference when it is dropped, it must be able to free the request, and hence it has to call __blk_mq_free_request.
We could tag the function with #[inline(never)], but that would impact performance.
Best regards,
Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 33 lines · Andreas Hindborg
Quoted 24 lines · Ming Lei
Quoted 23 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
(quoted diff) +0
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set);Quoted 7 lines
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 4 lines
(quoted diff) +1
-0+void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
Quoted 3 lines
It is not the rust null block driver that calls this symbol directly. It is called by the Rust block device driver API. But because of inlining, the symbol is referenced from the loadable object.
What is the exact Rust block device driver API? The key point is that how the body of one exported kernel C API(EXPORT_SYMBOL) becomes inlined with Rust driver.
Quoted 3 lines
The reason we have to call this symbol directly is to ensure proper lifetime of the
struct request. For example in C, when a driver
Sounds Rust API still calls into __blk_mq_free_request() directly, right?
If that is the case, the usecase need to be justified, and you need to write one standalone patch with the exact story for exporting __blk_mq_free_request().
Quoted 10 lines
converts a tag to a request, the developer makes sure to only ask for requests which are outstanding in the driver. In Rust, for the API to be sound, we must ensure that the developer cannot write safe code that obtains a reference to a request that is not owned by the driver.
A similar issue exists in the null block driver when timer completions are enabled. If the request is cancelled and the timer fires after the request has been recycled, there is a problem because the timer holds a reference to the request private data area.
Quoted 7 lines
To that end, I use the
atomic_t reffield of the Cstruct requestand implement theAlwaysRefCountedRust trait for the request type. This is a smart pointer that owns a reference to the pointee. In this way, the request is not freed and recycled until the smart pointer is dropped. But if the smart pointer holds the last reference when it is dropped, it must be able to free the request, and hence it has to call__blk_mq_free_request.
For callbacks(queue_rq, timeout, complete) implemented by driver, block layer core guaranteed that the passed request reference is live.
So driver needn't to worry about request lifetime, same with Rust driver, I think smart pointer isn't necessary for using request in Rust driver.
Thanks,
Ming
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 34 lines · Ming Lei
Quoted 33 lines · Andreas Hindborg
Quoted 31 lines · Ming Lei
Quoted 20 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 7 lines
(quoted diff) +1
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set); +void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
Quoted 7 lines
Quoted 3 lines
It is not the rust null block driver that calls this symbol directly. It is called by the Rust block device driver API. But because of inlining, the symbol is referenced from the loadable object.
What is the exact Rust block device driver API? The key point is that how the body of one exported kernel C
API(EXPORT_SYMBOL)becomes inlined with Rust driver.
This happens when ARef<Request<_>> is dropped. The drop method (destructor) of this smart pointer decrements the refcount and potentially calls __blk_mq_free_request.
Quoted 5 lines
Quoted 3 lines
The reason we have to call this symbol directly is to ensure proper lifetime of the
struct request. For example in C, when a driverSounds Rust API still calls into
__blk_mq_free_request()directly, right?
Yes, the Rust block device driver API will call this request if an ARef<Request<_>> is dropped and the refcount goes to 0.
Quoted 3 lines
If that is the case, the usecase need to be justified, and you need to write one standalone patch with the exact story for exporting
__blk_mq_free_request().
Ok, I can do that.
Quoted 19 lines
Quoted 11 lines
converts a tag to a request, the developer makes sure to only ask for requests which are outstanding in the driver. In Rust, for the API to be sound, we must ensure that the developer cannot write safe code that obtains a reference to a request that is not owned by the driver.
A similar issue exists in the null block driver when timer completions are enabled. If the request is cancelled and the timer fires after the request has been recycled, there is a problem because the timer holds a reference to the request private data area.
Quoted 7 lines
To that end, I use the
atomic_t reffield of the Cstruct requestand implement theAlwaysRefCountedRust trait for the request type. This is a smart pointer that owns a reference to the pointee. In this way, the request is not freed and recycled until the smart pointer is dropped. But if the smart pointer holds the last reference when it is dropped, it must be able to free the request, and hence it has to call__blk_mq_free_request.
Quoted 6 lines
For
callbacks(queue_rq, timeout, complete)implemented by driver, block layer core guaranteed that the passed request reference is live.So driver needn't to worry about request lifetime, same with Rust driver, I think smart pointer isn't necessary for using request in Rust driver.
Using the C API, there is nothing preventing a driver from using the request after the lifetime ends. With Rust, we have to make it impossible. Without the refcount and associated call to __blk_mq_free_request, it would be possible to write Rust code that access the request after the lifetime ends. This is not sound, and it is something we need to avoid in the Rust abstractions.
One concrete way to do write unsound code with a Rust API where lifetime is not tracked with refcount, is if the null block timer completion callback fires after the request is completed. Perhaps the driver cancels the request but forgets to cancel the timer. When the timer fires, it will access the request via the context pointer, but the request will be invalid. In C we have to write the driver code so this cannot happen. In Rust, the API must prevent this from happening. So any driver written in the safe subset of Rust using this API can never trigger this behavior.
By using the refcount, we ensure that the request is alive until all users who hold a reference to it are dropped.
Another concrete example is when a driver calls blk_mq_tag_to_rq with an invalid tag. This can return a reference to an invalid tag, if the driver is not implemented correctly. By using req_ref_inc_not_zero we can assert that the request is live before we create a Rust reference to it, and even if the driver code has bugs, it can never access an invalid request, and thus it can be memory safe.
We move the responsibility of correctness, in relation to memory safety, from the driver implementation to the API implementation.
Best regards,
Andreas
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 85 lines · Andreas Hindborg
Quoted 34 lines · Ming Lei
Quoted 33 lines · Andreas Hindborg
Quoted 31 lines · Ming Lei
Quoted 20 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 7 lines
(quoted diff) +1
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set); +void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
Quoted 7 lines
Quoted 3 lines
It is not the rust null block driver that calls this symbol directly. It is called by the Rust block device driver API. But because of inlining, the symbol is referenced from the loadable object.
What is the exact Rust block device driver API? The key point is that how the body of one exported kernel C
API(EXPORT_SYMBOL)becomes inlined with Rust driver.This happens when
ARef<Request<_>>is dropped. The drop method (destructor) of this smart pointer decrements the refcount and potentially calls__blk_mq_free_request.Quoted 5 lines
Quoted 3 lines
The reason we have to call this symbol directly is to ensure proper lifetime of the
struct request. For example in C, when a driverSounds Rust API still calls into
__blk_mq_free_request()directly, right?Yes, the Rust block device driver API will call this request if an
ARef<Request<_>>is dropped and the refcount goes to 0.Quoted 3 lines
If that is the case, the usecase need to be justified, and you need to write one standalone patch with the exact story for exporting
__blk_mq_free_request().Ok, I can do that.
Quoted 22 lines
Quoted 11 lines
converts a tag to a request, the developer makes sure to only ask for requests which are outstanding in the driver. In Rust, for the API to be sound, we must ensure that the developer cannot write safe code that obtains a reference to a request that is not owned by the driver.
A similar issue exists in the null block driver when timer completions are enabled. If the request is cancelled and the timer fires after the request has been recycled, there is a problem because the timer holds a reference to the request private data area.
Quoted 7 lines
To that end, I use the
atomic_t reffield of the Cstruct requestand implement theAlwaysRefCountedRust trait for the request type. This is a smart pointer that owns a reference to the pointee. In this way, the request is not freed and recycled until the smart pointer is dropped. But if the smart pointer holds the last reference when it is dropped, it must be able to free the request, and hence it has to call__blk_mq_free_request.For
callbacks(queue_rq, timeout, complete)implemented by driver, block layer core guaranteed that the passed request reference is live.
Quoted 6 lines
Quoted 3 lines
So driver needn't to worry about request lifetime, same with Rust driver, I think smart pointer isn't necessary for using request in Rust driver.
Using the C API, there is nothing preventing a driver from using the request after the lifetime ends.
Yes, it is true for C, so will Rust-for-linux need to add refcount for most exported kernel C structure? such as by implementing AlwaysRefCounted traits?
Quoted 6 lines
With Rust, we have to make it
impossible.Without the refcount and associated call to__blk_mq_free_request, it would be possible to write Rust code that access the request after the lifetime ends. This is not sound, and it is something we need to avoid in the Rust abstractions.
Quoted 6 lines
One concrete way to do write unsound code with a Rust API where lifetime is not tracked with refcount, is if the null block timer completion callback fires after the request is completed. Perhaps the driver cancels the request but forgets to cancel the timer. When the timer fires, it will access the request via the context pointer, but the request will be invalid.
The issue is less serious for blk-mq request, which is pre-allocated, and one freed request just means it can be re-allocated for other IO in same queue, and the pointed memory won't be really freed.
Also as I mentioned, inside driver's ->timeout(), the request is guaranteed to be live by block layer core(won't be re-allocated to other IO), the passed-in request is referenced already, please see bt_iter() which is called from blk_mq_timeout_work(). Here, block layer core just borrows request, then passed the reference to ->timeout(), when request is owned by driver actually.
I understand Rust block driver still need to implement ->queue_rq(), ->timeout(), ..., just like C driver, but maybe I am wrong? Or Rust block driver will re-implement part of block layer core code? such as, get one extra reference of request no matter block core has done that.
Quoted 7 lines
In C we have to write the driver code so this
cannot happen. In Rust, the API must prevent this from happening. So any driver written in the safe subset of Rust using this API can never trigger this behavior.By using the refcount, we ensure that the request is alive until all users who hold a reference to it are dropped.
block layer has provided such guarantee if Rust driver follows current block driver model.
Quoted 10 lines
Another concrete example is when a driver calls
blk_mq_tag_to_rqwith an invalid tag. This can return a reference to an invalid tag, if the driver is not implemented correctly. By usingreq_ref_inc_not_zerowe can assert that the request is live before we create a Rust reference to it, and even if the driver code has bugs, it can never access an invalid request, and thus it can be memory safe.We move the responsibility of correctness, in relation to memory safety, from the driver implementation to the API implementation.
After queue_rq(req) is called, request ownership is actually transferred to driver like Rust's move, then driver is free to call blk_mq_tag_to_rq(), and finally return request to block core after the request is completed by driver.
The biggest question should be how Rust block driver will be designed & implemented? Will rust block driver follow current C driver's model, such as implementing ->queue_rq(), ->timeout(), ->complete()...?
thanks,
Ming
Re: [RFC PATCH 1/5] rust: block: introduce `kernel::block::mq` module
Quoted 90 lines · Ming Lei
Quoted 89 lines · Andreas Hindborg
Quoted 34 lines · Ming Lei
Quoted 33 lines · Andreas Hindborg
Quoted 31 lines · Ming Lei
Quoted 20 lines · Andreas Hindborg
Quoted 9 lines · Miguel Ojeda
Quoted 7 lines · Andreas Hindborg
The way the current code compiles, <
kernel::block::mq::Requestas kernel::types::AlwaysRefCounted>::dec_refis inlined into thernullmodule. A relocation forrust_helper_blk_mq_free_request_internalappears inrnull_mod.ko. I didn't test it yet, but if__blk_mq_free_request` (or the helper) is not exported, I don't think this would be possible?Quoted 5 lines
Yeah, something needs to be exported since there is a generic involved, but even if you want to go the route of exporting only a different symbol, you would still want to put it in the C header so that you don't get the C missing declaration warning and so that we don't have to write the declaration manually in the helper.
That is what I did:
Review int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, · line 709
Quoted 7 lines
(quoted diff) +1
-0@@ -703,6 +703,7 @@ int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set, unsigned int set_flags); void blk_mq_free_tag_set(struct blk_mq_tag_set *set); +void __blk_mq_free_request(struct request *rq); void blk_mq_free_request(struct request *rq); int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, unsigned int poll_flags);Can you explain in detail why one block layer internal helper is called into rnull driver directly? It never happens in C driver code.
Quoted 7 lines
Quoted 3 lines
It is not the rust null block driver that calls this symbol directly. It is called by the Rust block device driver API. But because of inlining, the symbol is referenced from the loadable object.
What is the exact Rust block device driver API? The key point is that how the body of one exported kernel C
API(EXPORT_SYMBOL)becomes inlined with Rust driver.This happens when
ARef<Request<_>>is dropped. The drop method (destructor) of this smart pointer decrements the refcount and potentially calls__blk_mq_free_request.Quoted 5 lines
Quoted 3 lines
The reason we have to call this symbol directly is to ensure proper lifetime of the
struct request. For example in C, when a driverSounds Rust API still calls into
__blk_mq_free_request()directly, right?Yes, the Rust block device driver API will call this request if an
ARef<Request<_>>is dropped and the refcount goes to 0.Quoted 3 lines
If that is the case, the usecase need to be justified, and you need to write one standalone patch with the exact story for exporting
__blk_mq_free_request().Ok, I can do that.
Quoted 25 lines
Quoted 11 lines
converts a tag to a request, the developer makes sure to only ask for requests which are outstanding in the driver. In Rust, for the API to be sound, we must ensure that the developer cannot write safe code that obtains a reference to a request that is not owned by the driver.
A similar issue exists in the null block driver when timer completions are enabled. If the request is cancelled and the timer fires after the request has been recycled, there is a problem because the timer holds a reference to the request private data area.
Quoted 7 lines
To that end, I use the
atomic_t reffield of the Cstruct requestand implement theAlwaysRefCountedRust trait for the request type. This is a smart pointer that owns a reference to the pointee. In this way, the request is not freed and recycled until the smart pointer is dropped. But if the smart pointer holds the last reference when it is dropped, it must be able to free the request, and hence it has to call__blk_mq_free_request.For
callbacks(queue_rq, timeout, complete)implemented by driver, block layer core guaranteed that the passed request reference is live.So driver needn't to worry about request lifetime, same with Rust driver, I think smart pointer isn't necessary for using request in Rust driver.
Quoted 6 lines
Quoted 2 lines
Using the C API, there is nothing preventing a driver from using the request after the lifetime ends.
Yes, it is true for C, so will Rust-for-linux need to add refcount for most exported kernel C structure? such as by implementing AlwaysRefCounted traits?
Not for all types and not all the time. For instance the Rust block device driver API does not always use refcounting for struct request. Only when it cannot determine the lifetime of a request reference at compile time.
Quoted 14 lines
Quoted 7 lines
With Rust, we have to make it
impossible.Without the refcount and associated call to__blk_mq_free_request, it would be possible to write Rust code that access the request after the lifetime ends. This is not sound, and it is something we need to avoid in the Rust abstractions.Quoted 6 lines
One concrete way to do write unsound code with a Rust API where lifetime is not tracked with refcount, is if the null block timer completion callback fires after the request is completed. Perhaps the driver cancels the request but forgets to cancel the timer. When the timer fires, it will access the request via the context pointer, but the request will be invalid.
Quoted 3 lines
The issue is less serious for blk-mq request, which is pre-allocated, and one freed request just means it can be re-allocated for other IO in same queue, and the pointed memory won't be really freed.
The issue here is not so much use after free as it is aliasing of mutable and shared references. This is illegal in Rust, and programs that allow this may exhibit undefined behavior.
Quoted 6 lines
Also as I mentioned, inside driver's ->timeout(), the request is guaranteed to be live by block layer core(won't be re-allocated to other IO), the passed-in request is referenced already, please see
bt_iter()which is called fromblk_mq_timeout_work(). Here, block layer core just borrows request, then passed the reference to ->timeout(), when request is owned by driver actually.
I understand. I am not referring to blk_mq_opw.timeout. The null block driver has a feature where requests complete after a delay. This is implemented via the hrtimer subsystem.
Quoted 4 lines
I understand Rust block driver still need to implement ->queue_rq(), ->timeout(), ..., just like C driver, but maybe I am wrong? Or Rust block driver will re-implement part of block layer core code? such as, get one extra reference of request no matter block core has done that.
The Rust block driver API implements the blk_mq_ops vtable on behalf of the driver. There is a little bit of glue code inserted between the C symbols called by the kernel and the Rust functions that the block device driver provides.
Quoted 10 lines
Quoted 7 lines
In C we have to write the driver code so this
cannot happen. In Rust, the API must prevent this from happening. So any driver written in the safe subset of Rust using this API can never trigger this behavior.By using the refcount, we ensure that the request is alive until all users who hold a reference to it are dropped.
block layer has provided such guarantee if Rust driver follows current block driver model.
I understand that the driver has exclusive ownership of the request between queue_rq() and complete(). What we want to guarantee is that the author of a block device driver is not able to access a request after block layer has regained ownership of the request (after complete). The way we achieve this is by preventing block layer from calling __blk_mq_free_request if the Rust driver did not destroy all references to the request.
I understand that this is not necessary for correct operation of a block device driver. However, it is necessary to uphold invariants of the Rust language for references.
Quoted 8 lines
Quoted 8 lines
Another concrete example is when a driver calls
blk_mq_tag_to_rqwith an invalid tag. This can return a reference to an invalid tag, if the driver is not implemented correctly. By usingreq_ref_inc_not_zerowe can assert that the request is live before we create a Rust reference to it, and even if the driver code has bugs, it can never access an invalid request, and thus it can be memory safe.
Quoted 6 lines
Quoted 2 lines
We move the responsibility of correctness, in relation to memory safety, from the driver implementation to the API implementation.
After
queue_rq(req)is called, request ownership is actually transferred to driver like Rust's move, then driver is free to callblk_mq_tag_to_rq(), and finally return request to block core after the request is completed by driver.
As I said, I understand and appreciate this design. But there is a possibility for a buggy driver to not obey. The Rust abstractions must prevent this buggy code from compiling at all. In Rust, it must be impossible to call blk_mq_tag_to_rq() for a tag that is not owned by the driver. blk_mq_tag_to_rq takes an integer, so the driver developer can call this function with an invalid tag like blk_mq_tag_to_rq(tagset, 5). If 5 is not owned by the driver, this will return a request pointer that will alias with mutable access. When this pointer is converted to a Rust reference, this will give undefined behavior. For Rust, we must prevent code like this from compiling in the first place.
Quoted 3 lines
The biggest question should be how Rust block driver will be designed & implemented? Will rust block driver follow current C driver's model, such as implementing ->queue_rq(), ->timeout(), ->complete()...?
The Rust driver API does follow the design of the C driver model. It does implement the blk_mq_ops vtable. Rust block drivers must implement a set of Rust functions that very closely follow this vtable. But when it is not possible to statically determine the lifetime of an object, to the point where the compiler will refuse to compile the code that violates the lifetime durations of the object, we must revert to reference counting.
I understand that a correctly implemented block device driver will not violate lifetime of the request structure. Incorrect driver code might violate the lifetime though. With Rust, we must prevent incorrectly implemented drivers from compiling at all. We need the refcount for that. By only allowing access to the request through the refcounted pointer in certain cases, we prevent the safe driver code from misbehaving.
It might seem cumbersome to do this dance at first. After all, we can just write the device drivers correctly without memory safety bugs. But the reward for all this work is that if a device driver is implemented in the safe subset of Rust, it _cannot_ exhibit memory safety related bugs. We don't have to review a device driver implemented in safe Rust for memory safety issues at all.
Best regards,
Andreas
RFC PATCH 2/5 rust: block: introduce `kernel::block::bio` module
In reply to Andreas HindborgFrom: Andreas Hindborg <[email protected]>
Add abstractions for working with struct bio.
--- rust/kernel/block.rs | 1 + rust/kernel/block/bio.rs | 112 +++++++++++++ rust/kernel/block/bio/vec.rs | 279 ++++++++++++++++++++++++++++++++ rust/kernel/block/mq/request.rs | 22 +++ 4 files changed, 414 insertions(+) create mode 100644 rust/kernel/block/bio.rs create mode 100644 rust/kernel/block/bio/vec.rs
rust/kernel/block.rs +1 -0
@@ -2,4 +2,5 @@//! Types for working with the block layer +pub mod bio;pub mod mq;
rust/kernel/block/bio.rs new file +112 -0
112 lines not on this page · raw message
rust/kernel/block/bio/vec.rs new file +279 -0
279 lines not on this page · raw message
rust/kernel/block/mq/request.rs +22 -0
@@ -12,6 +12,9 @@ };use core::{ffi::c_void, marker::PhantomData , ops::Deref }; +use crate ::block::bio::Bio ; +use crate ::block::bio::BioIterator ; +/// A wrapper around a blk-mq `struct request`. This represents an IO request. /// /// # Invariants
@@ -84,6 +87,25 @@ pub fn complete(&self) { } } +/// Get a wrapper for the first Bio in this request +#[inline(always)] +pub fn bio (&self) ->Option <&Bio > { +// SAFETY: By type invariant of `Self`, `self.0` is valid and the deref +// is safe. +let ptr =unsafe { (*self.0 .get ()).bio }; +// SAFETY: By C API contract, if `bio` is not null it will have a +// positive refcount at least for the duration of the lifetime of +// `&self`. +unsafe {Bio ::from_raw (ptr) } + } + +/// Get an iterator over all bio structurs in this request +#[inline(always)] +pub fn bio_iter (&self) ->BioIterator <'_> { +BioIterator { bio: self.bio () } + } + +// TODO: Check if inline is still required for cross language LTO inlining into module /// Get the target sector for the request #[inline(always)] pub fn sector (&self) ->usize {
Signature · 1 line
2.44.0
RFC PATCH 3/5 rust: block: allow `hrtimer::Timer` in `RequestData`
In reply to Andreas HindborgFrom: Andreas Hindborg <[email protected]>
--- rust/kernel/block/mq/request.rs | 67 ++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-)
rust/kernel/block/mq/request.rs +66 -1
@@ -4,13 +4,16 @@//! //! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h) +use kernel::hrtimer::RawTimer ; +use crate ::{ bindings, block::mq::Operations , error::{Error ,Result }, + hrtimer::{HasTimer ,TimerCallback }, types::{ARef ,AlwaysRefCounted ,Opaque }, }; -use core::{ffi::c_void, marker::PhantomData , ops::Deref }; +use core::{ffi::c_void, marker::PhantomData , ops::Deref , ptr::NonNull };use crate ::block::bio::Bio ;use crate ::block::bio::BioIterator ;
@@ -175,6 +178,68 @@ fn deref(&self) -> &Self::Target { } } +impl <T >RawTimer for RequestDataRef <T > +where +T :Operations , +T ::RequestData :HasTimer <T ::RequestData >, +T ::RequestData :Sync , +{ +fn schedule (self, expires:u64 ) { +let self_ptr = self.deref ()as *const T ::RequestData ; + core::mem::forget (self); + +// SAFETY: `self_ptr` is a valid pointer to a `T::RequestData` +let timer_ptr =unsafe {T ::RequestData ::raw_get_timer (self_ptr) }; + +// `Timer` is `repr(transparent)` +let c_timer_ptr = timer_ptr.cast ::<bindings::hrtimer >(); + +// Schedule the timer - if it is already scheduled it is removed and +// inserted + +// SAFETY: c_timer_ptr points to a valid hrtimer instance that was +// initialized by `hrtimer_init` +unsafe { + bindings::hrtimer_start_range_ns ( + c_timer_ptras *mut _ , + expiresas i64 , +0 , + bindings::hrtimer_mode_HRTIMER_MODE_REL, + ); + } + } +} + +impl <T > kernel::hrtimer::RawTimerCallback for RequestDataRef <T > +where +T :Operations , +T :Sync , +T ::RequestData :HasTimer <T ::RequestData >, +T ::RequestData :TimerCallback <Receiver =Self >, +{ +unsafe extern "C" fn run (ptr: *mut bindings::hrtimer ) -> bindings::hrtimer_restart { +// `Timer` is `repr(transparent)` +let timer_ptr = ptr.cast ::<kernel::hrtimer::Timer <T ::RequestData >>(); + +// SAFETY: By C API contract `ptr` is the pointer we passed when +// enqueing the timer, so it is a `Timer<T::RequestData>` embedded in a `T::RequestData` +let receiver_ptr =unsafe {T ::RequestData ::timer_container_of (timer_ptr) }; + +// SAFETY: The pointer was returned by `T::timer_container_of` so it +// points to a valid `T::RequestData` +let request_ptr =unsafe { bindings::blk_mq_rq_from_pdu (receiver_ptr.cast ::<c_void >()) }; + +// SAFETY: We own a refcount that we leaked during `RawTimer::schedule()` +let dref =RequestDataRef ::new (unsafe { +ARef ::from_raw (NonNull ::new_unchecked (request_ptr.cast ::<Request <T >>())) + }); + +T ::RequestData ::run (dref); + + bindings::hrtimer_restart_HRTIMER_NORESTART + } +} +// SAFETY: All instances of `Request<T>` are reference counted. This // implementation of `AlwaysRefCounted` ensure that increments to the ref count // keeps the object alive in memory at least until a matching reference count
Signature · 1 line
2.44.0
Re: [RFC PATCH 3/5] rust: block: allow `hrtimer::Timer` in `RequestData`
On 3/13/24 12:05, Andreas Hindborg wrote:> From: Andreas Hindborg <[email protected]>
Quoted 58 lines
Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/block/mq/request.rs | 67 ++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-)rust/kernel/block/mq/request.rs +30
-1@@ -4,13 +4,16 @@//! //! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h) +use kernel::hrtimer::RawTimer ; +use crate ::{ bindings, block::mq::Operations , error::{Error ,Result }, + hrtimer::{HasTimer ,TimerCallback }, types::{ARef ,AlwaysRefCounted ,Opaque }, }; -use core::{ffi::c_void, marker::PhantomData , ops::Deref }; +use core::{ffi::c_void, marker::PhantomData , ops::Deref , ptr::NonNull };use crate ::block::bio::Bio ;use crate ::block::bio::BioIterator ;@@ -175,6 +178,68 @@ fn deref(&self) -> &Self::Target { } } +impl <T >RawTimer for RequestDataRef <T > +where +T :Operations , +T ::RequestData :HasTimer <T ::RequestData >, +T ::RequestData :Sync , +{ +fn schedule (self, expires:u64 ) { +let self_ptr = self.deref ()as *const T ::RequestData ; + core::mem::forget (self); + +// SAFETY: `self_ptr` is a valid pointer to a `T::RequestData` +let timer_ptr =unsafe {T ::RequestData ::raw_get_timer (self_ptr) }; + +// `Timer` is `repr(transparent)` +let c_timer_ptr = timer_ptr.cast ::<bindings::hrtimer >(); + +// Schedule the timer - if it is already scheduled it is removed and +// inserted + +// SAFETY: c_timer_ptr points to a valid hrtimer instance that was +// initialized by `hrtimer_init` +unsafe { + bindings::hrtimer_start_range_ns ( + c_timer_ptras *mut _ , + expiresas i64 , + 0,
rust/kernel/block/mq/request.rs fn deref(&self) -> &Self::Target { · line 216
Quoted 10 lines
rust/kernel/block/mq/request.rs +10
-0+ bindings::hrtimer_mode_HRTIMER_MODE_REL, + ); + } + } +} + +impl <T > kernel::hrtimer::RawTimerCallback for RequestDataRef <T > +where +T :Operations , +T :Sync ,
Why is this needed? Shouldn't this be T::RequestData: Sync?
Is the run function below executed on a different thread compared to the schedule function above?
If yes, then T::RequestData probably also needs to be Send. You also would need to adjust the bounds in the impl above.
Signature · 2 lines
Cheers, Benno
Quoted 32 lines
rust/kernel/block/mq/request.rs +26
-1+ T::RequestData: HasTimer<T::RequestData>, + T::RequestData: TimerCallback<Receiver = Self>, +{ +unsafe extern "C" fn run (ptr: *mut bindings::hrtimer ) -> bindings::hrtimer_restart { +// `Timer` is `repr(transparent)` +let timer_ptr = ptr.cast ::<kernel::hrtimer::Timer <T ::RequestData >>(); + +// SAFETY: By C API contract `ptr` is the pointer we passed when +// enqueing the timer, so it is a `Timer<T::RequestData>` embedded in a `T::RequestData` +let receiver_ptr =unsafe {T ::RequestData ::timer_container_of (timer_ptr) }; + +// SAFETY: The pointer was returned by `T::timer_container_of` so it +// points to a valid `T::RequestData` +let request_ptr =unsafe { bindings::blk_mq_rq_from_pdu (receiver_ptr.cast ::<c_void >()) }; + +// SAFETY: We own a refcount that we leaked during `RawTimer::schedule()` +let dref =RequestDataRef ::new (unsafe { +ARef ::from_raw (NonNull ::new_unchecked (request_ptr.cast ::<Request <T >>())) + }); + +T ::RequestData ::run (dref); + + bindings::hrtimer_restart_HRTIMER_NORESTART + } +} +// SAFETY: All instances of `Request<T>` are reference counted. This // implementation of `AlwaysRefCounted` ensure that increments to the ref count // keeps the object alive in memory at least until a matching reference count --2.44.0
Re: [RFC PATCH 3/5] rust: block: allow `hrtimer::Timer` in `RequestData`
Quoted 72 lines · Benno Lossin
On 3/13/24 12:05, Andreas Hindborg wrote:> From: Andreas Hindborg <[email protected]>
Quoted 58 lines
Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/block/mq/request.rs | 67 ++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-)rust/kernel/block/mq/request.rs +30
-1@@ -4,13 +4,16 @@//! //! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h) +use kernel::hrtimer::RawTimer ; +use crate ::{ bindings, block::mq::Operations , error::{Error ,Result }, + hrtimer::{HasTimer ,TimerCallback }, types::{ARef ,AlwaysRefCounted ,Opaque }, }; -use core::{ffi::c_void, marker::PhantomData , ops::Deref }; +use core::{ffi::c_void, marker::PhantomData , ops::Deref , ptr::NonNull };use crate ::block::bio::Bio ;use crate ::block::bio::BioIterator ;@@ -175,6 +178,68 @@ fn deref(&self) -> &Self::Target { } } +impl <T >RawTimer for RequestDataRef <T > +where +T :Operations , +T ::RequestData :HasTimer <T ::RequestData >, +T ::RequestData :Sync , +{ +fn schedule (self, expires:u64 ) { +let self_ptr = self.deref ()as *const T ::RequestData ; + core::mem::forget (self); + +// SAFETY: `self_ptr` is a valid pointer to a `T::RequestData` +let timer_ptr =unsafe {T ::RequestData ::raw_get_timer (self_ptr) }; + +// `Timer` is `repr(transparent)` +let c_timer_ptr = timer_ptr.cast ::<bindings::hrtimer >(); + +// Schedule the timer - if it is already scheduled it is removed and +// inserted + +// SAFETY: c_timer_ptr points to a valid hrtimer instance that was +// initialized by `hrtimer_init` +unsafe { + bindings::hrtimer_start_range_ns ( + c_timer_ptras *mut _ , + expiresas i64 , + 0,rust/kernel/block/mq/request.rs fn deref(&self) -> &Self::Target { · line 216
Quoted 10 lines
rust/kernel/block/mq/request.rs +10
-0+ bindings::hrtimer_mode_HRTIMER_MODE_REL, + ); + } + } +} + +impl <T > kernel::hrtimer::RawTimerCallback for RequestDataRef <T > +where +T :Operations , +T :Sync ,Why is this needed? Shouldn't this be
T::RequestData: Sync?
Quoted 4 lines
Is the
runfunction below executed on a different thread compared to theschedulefunction above?
If yes, thenT::RequestDataprobably also needs to beSend. You also would need to adjust the bounds in the impl above.
It's a typo, thanks for spotting. It should be T::RequestData: Sync.
BR Andreas
RFC PATCH 4/5 rust: block: add rnull, Rust null_blk implementation
In reply to Andreas HindborgFrom: Andreas Hindborg <[email protected]>
--- drivers/block/Kconfig | 4 + drivers/block/Makefile | 3 + drivers/block/rnull.rs | 323 +++++++++++++++++++++++++++++++++++++++++ rust/helpers.c | 1 + scripts/Makefile.build | 2 +- 5 files changed, 332 insertions(+), 1 deletion(-) create mode 100644 drivers/block/rnull.rs
drivers/block/Kconfig +4 -0
@@ -354,6 +354,10 @@ config VIRTIO_BLK This is the virtual block driver for virtio. It can be used with QEMU based VMMs (like KVM or Xen). Say Y or M. +config BLK_DEV_RUST_NULL + tristate "Rust null block driver" + depends on RUST + config BLK_DEV_RBD tristate "Rados block device (RBD)" depends on INET && BLOCK
drivers/block/Makefile +3 -0
@@ -9,6 +9,9 @@ # needed for trace events ccflags-y += -I$(src) +obj-$(CONFIG_BLK_DEV_RUST_NULL) += rnull_mod.o +rnull_mod-y := rnull.o + obj-$(CONFIG_MAC_FLOPPY) += swim3.o obj-$(CONFIG_BLK_DEV_SWIM) += swim_mod.o obj-$(CONFIG_BLK_DEV_FD) += floppy.o
drivers/block/rnull.rs new file +323 -0
323 lines not on this page · raw message
rust/helpers.c +1 -0
@@ -200,6 +200,7 @@ struct page *rust_helper_folio_page(struct folio *folio, size_t n) {return folio_page (folio, n); } +EXPORT_SYMBOL_GPL (rust_helper_folio_page);loff_t rust_helper_folio_pos (struct folio *folio) {
scripts/Makefile.build +1 -1
@@ -262,7 +262,7 @@ $(obj)/%.lst: $(src)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit,offset_of +rust_allowed_features := new_uninit,offset_of,allocator_api,impl_trait_in_assoc_type # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree
Signature · 1 line
2.44.0
Re: [RFC PATCH 4/5] rust: block: add rnull, Rust null_blk implementation
drivers/block/rnull.rs line 50
Quoted 12 lines · Andreas Hindborg
drivers/block/rnull.rs new file +12
-0+module! { +type :NullBlkModule , + name:"rnull_mod" , + author:"Andreas Hindborg" , + license:"GPL v2" , +params : { + param_memory_backed:bool { +default :true , + permissions:0 , + description:"Use memory backing" , + }, +// Problems with pin_init when `irq_mode`
Can you elaborate?
Signature · 2 lines
Cheers, Benno
Quoted 22 lines
drivers/block/rnull.rs new file +22
-0+ param_irq_mode: u8 { + default: 0, + permissions: 0, + description: "IRQ Mode (0: None, 1: Soft, 2: Timer)", + }, + param_capacity_mib: u64 { + default: 4096, + permissions: 0, + description: "Device capacity in MiB", + }, + param_completion_time_nsec: u64 { + default: 1_000_000, + permissions: 0, + description: "Completion time in nano seconds for timer mode", + }, + param_block_size: u16 { + default: 4096, + permissions: 0, + description: "Block size in bytes", + }, + }, +}
Re: [RFC PATCH 4/5] rust: block: add rnull, Rust null_blk implementation
Quoted 14 lines · Benno Lossin
Review
Quoted 12 lines · Andreas Hindborg
(quoted diff) +12
-0+module! { + type: NullBlkModule, + name: "rnull_mod", + author: "Andreas Hindborg", + license: "GPL v2", + params: { + param_memory_backed: bool { + default: true, + permissions: 0, + description: "Use memory backing", + }, + // Problems with pin_init when `irq_mode`
Quoted 1 line
Can you elaborate?
I think we discussed this before, but I do not recall what you decided was the issue.
It is probably easier if you can apply the patches and try to build with this on top:
drivers/block/rnull.rs +2 -2
@@ -48,7 +48,7 @@ description: "Use memory backing", },// Problems with pin_init when `irq_mode` - param_irq_mode: u8 { + irq_mode: u8 { default:0 , permissions:0 , description:"IRQ Mode (0: None, 1: Soft, 2: Timer)" ,
@@ -101,7 +101,7 @@ fn add_disk(tagset: Arc<TagSet<NullBlkDevice>>) -> Result<GenDisk<NullBlkDevice>return Err (kernel::error::code::EINVAL ); } -let irq_mode = (*param_irq_mode.read ()).try_into ()?; +let irq_mode = (*irq_mode.read ()).try_into ()?; let queue_data = Box::pin_init(pin_init!( QueueData {
---
There is some kind of name clash issue when using pin_init! in the expression on line 106:
let queue_data = Box::pin_init(pin_init!(
QueueData {
tree <- TreeContainer::new(),
completion_time_nsec: *param_completion_time_nsec.read(),
irq_mode,
memory_backed: *param_memory_backed.read(),
block_size,
}
))?;I cannot immediately decipher the error message:
RUSTC [M] drivers/block/rnull.o
error[E0277]: the trait bound __rnull_mod_irq_mode: From<u8> is not satisfied
--> /home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:104:39
|
104 | let irq_mode = (*irq_mode.read()).try_into()?;
| ^^^^^^^^ the trait `From<u8>` is not implemented for `__rnull_mod_irq_mode`
| = note: required for u8 to implement Into<__rnull_mod_irq_mode> = note: required for __rnull_mod_irq_mode to implement TryFrom<u8> = note: required for u8 to implement TryInto<__rnull_mod_irq_mode>
error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:106:36
|
106 | let queue_data = Box::pin_init(pin_init!(
| ____________________________________^
107 | | QueueData {
108 | | tree <- TreeContainer::new(),
109 | | completion_time_nsec: *param_completion_time_nsec.read(),
... |
113 | | }
114 | | ))?;
| | ^
| | |
| |_____expected `IRQMode`, found `__rnull_mod_irq_mode`
| arguments to this function are incorrect
|
note: function defined here
--> /home/aeh/.rustup/toolchains/1.74.1-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1365:21
|1365 | pub const unsafe fn write<T>(dst: *mut T, src: T) {
| ^^^^^
= note: this error originates in the macro $crate::__init_internal which comes from the expansion of the macro pin_init (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:106:36
|
39 | / module! {
40 | | type: NullBlkModule,
41 | | name: "rnull_mod",
42 | | author: "Andreas Hindborg",
... |
71 | | },
72 | | }
| |_- constant defined here
...
106 | let queue_data = Box::pin_init(pin_init!(
| ____________________________________^
| |____________________________________|
| |____________________________________|
| |____________________________________|
| |
107 | | QueueData {
108 | | tree <- TreeContainer::new(),
109 | | completion_time_nsec: *param_completion_time_nsec.read(),
... |
113 | | }
114 | | ))?;
| | ^
| |_____|
| |_____expected `DropGuard<IRQMode>`, found `__rnull_mod_irq_mode`
| |_____this expression has type `DropGuard<IRQMode>`
| |_____`irq_mode` is interpreted as a constant, not a new binding | help: introduce a new binding instead: other_irq_mode
|
= note: expected struct DropGuard<IRQMode>
found struct __rnull_mod_irq_mode
= note: this error originates in the macro $crate::__init_internal which comes from the expansion of the macro pin_init (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0308.
For more information about an error, try rustc --explain E0277.
make[5]: *** [/home/aeh/src/linux-rust/linux/scripts/Makefile.build:293: drivers/block/rnull.o] Error 1
Re: [RFC PATCH 4/5] rust: block: add rnull, Rust null_blk implementation
Quoted 16 lines · Andreas Hindborg
Quoted 14 lines · Benno Lossin
Quoted 12 lines · Andreas Hindborg
(quoted diff) +12
-0+module! { + type: NullBlkModule, + name: "rnull_mod", + author: "Andreas Hindborg", + license: "GPL v2", + params: { + param_memory_backed: bool { + default: true, + permissions: 0, + description: "Use memory backing", + }, + // Problems with pin_init when `irq_mode`
Quoted 4 lines
Quoted 1 line
Can you elaborate?
I think we discussed this before, but I do not recall what you decided was the issue.
Ah I vaguely remember.
Quoted 112 lines
It is probably easier if you can apply the patches and try to build with this on top:
drivers/block/rnull.rs +2
-3@@ -48,7 +48,7 @@ description: "Use memory backing", },// Problems with pin_init when `irq_mode` - param_irq_mode: u8 { + irq_mode: u8 { default:0 , permissions:0 , description:"IRQ Mode (0: None, 1: Soft, 2: Timer)" ,@@ -101,7 +101,7 @@ fn add_disk(tagset: Arc<TagSet<NullBlkDevice>>) -> Result<GenDisk<NullBlkDevice>return Err (kernel::error::code::EINVAL ); } -let irq_mode = (*param_irq_mode.read ()).try_into ()?; +let irq_mode = (*irq_mode.read ()).try_into ()?; let queue_data = Box::pin_init(pin_init!( QueueData { ---There is some kind of name clash issue when using
pin_init!in the expression on line 106:let queue_data = Box::pin_init(pin_init!( QueueData { tree <- TreeContainer::new(), completion_time_nsec: *param_completion_time_nsec.read(), irq_mode, memory_backed: *param_memory_backed.read(), block_size, } ))?;I cannot immediately decipher the error message:
RUSTC [M]
drivers/block/rnull.o
error[E0277]: the trait bound__rnull_mod_irq_mode: From<u8>is not satisfied
-->/home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:104:39| 104 | let irq_mode = (*irq_mode.read()).try_into()?; | ^^^^^^^^ the trait `From<u8>` is not implemented for `__rnull_mod_irq_mode` |= note: required for
u8to implementInto<__rnull_mod_irq_mode>= note: required for__rnull_mod_irq_modeto implementTryFrom<u8>= note: required foru8to implementTryInto<__rnull_mod_irq_mode>error[E0308]: mismatched types
--> /home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:106:36 | 106 | let queue_data = Box::pin_init(pin_init!( | ____________________________________^ 107 | | QueueData { 108 | | tree <- TreeContainer::new(), 109 | | completion_time_nsec: *param_completion_time_nsec.read(), ... | 113 | | } 114 | | ))?; | | ^ | | | | |_____expected `IRQMode`, found `__rnull_mod_irq_mode` | arguments to this function are incorrect | note: function defined here --> /home/aeh/.rustup/toolchains/1.74.1-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1365:21 |1365 | pub const unsafe fn write<T>(dst: *mut T, src: T) {
| ^^^^^
= note: this error originates in the macro$crate::__init_internalwhich comes from the expansion of the macropin_init(in Nightly builds, run with -Z macro-backtrace for more info)error[E0308]: mismatched types
-->/home/aeh/src/linux-rust/linux/drivers/block/rnull.rs:106:36| 39 | / module! { 40 | | type: NullBlkModule, 41 | | name: "rnull_mod", 42 | | author: "Andreas Hindborg", ... | 71 | | }, 72 | | } | |_- constant defined here ... 106 | let queue_data = Box::pin_init(pin_init!( | ____________________________________^ | |____________________________________| | |____________________________________| | |____________________________________| | | 107 | | QueueData { 108 | | tree <- TreeContainer::new(), 109 | | completion_time_nsec: *param_completion_time_nsec.read(), ... | 113 | | } 114 | | ))?; | | ^ | |_____| | |_____expected `DropGuard<IRQMode>`, found `__rnull_mod_irq_mode` | |_____this expression has type `DropGuard<IRQMode>` | |_____`irq_mode` is interpreted as a constant, not a new binding| help: introduce a new binding instead:
other_irq_mode
|
= note: expected structDropGuard<IRQMode>
found struct__rnull_mod_irq_mode
= note: this error originates in the macro$crate::__init_internalwhich comes from the expansion of the macropin_init(in Nightly builds, run with -Z macro-backtrace for more info)
Quoted 5 lines
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0308.
For more information about an error, tryrustc --explain E0277.
make[5]: *** [/home/aeh/src/linux-rust/linux/scripts/Makefile.build:293:drivers/block/rnull.o] Error 1
So I did some digging and there are multiple things at play. I am going to explain the second error first, since that one might be a problem with pin_init:
- the params extension of the module! macro creates constants with snake case names.
- your QueueData struct has the same name as a field.
- pin_init! generates let $field_name = ... statements for each field you initialize
Now when you define a constant in Rust, you are able to pattern-match with that constant, eg:
const FOO: u8 = 0;
fn main() {
match 10 {
FOO => println!("foo"),
_ => {}
}
}So when you do let FOO = x;, then it interprets FOO as the constant. This is still true if the constant has a snake case name. Since the expression in the pin_init! macro has type DropGuard<$field_type>, we get the error "expected DropGuard<IRQMode>, found __rnull_mod_irq_mode".
Now to the first error, this is a problem with the parameter handling of module. By the same argument above, your let binding in line 104:
let irq_mode = (*irq_mode.read()).try_into()?;
Tries to pattern-match the irq_mode constant with the right expression. Since you use the try_into function, it tries to search for a TryInto implementation for the type of irq_mode which is generated by the module! macro. The type is named __rnull_mod_irq_mode.
Now what to do about this. For the second error (the one related to pin_init), I could create a patch that fixes it by adding the suffix _guard to those let bindings, preventing the issue. Not sure if we need that though, since it will not get rid of the first issue.
For the first issue, I think there is no other way than to use a different name for either the field or the constant. Since constants are usually named using screaming snake case, I think it should be renamed. I believe your reason for using a snake case name is that these names are used directly as the names for the parameters when loading the module and there the convention is to use snake case, right? In that case I think we could expect people to write the screaming snake case name in rust and have it automatically be lower-cased by the module! macro when it creates the names that the parameters are shown with.
Hope this helps!
Signature · 2 lines
Cheers, Benno
Re: [RFC PATCH 4/5] rust: block: add rnull, Rust null_blk implementation
Benno Lossin <[email protected]> writes:
[...]
Quoted 23 lines
So I did some digging and there are multiple things at play. I am going to explain the second error first, since that one might be a problem with
pin_init:
- theparamsextension of themodule!macro creates constants with snake case names.
- yourQueueDatastruct has the same name as a field.
-pin_init!generateslet $field_name = ...statements for each field you initializeNow when you define a constant in Rust, you are able to pattern-match with that constant, eg:
const FOO: u8 = 0; fn main() { match 10 { FOO => println!("foo"), _ => {} } }
Quoted 5 lines
So when you do
let FOO = x;, then it interpretsFOOas the constant. This is still true if the constant has a snake case name. Since the expression in thepin_init!macro has typeDropGuard<$field_type>, we get the error "expectedDropGuard<IRQMode>, found__rnull_mod_irq_mode".
Thanks for the analysis!
So in this expanded code:
1 {
2 unsafe { ::core::ptr::write(&raw mut ((*slot).irq_mode), irq_mode) };
3 }
4 let irq_mode = unsafe {
5 $crate::init::__internal::DropGuard::new(&raw mut ((*slot).irq_mode))
6 };
the irq_mode on line 2 will refer to the correct thing, but the one on line 6 will be a pattern match against a constant? That is really surprising to me. Can we make the let binding in line 6 be let irq_mode_pin_init or something similar?
Quoted 13 lines
Now to the first error, this is a problem with the parameter handling of
module. By the same argument above, your let binding in line 104:let irq_mode = (*irq_mode.read()).try_into()?;Tries to pattern-match the
irq_modeconstant with the right expression. Since you use thetry_intofunction, it tries to search for aTryIntoimplementation for the type ofirq_modewhich is generated by themodule!macro. The type is named__rnull_mod_irq_mode.
Quoted 4 lines
Now what to do about this. For the second error (the one related to
pin_init), I could create a patch that fixes it by adding the suffix_guardto those let bindings, preventing the issue. Not sure if we need that though, since it will not get rid of the first issue.
I think that is a good idea 👍
Quoted 11 lines
For the first issue, I think there is no other way than to use a different name for either the field or the constant. Since constants are usually named using screaming snake case, I think it should be renamed. I believe your reason for using a snake case name is that these names are used directly as the names for the parameters when loading the module and there the convention is to use snake case, right? In that case I think we could expect people to write the screaming snake case name in rust and have it automatically be lower-cased by the
module!macro when it creates the names that the parameters are shown with.
I was thinking about putting the parameters in a separate name space, but making them screaming snake case is also a good idea. So it would be module_parameters::IRQ_MODE to access the parameter with the name irq_mode exposed towards the user. Developers can always opt in to bringing the symbols into scope with a use.
Best regards,
Andreas
Re: [RFC PATCH 4/5] rust: block: add rnull, Rust null_blk implementation
Quoted 44 lines · Andreas Hindborg
Benno Lossin <[email protected]> writes:
[...]
Quoted 23 lines
So I did some digging and there are multiple things at play. I am going to explain the second error first, since that one might be a problem with
pin_init:
- theparamsextension of themodule!macro creates constants with snake case names.
- yourQueueDatastruct has the same name as a field.
-pin_init!generateslet $field_name = ...statements for each field you initializeNow when you define a constant in Rust, you are able to pattern-match with that constant, eg:
const FOO: u8 = 0; fn main() { match 10 { FOO => println!("foo"), _ => {} } }Quoted 5 lines
So when you do
let FOO = x;, then it interpretsFOOas the constant. This is still true if the constant has a snake case name. Since the expression in thepin_init!macro has typeDropGuard<$field_type>, we get the error "expectedDropGuard<IRQMode>, found__rnull_mod_irq_mode".Thanks for the analysis!
So in this expanded code:
1 {
2 unsafe { ::core::ptr::write(&raw mut ((*slot).irq_mode),irq_mode) };
3 }
4 letirq_mode= unsafe {
5 $crate::init::__internal::DropGuard::new(&raw mut ((*slot).irq_mode))
6 };
Quoted 4 lines
the
irq_modeon line 2 will refer to the correct thing, but the one on line 6 will be a pattern match against a constant? That is really surprising to me. Can we make the let binding in line 6 belet irq_mode_pin_initor something similar?
The first occurrence of irq_mode in line 2 will refer to the field of QueueData. The second one in line 2 will refer to the constant. The one in line 4 is a pattern-match of the constant (since the type of the constant is a fieldless struct, only one value exists. Thus making the match irrefutable.) The occurrence in line 5 is again referring to the field of QueueData.
If you have a constant FOO, you are unable to create a local binding with the name FOO. So by creating the irq_mode constant, you cannot create (AFAIK) a irq_mode local variable (if the constant is in-scope).
Quoted 14 lines
Quoted 14 lines
Now to the first error, this is a problem with the parameter handling of
module. By the same argument above, your let binding in line 104:let irq_mode = (*irq_mode.read()).try_into()?;Tries to pattern-match the
irq_modeconstant with the right expression. Since you use thetry_intofunction, it tries to search for aTryIntoimplementation for the type ofirq_modewhich is generated by themodule!macro. The type is named__rnull_mod_irq_mode.
Quoted 6 lines
Quoted 4 lines
Now what to do about this. For the second error (the one related to
pin_init), I could create a patch that fixes it by adding the suffix_guardto those let bindings, preventing the issue. Not sure if we need that though, since it will not get rid of the first issue.I think that is a good idea 👍
Will do that.
Quoted 13 lines
Quoted 12 lines
For the first issue, I think there is no other way than to use a different name for either the field or the constant. Since constants are usually named using screaming snake case, I think it should be renamed. I believe your reason for using a snake case name is that these names are used directly as the names for the parameters when loading the module and there the convention is to use snake case, right? In that case I think we could expect people to write the screaming snake case name in rust and have it automatically be lower-cased by the
module!macro when it creates the names that the parameters are shown with.
Quoted 5 lines
I was thinking about putting the parameters in a separate name space, but making them screaming snake case is also a good idea. So it would be
module_parameters::IRQ_MODEto access the parameter with the nameirq_modeexposed towards the user. Developers can always opt in to bringing the symbols into scope with ause.
I really like the idea of putting them in a module. At the very first glance at the usage, I thought "where does this come from?!". So having module_parameters in front is really valuable.
Signature · 2 lines
Cheers, Benno
RFC PATCH 5/5 MAINTAINERS: add entry for Rust block device driver API
In reply to Andreas HindborgFrom: Andreas Hindborg <[email protected]>
--- MAINTAINERS | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
MAINTAINERS +14 -0
@@ -3623,6 +3623,20 @@ F: include/linux/blk* F: kernel/trace/blktrace.c F: lib/sbitmap.c +BLOCK LAYER DEVICE DRIVER API [RUST] +M: Andreas Hindborg <[email protected]> +R: Boqun Feng <[email protected]> +L: [email protected] +L: [email protected] +S: Supported +W: https://rust-for-linux.com +B: https://github.com/Rust-for-Linux/linux/issues +C: https://rust-for-linux.zulipchat.com/#narrow/stream/Block +T: git https://github.com/Rust-for-Linux/linux.git rust-block-next +F: drivers/block/rnull.rs +F: rust/kernel/block.rs +F: rust/kernel/block/ + BLOCK2MTD DRIVER M: Joern Engel <[email protected]> L: [email protected]
Signature · 1 line
2.44.0
Quoted 4 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null block driver. The context and motivation can be seen in cover letter of the RFC v1 [1]. If more context is required, a talk about this effort was recorded at LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C code and new Rust code. Please do not take this as personal criticism - I appreciate the effort that has been spent on coming up with great Rust bindings for the Linux kernel block layer.
Thanks,
Bart.
Quoted 10 lines · Bart Van Assche
Quoted 4 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null block driver. The context and motivation can be seen in cover letter of the RFC v1 [1]. If more context is required, a talk about this effort was recorded at LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C
I honestly doubt it, memory-safe is not free, basically you will still want unsafe part for the performance reason (or interacting with hardware), and provide a safe API for driver development. I don't think that part will be gone with a memory-safe C++. So the complication still exists. But I'm happy to be proved wrong ;-)
Regards,
Boqun
Quoted 8 lines
code and new Rust code. Please do not take this as personal criticism - I appreciate the effort that has been spent on coming up with great Rust bindings for the Linux kernel block layer.
Thanks,
Bart.
Quoted 12 lines · Boqun Feng
Quoted 10 lines · Bart Van Assche
Quoted 4 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null block driver. The context and motivation can be seen in cover letter of the RFC v1 [1]. If more context is required, a talk about this effort was recorded at LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C
Quoted 5 lines
I honestly doubt it, memory-safe is not free, basically you will still want unsafe part for the performance reason (or interacting with hardware), and provide a safe API for driver development. I don't think that part will be gone with a memory-safe C++. So the complication still exists. But I'm happy to be proved wrong ;-)
I think it is great that people are starting to realize that bringing memory safety to other systems languages is a good idea. But from one person blogging about it to things being ready for production is a long journey. Language designers have to design ways to express the new semantics, standards committees has to agree, compiler engineers have to build and test their compilers. Probably we need a few cycles of this to get things right. At any rate, it is going to take a while.
Second, as Boqun is saying, interfacing the unsafe C part of the kernel with memory safe C++ is going to require the same complicated abstraction logic as the safe Rust APIs are bringing. The complexity in bringing Rust to the kernel is not coming from interfacing a foreign language. It stems from the inherent difficulty in designing memory safe wrappers around unsafe C APIs.
Best regards,
Andreas
Quoted 2 lines · Andreas Hindborg
I think it is great that people are starting to realize that bringing memory safety to other systems languages is a good idea.
Totally agree :-)
Quoted 2 lines
But from one person blogging about it to things being ready for production is a long journey.
In case you wouldn't be aware of this, Herb Sutter is not a random blogger - he is the chair of the ISO C++ standards committee since 2002.
Thanks,
Bart.
Quoted 6 lines · Bart Van Assche
Quoted 4 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null block driver. The context and motivation can be seen in cover letter of the RFC v1 [1]. If more context is required, a talk about this effort was recorded at LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Quoted 7 lines
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C code and new Rust code. Please do not take this as personal criticism - I appreciate the effort that has been spent on coming up with great Rust bindings for the Linux kernel block layer.
You know, this reminds me of when I was at Intel working on NVMe. We had a product all ready to ship and a manager suggested that we delay shipping it until the SCSI-over-PCI standard was finished and ratified so that the same piece of silicon could support both.
Fortunately, said manager was overruled, but it's a great example of how this kind of FUD can actually work.
Quoted 10 lines · Bart Van Assche
Quoted 8 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null
block driver. The context and motivation can be seen in cover letter of the RFC
v1 [1]. If more context is required, a talk about this effort was recorded at
LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Quoted 5 lines
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C code and new Rust code.
Correct, but it would also most likely allow to just arbitrarily ignore the "modern, memory safe C" (or C++) and write it the old way.
Those discussions are, below the surface, frequently in truth about the
question: Can you (and do you want to) _force_ people?
The Kernel's C already has more memory safety than standardized C:
There's devres, and since last year there's the __cleanup attribute.
– but the thing is, you can just ignore it and do it the old way.
Once you give people freedom (which is necessary frequently), you'll get people who ignore "the right way to do it". You certainly get them once thousands of people are participating in your project. Actually, Rust in userspace has a similar problem: Your coprogrammers can call unwrap(), just ignoring those neat Result types and blow up your thread. So you have to review and reject that.
One of the stronger arguments behind the push for Rust is that the language by design forces you to obey, because otherwise the compiler will just reject building.
P.
Quoted 9 lines
Please do not take this as personal criticism -
I appreciate the effort that has been spent on coming up with great Rust bindings for the Linux kernel block layer.Thanks,
Bart.
Quoted 11 lines · Philipp Stanner
Quoted 10 lines · Bart Van Assche
Quoted 8 lines · Andreas Hindborg
This is the second version of the Rust block device driver API and the Rust null
block driver. The context and motivation can be seen in cover letter of the RFC
v1 [1]. If more context is required, a talk about this effort was recorded at
LPC [2]. I hope to be able to discuss this series at LSF this year [3].
Quoted 8 lines
Quoted 5 lines
Memory safety may land in C++ in the near future (see also
https://herbsutter.com/2024/03/). If memory-safe C++ or memory-safe C would be adopted in the kernel, it would allow writing memory-safe drivers without having to add complicated bindings between existing C code and new Rust code.Correct, but it would also most likely allow to just arbitrarily ignore the "modern, memory safe C" (or C++) and write it the old way.
Linux kernel developers have the choice today between memory-unsafe C and memory-safe Rust so they already have the freedom to ignore memory safety by choosing for C. In my opinion a compiler option should be introduced once memory-safe C or C++ is available that can be set per source file and that makes the build fail for source files that unintentionally do not follow the memory-safety rules.
Quoted 3 lines
The Kernel's C already has more memory safety than standardized C:
There's devres, and since last year there's the__cleanupattribute.
– but the thing is, you can just ignore it and do it the old way.
devres is controversial - see also Laurent Pinchart, "Why is devm_kzalloc() harmful and what can we do about it", LPC, 2022
(https://lpc.events/event/16/contributions/1227/).
Quoted 3 lines
One of the stronger arguments behind the push for Rust is that the language by design forces you to obey, because otherwise the compiler will just reject building.
Rust has a very significant disadvantage that memory-safe C/C++ won't
have: supporting Rust means adding Rust bindings for all C functions called from Rust code. This forces everyone who wants to change an interface to also change the Rust bindings and hence will make it harder to maintain the Linux kernel in its entirety.
Thanks,
Bart.
Just a passer-by here, but I noticed the link to Laurent's talk..
Quoted 9 lines · Bart Van Assche
Quoted 3 lines · Philipp Stanner
The Kernel's C already has more memory safety than standardized C:
There's devres, and since last year there's the__cleanupattribute.
– but the thing is, you can just ignore it and do it the old way.devres is controversial - see also Laurent Pinchart, "Why is
devm_kzalloc()harmful and what can we do about it", LPC, 2022
(https://lpc.events/event/16/contributions/1227/).
I don't think that's a great thing to cite, that talk prompted a series of others with (AFAIK*) the most recent being from Bart at LPC this year:
https://lpc.events/event/17/contributions/16f
The TL;DR is that it's not actually problem caused by devres.
* I think Wolfram also talked about it at an automotive conference, but that seemed like a bit of a pitch for funding from the safety conscious
Hi Bart,
Quoted 2 lines · Bart Van Assche
Quoted 1 line · Philipp Stanner
On Wed, 2024-03-13 at 11:02 -0700, Bart Van Assche wrote:
[...]
Quoted 9 lines
Quoted 3 lines
One of the stronger arguments behind the push for Rust is that the language by design forces you to obey, because otherwise the compiler will just reject building.
Rust has a very significant disadvantage that memory-safe C/C++ won't
have: supporting Rust means adding Rust bindings for all C functions called from Rust code. This forces everyone who wants to change an interface to also change the Rust bindings and hence will make it harder to maintain the Linux kernel in its entirety.
I think you might be missing a key point here. We actually generate Rust bindings to the existing C kernel automatically. No hand editing required, except for some corner cases we currently have with static methods and certain macros. If we just wanted to call the C APIa directly, there would be no engineering required. The main reason to deploy Rust would also go away, we might as well stay in C.
The actual engineering effort goes into building memory safe versions of the C APIs. This requirement will not magically go away, no matter what memory safe language (or language extensions) your use to interface the existing unsafe C APIs.
Best regards,
Andreas
Quoted 1 line · Andreas Hindborg
- Adopted the folio abstraction where applicable
I don't think this was the correct move. The memory you're managing with folios is only used for storing the data being stored in the blkdev. It's not mapped to userspace, it doesn't make use of the flags (locked, uptodate, writeback, etc), it doesn't need an LRU list, a mapping, an index, a refcount or memcg.
I think you should use pages instead of folios to keep a handle on this memory. Apologies for the confusion; we're in the middle of a years-long transition from the overly complex and overused struct page to splitting it into different data types for different purposes.
More detail on this here, if you're interested:
https://kernelnewbies.org/MatthewWilcox/Memdescs
Quoted 9 lines · Matthew Wilcox
Quoted 1 line · Andreas Hindborg
- Adopted the folio abstraction where applicable
I don't think this was the correct move. The memory you're managing with folios is only used for storing the data being stored in the blkdev. It's not mapped to userspace, it doesn't make use of the flags (locked, uptodate, writeback, etc), it doesn't need an LRU list, a mapping, an index, a refcount or memcg.
Quoted 4 lines
I think you should use pages instead of folios to keep a handle on this memory. Apologies for the confusion; we're in the middle of a years-long transition from the overly complex and overused struct page to splitting it into different data types for different purposes.
Ok, thanks. I'll swap it back.
I was under the impression that using folios also give the advantage that handles are always head pages. No need to worry about head/tail pages. If the driver moves to use higher order pages for larger block sizes, would it then make sense with folios, or are page still preferred?
Quoted 2 lines
More detail on this here, if you're interested:
https://kernelnewbies.org/MatthewWilcox/Memdescs
Thanks, that is useful.
Best regards,
Andreas
Quoted 5 lines · Andreas Hindborg
I was under the impression that using folios also give the advantage that handles are always head pages. No need to worry about head/tail pages. If the driver moves to use higher order pages for larger block sizes, would it then make sense with folios, or are page still preferred?
This is a good question.
If you do enhance this driver to support larger block sizes, I would recommend indexing the xarray by sector number instead of page number. You would allocate a compound page, but at no point would you need to ask the page what order it is (you already know), you don't need to change the page flags, etc, etc.
The page cache is in a bit of a different spot. It has to support multiple folio sizes for the same file; it has to support folios being split, it has to support lookup from users who don't know what the folio size is, etc, etc.
I don't think there's ever a point at which you'd need to call compound_head() because you'd always look up the head page. You'd still want an iterator of some kind to copy to a compound page (because you can only map one at a time). And that might look a lot like the folio copying code. Probably the right way to handle this is for the folio copying code to call the page copying code since a folio is always composed of pages.