From 28a2643f1c6b4f715f85176ce13fda6d898cbb92 Mon Sep 17 00:00:00 2001 From: Wedson Almeida Filho Date: Mon, 10 May 2021 16:00:09 +0100 Subject: [PATCH] Rename `KernelResult` to just `Result`. This is just a rename followed by `rustfmt`, no functional change is intended. Signed-off-by: Wedson Almeida Filho --- drivers/android/allocation.rs | 16 +++---- drivers/android/context.rs | 4 +- drivers/android/node.rs | 14 ++---- drivers/android/process.rs | 62 +++++++++++--------------- drivers/android/range_alloc.rs | 12 ++--- drivers/android/rust_binder.rs | 14 ++---- drivers/android/thread.rs | 24 +++++----- drivers/android/transaction.rs | 6 +-- rust/kernel/chrdev.rs | 6 +-- rust/kernel/error.rs | 8 ++-- rust/kernel/file_operations.rs | 49 +++++++------------- rust/kernel/io_buffer.rs | 18 ++++---- rust/kernel/iov_iter.rs | 8 ++-- rust/kernel/lib.rs | 4 +- rust/kernel/miscdev.rs | 6 +-- rust/kernel/pages.rs | 14 +++--- rust/kernel/prelude.rs | 2 +- rust/kernel/random.rs | 4 +- rust/kernel/sync/arc.rs | 4 +- rust/kernel/sysctl.rs | 14 +++--- rust/kernel/user_ptr.rs | 12 ++--- rust/module.rs | 4 +- samples/rust/rust_chrdev.rs | 2 +- samples/rust/rust_minimal.rs | 2 +- samples/rust/rust_miscdev.rs | 15 +++---- samples/rust/rust_module_parameters.rs | 2 +- samples/rust/rust_print.rs | 2 +- samples/rust/rust_random.rs | 14 +----- samples/rust/rust_semaphore.rs | 21 ++++----- samples/rust/rust_stack_probing.rs | 2 +- samples/rust/rust_sync.rs | 2 +- 31 files changed, 148 insertions(+), 219 deletions(-) diff --git a/drivers/android/allocation.rs b/drivers/android/allocation.rs index 80b96628c778c5..944d8735658dda 100644 --- a/drivers/android/allocation.rs +++ b/drivers/android/allocation.rs @@ -39,9 +39,9 @@ impl<'a> Allocation<'a> { } } - fn iterate(&self, mut offset: usize, mut size: usize, mut cb: T) -> KernelResult + fn iterate(&self, mut offset: usize, mut size: usize, mut cb: T) -> Result where - T: FnMut(&Pages<0>, usize, usize) -> KernelResult, + T: FnMut(&Pages<0>, usize, usize) -> Result, { // Check that the request is within the buffer. if offset.checked_add(size).ok_or(Error::EINVAL)? > self.size { @@ -65,13 +65,13 @@ impl<'a> Allocation<'a> { reader: &mut UserSlicePtrReader, offset: usize, size: usize, - ) -> KernelResult { + ) -> Result { self.iterate(offset, size, |page, offset, to_copy| { page.copy_into_page(reader, offset, to_copy) }) } - pub(crate) fn read(&self, offset: usize) -> KernelResult { + pub(crate) fn read(&self, offset: usize) -> Result { let mut out = MaybeUninit::::uninit(); let mut out_offset = 0; self.iterate(offset, size_of::(), |page, offset, to_copy| { @@ -90,7 +90,7 @@ impl<'a> Allocation<'a> { Ok(unsafe { out.assume_init() }) } - pub(crate) fn write(&self, offset: usize, obj: &T) -> KernelResult { + pub(crate) fn write(&self, offset: usize, obj: &T) -> Result { let mut obj_offset = 0; self.iterate(offset, size_of::(), |page, offset, to_copy| { // SAFETY: The sum of `offset` and `to_copy` is bounded by the size of T. @@ -112,7 +112,7 @@ impl<'a> Allocation<'a> { self.allocation_info = Some(info); } - fn cleanup_object(&self, index_offset: usize, view: &AllocationView) -> KernelResult { + fn cleanup_object(&self, index_offset: usize, view: &AllocationView) -> Result { let offset = self.read(index_offset)?; let header = view.read::(offset)?; // TODO: Handle other types. @@ -169,14 +169,14 @@ impl<'a> AllocationView<'a> { AllocationView { alloc, limit } } - pub fn read(&self, offset: usize) -> KernelResult { + pub fn read(&self, offset: usize) -> Result { if offset.checked_add(size_of::()).ok_or(Error::EINVAL)? > self.limit { return Err(Error::EINVAL); } self.alloc.read(offset) } - pub fn write(&self, offset: usize, obj: &T) -> KernelResult { + pub fn write(&self, offset: usize, obj: &T) -> Result { if offset.checked_add(size_of::()).ok_or(Error::EINVAL)? > self.limit { return Err(Error::EINVAL); } diff --git a/drivers/android/context.rs b/drivers/android/context.rs index 1ab2b26c8fd3af..2b1bd479ba3648 100644 --- a/drivers/android/context.rs +++ b/drivers/android/context.rs @@ -24,7 +24,7 @@ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { - pub(crate) fn new() -> KernelResult>> { + pub(crate) fn new() -> Result>> { let mut ctx_ref = Arc::try_new(Self { // SAFETY: Init is called below. manager: unsafe { @@ -44,7 +44,7 @@ impl Context { Ok(unsafe { Pin::new_unchecked(ctx_ref) }) } - pub(crate) fn set_manager_node(&self, node_ref: NodeRef) -> KernelResult { + pub(crate) fn set_manager_node(&self, node_ref: NodeRef) -> Result { let mut manager = self.manager.lock(); if manager.node.is_some() { return Err(Error::EBUSY); diff --git a/drivers/android/node.rs b/drivers/android/node.rs index 7933212ac9fa22..954ab322d59eee 100644 --- a/drivers/android/node.rs +++ b/drivers/android/node.rs @@ -170,11 +170,7 @@ impl GetLinks for NodeDeath { } impl DeliverToRead for NodeDeath { - fn do_work( - self: Arc, - _thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult { + fn do_work(self: Arc, _thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { let done = { let inner = self.inner.lock(); if inner.aborted { @@ -335,7 +331,7 @@ impl Node { inner.weak.has_count = true; } - fn write(&self, writer: &mut UserSlicePtrWriter, code: u32) -> KernelResult { + fn write(&self, writer: &mut UserSlicePtrWriter, code: u32) -> Result { writer.write(&code)?; writer.write(&self.ptr)?; writer.write(&self.cookie)?; @@ -344,11 +340,7 @@ impl Node { } impl DeliverToRead for Node { - fn do_work( - self: Arc, - _thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult { + fn do_work(self: Arc, _thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { let mut owner_inner = self.owner.inner.lock(); let inner = self.inner.access_mut(&mut owner_inner); let strong = inner.strong.count > 0; diff --git a/drivers/android/process.rs b/drivers/android/process.rs index 59b4eaa6f920f2..6df6678bae6b75 100644 --- a/drivers/android/process.rs +++ b/drivers/android/process.rs @@ -48,7 +48,7 @@ struct Mapping { } impl Mapping { - fn new(address: usize, size: usize, pages: Arc<[Pages<0>]>) -> KernelResult { + fn new(address: usize, size: usize, pages: Arc<[Pages<0>]>) -> Result { let alloc = RangeAllocator::new(size)?; Ok(Self { address, @@ -162,7 +162,7 @@ impl ProcessInner { /// Returns an existing node with the given pointer and cookie, if one exists. /// /// Returns an error if a node with the given pointer but a different cookie exists. - fn get_existing_node(&self, ptr: usize, cookie: usize) -> KernelResult>> { + fn get_existing_node(&self, ptr: usize, cookie: usize) -> Result>> { match self.nodes.get(&ptr) { None => Ok(None), Some(node) => { @@ -185,7 +185,7 @@ impl ProcessInner { cookie: usize, strong: bool, thread: Option<&Thread>, - ) -> KernelResult> { + ) -> Result> { Ok(match self.get_existing_node(ptr, cookie)? { None => None, Some(node) => Some(self.new_node_ref(node, strong, thread)), @@ -225,7 +225,7 @@ struct ArcReservation { } impl ArcReservation { - fn new() -> KernelResult { + fn new() -> Result { Ok(Self { mem: Arc::try_new(MaybeUninit::::uninit())?, }) @@ -293,7 +293,7 @@ unsafe impl Send for Process {} unsafe impl Sync for Process {} impl Process { - fn new(ctx: Arc) -> KernelResult> { + fn new(ctx: Arc) -> Result> { let mut proc_ref = Ref::try_new(Self { ref_count: RefCount::new(), ctx, @@ -338,7 +338,7 @@ impl Process { Either::Right(Registration::new(self, thread, &mut inner)) } - fn get_thread(&self, id: i32) -> KernelResult> { + fn get_thread(&self, id: i32) -> Result> { // TODO: Consider using read/write locks here instead. { let inner = self.inner.lock(); @@ -367,7 +367,7 @@ impl Process { self.inner.lock().push_work(work) } - fn set_as_manager(&self, info: Option, thread: &Thread) -> KernelResult { + fn set_as_manager(&self, info: Option, thread: &Thread) -> Result { let (ptr, cookie) = if let Some(obj) = info { (unsafe { obj.__bindgen_anon_1.binder }, obj.cookie) } else { @@ -390,7 +390,7 @@ impl Process { cookie: usize, strong: bool, thread: Option<&Thread>, - ) -> KernelResult { + ) -> Result { // Try to find an existing node. { let mut inner = self.inner.lock(); @@ -416,7 +416,7 @@ impl Process { &self, node_ref: NodeRef, is_mananger: bool, - ) -> KernelResult { + ) -> Result { let mut refs = self.node_refs.lock(); // Do a lookup before inserting. @@ -475,7 +475,7 @@ impl Process { drop(removed); } - pub(crate) fn update_ref(&self, handle: u32, inc: bool, strong: bool) -> KernelResult { + pub(crate) fn update_ref(&self, handle: u32, inc: bool, strong: bool) -> Result { if inc && handle == 0 { if let Ok(node_ref) = self.ctx.get_manager_node(strong) { if core::ptr::eq(self, &*node_ref.node.owner) { @@ -514,11 +514,7 @@ impl Process { } } - pub(crate) fn inc_ref_done( - &self, - reader: &mut UserSlicePtrReader, - strong: bool, - ) -> KernelResult { + pub(crate) fn inc_ref_done(&self, reader: &mut UserSlicePtrReader, strong: bool) -> Result { let ptr = reader.read::()?; let cookie = reader.read::()?; self.update_node(ptr, cookie, strong, true); @@ -539,7 +535,7 @@ impl Process { )) } - // TODO: Review if we want an Option or a KernelResult. + // TODO: Review if we want an Option or a Result. pub(crate) fn buffer_get(&self, ptr: usize) -> Option { let mut inner = self.inner.lock(); let mapping = inner.mapping.as_mut()?; @@ -574,7 +570,7 @@ impl Process { } } - fn create_mapping(&self, vma: &mut bindings::vm_area_struct) -> KernelResult { + fn create_mapping(&self, vma: &mut bindings::vm_area_struct) -> Result { let size = core::cmp::min( (vma.vm_end - vma.vm_start) as usize, bindings::SZ_4M as usize, @@ -606,7 +602,7 @@ impl Process { Ok(()) } - fn version(&self, data: UserSlicePtr) -> KernelResult { + fn version(&self, data: UserSlicePtr) -> Result { data.writer().write(&BinderVersion::current()) } @@ -623,7 +619,7 @@ impl Process { self.inner.lock().max_threads = max; } - fn get_node_debug_info(&self, data: UserSlicePtr) -> KernelResult { + fn get_node_debug_info(&self, data: UserSlicePtr) -> Result { let (mut reader, mut writer) = data.reader_writer(); // Read the starting point. @@ -643,7 +639,7 @@ impl Process { writer.write(&out) } - fn get_node_info_from_ref(&self, data: UserSlicePtr) -> KernelResult { + fn get_node_info_from_ref(&self, data: UserSlicePtr) -> Result { let (mut reader, mut writer) = data.reader_writer(); let mut out = reader.read::()?; @@ -686,11 +682,7 @@ impl Process { ret } - pub(crate) fn request_death( - &self, - reader: &mut UserSlicePtrReader, - thread: &Thread, - ) -> KernelResult { + pub(crate) fn request_death(&self, reader: &mut UserSlicePtrReader, thread: &Thread) -> Result { let handle: u32 = reader.read()?; let cookie: usize = reader.read()?; @@ -733,11 +725,7 @@ impl Process { Ok(()) } - pub(crate) fn clear_death( - &self, - reader: &mut UserSlicePtrReader, - thread: &Thread, - ) -> KernelResult { + pub(crate) fn clear_death(&self, reader: &mut UserSlicePtrReader, thread: &Thread) -> Result { let handle: u32 = reader.read()?; let cookie: usize = reader.read()?; @@ -767,7 +755,7 @@ impl Process { } impl IoctlHandler for Process { - fn write(&self, _file: &File, cmd: u32, reader: &mut UserSlicePtrReader) -> KernelResult { + fn write(&self, _file: &File, cmd: u32, reader: &mut UserSlicePtrReader) -> Result { let thread = self.get_thread(unsafe { rust_helper_current_pid() })?; match cmd { bindings::BINDER_SET_MAX_THREADS => self.set_max_threads(reader.read()?), @@ -781,7 +769,7 @@ impl IoctlHandler for Process { Ok(0) } - fn read_write(&self, file: &File, cmd: u32, data: UserSlicePtr) -> KernelResult { + fn read_write(&self, file: &File, cmd: u32, data: UserSlicePtr) -> Result { let thread = self.get_thread(unsafe { rust_helper_current_pid() })?; match cmd { bindings::BINDER_WRITE_READ => thread.write_read(data, file.is_blocking())?, @@ -801,7 +789,7 @@ unsafe impl RefCounted for Process { } impl FileOpener> for Process { - fn open(ctx: &Arc) -> KernelResult { + fn open(ctx: &Arc) -> Result { let process = Self::new(ctx.clone())?; // SAFETY: Pointer is pinned behind `Ref`. Ok(unsafe { Pin::new_unchecked(process) }) @@ -892,15 +880,15 @@ impl FileOperations for Process { } } - fn ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> KernelResult { + fn ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> Result { cmd.dispatch(self, file) } - fn compat_ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> KernelResult { + fn compat_ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> Result { cmd.dispatch(self, file) } - fn mmap(&self, _file: &File, vma: &mut bindings::vm_area_struct) -> KernelResult { + fn mmap(&self, _file: &File, vma: &mut bindings::vm_area_struct) -> Result { // TODO: Only group leader is allowed to create mappings. if vma.vm_start == 0 { @@ -918,7 +906,7 @@ impl FileOperations for Process { self.create_mapping(vma) } - fn poll(&self, file: &File, table: &PollTable) -> KernelResult { + fn poll(&self, file: &File, table: &PollTable) -> Result { let thread = self.get_thread(unsafe { rust_helper_current_pid() })?; let (from_proc, mut mask) = thread.poll(file, table); if mask == 0 && from_proc && !self.inner.lock().work.is_empty() { diff --git a/drivers/android/range_alloc.rs b/drivers/android/range_alloc.rs index 0278041cdf7638..4d6b8539fa8375 100644 --- a/drivers/android/range_alloc.rs +++ b/drivers/android/range_alloc.rs @@ -20,7 +20,7 @@ enum DescriptorState { } impl RangeAllocator { - pub(crate) fn new(size: usize) -> KernelResult { + pub(crate) fn new(size: usize) -> Result { let desc = Box::try_new(Descriptor::new(0, size))?; let mut list = List::new(); list.push_back(desc); @@ -49,7 +49,7 @@ impl RangeAllocator { best } - pub(crate) fn reserve_new(&mut self, size: usize) -> KernelResult { + pub(crate) fn reserve_new(&mut self, size: usize) -> Result { let desc_ptr = match self.find_best_match(size) { None => return Err(Error::ENOMEM), Some(found) => found, @@ -70,7 +70,7 @@ impl RangeAllocator { Ok(desc.offset) } - fn free_with_cursor(cursor: &mut CursorMut>>) -> KernelResult { + fn free_with_cursor(cursor: &mut CursorMut>>) -> Result { let mut size = match cursor.current() { None => return Err(Error::EINVAL), Some(ref mut entry) => { @@ -121,13 +121,13 @@ impl RangeAllocator { None } - pub(crate) fn reservation_abort(&mut self, offset: usize) -> KernelResult { + pub(crate) fn reservation_abort(&mut self, offset: usize) -> Result { // TODO: The force case is currently O(n), but could be made O(1) with unsafe. let mut cursor = self.find_at_offset(offset).ok_or(Error::EINVAL)?; Self::free_with_cursor(&mut cursor) } - pub(crate) fn reservation_commit(&mut self, offset: usize, data: Option) -> KernelResult { + pub(crate) fn reservation_commit(&mut self, offset: usize, data: Option) -> Result { // TODO: This is currently O(n), make it O(1). let mut cursor = self.find_at_offset(offset).ok_or(Error::ENOENT)?; let desc = cursor.current().unwrap(); @@ -140,7 +140,7 @@ impl RangeAllocator { /// [`DescriptorState::Reserved`]. /// /// Returns the size of the existing entry and the data associated with it. - pub(crate) fn reserve_existing(&mut self, offset: usize) -> KernelResult<(usize, Option)> { + pub(crate) fn reserve_existing(&mut self, offset: usize) -> Result<(usize, Option)> { // TODO: This is currently O(n), make it O(log n). let mut cursor = self.find_at_offset(offset).ok_or(Error::ENOENT)?; let desc = cursor.current().unwrap(); diff --git a/drivers/android/rust_binder.rs b/drivers/android/rust_binder.rs index 75640fc3f81c97..5d04784819fe31 100644 --- a/drivers/android/rust_binder.rs +++ b/drivers/android/rust_binder.rs @@ -46,11 +46,7 @@ trait DeliverToRead { /// Performs work. Returns true if remaining work items in the queue should be processed /// immediately, or false if it should return to caller before processing additional work /// items. - fn do_work( - self: Arc, - thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult; + fn do_work(self: Arc, thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result; /// Cancels the given work item. This is called instead of [`DeliverToRead::do_work`] when work /// won't be delivered. @@ -89,11 +85,7 @@ impl DeliverCode { } impl DeliverToRead for DeliverCode { - fn do_work( - self: Arc, - _thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult { + fn do_work(self: Arc, _thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { writer.write(&self.code)?; Ok(true) } @@ -115,7 +107,7 @@ struct BinderModule { } impl KernelModule for BinderModule { - fn init() -> KernelResult { + fn init() -> Result { let pinned_ctx = Context::new()?; let ctx = unsafe { Pin::into_inner_unchecked(pinned_ctx) }; let reg = Registration::>::new_pinned::( diff --git a/drivers/android/thread.rs b/drivers/android/thread.rs index f0c1a6cabe2449..ec290da2a0be02 100644 --- a/drivers/android/thread.rs +++ b/drivers/android/thread.rs @@ -23,7 +23,7 @@ use crate::{ DeliverCode, DeliverToRead, DeliverToReadListAdapter, Either, }; -pub(crate) type BinderResult = Result; +pub(crate) type BinderResult = core::result::Result; pub(crate) struct BinderError { pub(crate) reply: u32, @@ -157,7 +157,7 @@ impl InnerThread { /// Fetches the transaction the thread can reply to. If the thread has a pending transaction /// (that it could respond to) but it has also issued a transaction, it must first wait for the /// previously-issued transaction to complete. - fn pop_transaction_to_reply(&mut self, thread: &Thread) -> KernelResult> { + fn pop_transaction_to_reply(&mut self, thread: &Thread) -> Result> { let transaction = self.current_transaction.take().ok_or(Error::EINVAL)?; if core::ptr::eq(thread, transaction.from.as_ref()) { @@ -233,7 +233,7 @@ pub(crate) struct Thread { } impl Thread { - pub(crate) fn new(id: i32, process: Ref) -> KernelResult> { + pub(crate) fn new(id: i32, process: Ref) -> Result> { let return_work = Arc::try_new(ThreadError::new(InnerThread::set_return_work))?; let reply_work = Arc::try_new(ThreadError::new(InnerThread::set_reply_work))?; let mut arc = Arc::try_new(Self { @@ -269,7 +269,7 @@ impl Thread { /// Attempts to fetch a work item from the thread-local queue. The behaviour if the queue is /// empty depends on `wait`: if it is true, the function waits for some work to be queued (or a /// signal); otherwise it returns indicating that none is available. - fn get_work_local(self: &Arc, wait: bool) -> KernelResult> { + fn get_work_local(self: &Arc, wait: bool) -> Result> { // Try once if the caller does not want to wait. if !wait { return self.inner.lock().pop_work().ok_or(Error::EAGAIN); @@ -298,7 +298,7 @@ impl Thread { /// /// This must only be called when the thread is not participating in a transaction chain. If it /// is, the local version (`get_work_local`) should be used instead. - fn get_work(self: &Arc, wait: bool) -> KernelResult> { + fn get_work(self: &Arc, wait: bool) -> Result> { // Try to get work from the thread's work queue, using only a local lock. { let mut inner = self.inner.lock(); @@ -555,7 +555,7 @@ impl Thread { /// Determines the current top of the transaction stack. It fails if the top is in another /// thread (i.e., this thread belongs to a stack but it has called another thread). The top is /// [`None`] if the thread is not currently participating in a transaction stack. - fn top_of_transaction_stack(&self) -> KernelResult>> { + fn top_of_transaction_stack(&self) -> Result>> { let inner = self.inner.lock(); Ok(if let Some(cur) = &inner.current_transaction { if core::ptr::eq(self, cur.from.as_ref()) { @@ -605,7 +605,7 @@ impl Thread { Ok(()) } - fn write(self: &Arc, req: &mut BinderWriteRead) -> KernelResult { + fn write(self: &Arc, req: &mut BinderWriteRead) -> Result { let write_start = req.write_buffer.wrapping_add(req.write_consumed); let write_len = req.write_size - req.write_consumed; let mut reader = unsafe { UserSlicePtr::new(write_start as _, write_len as _).reader() }; @@ -650,7 +650,7 @@ impl Thread { Ok(()) } - fn read(self: &Arc, req: &mut BinderWriteRead, wait: bool) -> KernelResult { + fn read(self: &Arc, req: &mut BinderWriteRead, wait: bool) -> Result { let read_start = req.read_buffer.wrapping_add(req.read_consumed); let read_len = req.read_size - req.read_consumed; let mut writer = unsafe { UserSlicePtr::new(read_start as _, read_len as _) }.writer(); @@ -704,7 +704,7 @@ impl Thread { Ok(()) } - pub(crate) fn write_read(self: &Arc, data: UserSlicePtr, wait: bool) -> KernelResult { + pub(crate) fn write_read(self: &Arc, data: UserSlicePtr, wait: bool) -> Result { let (mut reader, mut writer) = data.reader_writer(); let mut req = reader.read::()?; @@ -802,11 +802,7 @@ impl ThreadError { } impl DeliverToRead for ThreadError { - fn do_work( - self: Arc, - thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult { + fn do_work(self: Arc, thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { let code = self.error_code; // Return the `ThreadError` to the thread. diff --git a/drivers/android/transaction.rs b/drivers/android/transaction.rs index e4489da37d1bdf..e0450d21bb68ae 100644 --- a/drivers/android/transaction.rs +++ b/drivers/android/transaction.rs @@ -137,11 +137,7 @@ impl Transaction { } impl DeliverToRead for Transaction { - fn do_work( - self: Arc, - thread: &Thread, - writer: &mut UserSlicePtrWriter, - ) -> KernelResult { + fn do_work(self: Arc, thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { /* TODO: Initialise the following fields from tr: pub sender_pid: pid_t, pub sender_euid: uid_t, diff --git a/rust/kernel/chrdev.rs b/rust/kernel/chrdev.rs index 6772a3a925ccf6..6ebaeac01b783f 100644 --- a/rust/kernel/chrdev.rs +++ b/rust/kernel/chrdev.rs @@ -16,7 +16,7 @@ use core::pin::Pin; use crate::bindings; use crate::c_types; -use crate::error::{Error, KernelResult}; +use crate::error::{Error, Result}; use crate::file_operations; use crate::types::CStr; @@ -67,7 +67,7 @@ impl Registration<{ N }> { name: CStr<'static>, minors_start: u16, this_module: &'static crate::ThisModule, - ) -> KernelResult>> { + ) -> Result>> { Ok(Pin::from(Box::try_new(Self::new( name, minors_start, @@ -78,7 +78,7 @@ impl Registration<{ N }> { /// Registers a character device. /// /// You may call this once per device type, up to `N` times. - pub fn register>(self: Pin<&mut Self>) -> KernelResult { + pub fn register>(self: Pin<&mut Self>) -> Result { // SAFETY: We must ensure that we never move out of `this`. let this = unsafe { self.get_unchecked_mut() }; if this.inner.is_none() { diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 432d866232c13c..27043dc8778d75 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -91,13 +91,13 @@ impl From for Error { /// /// In Rust, it is idiomatic to model functions that may fail as returning /// a [`Result`]. Since in the kernel many functions return an error code, -/// [`KernelResult`] is a type alias for a [`Result`] that uses [`Error`] as -/// its error type. +/// [`Result`] is a type alias for a [`core::result::Result`] that uses +/// [`Error`] as its error type. /// /// Note that even if a function does not return anything when it succeeds, -/// it should still be modeled as returning a `KernelResult` rather than +/// it should still be modeled as returning a `Result` rather than /// just an [`Error`]. -pub type KernelResult = Result; +pub type Result = core::result::Result; impl From for Error { fn from(_: AllocError) -> Error { diff --git a/rust/kernel/file_operations.rs b/rust/kernel/file_operations.rs index ad379ac981ca44..34b47c81aef7ce 100644 --- a/rust/kernel/file_operations.rs +++ b/rust/kernel/file_operations.rs @@ -12,7 +12,7 @@ use alloc::sync::Arc; use crate::{ bindings, c_types, - error::{Error, KernelResult}, + error::{Error, Result}, file::File, io_buffer::{IoBufferReader, IoBufferWriter}, iov_iter::IovIter, @@ -78,7 +78,7 @@ pub enum SeekFrom { Current(i64), } -fn from_kernel_result(r: KernelResult) -> T +fn from_kernel_result(r: Result) -> T where T: TryFrom, T::Error: core::fmt::Debug, @@ -423,30 +423,25 @@ macro_rules! declare_file_operations { /// For each macro, there is a handler function that takes the appropriate types as arguments. pub trait IoctlHandler: Sync { /// Handles ioctls defined with the `_IO` macro, that is, with no buffer as argument. - fn pure(&self, _file: &File, _cmd: u32, _arg: usize) -> KernelResult { + fn pure(&self, _file: &File, _cmd: u32, _arg: usize) -> Result { Err(Error::EINVAL) } /// Handles ioctls defined with the `_IOR` macro, that is, with an output buffer provided as /// argument. - fn read(&self, _file: &File, _cmd: u32, _writer: &mut UserSlicePtrWriter) -> KernelResult { + fn read(&self, _file: &File, _cmd: u32, _writer: &mut UserSlicePtrWriter) -> Result { Err(Error::EINVAL) } /// Handles ioctls defined with the `_IOW` macro, that is, with an input buffer provided as /// argument. - fn write( - &self, - _file: &File, - _cmd: u32, - _reader: &mut UserSlicePtrReader, - ) -> KernelResult { + fn write(&self, _file: &File, _cmd: u32, _reader: &mut UserSlicePtrReader) -> Result { Err(Error::EINVAL) } /// Handles ioctls defined with the `_IOWR` macro, that is, with a buffer for both input and /// output provided as argument. - fn read_write(&self, _file: &File, _cmd: u32, _data: UserSlicePtr) -> KernelResult { + fn read_write(&self, _file: &File, _cmd: u32, _data: UserSlicePtr) -> Result { Err(Error::EINVAL) } } @@ -482,7 +477,7 @@ impl IoctlCommand { /// /// It is meant to be used in implementations of [`FileOperations::ioctl`] and /// [`FileOperations::compat_ioctl`]. - pub fn dispatch(&mut self, handler: &T, file: &File) -> KernelResult { + pub fn dispatch(&mut self, handler: &T, file: &File) -> Result { let dir = (self.cmd >> bindings::_IOC_DIRSHIFT) & bindings::_IOC_DIRMASK; if dir == bindings::_IOC_NONE { return handler.pure(file, self.cmd, self.arg); @@ -534,11 +529,11 @@ pub trait FileOpener: FileOperations { /// Creates a new instance of this file. /// /// Corresponds to the `open` function pointer in `struct file_operations`. - fn open(context: &T) -> KernelResult; + fn open(context: &T) -> Result; } impl> + Default> FileOpener<()> for T { - fn open(_: &()) -> KernelResult { + fn open(_: &()) -> Result { Ok(Box::try_new(T::default())?) } } @@ -568,52 +563,42 @@ pub trait FileOperations: Send + Sync + Sized { /// Reads data from this file to the caller's buffer. /// /// Corresponds to the `read` and `read_iter` function pointers in `struct file_operations`. - fn read( - &self, - _file: &File, - _data: &mut T, - _offset: u64, - ) -> KernelResult { + fn read(&self, _file: &File, _data: &mut T, _offset: u64) -> Result { Err(Error::EINVAL) } /// Writes data from the caller's buffer to this file. /// /// Corresponds to the `write` and `write_iter` function pointers in `struct file_operations`. - fn write( - &self, - _file: &File, - _data: &mut T, - _offset: u64, - ) -> KernelResult { + fn write(&self, _file: &File, _data: &mut T, _offset: u64) -> Result { Err(Error::EINVAL) } /// Changes the position of the file. /// /// Corresponds to the `llseek` function pointer in `struct file_operations`. - fn seek(&self, _file: &File, _offset: SeekFrom) -> KernelResult { + fn seek(&self, _file: &File, _offset: SeekFrom) -> Result { Err(Error::EINVAL) } /// Performs IO control operations that are specific to the file. /// /// Corresponds to the `unlocked_ioctl` function pointer in `struct file_operations`. - fn ioctl(&self, _file: &File, _cmd: &mut IoctlCommand) -> KernelResult { + fn ioctl(&self, _file: &File, _cmd: &mut IoctlCommand) -> Result { Err(Error::EINVAL) } /// Performs 32-bit IO control operations on that are specific to the file on 64-bit kernels. /// /// Corresponds to the `compat_ioctl` function pointer in `struct file_operations`. - fn compat_ioctl(&self, _file: &File, _cmd: &mut IoctlCommand) -> KernelResult { + fn compat_ioctl(&self, _file: &File, _cmd: &mut IoctlCommand) -> Result { Err(Error::EINVAL) } /// Syncs pending changes to this file. /// /// Corresponds to the `fsync` function pointer in `struct file_operations`. - fn fsync(&self, _file: &File, _start: u64, _end: u64, _datasync: bool) -> KernelResult { + fn fsync(&self, _file: &File, _start: u64, _end: u64, _datasync: bool) -> Result { Err(Error::EINVAL) } @@ -621,7 +606,7 @@ pub trait FileOperations: Send + Sync + Sized { /// /// Corresponds to the `mmap` function pointer in `struct file_operations`. /// TODO: wrap `vm_area_struct` so that we don't have to expose it. - fn mmap(&self, _file: &File, _vma: &mut bindings::vm_area_struct) -> KernelResult { + fn mmap(&self, _file: &File, _vma: &mut bindings::vm_area_struct) -> Result { Err(Error::EINVAL) } @@ -629,7 +614,7 @@ pub trait FileOperations: Send + Sync + Sized { /// changes. /// /// Corresponds to the `poll` function pointer in `struct file_operations`. - fn poll(&self, _file: &File, _table: &PollTable) -> KernelResult { + fn poll(&self, _file: &File, _table: &PollTable) -> Result { Ok(bindings::POLLIN | bindings::POLLOUT | bindings::POLLRDNORM | bindings::POLLWRNORM) } } diff --git a/rust/kernel/io_buffer.rs b/rust/kernel/io_buffer.rs index c07d2b31ac8fa9..64bf21987cb55f 100644 --- a/rust/kernel/io_buffer.rs +++ b/rust/kernel/io_buffer.rs @@ -2,7 +2,7 @@ //! Buffers used in IO. -use crate::KernelResult; +use crate::Result; use alloc::vec::Vec; use core::mem::{size_of, MaybeUninit}; @@ -23,12 +23,12 @@ pub trait IoBufferReader { /// # Safety /// /// The output buffer must be valid. - unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> KernelResult; + unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result; /// Reads all data remaining in the io buffer. /// /// Returns `EFAULT` if the address does not currently point to mapped, readable memory. - fn read_all(&mut self) -> KernelResult> { + fn read_all(&mut self) -> Result> { let mut data = Vec::::new(); data.try_reserve_exact(self.len())?; data.resize(self.len(), 0); @@ -42,13 +42,13 @@ pub trait IoBufferReader { /// /// Returns `EFAULT` if the byte slice is bigger than the remaining size of the user slice or /// if the address does not currently point to mapped, readable memory. - fn read_slice(&mut self, data: &mut [u8]) -> KernelResult { + fn read_slice(&mut self, data: &mut [u8]) -> Result { // SAFETY: The output buffer is valid as it's coming from a live reference. unsafe { self.read_raw(data.as_mut_ptr(), data.len()) } } /// Reads the contents of a plain old data (POD) type from the io buffer. - fn read(&mut self) -> KernelResult { + fn read(&mut self) -> Result { let mut out = MaybeUninit::::uninit(); // SAFETY: The buffer is valid as it was just allocated. unsafe { self.read_raw(out.as_mut_ptr() as _, size_of::()) }?; @@ -77,13 +77,13 @@ pub trait IoBufferWriter { /// /// For example, if a caller requests that 100 bytes be cleared but a segfault happens after /// 20 bytes, then EFAULT is returned and the writer is advanced by 20 bytes. - fn clear(&mut self, len: usize) -> KernelResult; + fn clear(&mut self, len: usize) -> Result; /// Writes a byte slice into the io buffer. /// /// Returns `EFAULT` if the byte slice is bigger than the remaining size of the io buffer or if /// the address does not currently point to mapped, writable memory. - fn write_slice(&mut self, data: &[u8]) -> KernelResult { + fn write_slice(&mut self, data: &[u8]) -> Result { // SAFETY: The input buffer is valid as it's coming from a live reference. unsafe { self.write_raw(data.as_ptr(), data.len()) } } @@ -93,10 +93,10 @@ pub trait IoBufferWriter { /// # Safety /// /// The input buffer must be valid. - unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> KernelResult; + unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result; /// Writes the contents of the given data into the io buffer. - fn write(&mut self, data: &T) -> KernelResult<()> { + fn write(&mut self, data: &T) -> Result { // SAFETY: The input buffer is valid as it's coming from a live // reference to a type that implements `WritableToBytes`. unsafe { self.write_raw(data as *const T as _, size_of::()) } diff --git a/rust/kernel/iov_iter.rs b/rust/kernel/iov_iter.rs index d015cb3191eede..26bc0fc2dd151a 100644 --- a/rust/kernel/iov_iter.rs +++ b/rust/kernel/iov_iter.rs @@ -8,7 +8,7 @@ use crate::{ bindings, c_types, error::Error, io_buffer::{IoBufferReader, IoBufferWriter}, - KernelResult, + Result, }; extern "C" { @@ -56,7 +56,7 @@ impl IoBufferWriter for IovIter { self.common_len() } - fn clear(&mut self, mut len: usize) -> KernelResult { + fn clear(&mut self, mut len: usize) -> Result { while len > 0 { // SAFETY: `IovIter::ptr` is guaranteed to be valid by the type invariants. let written = unsafe { bindings::iov_iter_zero(len, self.ptr) }; @@ -69,7 +69,7 @@ impl IoBufferWriter for IovIter { Ok(()) } - unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> KernelResult { + unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result { let res = rust_helper_copy_to_iter(data as _, len, self.ptr); if res != len { Err(Error::EFAULT) @@ -84,7 +84,7 @@ impl IoBufferReader for IovIter { self.common_len() } - unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> KernelResult { + unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result { let res = rust_helper_copy_from_iter(out as _, len, self.ptr); if res != len { Err(Error::EFAULT) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index d34cb84eff50a0..da488d67776ae2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -65,7 +65,7 @@ pub mod iov_iter; mod types; pub mod user_ptr; -pub use crate::error::{Error, KernelResult}; +pub use crate::error::{Error, Result}; pub use crate::types::{CStr, Mode}; /// Page size defined in terms of the `PAGE_SHIFT` macro from C. @@ -86,7 +86,7 @@ pub trait KernelModule: Sized + Sync { /// should do. /// /// Equivalent to the `module_init` macro in the C API. - fn init() -> KernelResult; + fn init() -> Result; } /// Equivalent to `THIS_MODULE` in the C API. diff --git a/rust/kernel/miscdev.rs b/rust/kernel/miscdev.rs index 92c2181f305364..d61cc61f2f2bbb 100644 --- a/rust/kernel/miscdev.rs +++ b/rust/kernel/miscdev.rs @@ -6,7 +6,7 @@ //! //! Reference: -use crate::error::{Error, KernelResult}; +use crate::error::{Error, Result}; use crate::file_operations::{FileOpenAdapter, FileOpener, FileOperationsVtable}; use crate::{bindings, c_types, CStr}; use alloc::boxed::Box; @@ -44,7 +44,7 @@ impl Registration { name: CStr<'static>, minor: Option, context: T, - ) -> KernelResult>> { + ) -> Result>> { let mut r = Pin::from(Box::try_new(Self::new(context))?); r.as_mut().register::(name, minor)?; Ok(r) @@ -58,7 +58,7 @@ impl Registration { self: Pin<&mut Self>, name: CStr<'static>, minor: Option, - ) -> KernelResult { + ) -> Result { // SAFETY: We must ensure that we never move out of `this`. let this = unsafe { self.get_unchecked_mut() }; if this.registered { diff --git a/rust/kernel/pages.rs b/rust/kernel/pages.rs index 01c50a93c7ef6f..cc9ad7a2f76af5 100644 --- a/rust/kernel/pages.rs +++ b/rust/kernel/pages.rs @@ -5,8 +5,8 @@ //! TODO: This module is a work in progress. use crate::{ - bindings, c_types, io_buffer::IoBufferReader, user_ptr::UserSlicePtrReader, Error, - KernelResult, PAGE_SIZE, + bindings, c_types, io_buffer::IoBufferReader, user_ptr::UserSlicePtrReader, Error, Result, + PAGE_SIZE, }; use core::{marker::PhantomData, ptr}; @@ -38,7 +38,7 @@ pub struct Pages { impl Pages { /// Allocates a new set of contiguous pages. - pub fn new() -> KernelResult { + pub fn new() -> Result { // TODO: Consider whether we want to allow callers to specify flags. // SAFETY: This only allocates pages. We check that it succeeds in the next statement. let pages = unsafe { @@ -57,7 +57,7 @@ impl Pages { /// Maps a single page at the given address in the given VM area. /// /// This is only meant to be used by pages of order 0. - pub fn insert_page(&self, vma: &mut bindings::vm_area_struct, address: usize) -> KernelResult { + pub fn insert_page(&self, vma: &mut bindings::vm_area_struct, address: usize) -> Result { if ORDER != 0 { return Err(Error::EINVAL); } @@ -78,7 +78,7 @@ impl Pages { reader: &mut UserSlicePtrReader, offset: usize, len: usize, - ) -> KernelResult { + ) -> Result { // TODO: For now this only works on the first page. let end = offset.checked_add(len).ok_or(Error::EINVAL)?; if end > PAGE_SIZE { @@ -99,7 +99,7 @@ impl Pages { /// Callers must ensure that the destination buffer is valid for the given length. /// Additionally, if the raw buffer is intended to be recast, they must ensure that the data /// can be safely cast; [`crate::io_buffer::ReadableFromBytes`] has more details about it. - pub unsafe fn read(&self, dest: *mut u8, offset: usize, len: usize) -> KernelResult { + pub unsafe fn read(&self, dest: *mut u8, offset: usize, len: usize) -> Result { // TODO: For now this only works on the first page. let end = offset.checked_add(len).ok_or(Error::EINVAL)?; if end > PAGE_SIZE { @@ -119,7 +119,7 @@ impl Pages { /// page is (or will be) mapped by userspace, they must ensure that no kernel data is leaked /// through padding if it was cast from another type; [`crate::io_buffer::WritableToBytes`] has /// more details about it. - pub unsafe fn write(&self, src: *const u8, offset: usize, len: usize) -> KernelResult { + pub unsafe fn write(&self, src: *const u8, offset: usize, len: usize) -> Result { // TODO: For now this only works on the first page. let end = offset.checked_add(len).ok_or(Error::EINVAL)?; if end > PAGE_SIZE { diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 2f8215bc23525d..956639c4a3548d 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -19,4 +19,4 @@ pub use super::{pr_alert, pr_cont, pr_crit, pr_emerg, pr_err, pr_info, pr_notice pub use super::static_assert; -pub use super::{KernelModule, KernelResult}; +pub use super::{KernelModule, Result}; diff --git a/rust/kernel/random.rs b/rust/kernel/random.rs index a7df79c1f7bf7b..723a89829f6619 100644 --- a/rust/kernel/random.rs +++ b/rust/kernel/random.rs @@ -12,7 +12,7 @@ use crate::{bindings, c_types, error}; /// /// Ensures that the CSPRNG has been seeded before generating any random bytes, /// and will block until it is ready. -pub fn getrandom(dest: &mut [u8]) -> error::KernelResult { +pub fn getrandom(dest: &mut [u8]) -> error::Result { let res = unsafe { bindings::wait_for_random_bytes() }; if res != 0 { return Err(error::Error::from_kernel_errno(res)); @@ -30,7 +30,7 @@ pub fn getrandom(dest: &mut [u8]) -> error::KernelResult { /// Fills a byte slice with random bytes generated from the kernel's CSPRNG. /// /// If the CSPRNG is not yet seeded, returns an `Err(EAGAIN)` immediately. -pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult { +pub fn getrandom_nonblock(dest: &mut [u8]) -> error::Result { if !unsafe { bindings::rng_is_initialized() } { return Err(error::Error::EAGAIN); } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 9b3ae495144363..301d25c144db00 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -13,7 +13,7 @@ //! //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html -use crate::KernelResult; +use crate::Result; use alloc::boxed::Box; use core::{ mem::ManuallyDrop, @@ -48,7 +48,7 @@ unsafe impl Sync for Ref {} impl Ref { /// Constructs a new reference counted instance of `T`. - pub fn try_new(contents: T) -> KernelResult { + pub fn try_new(contents: T) -> Result { let boxed = Box::try_new(contents)?; boxed.get_count().count.store(1, Ordering::Relaxed); let ptr = NonNull::from(Box::leak(boxed)); diff --git a/rust/kernel/sysctl.rs b/rust/kernel/sysctl.rs index 19236c4ed57510..f70b09c9147ef2 100644 --- a/rust/kernel/sysctl.rs +++ b/rust/kernel/sysctl.rs @@ -22,10 +22,10 @@ use crate::{ /// Sysctl storage. pub trait SysctlStorage: Sync { /// Writes a byte slice. - fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult); + fn store_value(&self, data: &[u8]) -> (usize, error::Result); /// Reads via a [`UserSlicePtrWriter`]. - fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult); + fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::Result); } fn trim_whitespace(mut data: &[u8]) -> &[u8] { @@ -46,17 +46,17 @@ impl SysctlStorage for &T where T: SysctlStorage, { - fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult) { + fn store_value(&self, data: &[u8]) -> (usize, error::Result) { (*self).store_value(data) } - fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult) { + fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::Result) { (*self).read_value(data) } } impl SysctlStorage for atomic::AtomicBool { - fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult) { + fn store_value(&self, data: &[u8]) -> (usize, error::Result) { let result = match trim_whitespace(data) { b"0" => { self.store(false, atomic::Ordering::Relaxed); @@ -71,7 +71,7 @@ impl SysctlStorage for atomic::AtomicBool { (data.len(), result) } - fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult) { + fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::Result) { let value = if self.load(atomic::Ordering::Relaxed) { b"1\n" } else { @@ -134,7 +134,7 @@ impl Sysctl { name: types::CStr<'static>, storage: T, mode: types::Mode, - ) -> error::KernelResult> { + ) -> error::Result> { if name.contains('/') { return Err(error::Error::EINVAL); } diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs index 87985ce38b0eec..2193991bb598d4 100644 --- a/rust/kernel/user_ptr.rs +++ b/rust/kernel/user_ptr.rs @@ -8,7 +8,7 @@ use crate::{ c_types, error::Error, io_buffer::{IoBufferReader, IoBufferWriter}, - KernelResult, + Result, }; use alloc::vec::Vec; @@ -75,7 +75,7 @@ impl UserSlicePtr { /// /// Returns `EFAULT` if the address does not currently point to /// mapped, readable memory. - pub fn read_all(self) -> KernelResult> { + pub fn read_all(self) -> Result> { self.reader().read_all() } @@ -90,7 +90,7 @@ impl UserSlicePtr { /// mapped, writable memory (in which case some data from before the /// fault may be written), or `data` is larger than the user slice /// (in which case no data is written). - pub fn write_all(self, data: &[u8]) -> KernelResult { + pub fn write_all(self, data: &[u8]) -> Result { self.writer().write_slice(data) } @@ -126,7 +126,7 @@ impl IoBufferReader for UserSlicePtrReader { /// # Safety /// /// The output buffer must be valid. - unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> KernelResult { + unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result { if len > self.1 || len > u32::MAX as usize { return Err(Error::EFAULT); } @@ -153,7 +153,7 @@ impl IoBufferWriter for UserSlicePtrWriter { self.1 } - fn clear(&mut self, mut len: usize) -> KernelResult { + fn clear(&mut self, mut len: usize) -> Result { let mut ret = Ok(()); if len > self.1 { ret = Err(Error::EFAULT); @@ -173,7 +173,7 @@ impl IoBufferWriter for UserSlicePtrWriter { ret } - unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> KernelResult { + unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result { if len > self.1 || len > u32::MAX as usize { return Err(Error::EFAULT); } diff --git a/rust/module.rs b/rust/module.rs index ef9e215c881a29..dfd2d2cfce0277 100644 --- a/rust/module.rs +++ b/rust/module.rs @@ -434,7 +434,7 @@ impl ModuleInfo { /// struct MyKernelModule; /// /// impl KernelModule for MyKernelModule { -/// fn init() -> KernelResult { +/// fn init() -> Result { /// // If the parameter is writeable, then the kparam lock must be /// // taken to read the parameter: /// { @@ -818,7 +818,7 @@ pub fn module_misc_device(ts: TokenStream) -> TokenStream { }} impl kernel::KernelModule for {module} {{ - fn init() -> kernel::KernelResult {{ + fn init() -> kernel::Result {{ Ok(Self {{ _dev: kernel::miscdev::Registration::new_pinned::<{type_}>( kernel::cstr!(\"{name}\"), diff --git a/samples/rust/rust_chrdev.rs b/samples/rust/rust_chrdev.rs index ddc6ad145531d4..3bfe624de0658c 100644 --- a/samples/rust/rust_chrdev.rs +++ b/samples/rust/rust_chrdev.rs @@ -30,7 +30,7 @@ struct RustChrdev { } impl KernelModule for RustChrdev { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust character device sample (init)\n"); let mut chrdev_reg = diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 8238bf28578a2c..84a227021aafdd 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -20,7 +20,7 @@ struct RustMinimal { } impl KernelModule for RustMinimal { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); diff --git a/samples/rust/rust_miscdev.rs b/samples/rust/rust_miscdev.rs index 3c8520a907f249..12171172378f72 100644 --- a/samples/rust/rust_miscdev.rs +++ b/samples/rust/rust_miscdev.rs @@ -38,7 +38,7 @@ struct SharedState { } impl SharedState { - fn try_new() -> KernelResult> { + fn try_new() -> Result> { let state = Arc::try_new(Self { // SAFETY: `condvar_init!` is called below. state_changed: unsafe { CondVar::new() }, @@ -60,7 +60,7 @@ struct Token { } impl FileOpener> for Token { - fn open(shared: &Arc) -> KernelResult { + fn open(shared: &Arc) -> Result { Ok(Box::try_new(Self { shared: shared.clone(), })?) @@ -72,7 +72,7 @@ impl FileOperations for Token { kernel::declare_file_operations!(read, write); - fn read(&self, _: &File, data: &mut T, offset: u64) -> KernelResult { + fn read(&self, _: &File, data: &mut T, offset: u64) -> Result { // Succeed if the caller doesn't provide a buffer or if not at the start. if data.is_empty() || offset != 0 { return Ok(0); @@ -100,12 +100,7 @@ impl FileOperations for Token { Ok(1) } - fn write( - &self, - _: &File, - data: &mut T, - _offset: u64, - ) -> KernelResult { + fn write(&self, _: &File, data: &mut T, _offset: u64) -> Result { { let mut inner = self.shared.inner.lock(); @@ -131,7 +126,7 @@ struct RustMiscdev { } impl KernelModule for RustMiscdev { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust miscellaneous device sample (init)\n"); let state = SharedState::try_new()?; diff --git a/samples/rust/rust_module_parameters.rs b/samples/rust/rust_module_parameters.rs index d9b6de695384f7..57e59e80502759 100644 --- a/samples/rust/rust_module_parameters.rs +++ b/samples/rust/rust_module_parameters.rs @@ -45,7 +45,7 @@ module! { struct RustModuleParameters; impl KernelModule for RustModuleParameters { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust module parameters sample (init)\n"); { diff --git a/samples/rust/rust_print.rs b/samples/rust/rust_print.rs index 5717b398b4348f..a457e1e87fe50c 100644 --- a/samples/rust/rust_print.rs +++ b/samples/rust/rust_print.rs @@ -18,7 +18,7 @@ module! { struct RustPrint; impl KernelModule for RustPrint { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust printing macros sample (init)\n"); pr_emerg!("Emergency message (level 0) without args\n"); diff --git a/samples/rust/rust_random.rs b/samples/rust/rust_random.rs index ed2d159180f52d..2b42956073c6d8 100644 --- a/samples/rust/rust_random.rs +++ b/samples/rust/rust_random.rs @@ -21,12 +21,7 @@ struct RandomFile; impl FileOperations for RandomFile { kernel::declare_file_operations!(read, write, read_iter, write_iter); - fn read( - &self, - file: &File, - buf: &mut T, - _offset: u64, - ) -> KernelResult { + fn read(&self, file: &File, buf: &mut T, _offset: u64) -> Result { let total_len = buf.len(); let mut chunkbuf = [0; 256]; @@ -44,12 +39,7 @@ impl FileOperations for RandomFile { Ok(total_len) } - fn write( - &self, - _file: &File, - buf: &mut T, - _offset: u64, - ) -> KernelResult { + fn write(&self, _file: &File, buf: &mut T, _offset: u64) -> Result { let total_len = buf.len(); let mut chunkbuf = [0; 256]; while !buf.is_empty() { diff --git a/samples/rust/rust_semaphore.rs b/samples/rust/rust_semaphore.rs index 115e92388cbf9e..157d2523863b12 100644 --- a/samples/rust/rust_semaphore.rs +++ b/samples/rust/rust_semaphore.rs @@ -58,7 +58,7 @@ struct FileState { } impl FileState { - fn consume(&self) -> KernelResult { + fn consume(&self) -> Result { let mut inner = self.shared.inner.lock(); while inner.count == 0 { if self.shared.changed.wait(&mut inner) { @@ -71,7 +71,7 @@ impl FileState { } impl FileOpener> for FileState { - fn open(shared: &Arc) -> KernelResult> { + fn open(shared: &Arc) -> Result> { Ok(Box::try_new(Self { read_count: AtomicU64::new(0), shared: shared.clone(), @@ -84,7 +84,7 @@ impl FileOperations for FileState { declare_file_operations!(read, write, ioctl); - fn read(&self, _: &File, data: &mut T, offset: u64) -> KernelResult { + fn read(&self, _: &File, data: &mut T, offset: u64) -> Result { if data.is_empty() || offset > 0 { return Ok(0); } @@ -94,12 +94,7 @@ impl FileOperations for FileState { Ok(1) } - fn write( - &self, - _: &File, - data: &mut T, - _offset: u64, - ) -> KernelResult { + fn write(&self, _: &File, data: &mut T, _offset: u64) -> Result { { let mut inner = self.shared.inner.lock(); inner.count = inner.count.saturating_add(data.len()); @@ -112,7 +107,7 @@ impl FileOperations for FileState { Ok(data.len()) } - fn ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> KernelResult { + fn ioctl(&self, file: &File, cmd: &mut IoctlCommand) -> Result { cmd.dispatch(self, file) } } @@ -122,7 +117,7 @@ struct RustSemaphore { } impl KernelModule for RustSemaphore { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust semaphore sample (init)\n"); let sema = Arc::try_new(Semaphore { @@ -160,7 +155,7 @@ const IOCTL_GET_READ_COUNT: u32 = 0x80086301; const IOCTL_SET_READ_COUNT: u32 = 0x40086301; impl IoctlHandler for FileState { - fn read(&self, _: &File, cmd: u32, writer: &mut UserSlicePtrWriter) -> KernelResult { + fn read(&self, _: &File, cmd: u32, writer: &mut UserSlicePtrWriter) -> Result { match cmd { IOCTL_GET_READ_COUNT => { writer.write(&self.read_count.load(Ordering::Relaxed))?; @@ -170,7 +165,7 @@ impl IoctlHandler for FileState { } } - fn write(&self, _: &File, cmd: u32, reader: &mut UserSlicePtrReader) -> KernelResult { + fn write(&self, _: &File, cmd: u32, reader: &mut UserSlicePtrReader) -> Result { match cmd { IOCTL_SET_READ_COUNT => { self.read_count.store(reader.read()?, Ordering::Relaxed); diff --git a/samples/rust/rust_stack_probing.rs b/samples/rust/rust_stack_probing.rs index aeabb3d1361e1f..56f96e1e05b17e 100644 --- a/samples/rust/rust_stack_probing.rs +++ b/samples/rust/rust_stack_probing.rs @@ -19,7 +19,7 @@ module! { struct RustStackProbing; impl KernelModule for RustStackProbing { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust stack probing sample (init)\n"); // Including this large variable on the stack will trigger diff --git a/samples/rust/rust_sync.rs b/samples/rust/rust_sync.rs index 14796286b0f087..de11da04216ca0 100644 --- a/samples/rust/rust_sync.rs +++ b/samples/rust/rust_sync.rs @@ -24,7 +24,7 @@ module! { struct RustSync; impl KernelModule for RustSync { - fn init() -> KernelResult { + fn init() -> Result { pr_info!("Rust synchronisation primitives sample (init)\n"); // Test mutexes.