Skip to contentSkip to conversation

rust: miscdevice: add llseek support

PATCH In review Ryosuke Yasuoka 2 participants 8 messages Oct 15, 2025 – Oct 16, 2025

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

v2 cover rust: miscdevice: add llseek support

Hi all,

This patch series add support for the llseek file operation to misc devices written in Rust.

The first patch introduces pos()/pos_mut() methods to LocalFile and File. These helpers allow to refer to the file's position, which is required for implementing lseek in misc_device.

The second patch adds the llseek hook to the MiscDevice trait, enabling Rust drivers to implement the seeking logic.

The last one updates the rust_misc_device sample to demonstrate the usage of the new llseek hook, including a C test program that verifies the functionality.

history of this patch:

v2:
- Introduce pos() and pos_mut() methods to get file positions, and use them in sample programs.
- Add read, write and lseek in the userspace sample program.
- Remove unsafe block from the sample program.
- In this v2 patch, remove SEEK_END related codes from a sample program because it needs inode->i_size which has not implemented yet. The purpose of this patch is to introduce lseek(). Since implementing an 'inode wrap' requires more extensive discussion than adding llseek hook(), I just exclude it from this patch series. I believe that whether SEEK_END is supported or not has no impact on adding lseek() to MiscDevice.

v1:
https://lore.kernel.org/rust-for-linux/[email protected]/

Ryosuke Yasuoka (3):
rust: fs: add pos/pos_mut methods for LocalFile struct
rust: miscdevice: add llseek support
rust: samples: miscdevice: add lseek samples

 rust/kernel/fs/file.rs           | 61 ++++++++++++++++++++++++++++
 rust/kernel/miscdevice.rs        | 36 +++++++++++++++++
 samples/rust/rust_misc_device.rs | 68 ++++++++++++++++++++++++++++++++
 3 files changed, 165 insertions(+)

base-commit: 98906f9d850e4882004749eccb8920649dc98456

Signature · 1 line
2.51.0
#1 lore raw

PATCH v2 1/3 rust: fs: add pos/pos_mut methods for LocalFile struct

Add pos() and pos_mut() methods to get and set a file position.

---
 rust/kernel/fs/file.rs | 61 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 61 insertions(+)
rust/kernel/fs/file.rs +61 -0
index cf06e73a6da0..bda6cc540dfe 100644
@@ -283,6 +283,23 @@ pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a LocalFile {
         unsafe { &*ptr.cast() }
     }
 
+    /// Create a mutable reference to a [`LocalFile`] from a valid pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
+    ///   positive for the duration of `'a`.
+    /// * The caller must ensure that if there is an active call to `fdget_pos` that did not take
+    ///   the `f_pos_lock` mutex, then that call is on the current thread.
+    #[inline]
+    pub unsafe fn from_raw_file_mut<'a>(ptr: *mut bindings::file) -> &'a mut LocalFile {
+        // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
+        // duration of `'a`. The cast is okay because `LocalFile` is `repr(transparent)`.
+        //
+        // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
+        unsafe { &mut *ptr.cast() }
+    }
+
     /// Assume that there are no active `fdget_pos` calls that prevent us from sharing this file.
     ///
     /// This makes it safe to transfer this file to other threads. No checks are performed, and
@@ -337,6 +354,20 @@ pub fn flags(&self) -> u32 {
         // FIXME(read_once): Replace with `read_once` when available on the Rust side.
         unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
     }
+
+    /// Get the current `f_pos` with the file.
+    #[inline]
+    pub fn pos(&self) -> i64 {
+        // SAFETY: The `f_pos` is valid while `LocalFile` is valid
+        unsafe { (*self.as_ptr()).f_pos }
+    }
+
+    /// Get a mutable reference to the `f_pos`.
+    #[inline]
+    pub fn pos_mut(&mut self) -> &mut i64 {
+        // SAFETY: The `f_pos` is valid while `LocalFile` is valid
+        unsafe { &mut (*self.as_ptr()).f_pos }
+    }
 }
 
 impl File {
@@ -356,6 +387,23 @@ pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a File {
         // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
         unsafe { &*ptr.cast() }
     }
+
+    /// Creates a mutable reference to a [`File`] from a valid pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
+    ///   positive for the duration of `'a`.
+    /// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they
+    ///   took the `f_pos_lock` mutex.
+    #[inline]
+    pub unsafe fn from_raw_file_mut<'a>(ptr: *mut bindings::file) -> &'a mut File {
+        // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
+        // duration of `'a`. The cast is okay because `File` is `repr(transparent)`.
+        //
+        // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
+        unsafe { &mut *ptr.cast() }
+    }
 }
 
 // Make LocalFile methods available on File.
@@ -372,6 +420,19 @@ fn deref(&self) -> &LocalFile {
     }
 }
 
+// Make LocalFile methods available on File.
+impl core::ops::DerefMut for File {
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        // SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a
+        // valid file for the desired duration.
+        //
+        // By the type invariants, there are no `fdget_pos` calls that did not take the
+        // `f_pos_lock` mutex.
+        unsafe { LocalFile::from_raw_file_mut(core::ptr::from_mut(self).cast()) }
+    }
+}
+
 /// A file descriptor reservation.
 ///
 /// This allows the creation of a file descriptor in two steps: first, we reserve a slot for it,
Signature · 1 line
2.51.0
#2 lore raw

PATCH v2 2/3 rust: miscdevice: add llseek support

In reply to Ryosuke Yasuoka

Add the ability to write a file_operations->llseek hook in Rust when using the miscdevice abstraction.

---
 rust/kernel/miscdevice.rs | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
rust/kernel/miscdevice.rs +36 -0
index d698cddcb4a5..2efd0847cde1 100644
@@ -126,6 +126,16 @@ fn release(device: Self::Ptr, _file: &File) {
         drop(device);
     }
 
+    /// Handler for llseek.
+    fn llseek(
+        _device: <Self::Ptr as ForeignOwnable>::Borrowed<'_>,
+        _file: &mut File,
+        _offset: i64,
+        _whence: i32,
+    ) -> Result<isize> {
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+
     /// Handle for mmap.
     ///
     /// This function is invoked when a user space process invokes the `mmap` system call on
@@ -296,6 +306,27 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
         }
     }
 
+    /// # Safety
+    ///
+    /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
+    unsafe extern "C" fn llseek(file: *mut bindings::file, offset: i64, whence: c_int) -> i64 {
+        // SAFETY: The llseek call of a file can access the private data.
+        let private = unsafe { (*file).private_data };
+        // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `open` and
+        // `from_foreign` in `release`, and `fops_llseek` is guaranteed to be called between those
+        // two operations.
+        let device = unsafe { <T::Ptr as ForeignOwnable>::borrow(private) };
+        // SAFETY:
+        // * The file is valid for the duration of this call.
+        // * There is no active fdget_pos region on the file on this thread.
+        let file = unsafe { File::from_raw_file_mut(file) };
+
+        match T::llseek(device, file, offset, whence) {
+            Ok(res) => res as i64,
+            Err(err) => i64::from(err.to_errno()),
+        }
+    }
+
     /// # Safety
     ///
     /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
@@ -391,6 +422,11 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
     const VTABLE: bindings::file_operations = bindings::file_operations {
         open: Some(Self::open),
         release: Some(Self::release),
+        llseek: if T::HAS_LLSEEK {
+            Some(Self::llseek)
+        } else {
+            None
+        },
         mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },
         read_iter: if T::HAS_READ_ITER {
             Some(Self::read_iter)
Signature · 1 line
2.51.0
#3 lore raw

PATCH v2 3/3 rust: samples: miscdevice: add lseek samples

In reply to Ryosuke Yasuoka

Add lseek samples in Rust MiscDevice samples

---
 samples/rust/rust_misc_device.rs | 68 ++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)
samples/rust/rust_misc_device.rs +68 -0
index d69bc33dbd99..7f227deef69d 100644
@@ -12,6 +12,7 @@
 //! #include <errno.h>
 //! #include <fcntl.h>
 //! #include <unistd.h>
+//! #include <string.h>
 //! #include <sys/ioctl.h>
 //!
 //! #define RUST_MISC_DEV_FAIL _IO('|', 0)
@@ -19,9 +20,11 @@
 //! #define RUST_MISC_DEV_GET_VALUE _IOR('|', 0x81, int)
 //! #define RUST_MISC_DEV_SET_VALUE _IOW('|', 0x82, int)
 //!
+//! #define BUF_SIZE 16
 //! int main() {
 //!   int value, new_value;
 //!   int fd, ret;
+//!   char *buf[BUF_SIZE];
 //!
 //!   // Open the device file
 //!   printf("Opening /dev/rust-misc-device for reading and writing\n");
@@ -86,6 +89,40 @@
 //!     return -1;
 //!   }
 //!
+//!   // Write values to the buffer
+//!   char *w_buf = "ABCDEFG";
+//!   ret = write(fd, w_buf, strlen(w_buf));
+//!   if (ret < 0) {
+//!     perror("write");
+//!     close(fd);
+//!     return errno;
+//!   }
+//!   printf("Write values to the buffer: %.*s\n", ret, w_buf);
+//!
+//!   // Read values from the buffer
+//!   lseek(fd, 0, SEEK_SET);
+//!   ret = read(fd, buf, BUF_SIZE - 1);
+//!   if (ret < 0) {
+//!   	perror("read");
+//! 	close(fd);
+//! 	return errno;
+//!   }
+//!   buf[ret] = '\0';
+//!   printf("Read values from the buffer: %s\n", buf);
+//!
+//!   // Read value from the middle of the buffer
+//!   memset(buf, 0, sizeof(buf));
+//!   lseek(fd, 1, SEEK_SET);
+//!   lseek(fd, 2, SEEK_CUR);
+//!   ret = read(fd, buf, BUF_SIZE - 1);
+//!   if (ret < 0) {
+//!   	perror("read");
+//! 	close(fd);
+//! 	return errno;
+//!   }
+//!   buf[ret] = '\0';
+//!   printf("Read values from the middle of the buffer: %s\n", buf);
+//!
 //!   // Close the device file
 //!   printf("Closing /dev/rust-misc-device\n");
 //!   close(fd);
@@ -114,6 +151,9 @@
 const RUST_MISC_DEV_GET_VALUE: u32 = _IOR::<i32>('|' as u32, 0x81);
 const RUST_MISC_DEV_SET_VALUE: u32 = _IOW::<i32>('|' as u32, 0x82);
 
+const SEEK_SET: i32 = 0;
+const SEEK_CUR: i32 = 1;
+
 module! {
     type: RustMiscDeviceModule,
     name: "rust_misc_device",
@@ -204,6 +244,34 @@ fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource<'_>) -> R
         Ok(len)
     }
 
+    fn llseek(
+        me: Pin<&RustMiscDevice>,
+        file: &mut File,
+        offset: i64,
+        whence: i32,
+    ) -> Result<isize> {
+        dev_info!(me.dev, "LLSEEK Rust Misc Device Sample\n");
+        let pos: i64 = file.pos();
+
+        let new_pos = match whence {
+            SEEK_SET => offset,
+            SEEK_CUR => pos + offset,
+            _ => {
+                dev_err!(me.dev, "LLSEEK does not recognised: {}.\n", whence);
+                return Err(EINVAL);
+            }
+        };
+
+        if new_pos < 0 {
+            dev_err!(me.dev, "The file offset becomes negative: {}.\n", new_pos);
+            return Err(EINVAL);
+        }
+
+        *file.pos_mut() = new_pos;
+
+        Ok(new_pos as isize)
+    }
+
     fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> {
         dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n");
 
Signature · 1 line
2.51.0
maintainer
#4 lore raw
In reply to Ryosuke Yasuoka
Quoted 4 lines · Ryosuke Yasuoka

Hi all,

This patch series add support for the llseek file operation to misc devices written in Rust.

Cool, but what miscdevice driver needs llseek support? Do you have a real user for this that we can see as well?

thanks,

greg k-h

#5 lore raw
Quoted 8 lines · Greg KH
Quoted 4 lines · Ryosuke Yasuoka

Hi all,

This patch series add support for the llseek file operation to misc devices written in Rust.

Cool, but what miscdevice driver needs llseek support? Do you have a real user for this that we can see as well?

Currently no. Because lseek is one of fundamental functions for device driver, I think it's valuable to add support. I believe we'll have real users based on read, write, and this lseek support.

What do you think? Thank you for your comment.

Best regards,
Ryosuke

Quoted 4 lines

thanks,

greg k-h

maintainer
#6 lore raw
Quoted 7 lines · Ryosuke Yasuoka
Quoted 6 lines · Greg KH
Quoted 4 lines · Ryosuke Yasuoka

Hi all,

This patch series add support for the llseek file operation to misc devices written in Rust.

Quoted 6 lines
Quoted 2 lines

Cool, but what miscdevice driver needs llseek support? Do you have a real user for this that we can see as well?

Currently no. Because lseek is one of fundamental functions for device driver, I think it's valuable to add support. I believe we'll have real users based on read, write, and this lseek support.

Char devices that use lseek are "odd", don't you agree? There are no such current users under drivers/misc/ and only a rare few under drivers/char/ (the huge user of that is mem.c but we aren't going to be reimplementing that in rust any time soon...)

So without a real user of this api, I suggest we hold-off on adding it. Let's not add it until someone comes up with a very valid reason for it.

thanks,

greg k-h

#7 lore raw
Quoted 15 lines · Greg KH
Quoted 7 lines · Ryosuke Yasuoka
Quoted 6 lines · Greg KH
Quoted 4 lines · Ryosuke Yasuoka

Hi all,

This patch series add support for the llseek file operation to misc devices written in Rust.

Quoted 6 lines
Quoted 2 lines

Cool, but what miscdevice driver needs llseek support? Do you have a real user for this that we can see as well?

Currently no. Because lseek is one of fundamental functions for device driver, I think it's valuable to add support. I believe we'll have real users based on read, write, and this lseek support.

Quoted 7 lines

Char devices that use lseek are "odd", don't you agree? There are no such current users under drivers/misc/ and only a rare few under drivers/char/ (the huge user of that is mem.c but we aren't going to be reimplementing that in rust any time soon...)

So without a real user of this api, I suggest we hold-off on adding it. Let's not add it until someone comes up with a very valid reason for it.

Thank you for your review and clear explanation.

I understand your point. It makes sense not to add this without real user. I'll hold off on this and will revisit it if a concrete use case emerges.

Best regards,
Ryosuke

Quoted 4 lines

thanks,

greg k-h