Skip to contentSkip to conversation

rust: honor the maximum DMA segment size

PATCH Superseded Matteo Kloiber 5 participants 23 messages Aug 31 – Nov 15

Subsystems (7)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover rust: honor the maximum DMA segment size

Booting nova-core against a real GSP with CONFIG_DMA_API_DEBUG=y warns when the ~60 MiB firmware image is mapped as a scatter-gather table:

DMA-API: nova-core 0000:00:03.0: mapping sg segment longer than device claims to support [len=62914560] [max=65536]

There are two separate issues behind it.

Patch 1 has nova-core declare the segment size it actually supports. It re-decomposes every segment into 4 KiB GSP page-table entries, so it has no upper bound on segment length.

Furthermore, I also checked what other GPUs do, and most do the same:
set the max segment size u32::MAX. So this should be the correct behavior for nova as well.

Patch 2 has SGTable::new() honor dma_get_max_seg_size() in addition to dma_max_mapping_size(). The abstraction is generic, so a driver with a real hardware segment limit would otherwise silently be handed segments it cannot express in a single descriptor.

Tested on an RTX 5080 (GB203) passed through to a QEMU guest via VFIO with CONFIG_DMA_API_DEBUG=y: the warning is gone, and GSP boot and RPC still work.

Discussed on Zulip:
https://rust-for-linux.zulipchat.com/#narrow/channel/509436-Nova/topic/nova.20core.3A.20DMA-API.3A.20nova-core.200000.3A00.3A03.2E0.3A.20mapping.20sg.20segme/with/618319830

Matteo Kloiber (2):
gpu: nova-core: declare unlimited DMA max segment size
rust: scatterlist: honor the device's maximum segment size

 drivers/gpu/nova-core/gpu.rs |  7 +++++++
 rust/helpers/dma.c           |  5 +++++
 rust/kernel/scatterlist.rs   | 12 ++++++++++--
 3 files changed, 22 insertions(+), 2 deletions(-)

base-commit: cee9395acd8043be0644b25c34bfa86623f2b935

Signature · 1 line
2.51.2
#1 lore raw

PATCH 1/2 gpu: nova-core: declare unlimited DMA max segment size

The PCI default max_seg_size is 64 KiB. nova-core never raises it, so mapping the GSP firmware image (~60 MiB) as a scatter-gather table triggers a DMA-API debug warning when contiguous pages coalesce into segments that exceed the default:

DMA-API: nova-core 0000:00:03.0: mapping sg segment longer than device claims to support [len=62914560] [max=65536]

CONFIG_DMA_API_DEBUG=y is required to see this warning.

Assisted-by Claude:claude-opus-4-8
---
 drivers/gpu/nova-core/gpu.rs | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/gpu/nova-core/gpu.rs +7 -0
index fd1414004dd0..233ef2dc9688 100644
@@ -343,6 +343,13 @@ pub(crate) fn new<'a>(
                 // still constructing it, so no concurrent DMA allocations can exist.
                 unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? };
 
+                // Nova re-decomposes SG segments into 4 KiB page-table entries, so it
+                // has no upper bound on segment length; declare that to the DMA layer.
+                //
+                // SAFETY: same invariant as above -- still constructing, no concurrent
+                // DMA mapping can exist.
+                unsafe { pdev.dma_set_max_seg_size(u32::MAX) };
+
                 hal.wait_gfw_boot_completion(bar)
                     .inspect_err(|_| dev_err!(dev, "GFW boot did not complete\n"))?;
             },
Signature · 1 line
2.51.2
#2 lore raw

Re: [PATCH 1/2] gpu: nova-core: declare unlimited DMA max segment size

Quoted 5 lines · Matteo Kloiber

The PCI default max_seg_size is 64 KiB. nova-core never raises it, so mapping the GSP firmware image (~60 MiB) as a scatter-gather table triggers a DMA-API debug warning when contiguous pages coalesce into segments that exceed the default:

Quoted 7 lines

DMA-API: nova-core 0000:00:03.0: mapping sg segment longer than device claims to support [len=62914560] [max=65536]

CONFIG_DMA_API_DEBUG=y is required to see this warning.

Assisted-by Claude:claude-opus-4-8

Note: new kernel policy [1] asks that the specific model is not named, so this should just be Assisted-by: LLM.

(also should be placed before your Signed-off-by)

[1] https://docs.kernel.org/process/coding-assistants.html

Quoted 9 lines
---
 drivers/gpu/nova-core/gpu.rs | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/gpu/nova-core/gpu.rs +0 -0
index fd1414004dd0..233ef2dc9688 100644

drivers/gpu/nova-core/gpu.rs pub(crate) fn new<'a>( · line 351

Quoted 9 lines
drivers/gpu/nova-core/gpu.rs +6 -0
@@ -343,6 +343,13 @@ pub(crate) fn new<'a>(
                 // still constructing it, so no concurrent DMA allocations can exist.
                 unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? };
 
+                // Nova re-decomposes SG segments into 4 KiB page-table entries, so it
+                // has no upper bound on segment length; declare that to the DMA layer.
+                //
+                // SAFETY: same invariant as above -- still constructing, no concurrent
+                // DMA mapping can exist.
+                unsafe { pdev.dma_set_max_seg_size(u32::MAX) };

Thanks, this patch looks correct and I would like to merge it early, but one thing about the comment: it carries way more context than needed and reads heavily, as is often the case when AI-generated. For instance, "declare that to the DMA layer" is obvious from the method we are calling. Make sure to give a human pass to such comments as they can make the code tedious when they accumulate.

Conversely, as above is risky because the above in question might change and we then lose the reference, so here it's actually better to state the invariant in a self-contained way. Copy-pasting is ok. For instance:

// Nova walks SG segments to build page tables, so their length is // irrelevant to the device.
//
// SAFETY: Gpu owns all DMA allocations for this device, and we are // still constructing it, so no concurrent DMA allocations can exist.

Since this seems to be your first patch, this is a good opportunity to practice sending a v2. :)

#3 lore raw

Re: [PATCH 1/2] gpu: nova-core: declare unlimited DMA max segment size

Quoted 2 lines · Alexandre Courbot

Note: new kernel policy [1] asks that the specific model is not named, so this should just be Assisted-by: LLM.

Got it, thanks! I was checking what other people did and noticed a lot of mentions of Claude, etc., so I went with it. Changed for v2.

Quoted 6 lines

Thanks, this patch looks correct and I would like to merge it early, but one thing about the comment: it carries way more context than needed and reads heavily, as is often the case when AI-generated. For instance, "declare that to the DMA layer" is obvious from the method we are calling. Make sure to give a human pass to such comments as they can make the code tedious when they accumulate.

Thanks! I agree. I was unsure about that and decided to leave a bit more in for the review. I'll just use your comment verbatim.

Quoted 2 lines

Since this seems to be your first patch, this is a good opportunity to practice sending a v2. :)

Yes, submitting patches to the mailing list was certainly a new experience. Thank you for your help and time so far!

#4 lore raw

PATCH 2/2 rust: scatterlist: honor the device's maximum segment size

In reply to Matteo Kloiber

SGTable::new() caps segment length at dma_max_mapping_size() only, which limits the DMA mapping path (e.g. swiotlb), not the device itself. The per-device limit from dma_set_max_seg_size() is ignored, so contiguous page segments can be longer than the declared max segment size, potentially causing problems for future drivers that use this abstraction.

nova-core declares an unlimited segment size, so this does not change its behavior.

Fixes 05aa6fb1c21d ("rust: scatterlist: Add abstraction for sg_table")
---
 rust/helpers/dma.c         |  5 +++++
 rust/kernel/scatterlist.rs | 12 ++++++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
rust/helpers/dma.c +5 -0
index 9fbeb507b08c..ff8f24dae9df 100644
@@ -49,3 +49,8 @@ __rust_helper void rust_helper_dma_set_max_seg_size(struct device *dev,
 {
 	dma_set_max_seg_size(dev, size);
 }
+
+__rust_helper unsigned int rust_helper_dma_get_max_seg_size(struct device *dev)
+{
+	return dma_get_max_seg_size(dev);
+}
rust/kernel/scatterlist.rs +10 -2
index b83c468b5c63..d677dcbe7aac 100644
@@ -350,15 +350,23 @@ fn new(
             page_vec.push(page.as_ptr(), flags)?;
         }
 
+        // Cap segments at both the DMA mapping-path limit and the device's declared
+        // max segment size.
+        //
         // `dma_max_mapping_size` returns `size_t`, but `sg_alloc_table_from_pages_segment()` takes
         // an `unsigned int`.
         //
         // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`.
-        let max_segment = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } {
+        let max_mapping = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } {
             0 => u32::MAX,
-            max_segment => u32::try_from(max_segment).unwrap_or(u32::MAX),
+            max_mapping => u32::try_from(max_mapping).unwrap_or(u32::MAX),
         };
 
+        // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`.
+        let max_seg_size = unsafe { bindings::dma_get_max_seg_size(dev.as_raw()) };
+
+        let max_segment = max_mapping.min(max_seg_size);
+
         Ok(try_pin_init!(&this in Self {
             // SAFETY:
             // - `page_vec` is a `KVec` of valid `struct page *` obtained from `pages`.
Signature · 1 line
2.51.2
maintainer Reviewed-by on v1 2/2
#5 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 9 lines · Matteo Kloiber

SGTable::new() caps segment length at dma_max_mapping_size() only, which limits the DMA mapping path (e.g. swiotlb), not the device itself. The per-device limit from dma_set_max_seg_size() is ignored, so contiguous page segments can be longer than the declared max segment size, potentially causing problems for future drivers that use this abstraction.

nova-core declares an unlimited segment size, so this does not change its behavior.

I guess what this last paragraph wants to state is that no user is affected by this patch? There is another subtle user though: the Rust DMA sample.

In any case, this patch without patch 1 wouldn't break either of those (only waste a bit more memory in SG entries with nova-core), so maybe we can skip it.

Quoted 31 lines
Fixes 05aa6fb1c21d ("rust: scatterlist: Add abstraction for sg_table")
---
 rust/helpers/dma.c         |  5 +++++
 rust/kernel/scatterlist.rs | 12 ++++++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
rust/helpers/dma.c +5 -0
index 9fbeb507b08c..ff8f24dae9df 100644
@@ -49,3 +49,8 @@ __rust_helper void rust_helper_dma_set_max_seg_size(struct device *dev,
 {
 	dma_set_max_seg_size(dev, size);
 }
+
+__rust_helper unsigned int rust_helper_dma_get_max_seg_size(struct device *dev)
+{
+	return dma_get_max_seg_size(dev);
+}
rust/kernel/scatterlist.rs +2 -0
index b83c468b5c63..d677dcbe7aac 100644
@@ -350,15 +350,23 @@ fn new(
             page_vec.push(page.as_ptr(), flags)?;
         }
 
+        // Cap segments at both the DMA mapping-path limit and the device's declared
+        // max segment size.

rust/kernel/scatterlist.rs fn new( · line 362

Quoted 10 lines
rust/kernel/scatterlist.rs +3 -2
+        //
         // `dma_max_mapping_size` returns `size_t`, but `sg_alloc_table_from_pages_segment()` takes
         // an `unsigned int`.
         //
         // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`.
-        let max_segment = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } {
+        let max_mapping = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } {
             0 => u32::MAX,
-            max_segment => u32::try_from(max_segment).unwrap_or(u32::MAX),
+            max_mapping => u32::try_from(max_mapping).unwrap_or(u32::MAX),

nit: if we rename this variable, let's name it max_mapping_size for consistency.

rust/kernel/scatterlist.rs fn new( · line 368

Quoted 6 lines
rust/kernel/scatterlist.rs +4 -0
         };
 
+        // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`.
+        let max_seg_size = unsafe { bindings::dma_get_max_seg_size(dev.as_raw()) };
+
+        let max_segment = max_mapping.min(max_seg_size);

This looks like the correct thing to do indeed.

(the following is a related thought, not a request for this patch)

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

#6 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 3 lines · Alexandre Courbot

I guess what this last paragraph wants to state is that no user is affected by this patch? There is another subtle user though: the Rust DMA sample.

Yes, that's what I meant. I missed the sample, but it wouldn't make a difference anyway. So I just removed the paragraph in v2.

Quoted 2 lines

nit: if we rename this variable, let's name it max_mapping_size for consistency.

Agreed. Fixed. Let me know if everything is fixed in v2.

Quoted 8 lines

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

#7 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

maintainer
#8 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 11 lines · Alexandre Courbot
Quoted 10 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

Quoted 5 lines
Quoted 1 line

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Now, we can't really have drivers define them statically (e.g. in the driver trait) as there may be cases where it depends on the runtime state or properties of the device queried at runtime. Sometimes it is also defined through OF properties (which from a kernel perspective are runtime values too).

For the same reason it is also pretty hard to invent a type state pattern for those setters that is not getting ridiculously complex without much value, which is why we just kept them unsafe for the time being.

The best option to get rid of the unsafe would probably be to use atomics instead. It would however be a rather big change, what makes it a bit of a hard sell, given that the reason of this unsafe is more on the theoretical side of things.

Theoretically, we could also optimize the situation for when it is statically known, e.g. some dma::Config trait that can be implemented, such that the bus can set the before calling probe(). But we'd really want this to work per device ID table entry, as it may differ between supported devices. But that might not be quite straight forward without associated_type_defaults. The simplest thing I could think of is some callback, such as

	fn dma_info(id_info: Option<&Self::IdInfo>) -> DmaInfo

which is called before probe(), but that's not great either. Maybe there is a good solution for this, but I'd first want to exhaust getting the setters safe.

reviewer
#9 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 14 lines · Danilo Krummrich
Quoted 13 lines · Alexandre Courbot
Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Quoted 8 lines
Quoted 3 lines

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

If it's the former, we can require these to require mutable reference instead, so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

Best,
Gary

reviewer
#10 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 19 lines · Gary Guo
Quoted 18 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

Quoted 7 lines
Quoted 4 lines

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

Similar to DMA masks, the segment parameters should be set appropriately before any dma_map_sg() operation. Plus since they likely influence scatterlist geometry, that means typically they're also going to need to be set before building the scatterlist to be mapped in the first place.

I don't think there's any expectation that they would ever change *between* different mappings - especially given the underlying hardware properties they represent - so while that might technically be possible in the C API if the caller can enforce sufficient ordering, it should be fine to rule it out in the Rust abstraction if that makes things easier to reason about.

Thanks,
Robin.

Quoted 8 lines

If it's the former, we can require these to require mutable reference instead, so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

Best,
Gary

reviewer
#11 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 25 lines · Robin Murphy
Quoted 24 lines · Gary Guo
Quoted 22 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Quoted 10 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

Quoted 5 lines
Quoted 1 line

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Quoted 7 lines
Quoted 2 lines

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

Similar to DMA masks, the segment parameters should be set appropriately before any dma_map_sg() operation. Plus since they likely influence scatterlist geometry, that means typically they're also going to need to be set before building the scatterlist to be mapped in the first place.

Right, in that case I think we have the following options:

1. Have setters these being unsafe, with precondition that they must be done before creation of DMA mappings.

2. Have a dma_info() method like Danilo mentioned. However, we cannot expose &Device<Core<'_>> inside such callbacks, because otherwise driver would be able create DMA mappings. This however is too restrictive to be the only way of setting DMA masks, because Nova needs to access the bar before setting the DMA masks.

3. Use wrapper type instead of generics for typestate. Then, we can express the pattern of typestate transformation (generics cannot do this because we always place it behind a reference).

For example, we can have Device to mean Device<Normal>, and then have Bound<Device> to mean Device<Bound> (both of which are behind a shared reference, like today, and Bound<D> can deref to &D).

Then, for Core typestate, we can instead have

struct Core<'a, D>(&'a Bound<Device>);

where it's passed by value. We can then define the DMA setters methods to operate on Core like we did today, but safely. Instead of providing a Deref impl that turns &Core<'_, D> to &Bound<D>, we only implement forwarding functions for APIs that can work without DMA configured (e.g. PCI bar).

Then, provide a into_bound() method which *consumes* Core<'a, D> and give out &'a Bound<Device> (this is why typestate generics cannot work, because &'a Device<Core<'_>> is Copy and we cannot represent the ownership consumption).

Quoted 8 lines

I don't think there's any expectation that they would ever change *between* different mappings - especially given the underlying hardware properties they represent - so while that might technically be possible in the C API if the caller can enforce sufficient ordering, it should be fine to rule it out in the Rust abstraction if that makes things easier to reason about.

Quoted 4 lines

Thanks,
Robin.

Quoted 1 line

If it's the former, we can require these to require mutable reference instead,

Correction: this should say "latter".

Best,
Gary

Quoted 7 lines
Quoted 7 lines

so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

Best,
Gary

maintainer
#12 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 34 lines · Gary Guo
Quoted 25 lines · Robin Murphy
Quoted 24 lines · Gary Guo
Quoted 22 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Quoted 10 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

Quoted 5 lines
Quoted 1 line

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Quoted 7 lines
Quoted 2 lines

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

Similar to DMA masks, the segment parameters should be set appropriately before any dma_map_sg() operation. Plus since they likely influence scatterlist geometry, that means typically they're also going to need to be set before building the scatterlist to be mapped in the first place.

Quoted 4 lines

Right, in that case I think we have the following options:

1. Have setters these being unsafe, with precondition that they must be done before creation of DMA mappings.

As mentioned, I don't think the safety requirement has to be before using other DMA APIs, but just requiring to not do it concurrently. Not doing it would be a semantic bug, but it shouldn't have any safety implications.

Quoted 5 lines

2. Have a dma_info() method like Danilo mentioned. However, we cannot expose &Device<Core<'_>> inside such callbacks, because otherwise driver would be able create DMA mappings. This however is too restrictive to be the only way of setting DMA masks, because Nova needs to access the bar before setting the DMA masks.

Just to clarify, I mentioned this to be something we could do in addition to (1) for drivers where those values are statically known.

Quoted 18 lines

3. Use wrapper type instead of generics for typestate. Then, we can express the pattern of typestate transformation (generics cannot do this because we always place it behind a reference).

For example, we can have Device to mean Device<Normal>, and then have Bound<Device> to mean Device<Bound> (both of which are behind a shared reference, like today, and Bound<D> can deref to &D).

Then, for Core typestate, we can instead have

struct Core<'a, D>(&'a Bound<Device>);

where it's passed by value. We can then define the DMA setters methods to operate on Core like we did today, but safely. Instead of providing a Deref impl that turns &Core<'_, D> to &Bound<D>, we only implement forwarding functions for APIs that can work without DMA configured (e.g. PCI bar).

Quoted 4 lines

Then, provide a into_bound() method which *consumes* Core<'a, D> and give out &'a Bound<Device> (this is why typestate generics cannot work, because &'a Device<Core<'_>> is Copy and we cannot represent the ownership consumption).

Yeah, we had this discussion in the past with similar ideas; it is the kind of complication that we concluded not to be worth it and that I mentioned in my initial reply.

The only safety relevant issue should really be the data race of the primitives values being set, which is more on the theoretical side of things.

Quoted 7 lines
Quoted 7 lines

I don't think there's any expectation that they would ever change *between* different mappings - especially given the underlying hardware properties they represent - so while that might technically be possible in the C API if the caller can enforce sufficient ordering, it should be fine to rule it out in the Rust abstraction if that makes things easier to reason about.

Quoted 7 lines
Quoted 1 line
Quoted 1 line

If it's the former, we can require these to require mutable reference instead,

Correction: this should say "latter".

Quoted 3 lines
Quoted 3 lines

so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

I think that doesn't work, there are drivers that need to perform MMIO before knowing e.g. the DMA mask, i.e. we can't have Pin<&'bound mut Device<Core<'_>>> at the same time as e.g. pci::Bar<'_>, which borrows a &Device<Bound>.

#13 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 35 lines · Danilo Krummrich
Quoted 34 lines · Gary Guo
Quoted 32 lines · Robin Murphy
Quoted 19 lines · Gary Guo
Quoted 18 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

Quoted 7 lines
Quoted 4 lines

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

Similar to DMA masks, the segment parameters should be set appropriately before any dma_map_sg() operation. Plus since they likely influence scatterlist geometry, that means typically they're also going to need to be set before building the scatterlist to be mapped in the first place.

Quoted 8 lines
Quoted 4 lines

Right, in that case I think we have the following options:

1. Have setters these being unsafe, with precondition that they must be done before creation of DMA mappings.

As mentioned, I don't think the safety requirement has to be before using other DMA APIs, but just requiring to not do it concurrently. Not doing it would be a semantic bug, but it shouldn't have any safety implications.

Agreed on the safety requirement; but Robin's reply does suggest that we really have no reason to not go the extra step and require these parameters to be set before any DMA op takes place. Which is honestly the answer I was hoping for as it makes things much simpler (see below).

Quoted 28 lines
Quoted 6 lines

2. Have a dma_info() method like Danilo mentioned. However, we cannot expose &Device<Core<'_>> inside such callbacks, because otherwise driver would be able create DMA mappings. This however is too restrictive to be the only way of setting DMA masks, because Nova needs to access the bar before setting the DMA masks.

Just to clarify, I mentioned this to be something we could do in addition to (1) for drivers where those values are statically known.

Quoted 18 lines

3. Use wrapper type instead of generics for typestate. Then, we can express the pattern of typestate transformation (generics cannot do this because we always place it behind a reference).

For example, we can have Device to mean Device<Normal>, and then have Bound<Device> to mean Device<Bound> (both of which are behind a shared reference, like today, and Bound<D> can deref to &D).

Then, for Core typestate, we can instead have

struct Core<'a, D>(&'a Bound<Device>);

where it's passed by value. We can then define the DMA setters methods to operate on Core like we did today, but safely. Instead of providing a Deref impl that turns &Core<'_, D> to &Bound<D>, we only implement forwarding functions for APIs that can work without DMA configured (e.g. PCI bar).

Quoted 8 lines
Quoted 4 lines

Then, provide a into_bound() method which *consumes* Core<'a, D> and give out &'a Bound<Device> (this is why typestate generics cannot work, because &'a Device<Core<'_>> is Copy and we cannot represent the ownership consumption).

Yeah, we had this discussion in the past with similar ideas; it is the kind of complication that we concluded not to be worth it and that I mentioned in my initial reply.

How about this:

fn probe<'bound>(

      pdev: &'bound pci::Device<Core<'_>>,
      dma: dma::Setup<'bound>,
      _info: Option<&'bound Self::IdInfo>,

) -> ...

dma::Setup is a token carrying the DMA capability. You turn it into a dma::Handle<'bound> by acknowledging the DMA masks and segment parameters using setters and a finish method. Then all DMA operations are performed on that dma::Handle. This proves the DMA setup has been performed before any operation takes place.

It doesn't complicate Device any further, and drivers that don't need DMA can just drop the token and don't need to think about it anymore.

The DMA token is not opened from the Device because it needs to be unique, so this adds one extra argument to probe, but this removes the need to use unsafe while strictly enforcing the ordering (and staying trivial to use).

#14 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

First of all, thanks for merging my first two patches and sorry about my late reply.

What I think Alex meant and what I agree with is that the new API should focus on making semantic bugs harder, not to necessarily make it easier to write safer drivers. That being said, I think we can do both with this change.

The key change here is that we introduce a structure that defines dma parameters for a device. This structure deliberately has no default implementation and new fields should be added even if they require changes for all dma drivers.

```
pub struct Params {
    pub streaming_mask: DmaMask,
    pub coherent_mask: DmaMask,
    pub max_seg_size: NonZeroU32,
}
```

Suppose, we didn't have max_seg_size before and only discovered it later. We would add it and the compiler would guide us to any drivers that will need to consider an appropriate value for max_seg_size.

If rust was bigger in the kernel, this could be quite a bit of work, requiring coordination with other maintainers, but I would call this a feature because it actually requires everyone to at least consider what the right value is instead of forgetting to set it.

The same is also true for new drivers. Authors do not have to be omniscient of all dma related settings and instead just fill out the struct and already have some important ones set.

If a parameter is only important for some drivers but those drivers should not forget it, we could make it an Option so that drivers that really don't need a parameter can set it to None, but they had to think about it at least.

I think, instead of discussing different possibilities, it might be easier to discuss code directly. Taking Alex's example, I went ahead and wrote a small LLM assisted PoC. I'm happy to share it here or in another thread, but here are the main changes:

1. The PCI and platform probe callbacks receive a unique setup token:

```rust
    fn probe<'bound>(
        dev: &'bound Device<device::Core<'_>>,
        dma: dma::Setup<'bound>,
        id_info: Option<&'bound Self::IdInfo>,
    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
```

The bus driver creates this token and drivers cannot obtain another one from the device.

2. setup.configure(params) consumes the token, applies the parameters through the C DMA setters, and returns a dma::Handle<'bound> on success. This combines the setters and finish() from Alex's outline into one call.

```
pub fn configure(self, params: Params) -> Result<Handle<'bound>> {
    let dev = self.dev.as_raw();

    // SAFETY: `dev` is valid and its DMA parameters are initialized by the bus. The `Setup`
    // invariants exclude concurrent DMA operations and other parameter setters. Consuming
    // the unique token prevents reconfiguration after a handle has been issued.
    unsafe {
        to_result(bindings::dma_set_mask(dev, params.streaming_mask.value()))?;
        to_result(bindings::dma_set_coherent_mask(dev, params.coherent_mask.value()))?;
        bindings::dma_set_max_seg_size(dev, params.max_seg_size.get());
    }

    Ok(Handle { dev: self.dev })
}
```

3. The handle contains a bound device reference and is copyable, but provides no way to reconfigure DMA:

```rust
#[derive(Clone, Copy)]
pub struct Handle<'bound> {
  dev: &'bound device::Device<Bound>,
}
```

4. Allocation and mapping APIs now require a Handle.

For example, scatter list now takes:

```
pub fn new<'a>(
  dma: dma::Handle<'a>,
  pages: P,
  dir: dma::DataDirection,
  flags: alloc::Flags,
) -> impl PinInit<Self, Error> + 'a {
```

The PoC uses Handle for coherent allocations, owned scatterlists, and DRM scatterlist mappings.

5. Each pci/platform driver that uses DMA configures its own Params. Let's look at samples/rust/rust_dma.rs:

```rust
fn probe<'bound>(
    pdev: &'bound pci::Device<Core<'_>>,
    setup: dma::Setup<'bound>,
    _info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
    pin_init::pin_init_scope(move || {
        dev_info!(pdev, "Probe DMA test driver.\n");

        let mask = DmaMask::new::<64>();

        let dma = setup.configure(dma::Params {
            streaming_mask: mask,
            coherent_mask: mask,
            max_seg_size: const { NonZeroU32::new(u32::SZ_64K).unwrap() },
        })?;

        let ca: Coherent<'_, [MyStruct]> =
            Coherent::zeroed_slice(dma, TEST_VALUES.len(), GFP_KERNEL)?;

        for (i, value) in TEST_VALUES.into_iter().enumerate() {
            io_project!(ca, [panic: i]).copy_write(MyStruct::new(value.0, value.1));
        }

        let size = 4 * page::PAGE_SIZE;
        let pages = VVec::with_capacity(size, GFP_KERNEL)?;

        let sgt = SGTable::new(dma, pages, DataDirection::ToDevice, GFP_KERNEL);

        Ok(try_pin_init!(Self::Data {
            pdev,
            ca,
            sgt <- sgt,
        }))
    })
}
```

What I am not 100% sure about is how we should handle drivers that don't use dma. Currently I just discarded the setup token like suggested, for example samples/rust/rust_driver_auxiliary.rs:

```rust
impl pci::Driver for ParentDriver {
  fn probe<'bound>(
    pdev: &'bound pci::Device<Core<'_>>,
    _dma: kernel::dma::Setup<'bound>,
    _info: Option<&'bound Self::IdInfo>,
  ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { ... }
}
```

But maybe it would make sense to introduce a C API such as: debug_no_dma and have the bus call it unless configure was called first. This would then trigger a debug warning if a marked rust device calls any C APIs that use DMA regardless. But this could also very well be a worthwhile follow up.

#15 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 10 lines · Matteo Kloiber

First of all, thanks for merging my first two patches and sorry about my late reply.

What I think Alex meant and what I agree with is that the new API should focus on making semantic bugs harder, not to necessarily make it easier to write safer drivers. That being said, I think we can do both with this change.

The key change here is that we introduce a structure that defines dma parameters for a device. This structure deliberately has no default implementation and new fields should be added even if they require changes for all dma drivers.

<...>

Thanks for the detailed plan; I think it mostly makes sense.

A few details that we have discussed offline with Danilo:

- The probe methods should not take the dma::Setup token directly, but rather a bus-specific struct that contains it and can be augmented with other capabilities. Drivers would have to deconstruct it using the .. operator to make sure code doesn't break if we add new tokens to it.
- The token should not assume default parameters and only call functions corresponding to parameters explicitly set; converting the token to a handler means the driver acknowledged all the settings, so we should not make any parameter mandatory (the doc should of course detail what drivers *should* do).

With that and your plan I believe you have a solid basis to send a RFC/PoC. :)

reviewer
#16 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 15 lines · Alexandre Courbot
Quoted 10 lines · Matteo Kloiber

First of all, thanks for merging my first two patches and sorry about my late reply.

What I think Alex meant and what I agree with is that the new API should focus on making semantic bugs harder, not to necessarily make it easier to write safer drivers. That being said, I think we can do both with this change.

The key change here is that we introduce a structure that defines dma parameters for a device. This structure deliberately has no default implementation and new fields should be added even if they require changes for all dma drivers.

<...>

Thanks for the detailed plan; I think it mostly makes sense.

Quoted 7 lines

A few details that we have discussed offline with Danilo:

- The probe methods should not take the dma::Setup token directly, but rather a bus-specific struct that contains it and can be augmented with other capabilities. Drivers would have to deconstruct it using the .. operator to make sure code doesn't break if we add new tokens to it.

I was quite skeptical whether the complication of adding the dma setup token is worth the effort, but the capacity struct sounds like a very nice design as it's infinitely extensible. I can foresee that we might want to eventually get rid of the special Core typestate and just replace everything with setup capabilities.

Best,
Gary

Quoted 8 lines

- The token should not assume default parameters and only call functions corresponding to parameters explicitly set; converting the token to a handler means the driver acknowledged all the settings, so we should not make any parameter mandatory (the doc should of course detail what drivers *should* do).

With that and your plan I believe you have a solid basis to send a RFC/PoC. :)

maintainer
#17 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 5 lines · Gary Guo

I was quite skeptical whether the complication of adding the dma setup token is worth the effort, but the capacity struct sounds like a very nice design as it's infinitely extensible. I can foresee that we might want to eventually get rid of the special Core typestate and just replace everything with setup capabilities.

I had a similar thought (which is one of the reasons I proposed it), but I don't think we can replace the Core type state entirely.

There's more than just one bus callback that holds the Core type state, so I think the bus setup token is rather the (much) better version of a Probe type state.

#18 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

In reply to Alexandre Courbot
Quoted 28 lines · Alexandre Courbot
Quoted 10 lines · Matteo Kloiber

First of all, thanks for merging my first two patches and sorry about my late reply.

What I think Alex meant and what I agree with is that the new API should focus on making semantic bugs harder, not to necessarily make it easier to write safer drivers. That being said, I think we can do both with this change.

The key change here is that we introduce a structure that defines dma parameters for a device. This structure deliberately has no default implementation and new fields should be added even if they require changes for all dma drivers.

<...>

Thanks for the detailed plan; I think it mostly makes sense.

A few details that we have discussed offline with Danilo:

- The probe methods should not take the dma::Setup token directly, but rather a bus-specific struct that contains it and can be augmented with other capabilities. Drivers would have to deconstruct it using the .. operator to make sure code doesn't break if we add new tokens to it.
- The token should not assume default parameters and only call functions corresponding to parameters explicitly set; converting the token to a handler means the driver acknowledged all the settings, so we should not make any parameter mandatory (the doc should of course detail what drivers *should* do).

Quoted 2 lines

With that and your plan I believe you have a solid basis to send a RFC/PoC. :)

Stumbled upon the notes I took while discussing with Danilo so sharing the extra info that was there:

- As a consequence of this, the DmaDevice trait is likely to go away.
- The name of the capabilities struct is not clear yet, but something like pci::InitTokens could work (because it would only contain such tokens that reference the device).

#19 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

In reply to Gary Guo
Quoted 24 lines · Gary Guo
Quoted 14 lines · Danilo Krummrich
Quoted 13 lines · Alexandre Courbot
Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Quoted 8 lines
Quoted 3 lines

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Quoted 7 lines

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

If it's the former, we can require these to require mutable reference instead, so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

As Danilo pointed out [1] from a strict safety perspective they must not be called concurrently to DMA allocations. So there is not a hard need to call them before.

But my point is different: until patch 1 of this series, nova-core didn't do anything particularly wrong but was operating with an inaccurate DMA segment size. Which is currently inconsequential as long as you don't set CONFIG_DMA_API_DEBUG, but will become sub-optimal if patch 2 gets merged (which it should be, otherwise more DMA-limited devices could start misbehaving).

The thing is that every driver *really* should set their DMA mask and max segment size ASAP, but at the moment this is done through two unsafe functions that are very easy to overlook.

And practically speaking, is there a reason *not* to do that setup before allocating objects?

So I am thinking that maybe we could have a kind of DeviceDma type which construction involves setting the core DMA parameters (or acknowledging the defaults), and to which all allocations would be tied. IOW, Danilo's DMA allocations rework [2] would tie to that DeviceDma object (which itself would be tied to the bound device) instead of the device itself.

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

#20 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 58 lines · Alexandre Courbot
Quoted 24 lines · Gary Guo
Quoted 14 lines · Danilo Krummrich
Quoted 13 lines · Alexandre Courbot
Quoted 11 lines · Matteo Kloiber
Quoted 8 lines · Alexandre Courbot

It also means that without patch 1, nova-core would split the firmware into hundreds of 64KB SG entries, which is not breaking but still something we want to avoid. The correct fix is to make sure that dma_set_max_seg_size is called by the driver, and while we are at it we also want every driver to call dma_set_mask_and_coherent. Ideally we would use the type system to make sure that both functions are called before any DMA operation can take place (using a safe interface), but I'm not quite sure yet how we can do this.

This sounds sensible indeed. Should I open a thread regarding that on Zulip?

Quoted 8 lines
Quoted 3 lines

Probably not necessary, the mailing-list has a larger audience and is the right place for this. I expect people will jump in here with their thoughts.

The problem with those is not that they must strictly be called before allocating DMA memory, but they must not be called concurrently with other DMA operations, such as allocating DMA memory, as it would technically be a data race.

Quoted 7 lines

Do they really have to be called *before* allocating DMA memory, not do they just need not be called *concurrent* to DMA memory allocation?

If it's the former, we can require these to require mutable reference instead, so the probe takes Pin<&'bound mut Device<Core<'_>>> which still derefs to &'bound Device<Bound>, but Rust will require the shared reference to not co-exist with the mutable reference.

As Danilo pointed out [1] from a strict safety perspective they must not be called concurrently to DMA allocations. So there is not a hard need to call them before.

But my point is different: until patch 1 of this series, nova-core didn't do anything particularly wrong but was operating with an inaccurate DMA segment size. Which is currently inconsequential as long as you don't set CONFIG_DMA_API_DEBUG, but will become sub-optimal if patch 2 gets merged (which it should be, otherwise more DMA-limited devices could start misbehaving).

The thing is that every driver *really* should set their DMA mask and max segment size ASAP, but at the moment this is done through two unsafe functions that are very easy to overlook.

And practically speaking, is there a reason *not* to do that setup before allocating objects?

So I am thinking that maybe we could have a kind of DeviceDma type which construction involves setting the core DMA parameters (or acknowledging the defaults), and to which all allocations would be tied. IOW, Danilo's DMA allocations rework [2] would tie to that DeviceDma object (which itself would be tied to the bound device) instead of the device itself.

Quoted 2 lines

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

Sorry, I typed this message while travelling (and offline) and sent it before noticing there has been new replies that make most of it irrelevant.

#21 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

In reply to Matteo Kloiber
Quoted 9 lines · Matteo Kloiber

SGTable::new() caps segment length at dma_max_mapping_size() only, which limits the DMA mapping path (e.g. swiotlb), not the device itself. The per-device limit from dma_set_max_seg_size() is ignored, so contiguous page segments can be longer than the declared max segment size, potentially causing problems for future drivers that use this abstraction.

nova-core declares an unlimited segment size, so this does not change its behavior.

Hi Matteo,

Do you have plans to keep working on this and follow up on the feedback received on this revision?

#22 lore raw

Re: [PATCH 2/2] rust: scatterlist: honor the device's maximum segment size

Quoted 4 lines · Alexandre Courbot

Hi Matteo,

Do you have plans to keep working on this and follow up on the feedback received on this revision?

Hi Alex,

Yes, I do. Sorry for not getting back to you sooner, I was unusual busy at work.

I've had a patch implementing the approach we discussed ready for quite a while now, but haven't found the time to review it properly myself. I plan to do that and send it out as an RFC by the end of this week.