1 // SPDX-License-Identifier: GPL-2.0
3 //! Kernel page allocation and management.
6 alloc::{AllocError, Flags},
10 uaccess::UserSliceReader,
12 use core::ptr::{self, NonNull};
14 /// A bitwise shift for the page size.
15 pub const PAGE_SHIFT: usize = bindings::PAGE_SHIFT as usize;
17 /// The number of bytes in a page.
18 pub const PAGE_SIZE: usize = bindings::PAGE_SIZE;
20 /// A bitmask that gives the page containing a given address.
21 pub const PAGE_MASK: usize = !(PAGE_SIZE - 1);
23 /// A pointer to a page that owns the page allocation.
27 /// The pointer is valid, and has ownership over the page.
29 page: NonNull<bindings::page>,
32 // SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across
34 unsafe impl Send for Page {}
36 // SAFETY: Pages have no logic that relies on them not being accessed concurrently, so accessing
37 // them concurrently is safe.
38 unsafe impl Sync for Page {}
41 /// Allocates a new page.
45 /// Allocate memory for a page.
48 /// use kernel::page::Page;
50 /// # fn dox() -> Result<(), kernel::alloc::AllocError> {
51 /// let page = Page::alloc_page(GFP_KERNEL)?;
55 /// Allocate memory for a page and zero its contents.
58 /// use kernel::page::Page;
60 /// # fn dox() -> Result<(), kernel::alloc::AllocError> {
61 /// let page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?;
64 pub fn alloc_page(flags: Flags) -> Result<Self, AllocError> {
65 // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
66 // is always safe to call this method.
67 let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) };
68 let page = NonNull::new(page).ok_or(AllocError)?;
69 // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly
70 // allocated page. We transfer that ownership to the new `Page` object.
74 /// Returns a raw pointer to the page.
75 pub fn as_ptr(&self) -> *mut bindings::page {
79 /// Runs a piece of code with this page mapped to an address.
81 /// The page is unmapped when this call returns.
83 /// # Using the raw pointer
85 /// It is up to the caller to use the provided raw pointer correctly. The pointer is valid for
86 /// `PAGE_SIZE` bytes and for the duration in which the closure is called. The pointer might
87 /// only be mapped on the current thread, and when that is the case, dereferencing it on other
88 /// threads is UB. Other than that, the usual rules for dereferencing a raw pointer apply: don't
89 /// cause data races, the memory may be uninitialized, and so on.
91 /// If multiple threads map the same page at the same time, then they may reference with
92 /// different addresses. However, even if the addresses are different, the underlying memory is
93 /// still the same for these purposes (e.g., it's still a data race if they both write to the
94 /// same underlying byte at the same time).
95 fn with_page_mapped<T>(&self, f: impl FnOnce(*mut u8) -> T) -> T {
96 // SAFETY: `page` is valid due to the type invariants on `Page`.
97 let mapped_addr = unsafe { bindings::kmap_local_page(self.as_ptr()) };
99 let res = f(mapped_addr.cast());
101 // This unmaps the page mapped above.
103 // SAFETY: Since this API takes the user code as a closure, it can only be used in a manner
104 // where the pages are unmapped in reverse order. This is as required by `kunmap_local`.
106 // In other words, if this call to `kunmap_local` happens when a different page should be
107 // unmapped first, then there must necessarily be a call to `kmap_local_page` other than the
108 // call just above in `with_page_mapped` that made that possible. In this case, it is the
109 // unsafe block that wraps that other call that is incorrect.
110 unsafe { bindings::kunmap_local(mapped_addr) };
115 /// Runs a piece of code with a raw pointer to a slice of this page, with bounds checking.
117 /// If `f` is called, then it will be called with a pointer that points at `off` bytes into the
118 /// page, and the pointer will be valid for at least `len` bytes. The pointer is only valid on
119 /// this task, as this method uses a local mapping.
121 /// If `off` and `len` refers to a region outside of this page, then this method returns
122 /// [`EINVAL`] and does not call `f`.
124 /// # Using the raw pointer
126 /// It is up to the caller to use the provided raw pointer correctly. The pointer is valid for
127 /// `len` bytes and for the duration in which the closure is called. The pointer might only be
128 /// mapped on the current thread, and when that is the case, dereferencing it on other threads
129 /// is UB. Other than that, the usual rules for dereferencing a raw pointer apply: don't cause
130 /// data races, the memory may be uninitialized, and so on.
132 /// If multiple threads map the same page at the same time, then they may reference with
133 /// different addresses. However, even if the addresses are different, the underlying memory is
134 /// still the same for these purposes (e.g., it's still a data race if they both write to the
135 /// same underlying byte at the same time).
136 fn with_pointer_into_page<T>(
140 f: impl FnOnce(*mut u8) -> Result<T>,
142 let bounds_ok = off <= PAGE_SIZE && len <= PAGE_SIZE && (off + len) <= PAGE_SIZE;
145 self.with_page_mapped(move |page_addr| {
146 // SAFETY: The `off` integer is at most `PAGE_SIZE`, so this pointer offset will
147 // result in a pointer that is in bounds or one off the end of the page.
148 f(unsafe { page_addr.add(off) })
155 /// Maps the page and reads from it into the given buffer.
157 /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes
158 /// outside of the page, then this call returns [`EINVAL`].
162 /// * Callers must ensure that `dst` is valid for writing `len` bytes.
163 /// * Callers must ensure that this call does not race with a write to the same page that
164 /// overlaps with this read.
165 pub unsafe fn read_raw(&self, dst: *mut u8, offset: usize, len: usize) -> Result {
166 self.with_pointer_into_page(offset, len, move |src| {
167 // SAFETY: If `with_pointer_into_page` calls into this closure, then
168 // it has performed a bounds check and guarantees that `src` is
169 // valid for `len` bytes.
171 // There caller guarantees that there is no data race.
172 unsafe { ptr::copy_nonoverlapping(src, dst, len) };
177 /// Maps the page and writes into it from the given buffer.
179 /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes
180 /// outside of the page, then this call returns [`EINVAL`].
184 /// * Callers must ensure that `src` is valid for reading `len` bytes.
185 /// * Callers must ensure that this call does not race with a read or write to the same page
186 /// that overlaps with this write.
187 pub unsafe fn write_raw(&self, src: *const u8, offset: usize, len: usize) -> Result {
188 self.with_pointer_into_page(offset, len, move |dst| {
189 // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a
190 // bounds check and guarantees that `dst` is valid for `len` bytes.
192 // There caller guarantees that there is no data race.
193 unsafe { ptr::copy_nonoverlapping(src, dst, len) };
198 /// Maps the page and zeroes the given slice.
200 /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes
201 /// outside of the page, then this call returns [`EINVAL`].
205 /// Callers must ensure that this call does not race with a read or write to the same page that
206 /// overlaps with this write.
207 pub unsafe fn fill_zero_raw(&self, offset: usize, len: usize) -> Result {
208 self.with_pointer_into_page(offset, len, move |dst| {
209 // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a
210 // bounds check and guarantees that `dst` is valid for `len` bytes.
212 // There caller guarantees that there is no data race.
213 unsafe { ptr::write_bytes(dst, 0u8, len) };
218 /// Copies data from userspace into this page.
220 /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes
221 /// outside of the page, then this call returns [`EINVAL`].
223 /// Like the other `UserSliceReader` methods, data races are allowed on the userspace address.
224 /// However, they are not allowed on the page you are copying into.
228 /// Callers must ensure that this call does not race with a read or write to the same page that
229 /// overlaps with this write.
230 pub unsafe fn copy_from_user_slice_raw(
232 reader: &mut UserSliceReader,
236 self.with_pointer_into_page(offset, len, move |dst| {
237 // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a
238 // bounds check and guarantees that `dst` is valid for `len` bytes. Furthermore, we have
239 // exclusive access to the slice since the caller guarantees that there are no races.
240 reader.read_raw(unsafe { core::slice::from_raw_parts_mut(dst.cast(), len) })
247 // SAFETY: By the type invariants, we have ownership of the page and can free it.
248 unsafe { bindings::__free_pages(self.page.as_ptr(), 0) };