rust_misc_device.rs 7.2 KB

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