xref: /linux/rust/kernel/fs/file.rs (revision 182d95571ffa278f7c68a80d76de88a5333fb69f)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 // Copyright (C) 2024 Google LLC.
4 
5 //! Files and file descriptors.
6 //!
7 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h) and
8 //! [`include/linux/file.h`](srctree/include/linux/file.h)
9 
10 use crate::{
11     bindings,
12     cred::Credential,
13     error::{code::*, Error, Result},
14     fmt,
15     types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque},
16 };
17 use core::ptr;
18 
19 /// Flags associated with a [`File`].
20 pub mod flags {
21     /// File is opened in append mode.
22     pub const O_APPEND: u32 = bindings::O_APPEND;
23 
24     /// Signal-driven I/O is enabled.
25     pub const O_ASYNC: u32 = bindings::FASYNC;
26 
27     /// Close-on-exec flag is set.
28     pub const O_CLOEXEC: u32 = bindings::O_CLOEXEC;
29 
30     /// File was created if it didn't already exist.
31     pub const O_CREAT: u32 = bindings::O_CREAT;
32 
33     /// Direct I/O is enabled for this file.
34     pub const O_DIRECT: u32 = bindings::O_DIRECT;
35 
36     /// File must be a directory.
37     pub const O_DIRECTORY: u32 = bindings::O_DIRECTORY;
38 
39     /// Like [`O_SYNC`] except metadata is not synced.
40     pub const O_DSYNC: u32 = bindings::O_DSYNC;
41 
42     /// Ensure that this file is created with the `open(2)` call.
43     pub const O_EXCL: u32 = bindings::O_EXCL;
44 
45     /// Large file size enabled (`off64_t` over `off_t`).
46     pub const O_LARGEFILE: u32 = bindings::O_LARGEFILE;
47 
48     /// Do not update the file last access time.
49     pub const O_NOATIME: u32 = bindings::O_NOATIME;
50 
51     /// File should not be used as process's controlling terminal.
52     pub const O_NOCTTY: u32 = bindings::O_NOCTTY;
53 
54     /// If basename of path is a symbolic link, fail open.
55     pub const O_NOFOLLOW: u32 = bindings::O_NOFOLLOW;
56 
57     /// File is using nonblocking I/O.
58     pub const O_NONBLOCK: u32 = bindings::O_NONBLOCK;
59 
60     /// File is using nonblocking I/O.
61     ///
62     /// This is effectively the same flag as [`O_NONBLOCK`] on all architectures
63     /// except SPARC64.
64     pub const O_NDELAY: u32 = bindings::O_NDELAY;
65 
66     /// Used to obtain a path file descriptor.
67     pub const O_PATH: u32 = bindings::O_PATH;
68 
69     /// Write operations on this file will flush data and metadata.
70     pub const O_SYNC: u32 = bindings::O_SYNC;
71 
72     /// This file is an unnamed temporary regular file.
73     pub const O_TMPFILE: u32 = bindings::O_TMPFILE;
74 
75     /// File should be truncated to length 0.
76     pub const O_TRUNC: u32 = bindings::O_TRUNC;
77 
78     /// Bitmask for access mode flags.
79     ///
80     /// # Examples
81     ///
82     /// ```
83     /// use kernel::fs::file;
84     /// # fn do_something() {}
85     /// # let flags = 0;
86     /// if (flags & file::flags::O_ACCMODE) == file::flags::O_RDONLY {
87     ///     do_something();
88     /// }
89     /// ```
90     pub const O_ACCMODE: u32 = bindings::O_ACCMODE;
91 
92     /// File is read only.
93     pub const O_RDONLY: u32 = bindings::O_RDONLY;
94 
95     /// File is write only.
96     pub const O_WRONLY: u32 = bindings::O_WRONLY;
97 
98     /// File can be both read and written.
99     pub const O_RDWR: u32 = bindings::O_RDWR;
100 }
101 
102 /// Wraps the kernel's `struct file`. Thread safe.
103 ///
104 /// This represents an open file rather than a file on a filesystem. Processes generally reference
105 /// open files using file descriptors. However, file descriptors are not the same as files. A file
106 /// descriptor is just an integer that corresponds to a file, and a single file may be referenced
107 /// by multiple file descriptors.
108 ///
109 /// # Refcounting
110 ///
111 /// Instances of this type are reference-counted. The reference count is incremented by the
112 /// `fget`/`get_file` functions and decremented by `fput`. The Rust type `ARef<File>` represents a
113 /// pointer that owns a reference count on the file.
114 ///
115 /// Whenever a process opens a file descriptor (fd), it stores a pointer to the file in its fd
116 /// table (`struct files_struct`). This pointer owns a reference count to the file, ensuring the
117 /// file isn't prematurely deleted while the file descriptor is open. In Rust terminology, the
118 /// pointers in `struct files_struct` are `ARef<File>` pointers.
119 ///
120 /// ## Light refcounts
121 ///
122 /// Whenever a process has an fd to a file, it may use something called a "light refcount" as a
123 /// performance optimization. Light refcounts are acquired by calling `fdget` and released with
124 /// `fdput`. The idea behind light refcounts is that if the fd is not closed between the calls to
125 /// `fdget` and `fdput`, then the refcount cannot hit zero during that time, as the `struct
126 /// files_struct` holds a reference until the fd is closed. This means that it's safe to access the
127 /// file even if `fdget` does not increment the refcount.
128 ///
129 /// The requirement that the fd is not closed during a light refcount applies globally across all
130 /// threads - not just on the thread using the light refcount. For this reason, light refcounts are
131 /// only used when the `struct files_struct` is not shared with other threads, since this ensures
132 /// that other unrelated threads cannot suddenly start using the fd and close it. Therefore,
133 /// calling `fdget` on a shared `struct files_struct` creates a normal refcount instead of a light
134 /// refcount.
135 ///
136 /// Light reference counts must be released with `fdput` before the system call returns to
137 /// userspace. This means that if you wait until the current system call returns to userspace, then
138 /// all light refcounts that existed at the time have gone away.
139 ///
140 /// ### The file position
141 ///
142 /// Each `struct file` has a position integer, which is protected by the `f_pos_lock` mutex.
143 /// However, if the `struct file` is not shared, then the kernel may avoid taking the lock as a
144 /// performance optimization.
145 ///
146 /// The condition for avoiding the `f_pos_lock` mutex is different from the condition for using
147 /// `fdget`. With `fdget`, you may avoid incrementing the refcount as long as the current fd table
148 /// is not shared; it is okay if there are other fd tables that also reference the same `struct
149 /// file`. However, `fdget_pos` can only avoid taking the `f_pos_lock` if the entire `struct file`
150 /// is not shared, as different processes with an fd to the same `struct file` share the same
151 /// position.
152 ///
153 /// To represent files that are not thread safe due to this optimization, the [`LocalFile`] type is
154 /// used.
155 ///
156 /// ## Rust references
157 ///
158 /// The reference type `&File` is similar to light refcounts:
159 ///
160 /// * `&File` references don't own a reference count. They can only exist as long as the reference
161 ///   count stays positive, and can only be created when there is some mechanism in place to ensure
162 ///   this.
163 ///
164 /// * The Rust borrow-checker normally ensures this by enforcing that the `ARef<File>` from which
165 ///   a `&File` is created outlives the `&File`.
166 ///
167 /// * Using the unsafe [`File::from_raw_file`] means that it is up to the caller to ensure that the
168 ///   `&File` only exists while the reference count is positive.
169 ///
170 /// * You can think of `fdget` as using an fd to look up an `ARef<File>` in the `struct
171 ///   files_struct` and create an `&File` from it. The "fd cannot be closed" rule is like the Rust
172 ///   rule "the `ARef<File>` must outlive the `&File`".
173 ///
174 /// # Invariants
175 ///
176 /// * All instances of this type are refcounted using the `f_count` field.
177 /// * There must not be any active calls to `fdget_pos` on this file that did not take the
178 ///   `f_pos_lock` mutex.
179 #[repr(transparent)]
180 pub struct File {
181     inner: Opaque<bindings::file>,
182 }
183 
184 // SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the
185 // `f_pos_lock` mutex, so it is safe to transfer it between threads.
186 unsafe impl Send for File {}
187 
188 // SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the
189 // `f_pos_lock` mutex, so it is safe to access its methods from several threads in parallel.
190 unsafe impl Sync for File {}
191 
192 // SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation
193 // makes `ARef<File>` own a normal refcount.
194 unsafe impl AlwaysRefCounted for File {
195     #[inline]
196     fn inc_ref(&self) {
197         // SAFETY: The existence of a shared reference means that the refcount is nonzero.
198         unsafe { bindings::get_file(self.as_ptr()) };
199     }
200 
201     #[inline]
202     unsafe fn dec_ref(obj: ptr::NonNull<File>) {
203         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
204         // may drop it. The cast is okay since `File` has the same representation as `struct file`.
205         unsafe { bindings::fput(obj.cast().as_ptr()) }
206     }
207 }
208 
209 /// Wraps the kernel's `struct file`. Not thread safe.
210 ///
211 /// This type represents a file that is not known to be safe to transfer across thread boundaries.
212 /// To obtain a thread-safe [`File`], use the [`assume_no_fdget_pos`] conversion.
213 ///
214 /// See the documentation for [`File`] for more information.
215 ///
216 /// # Invariants
217 ///
218 /// * All instances of this type are refcounted using the `f_count` field.
219 /// * If there is an active call to `fdget_pos` that did not take the `f_pos_lock` mutex, then it
220 ///   must be on the same thread as this file.
221 ///
222 /// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos
223 #[repr(transparent)]
224 pub struct LocalFile {
225     inner: Opaque<bindings::file>,
226 }
227 
228 // SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation
229 // makes `ARef<LocalFile>` own a normal refcount.
230 unsafe impl AlwaysRefCounted for LocalFile {
231     #[inline]
232     fn inc_ref(&self) {
233         // SAFETY: The existence of a shared reference means that the refcount is nonzero.
234         unsafe { bindings::get_file(self.as_ptr()) };
235     }
236 
237     #[inline]
238     unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
239         // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
240         // may drop it. The cast is okay since `LocalFile` has the same representation as
241         // `struct file`.
242         unsafe { bindings::fput(obj.cast().as_ptr()) }
243     }
244 }
245 
246 impl LocalFile {
247     /// Constructs a new `struct file` wrapper from a file descriptor.
248     ///
249     /// The file descriptor belongs to the current process, and there might be active local calls
250     /// to `fdget_pos` on the same file.
251     ///
252     /// To obtain an `ARef<File>`, use the [`assume_no_fdget_pos`] function to convert.
253     ///
254     /// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos
255     #[inline]
256     pub fn fget(fd: u32) -> Result<ARef<LocalFile>, BadFdError> {
257         // SAFETY: FFI call, there are no requirements on `fd`.
258         let ptr = ptr::NonNull::new(unsafe { bindings::fget(fd) }).ok_or(BadFdError)?;
259 
260         // SAFETY: `bindings::fget` created a refcount, and we pass ownership of it to the `ARef`.
261         //
262         // INVARIANT: This file is in the fd table on this thread, so either all `fdget_pos` calls
263         // are on this thread, or the file is shared, in which case `fdget_pos` calls took the
264         // `f_pos_lock` mutex.
265         Ok(unsafe { ARef::from_raw(ptr.cast()) })
266     }
267 
268     /// Creates a reference to a [`LocalFile`] from a valid pointer.
269     ///
270     /// # Safety
271     ///
272     /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
273     ///   positive for the duration of `'a`.
274     /// * The caller must ensure that if there is an active call to `fdget_pos` that did not take
275     ///   the `f_pos_lock` mutex, then that call is on the current thread.
276     #[inline]
277     pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a LocalFile {
278         // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
279         // duration of `'a`. The cast is okay because `LocalFile` is `repr(transparent)`.
280         //
281         // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
282         unsafe { &*ptr.cast() }
283     }
284 
285     /// Assume that there are no active `fdget_pos` calls that prevent us from sharing this file.
286     ///
287     /// This makes it safe to transfer this file to other threads. No checks are performed, and
288     /// using it incorrectly may lead to a data race on the file position if the file is shared
289     /// with another thread.
290     ///
291     /// This method is intended to be used together with [`LocalFile::fget`] when the caller knows
292     /// statically that there are no `fdget_pos` calls on the current thread. For example, you
293     /// might use it when calling `fget` from an ioctl, since ioctls usually do not touch the file
294     /// position.
295     ///
296     /// # Safety
297     ///
298     /// There must not be any active `fdget_pos` calls on the current thread.
299     #[inline]
300     pub unsafe fn assume_no_fdget_pos(me: ARef<LocalFile>) -> ARef<File> {
301         // INVARIANT: There are no `fdget_pos` calls on the current thread, and by the type
302         // invariants, if there is a `fdget_pos` call on another thread, then it took the
303         // `f_pos_lock` mutex.
304         //
305         // SAFETY: `LocalFile` and `File` have the same layout.
306         unsafe { ARef::from_raw(ARef::into_raw(me).cast()) }
307     }
308 
309     /// Returns a raw pointer to the inner C struct.
310     #[inline]
311     pub fn as_ptr(&self) -> *mut bindings::file {
312         self.inner.get()
313     }
314 
315     /// Returns the credentials of the task that originally opened the file.
316     pub fn cred(&self) -> &Credential {
317         // SAFETY: It's okay to read the `f_cred` field without synchronization because `f_cred` is
318         // never changed after initialization of the file.
319         let ptr = unsafe { (*self.as_ptr()).f_cred };
320 
321         // SAFETY: The signature of this function ensures that the caller will only access the
322         // returned credential while the file is still valid, and the C side ensures that the
323         // credential stays valid at least as long as the file.
324         unsafe { Credential::from_ptr(ptr) }
325     }
326 
327     /// Returns the flags associated with the file.
328     ///
329     /// The flags are a combination of the constants in [`flags`].
330     #[inline]
331     pub fn flags(&self) -> u32 {
332         // This `read_volatile` is intended to correspond to a READ_ONCE call.
333         //
334         // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
335         //
336         // FIXME(read_once): Replace with `read_once` when available on the Rust side.
337         unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
338     }
339 }
340 
341 impl File {
342     /// Creates a reference to a [`File`] from a valid pointer.
343     ///
344     /// # Safety
345     ///
346     /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
347     ///   positive for the duration of `'a`.
348     /// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they
349     ///   took the `f_pos_lock` mutex.
350     #[inline]
351     pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a File {
352         // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
353         // duration of `'a`. The cast is okay because `File` is `repr(transparent)`.
354         //
355         // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
356         unsafe { &*ptr.cast() }
357     }
358 }
359 
360 // Make LocalFile methods available on File.
361 impl core::ops::Deref for File {
362     type Target = LocalFile;
363     #[inline]
364     fn deref(&self) -> &LocalFile {
365         // SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a
366         // valid file for the desired duration.
367         //
368         // By the type invariants, there are no `fdget_pos` calls that did not take the
369         // `f_pos_lock` mutex.
370         unsafe { LocalFile::from_raw_file(core::ptr::from_ref(self).cast()) }
371     }
372 }
373 
374 /// A file descriptor reservation.
375 ///
376 /// This allows the creation of a file descriptor in two steps: first, we reserve a slot for it,
377 /// then we commit or drop the reservation. The first step may fail (e.g., the current process ran
378 /// out of available slots), but commit and drop never fail (and are mutually exclusive).
379 ///
380 /// Dropping the reservation happens in the destructor of this type.
381 ///
382 /// # Invariants
383 ///
384 /// The fd stored in this struct must correspond to a reserved file descriptor of the current task.
385 pub struct FileDescriptorReservation {
386     fd: u32,
387     /// Prevent values of this type from being moved to a different task.
388     ///
389     /// The `fd_install` and `put_unused_fd` functions assume that the value of `current` is
390     /// unchanged since the call to `get_unused_fd_flags`. By adding this marker to this type, we
391     /// prevent it from being moved across task boundaries, which ensures that `current` does not
392     /// change while this value exists.
393     _not_send: NotThreadSafe,
394 }
395 
396 impl FileDescriptorReservation {
397     /// Creates a new file descriptor reservation.
398     #[inline]
399     pub fn get_unused_fd_flags(flags: u32) -> Result<Self> {
400         // SAFETY: FFI call, there are no safety requirements on `flags`.
401         let fd: i32 = unsafe { bindings::get_unused_fd_flags(flags) };
402         if fd < 0 {
403             return Err(Error::from_errno(fd));
404         }
405         Ok(Self {
406             fd: fd as u32,
407             _not_send: NotThreadSafe,
408         })
409     }
410 
411     /// Returns the file descriptor number that was reserved.
412     #[inline]
413     pub fn reserved_fd(&self) -> u32 {
414         self.fd
415     }
416 
417     /// Commits the reservation.
418     ///
419     /// The previously reserved file descriptor is bound to `file`. This method consumes the
420     /// [`FileDescriptorReservation`], so it will not be usable after this call.
421     #[inline]
422     pub fn fd_install(self, file: ARef<File>) {
423         // SAFETY: `self.fd` was previously returned by `get_unused_fd_flags`. We have not yet used
424         // the fd, so it is still valid, and `current` still refers to the same task, as this type
425         // cannot be moved across task boundaries.
426         //
427         // Furthermore, the file pointer is guaranteed to own a refcount by its type invariants,
428         // and we take ownership of that refcount by not running the destructor below.
429         // Additionally, the file is known to not have any non-shared `fdget_pos` calls, so even if
430         // this process starts using the file position, this will not result in a data race on the
431         // file position.
432         unsafe { bindings::fd_install(self.fd, file.as_ptr()) };
433 
434         // `fd_install` consumes both the file descriptor and the file reference, so we cannot run
435         // the destructors.
436         core::mem::forget(self);
437         core::mem::forget(file);
438     }
439 }
440 
441 impl Drop for FileDescriptorReservation {
442     #[inline]
443     fn drop(&mut self) {
444         // SAFETY: By the type invariants of this type, `self.fd` was previously returned by
445         // `get_unused_fd_flags`. We have not yet used the fd, so it is still valid, and `current`
446         // still refers to the same task, as this type cannot be moved across task boundaries.
447         unsafe { bindings::put_unused_fd(self.fd) };
448     }
449 }
450 
451 /// Represents the `EBADF` error code.
452 ///
453 /// Used for methods that can only fail with `EBADF`.
454 #[derive(Copy, Clone, Eq, PartialEq)]
455 pub struct BadFdError;
456 
457 impl From<BadFdError> for Error {
458     #[inline]
459     fn from(_: BadFdError) -> Error {
460         EBADF
461     }
462 }
463 
464 impl fmt::Debug for BadFdError {
465     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466         f.pad("EBADF")
467     }
468 }
469