1 // SPDX-License-Identifier: GPL-2.0 2 3 // Copyright (C) 2024 Google LLC. 4 5 //! Rust misc device sample. 6 //! 7 //! Below is an example userspace C program that exercises this sample's functionality. 8 //! 9 //! ```c 10 //! #include <stdio.h> 11 //! #include <stdlib.h> 12 //! #include <errno.h> 13 //! #include <fcntl.h> 14 //! #include <unistd.h> 15 //! #include <sys/ioctl.h> 16 //! 17 //! #define RUST_MISC_DEV_FAIL _IO('|', 0) 18 //! #define RUST_MISC_DEV_HELLO _IO('|', 0x80) 19 //! #define RUST_MISC_DEV_GET_VALUE _IOR('|', 0x81, int) 20 //! #define RUST_MISC_DEV_SET_VALUE _IOW('|', 0x82, int) 21 //! 22 //! int main() { 23 //! int value, new_value; 24 //! int fd, ret; 25 //! 26 //! // Open the device file 27 //! printf("Opening /dev/rust-misc-device for reading and writing\n"); 28 //! fd = open("/dev/rust-misc-device", O_RDWR); 29 //! if (fd < 0) { 30 //! perror("open"); 31 //! return errno; 32 //! } 33 //! 34 //! // Make call into driver to say "hello" 35 //! printf("Calling Hello\n"); 36 //! ret = ioctl(fd, RUST_MISC_DEV_HELLO, NULL); 37 //! if (ret < 0) { 38 //! perror("ioctl: Failed to call into Hello"); 39 //! close(fd); 40 //! return errno; 41 //! } 42 //! 43 //! // Get initial value 44 //! printf("Fetching initial value\n"); 45 //! ret = ioctl(fd, RUST_MISC_DEV_GET_VALUE, &value); 46 //! if (ret < 0) { 47 //! perror("ioctl: Failed to fetch the initial value"); 48 //! close(fd); 49 //! return errno; 50 //! } 51 //! 52 //! value++; 53 //! 54 //! // Set value to something different 55 //! printf("Submitting new value (%d)\n", value); 56 //! ret = ioctl(fd, RUST_MISC_DEV_SET_VALUE, &value); 57 //! if (ret < 0) { 58 //! perror("ioctl: Failed to submit new value"); 59 //! close(fd); 60 //! return errno; 61 //! } 62 //! 63 //! // Ensure new value was applied 64 //! printf("Fetching new value\n"); 65 //! ret = ioctl(fd, RUST_MISC_DEV_GET_VALUE, &new_value); 66 //! if (ret < 0) { 67 //! perror("ioctl: Failed to fetch the new value"); 68 //! close(fd); 69 //! return errno; 70 //! } 71 //! 72 //! if (value != new_value) { 73 //! printf("Failed: Committed and retrieved values are different (%d - %d)\n", value, new_value); 74 //! close(fd); 75 //! return -1; 76 //! } 77 //! 78 //! // Call the unsuccessful ioctl 79 //! printf("Attempting to call in to an non-existent IOCTL\n"); 80 //! ret = ioctl(fd, RUST_MISC_DEV_FAIL, NULL); 81 //! if (ret < 0) { 82 //! perror("ioctl: Succeeded to fail - this was expected"); 83 //! } else { 84 //! printf("ioctl: Failed to fail\n"); 85 //! close(fd); 86 //! return -1; 87 //! } 88 //! 89 //! // Close the device file 90 //! printf("Closing /dev/rust-misc-device\n"); 91 //! close(fd); 92 //! 93 //! printf("Success\n"); 94 //! return 0; 95 //! } 96 //! ``` 97 98 use kernel::{ 99 c_str, 100 device::Device, 101 fs::{File, Kiocb}, 102 ioctl::{_IO, _IOC_SIZE, _IOR, _IOW}, 103 iov::{IovIterDest, IovIterSource}, 104 miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration}, 105 new_mutex, 106 prelude::*, 107 sync::{aref::ARef, Mutex}, 108 uaccess::{UserSlice, UserSliceReader, UserSliceWriter}, 109 }; 110 111 const RUST_MISC_DEV_HELLO: u32 = _IO('|' as u32, 0x80); 112 const RUST_MISC_DEV_GET_VALUE: u32 = _IOR::<i32>('|' as u32, 0x81); 113 const RUST_MISC_DEV_SET_VALUE: u32 = _IOW::<i32>('|' as u32, 0x82); 114 115 module! { 116 type: RustMiscDeviceModule, 117 name: "rust_misc_device", 118 authors: ["Lee Jones"], 119 description: "Rust misc device sample", 120 license: "GPL", 121 } 122 123 #[pin_data] 124 struct RustMiscDeviceModule { 125 #[pin] 126 _miscdev: MiscDeviceRegistration<RustMiscDevice>, 127 } 128 129 impl kernel::InPlaceModule for RustMiscDeviceModule { 130 fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> { 131 pr_info!("Initialising Rust Misc Device Sample\n"); 132 133 let options = MiscDeviceOptions { 134 name: c_str!("rust-misc-device"), 135 }; 136 137 try_pin_init!(Self { 138 _miscdev <- MiscDeviceRegistration::register(options), 139 }) 140 } 141 } 142 143 struct Inner { 144 value: i32, 145 buffer: KVVec<u8>, 146 } 147 148 #[pin_data(PinnedDrop)] 149 struct RustMiscDevice { 150 #[pin] 151 inner: Mutex<Inner>, 152 dev: ARef<Device>, 153 } 154 155 #[vtable] 156 impl MiscDevice for RustMiscDevice { 157 type Ptr = Pin<KBox<Self>>; 158 159 fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Self>>> { 160 let dev = ARef::from(misc.device()); 161 162 dev_info!(dev, "Opening Rust Misc Device Sample\n"); 163 164 KBox::try_pin_init( 165 try_pin_init! { 166 RustMiscDevice { 167 inner <- new_mutex!(Inner { 168 value: 0_i32, 169 buffer: KVVec::new(), 170 }), 171 dev: dev, 172 } 173 }, 174 GFP_KERNEL, 175 ) 176 } 177 178 fn read_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterDest<'_>) -> Result<usize> { 179 let me = kiocb.file(); 180 dev_info!(me.dev, "Reading from Rust Misc Device Sample\n"); 181 182 let inner = me.inner.lock(); 183 // Read the buffer contents, taking the file position into account. 184 let read = iov.simple_read_from_buffer(kiocb.ki_pos_mut(), &inner.buffer)?; 185 186 Ok(read) 187 } 188 189 fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource<'_>) -> Result<usize> { 190 let me = kiocb.file(); 191 dev_info!(me.dev, "Writing to Rust Misc Device Sample\n"); 192 193 let mut inner = me.inner.lock(); 194 195 // Replace buffer contents. 196 inner.buffer.clear(); 197 let len = iov.copy_from_iter_vec(&mut inner.buffer, GFP_KERNEL)?; 198 199 // Set position to zero so that future `read` calls will see the new contents. 200 *kiocb.ki_pos_mut() = 0; 201 202 Ok(len) 203 } 204 205 fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> { 206 dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n"); 207 208 // Treat the ioctl argument as a user pointer. 209 let arg = UserPtr::from_addr(arg); 210 let size = _IOC_SIZE(cmd); 211 212 match cmd { 213 RUST_MISC_DEV_GET_VALUE => me.get_value(UserSlice::new(arg, size).writer())?, 214 RUST_MISC_DEV_SET_VALUE => me.set_value(UserSlice::new(arg, size).reader())?, 215 RUST_MISC_DEV_HELLO => me.hello()?, 216 _ => { 217 dev_err!(me.dev, "-> IOCTL not recognised: {}\n", cmd); 218 return Err(ENOTTY); 219 } 220 }; 221 222 Ok(0) 223 } 224 } 225 226 #[pinned_drop] 227 impl PinnedDrop for RustMiscDevice { 228 fn drop(self: Pin<&mut Self>) { 229 dev_info!(self.dev, "Exiting the Rust Misc Device Sample\n"); 230 } 231 } 232 233 impl RustMiscDevice { 234 fn set_value(&self, mut reader: UserSliceReader) -> Result<isize> { 235 let new_value = reader.read::<i32>()?; 236 let mut guard = self.inner.lock(); 237 238 dev_info!( 239 self.dev, 240 "-> Copying data from userspace (value: {})\n", 241 new_value 242 ); 243 244 guard.value = new_value; 245 Ok(0) 246 } 247 248 fn get_value(&self, mut writer: UserSliceWriter) -> Result<isize> { 249 let guard = self.inner.lock(); 250 let value = guard.value; 251 252 // Free-up the lock and use our locally cached instance from here 253 drop(guard); 254 255 dev_info!( 256 self.dev, 257 "-> Copying data to userspace (value: {})\n", 258 &value 259 ); 260 261 writer.write::<i32>(&value)?; 262 Ok(0) 263 } 264 265 fn hello(&self) -> Result<isize> { 266 dev_info!(self.dev, "-> Hello from the Rust Misc Device\n"); 267 268 Ok(0) 269 } 270 } 271