Skip to content

Commit 9cd486e

Browse files
Danilo Krummrichgregkh
authored andcommitted
rust: drm: ensure kmalloc() compatible Layout
[ Upstream commit 22ab064 ] drm::Device is allocated through __drm_dev_alloc() (which uses kmalloc()) and the driver private data, <T as drm::Driver>::Data, is initialized in-place. Due to the order of fields in drm::Device pub struct Device<T: drm::Driver> { dev: Opaque<bindings::drm_device>, data: T::Data, } even with an arbitrary large alignment requirement of T::Data it can't happen that the size of Device is smaller than its alignment requirement. However, let's not rely on this subtle circumstance and create a proper kmalloc() compatible Layout. Fixes: 1e4b889 ("rust: drm: add device abstraction") Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250731154919.4132-3-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org> Signed-off-by: Sasha Levin <sashal@kernel.org>
1 parent 3340149 commit 9cd486e

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

rust/kernel/drm/device.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
//! C header: [`include/linux/drm/drm_device.h`](srctree/include/linux/drm/drm_device.h)
66
77
use crate::{
8+
alloc::allocator::Kmalloc,
89
bindings, device, drm,
910
drm::driver::AllocImpl,
1011
error::from_err_ptr,
1112
error::Result,
1213
prelude::*,
1314
types::{ARef, AlwaysRefCounted, Opaque},
1415
};
15-
use core::{mem, ops::Deref, ptr, ptr::NonNull};
16+
use core::{alloc::Layout, mem, ops::Deref, ptr, ptr::NonNull};
1617

1718
#[cfg(CONFIG_DRM_LEGACY)]
1819
macro_rules! drm_legacy_fields {
@@ -96,14 +97,18 @@ impl<T: drm::Driver> Device<T> {
9697

9798
/// Create a new `drm::Device` for a `drm::Driver`.
9899
pub fn new(dev: &device::Device, data: impl PinInit<T::Data, Error>) -> Result<ARef<Self>> {
100+
// `__drm_dev_alloc` uses `kmalloc()` to allocate memory, hence ensure a `kmalloc()`
101+
// compatible `Layout`.
102+
let layout = Kmalloc::aligned_layout(Layout::new::<Self>());
103+
99104
// SAFETY:
100105
// - `VTABLE`, as a `const` is pinned to the read-only section of the compilation,
101106
// - `dev` is valid by its type invarants,
102107
let raw_drm: *mut Self = unsafe {
103108
bindings::__drm_dev_alloc(
104109
dev.as_raw(),
105110
&Self::VTABLE,
106-
mem::size_of::<Self>(),
111+
layout.size(),
107112
mem::offset_of!(Self, dev),
108113
)
109114
}

0 commit comments

Comments
 (0)