rust: drm: ioctl: make DRM ioctls easier to understand
Subsystems (6)
Alice Ryhl
maintainercover rust: drm: ioctl: make DRM ioctls easier to understand
Two small improvements to declare_drm_ioctls! motivated by questions and feedback from teaching my Rust for Linux course.
---
Alice Ryhl (2):
rust: drm: ioctl: return Result<i32> from ioctl handlers
rust: drm: ioctl: document declare_drm_ioctls! arguments and assertions
drivers/gpu/drm/nova/file.rs | 6 ++--- drivers/gpu/drm/tyr/file.rs | 2 +- rust/kernel/drm/ioctl.rs | 57 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 48 insertions(+), 17 deletions(-)
---
base-commit: abfb640b2374e26de8ff81d488c39d8254db538e
change-id: 20261127-drm-ioctl-return-i32-47887b37769f
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
maintainerPATCH 1/2 rust: drm: ioctl: return Result<i32> from ioctl handlers
Currently drm ioctl handlers return a Result<u32> where errors are translated to negative numbers and values are converted to a non-negative i32. The values above i32::MAX are considered erroronous and mapped to -ERANGE.
While teaching the Rust for Linux course, we ended up discussing the above after a student found it confusing and asked about this return value. Of course, the students knew that the C side returns a signed integer, so it's not clear what values about i32::MAX would mean.
Based on this discussion, I'm suggesting here that we change the return value to Result<i32>. This means that there are two ways of returning a negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other. But in the course, people generally thought this was less confusing.
Thus, change declare_drm_ioctls! and its in-tree handlers in nova and tyr to return Result<i32>.
Note this matches miscdevice's ioctl API that already behaves like this.
--- drivers/gpu/drm/nova/file.rs | 6 +++--- drivers/gpu/drm/tyr/file.rs | 2 +- rust/kernel/drm/ioctl.rs | 5 ++--- 3 files changed, 6 insertions(+), 7 deletions(-)
drivers/gpu/drm/nova/file.rs +3 -3
@@ -117,7 +117,7 @@ pub(crate) fn gem_create( _reg_data: &DrmRegData<'_>, req: &mut uapi::drm_nova_gem_create, file: &drm::File<NovaDriver>, - ) -> Result<u32> { + ) -> Result<i32> {let obj =NovaObject ::new (dev, req.size.try_into ()?)?; req.handle = obj.create_handle (file)?;
@@ -131,7 +131,7 @@ pub(crate) fn gem_info( _reg_data: &DrmRegData<'_>, req: &mut uapi::drm_nova_gem_info, file: &drm::File<NovaDriver>, - ) -> Result<u32> { + ) -> Result<i32> {let bo =NovaObject ::lookup_handle (file, req.handle)?; req.size = bo.size ().try_into ()?;
@@ -145,7 +145,7 @@ pub(crate) fn info( reg_data: &DrmRegData<'_>, info: &mut uapi::drm_nova_info, _file: &drm::File<NovaDriver>, - ) -> Result<u32> { + ) -> Result<i32> {match info.id { uapi::DRM_NOVA_INFO_GPU =>write_info (info,GpuInfo ::new (reg_data)?)?, _ =>return Err (EINVAL ),
drivers/gpu/drm/tyr/file.rs +1 -1
@@ -75,7 +75,7 @@ pub(crate) fn dev_query( reg_data: &TyrDrmRegistrationData<'_>, devquery: &mut uapi::drm_panthor_dev_query, _file: &TyrDrmFile, - ) -> Result<u32> { + ) -> Result<i32> {if devquery.pointer ==0 {match devquery.type_ { uapi::drm_panthor_dev_query_type_DRM_PANTHOR_DEV_QUERY_GPU_INFO => {
rust/kernel/drm/ioctl.rs +2 -3
@@ -98,7 +98,7 @@ pub const fn __dev_ctx_cast<T: crate::drm::Driver>(/// reg_data: &Self::RegistrationData<'_>, /// data: &mut uapi::argument_type, /// file: &kernel::drm::File<Self>, -/// ) -> Result<u32> +/// ) -> Result<i32> /// ``` /// where `Self` is the drm::drv::Driver implementation these ioctls are being declared within. ///
@@ -201,8 +201,7 @@ macro_rules! declare_drm_ioctls { $func(&*guard, reg_data, data, file) }) { Err(e) => e.to_errno(), - Ok(i) => i.try_into() - .unwrap_or($crate::error::code::ERANGE.to_errno()), + Ok(i) => i, } }Some ($cmd)
Signature · 1 line
2.56.1.839.g22a8290db9-goog
Re: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 10 lines · Alice Ryhl
Currently drm ioctl handlers return a Result<u32> where errors are translated to negative numbers and values are converted to a non-negative i32. The values above
i32::MAXare considered erroronous and mapped to-ERANGE.While teaching the Rust for Linux course, we ended up discussing the above after a student found it confusing and asked about this return value. Of course, the students knew that the C side returns a signed integer, so it's not clear what values about
i32::MAXwould mean.
Quoted 4 lines
Based on this discussion, I'm suggesting here that we change the return value to Result<i32>. This means that there are two ways of returning a negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.
I'd argue that userspace is not the main problem but allowing more sutle variants of Ok(EINVAL.to_errno()) in the driver may hide bugs. I'm not sure what happens if the the ioctl returns a random negative number and not a defined error. If that ends up in userspace's errno it is probably confusing as well.
Would be using Bounded::<u32, 31> as return value an option? Do we even have DRM ioctls that return a different value than 0 on success? If not and we don't foresee ever adding them we could simplify the return value to a plain Result.
Janne
Alice Ryhl
maintainerRe: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 23 lines · Janne Grunau
Quoted 10 lines · Alice Ryhl
Currently drm ioctl handlers return a Result<u32> where errors are translated to negative numbers and values are converted to a non-negative i32. The values above
i32::MAXare considered erroronous and mapped to-ERANGE.While teaching the Rust for Linux course, we ended up discussing the above after a student found it confusing and asked about this return value. Of course, the students knew that the C side returns a signed integer, so it's not clear what values about
i32::MAXwould mean.Quoted 4 lines
Based on this discussion, I'm suggesting here that we change the return value to Result<i32>. This means that there are two ways of returning a negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.
I'd argue that userspace is not the main problem but allowing more sutle variants of
Ok(EINVAL.to_errno())in the driver may hide bugs. I'm not sure what happens if the the ioctl returns a random negative number and not a defined error. If that ends up in userspace's errno it is probably confusing as well.
Quoted 4 lines
Would be using
Bounded::<u32, 31>as return value an option? Do we even have DRM ioctls that return a different value than0on success? If not and we don't foresee ever adding them we could simplify the return value to a plain Result.
I don't think that's a good idea. Too inconvenient for the common case.
Alice
Re: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
In reply to Alice RyhlQuoted 2 lines · Alice Ryhl
While teaching the Rust for Linux course,
Without context, people will not know what course it means. Maybe add the company name?
Quoted 1 line
integer, so it's not clear what values about
i32::MAXwould mean.
"above"
Quoted 3 lines
This means that there are two ways of returning a
negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.
Yeah, I am not thrilled about having two ways that look different but do the same.
Cheers,
Miguel
Alice Ryhl
maintainerRe: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 7 lines · Miguel Ojeda
Quoted 2 lines · Alice Ryhl
While teaching the Rust for Linux course,
Without context, people will not know what course it means. Maybe add the company name?
Yeah I worded this "my" elsewhere but forgot to do so here.
Quoted 10 lines
Quoted 1 line
integer, so it's not clear what values about
i32::MAXwould mean."above"
Quoted 3 lines
This means that there are two ways of returning a
negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.Yeah, I am not thrilled about having two ways that look different but do the same.
Well, I don't think the current behavior that has errornous behavior is great either. Perhaps we can just return Result<()>, but I am not sure if any DRM drivers actually need non-zero return value.
Alice
Re: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 20 lines · Alice Ryhl
Quoted 7 lines · Miguel Ojeda
Quoted 2 lines · Alice Ryhl
While teaching the Rust for Linux course,
Without context, people will not know what course it means. Maybe add the company name?
Yeah I worded this "my" elsewhere but forgot to do so here.
Quoted 8 lines
Quoted 1 line
integer, so it's not clear what values about
i32::MAXwould mean."above"
Quoted 3 lines
This means that there are two ways of returning a
negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.
Quoted 6 lines
Quoted 2 lines
Yeah, I am not thrilled about having two ways that look different but do the same.
Well, I don't think the current behavior that has errornous behavior is great either. Perhaps we can just return Result<()>, but I am not sure if any DRM drivers actually need non-zero return value.
drm_ioctl() is annotated to return "Zero on success, negative error code on failure." [1] so it should be safe to switch to Result<()>. I verified that it's true for the asahi downstream driver. A quick verification of panthor's (and nouveau's?) ioctl wouldn't hurt but I'd be surprised if those return values other than 0 on success. So it should be safe to return Result<()> at least for now but I wouldn't expect this to change.
The drm_ioctl implementation had since forever (the git root commit in 2005) a debug log statement on non-zero ioctl return values.
Janne
Gary Guo
reviewerRe: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 28 lines · Janne Grunau
Quoted 20 lines · Alice Ryhl
Quoted 7 lines · Miguel Ojeda
Quoted 2 lines · Alice Ryhl
While teaching the Rust for Linux course,
Without context, people will not know what course it means. Maybe add the company name?
Yeah I worded this "my" elsewhere but forgot to do so here.
Quoted 8 lines
Quoted 1 line
integer, so it's not clear what values about
i32::MAXwould mean."above"
Quoted 3 lines
This means that there are two ways of returning a
negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.Quoted 6 lines
Quoted 2 lines
Yeah, I am not thrilled about having two ways that look different but do the same.
Well, I don't think the current behavior that has errornous behavior is great either. Perhaps we can just return Result<()>, but I am not sure if any DRM drivers actually need non-zero return value.
Quoted 9 lines
drm_ioctl()is annotated to return "Zero on success, negative error code on failure." [1] so it should be safe to switch to Result<()>. I verified that it's true for the asahi downstream driver. A quick verification of panthor's (and nouveau's?) ioctl wouldn't hurt but I'd be surprised if those return values other than 0 on success. So it should be safe to return Result<()> at least for now but I wouldn't expect this to change.
Thedrm_ioctlimplementation had since forever (the git root commit in 2005) a debug log statement on non-zero ioctl return values.
I asked a clanker to search for the codebase (and I verified), and there're a few ioctls that return non-zero on success:
- DRM_IOCTL_I915_PERF_OPEN -- returning a file descriptor
- DRM_IOCTL_I915_PERF_ADD_CONFIG -- returning a OA config ID
- DRM_IOCTL_XE_OBSERVATION -- returning FD or OA config ID
- DRM_IOCTL_MSM_PERFCNTR_CONFIG -- returning a FD
All of them are driver-specific ioctls and according to the clanker none of the core ioctls return non-zero on success (unverified).
I think we can define a trait for allowed return values perhaps? Initially just implement it for () which converts to 0, and we can add more when it's needed in the future.
Best,
Gary
Quoted 4 lines
Janne
Danilo Krummrich
maintainerRe: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
Quoted 8 lines · Gary Guo
I asked a clanker to search for the codebase (and I verified), and there're a few ioctls that return non-zero on success:
-
DRM_IOCTL_I915_PERF_OPEN-- returning a file descriptor
-DRM_IOCTL_I915_PERF_ADD_CONFIG-- returning a OA config ID
-DRM_IOCTL_XE_OBSERVATION-- returning FD or OA config ID
-DRM_IOCTL_MSM_PERFCNTR_CONFIG-- returning a FD
Quoted 6 lines
All of them are driver-specific ioctls and according to the clanker none of the core ioctls return non-zero on success (unverified).
I think we can define a trait for allowed return values perhaps? Initially just implement it for () which converts to 0, and we can add more when it's needed in the future.
I think we should keep it simple and just return Result for now; it seems unlikely we ever need something else.
Gary Guo
reviewerRe: [PATCH 1/2] rust: drm: ioctl: return Result<i32> from ioctl handlers
In reply to Miguel OjedaQuoted 9 lines · Miguel Ojeda
Quoted 2 lines · Alice Ryhl
While teaching the Rust for Linux course,
Without context, people will not know what course it means. Maybe add the company name?
Quoted 1 line
integer, so it's not clear what values about
i32::MAXwould mean.
Quoted 8 lines
"above"
Quoted 3 lines
This means that there are two ways of returning a
negative value to userspace (either Err(err) or Ok(-x)), and that userspace cannot distinguish whether the driver did one or the other.Yeah, I am not thrilled about having two ways that look different but do the same.
Yeah I agree, I think the EB of overflowing return turned to ERANGE is better than two ways of returning an errno.
Best,
Gary
Alice Ryhl
maintainerPATCH 2/2 rust: drm: ioctl: document declare_drm_ioctls! arguments and assertions
In reply to Alice RyhlThe documentation for declare_drm_ioctls! is currently quite incomplete, and the assertions do not provide a easily readable error message. Thus update the docs and assertions to better document how to create drm ioctls.
This came up while I was teaching my Rust for Linux course.
--- rust/kernel/drm/ioctl.rs | 52 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 10 deletions(-)
rust/kernel/drm/ioctl.rs +42 -10
@@ -90,17 +90,43 @@ pub const fn __dev_ctx_cast<T: crate::drm::Driver>(/// /// `(ioctl_number, argument_type, flags, user_callback),` /// -/// `argument_type` is the type name within the `bindings` crate. -/// `user_callback` should have the following prototype: +/// where: +/// +/// - `ioctl_number` is the ioctl name without the `DRM_IOCTL_` prefix; the macro prepends +/// `DRM_IOCTL_` and looks up the resulting constant in the uapi header (the header must be +/// included in `rust/uapi/uapi_helper.h`). Entries must be listed in ascending order with no +/// gaps. +/// - `argument_type` is the type name of the ioctl argument struct within `uapi`. Its size must +/// match the size encoded in the ioctl number. +/// - `flags` is a bitmask of DRM ioctl flags such as [`AUTH`](crate::drm::ioctl::AUTH), +/// [`MASTER`](crate::drm::ioctl::MASTER), [`ROOT_ONLY`](crate::drm::ioctl::ROOT_ONLY), or +/// [`RENDER_ALLOW`](crate::drm::ioctl::RENDER_ALLOW). +/// - `user_callback` is the handler function, which should have the following prototype: /// /// ```ignore -/// fn foo(device: &kernel::drm::Device<Self, kernel::drm::Registered>, -/// reg_data: &Self::RegistrationData<'_>, -/// data: &mut uapi::argument_type, -/// file: &kernel::drm::File<Self>, +/// fn foo( +/// device: &kernel::drm::Device<Self, kernel::drm::Registered>, +/// reg_data: &Self::RegistrationData<'_>, +/// data: &mut uapi::argument_type, +/// file: &kernel::drm::File<Self>, /// ) -> Result<i32> /// ``` -/// where `Self` is the drm::drv::Driver implementation these ioctls are being declared within. +/// +/// where `Self` is the [`drm::Driver`](crate::drm::Driver) implementation these ioctls are being +/// declared within. The callback receives four arguments: +/// +/// - `device`: the registered [`drm::Device`](crate::drm::Device) on which the ioctl was invoked. +/// - `reg_data`: the driver's [`RegistrationData`](crate::drm::Driver::RegistrationData) provided +/// when the device was registered. +/// - `data`: a mutable reference to the ioctl argument struct copied from userspace (or +/// zero-initialized when the ioctl has no input). This parameter is always `&mut` regardless of +/// the ioctl direction, even for write-only (`DRM_IOW`) ioctls; modifications are only copied +/// back to userspace when the ioctl command includes `DRM_IOR` or `DRM_IOWR`. +/// - `file`: the [`drm::File`](crate::drm::File) representing the open file descriptor on which +/// the ioctl was called. +/// +/// Returning `Ok(val)` returns `val` as the `ioctl(2)` return value (typically `0`), whereas +/// `Err(err)` returns the corresponding negative errno. /// /// # Examples ///
@@ -121,9 +147,15 @@ macro_rules! declare_drm_ioctls {// and that the size of the specified type is correct. $( let cmd: u32 = $crate::macros::concat_idents!(DRM_IOCTL_, $cmd); - ::core::assert!(i == $crate ::ioctl::_IOC_NR (cmd)); - ::core::assert!(core::mem::size_of ::<$crate ::uapi::$struct >() == - $crate ::ioctl::_IOC_SIZE (cmd)); + ::core::assert!( + i == $crate ::ioctl::_IOC_NR (cmd), +"DRM ioctls must be listed in order starting from DRM_COMMAND_BASE with no gaps" + ); + ::core::assert!( + ::core::mem::size_of ::<$crate ::uapi::$struct >() == + $crate ::ioctl::_IOC_SIZE (cmd), +"DRM ioctl argument type size does not match ioctl command size" + );let i:u32 = i +1 ; )* };
Signature · 1 line
2.56.1.839.g22a8290db9-goog
Re: [PATCH 2/2] rust: drm: ioctl: document declare_drm_ioctls! arguments and assertions
Quoted 76 lines · Alice Ryhl
The documentation for
declare_drm_ioctls!is currently quite incomplete, and the assertions do not provide a easily readable error message. Thus update the docs and assertions to better document how to create drm ioctls.This came up while I was teaching my Rust for Linux course.
Signed-off-by Alice Ryhl <[email protected]>--- rust/kernel/drm/ioctl.rs | 52 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 10 deletions(-)rust/kernel/drm/ioctl.rs +35
-10@@ -90,17 +90,43 @@ pub const fn __dev_ctx_cast<T: crate::drm::Driver>(/// /// `(ioctl_number, argument_type, flags, user_callback),` /// -/// `argument_type` is the type name within the `bindings` crate. -/// `user_callback` should have the following prototype: +/// where: +/// +/// - `ioctl_number` is the ioctl name without the `DRM_IOCTL_` prefix; the macro prepends +/// `DRM_IOCTL_` and looks up the resulting constant in the uapi header (the header must be +/// included in `rust/uapi/uapi_helper.h`). Entries must be listed in ascending order with no +/// gaps. +/// - `argument_type` is the type name of the ioctl argument struct within `uapi`. Its size must +/// match the size encoded in the ioctl number. +/// - `flags` is a bitmask of DRM ioctl flags such as [`AUTH`](crate::drm::ioctl::AUTH), +/// [`MASTER`](crate::drm::ioctl::MASTER), [`ROOT_ONLY`](crate::drm::ioctl::ROOT_ONLY), or +/// [`RENDER_ALLOW`](crate::drm::ioctl::RENDER_ALLOW). +/// - `user_callback` is the handler function, which should have the following prototype: /// /// ```ignore -/// fn foo(device: &kernel::drm::Device<Self, kernel::drm::Registered>, -/// reg_data: &Self::RegistrationData<'_>, -/// data: &mut uapi::argument_type, -/// file: &kernel::drm::File<Self>, +/// fn foo( +/// device: &kernel::drm::Device<Self, kernel::drm::Registered>, +/// reg_data: &Self::RegistrationData<'_>, +/// data: &mut uapi::argument_type, +/// file: &kernel::drm::File<Self>, /// ) -> Result<i32> /// ``` -/// where `Self` is the drm::drv::Driver implementation these ioctls are being declared within. +/// +/// where `Self` is the [`drm::Driver`](crate::drm::Driver) implementation these ioctls are being +/// declared within. The callback receives four arguments: +/// +/// - `device`: the registered [`drm::Device`](crate::drm::Device) on which the ioctl was invoked. +/// - `reg_data`: the driver's [`RegistrationData`](crate::drm::Driver::RegistrationData) provided +/// when the device was registered. +/// - `data`: a mutable reference to the ioctl argument struct copied from userspace (or +/// zero-initialized when the ioctl has no input). This parameter is always `&mut` regardless of +/// the ioctl direction, even for write-only (`DRM_IOW`) ioctls; modifications are only copied +/// back to userspace when the ioctl command includes `DRM_IOR` or `DRM_IOWR`. +/// - `file`: the [`drm::File`](crate::drm::File) representing the open file descriptor on which +/// the ioctl was called. +/// +/// Returning `Ok(val)` returns `val` as the `ioctl(2)` return value (typically `0`), whereas +/// `Err(err)` returns the corresponding negative errno. /// /// # Examples /// @@ -121,9 +147,15 @@ macro_rules! declare_drm_ioctls {// and that the size of the specified type is correct. $( let cmd: u32 = $crate::macros::concat_idents!(DRM_IOCTL_, $cmd); - ::core::assert!(i == $crate ::ioctl::_IOC_NR (cmd)); - ::core::assert!(core::mem::size_of ::<$crate ::uapi::$struct >() == - $crate ::ioctl::_IOC_SIZE (cmd)); + ::core::assert!( + i == $crate::ioctl::_IOC_NR(cmd),
rust/kernel/drm/ioctl.rs macro_rules! declare_drm_ioctls { · line 161
Quoted 10 lines
rust/kernel/drm/ioctl.rs +7
-0+"DRM ioctls must be listed in order starting from DRM_COMMAND_BASE with no gaps" + ); + ::core::assert!( + ::core::mem::size_of ::<$crate ::uapi::$struct >() == + $crate ::ioctl::_IOC_SIZE (cmd), +"DRM ioctl argument type size does not match ioctl command size" + );let i:u32 = i +1 ; )* };
Janne