Skip to main content

starnix_modules_ashmem/
lib.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use linux_uapi::{
6    ASHMEM_GET_NAME, ASHMEM_GET_PIN_STATUS, ASHMEM_GET_PROT_MASK, ASHMEM_GET_SIZE,
7    ASHMEM_IS_PINNED, ASHMEM_IS_UNPINNED, ASHMEM_NOT_PURGED, ASHMEM_PIN, ASHMEM_PURGE_ALL_CACHES,
8    ASHMEM_SET_NAME, ASHMEM_SET_PROT_MASK, ASHMEM_SET_SIZE, ASHMEM_UNPIN, ASHMEM_WAS_PURGED,
9};
10use once_cell::sync::OnceCell;
11use range_map::RangeMap;
12use starnix_core::device::DeviceOps;
13use starnix_core::mm::memory::MemoryObject;
14use starnix_core::mm::{
15    DesiredAddress, MappingName, MappingOptions, MemoryAccessor, MemoryAccessorExt, PAGE_SIZE,
16    ProtectionFlags,
17};
18use starnix_core::task::{CurrentTask, Kernel};
19use starnix_core::vfs::{
20    FileObject, FileOps, FsString, InputBuffer, NamespaceNode, OutputBuffer, SeekTarget,
21    default_seek, fileops_impl_noop_sync,
22};
23use starnix_lifecycle::AtomicCounter;
24use starnix_sync::{AshmemStateLock, LockDepMutex};
25use starnix_syscalls::{SUCCESS, SyscallArg, SyscallResult};
26use starnix_uapi::errors::Errno;
27use starnix_uapi::math::round_up_to_increment;
28use starnix_uapi::open_flags::OpenFlags;
29use starnix_uapi::user_address::{UserAddress, UserCString, UserRef};
30use starnix_uapi::{ASHMEM_NAME_LEN, ashmem_pin, device_id, errno, error, off_t, uapi};
31use std::sync::Arc;
32
33/// Initializes the ashmem device.
34pub fn ashmem_device_init(kernel: &Kernel) {
35    let registry = &kernel.device_registry;
36
37    registry
38        .register_misc_device(kernel, "ashmem".into(), AshmemDevice::new())
39        .expect("can register ashmem");
40}
41
42#[derive(Clone)]
43pub struct AshmemDevice {
44    pub next_id: Arc<AtomicCounter<u32>>,
45}
46
47pub struct Ashmem {
48    memory: OnceCell<Arc<MemoryObject>>,
49    state: LockDepMutex<AshmemState, AshmemStateLock>,
50}
51
52struct AshmemState {
53    size: usize,
54    name: FsString,
55    prot_flags: ProtectionFlags,
56    unpinned: RangeMap<u32, bool>,
57    id: u32,
58}
59
60impl AshmemDevice {
61    pub fn new() -> AshmemDevice {
62        AshmemDevice { next_id: Arc::new(AtomicCounter::new(1)) }
63    }
64}
65
66impl DeviceOps for AshmemDevice {
67    fn open(
68        &self,
69        _current_task: &CurrentTask,
70        _id: device_id::DeviceId,
71        _node: &NamespaceNode,
72        _flags: OpenFlags,
73    ) -> Result<Box<dyn FileOps>, Errno> {
74        let ashmem = Ashmem::new(self.next_id.next());
75        Ok(Box::new(ashmem))
76    }
77}
78
79impl Ashmem {
80    fn new(id: u32) -> Ashmem {
81        let state = AshmemState {
82            size: 0,
83            name: b"dev/ashmem\0".into(),
84            prot_flags: ProtectionFlags::ACCESS_FLAGS,
85            unpinned: RangeMap::<u32, bool>::default(),
86            id: id,
87        };
88
89        Ashmem { memory: OnceCell::new(), state: state.into() }
90    }
91
92    fn memory(&self) -> Result<&Arc<MemoryObject>, Errno> {
93        self.memory.get().ok_or_else(|| errno!(EINVAL))
94    }
95
96    fn is_mapped(&self) -> bool {
97        self.memory.get().is_some()
98    }
99}
100
101impl FileOps for Ashmem {
102    fileops_impl_noop_sync!();
103
104    fn is_seekable(&self) -> bool {
105        true
106    }
107
108    fn seek(
109        &self,
110        _file: &FileObject,
111        _current_task: &CurrentTask,
112        current_offset: off_t,
113        target: SeekTarget,
114    ) -> Result<off_t, Errno> {
115        if !self.is_mapped() {
116            return error!(EBADF);
117        }
118        let eof_offset = self.state.lock().size;
119        default_seek(current_offset, target, || Ok(eof_offset.try_into().unwrap()))
120    }
121
122    fn read(
123        &self,
124        _file: &FileObject,
125        _current_task: &CurrentTask,
126        offset: usize,
127        data: &mut dyn OutputBuffer,
128    ) -> Result<usize, Errno> {
129        let memory = self.memory().map_err(|_| errno!(EBADF))?;
130        let file_length = self.state.lock().size;
131        let actual = {
132            let want_read = data.available();
133            if offset < file_length {
134                let to_read =
135                    if file_length < offset + want_read { file_length - offset } else { want_read };
136                let buf =
137                    memory.read_to_vec(offset as u64, to_read as u64).map_err(|_| errno!(EIO))?;
138                data.write_all(&buf[..])?;
139                to_read
140            } else {
141                0
142            }
143        };
144        Ok(actual)
145    }
146
147    fn write(
148        &self,
149        _file: &FileObject,
150        _current_task: &CurrentTask,
151        _offset: usize,
152        _data: &mut dyn InputBuffer,
153    ) -> Result<usize, Errno> {
154        error!(EINVAL)
155    }
156
157    fn mmap(
158        &self,
159        _file: &FileObject,
160        current_task: &CurrentTask,
161        addr: DesiredAddress,
162        memory_offset: u64,
163        length: usize,
164        prot_flags: ProtectionFlags,
165        mapping_options: MappingOptions,
166    ) -> Result<UserAddress, Errno> {
167        let state = self.state.lock();
168        let size_paged_aligned = round_up_to_increment(state.size, *PAGE_SIZE as usize)?;
169
170        // Filter protections
171        if !state.prot_flags.contains(prot_flags) {
172            return error!(EINVAL);
173        }
174        // Filter size
175        if size_paged_aligned < length {
176            return error!(EINVAL);
177        }
178
179        let memory = self
180            .memory
181            .get_or_try_init(|| {
182                if size_paged_aligned == 0 {
183                    return error!(EINVAL);
184                }
185                // Round up to page boundary
186                let vmo = zx::Vmo::create(size_paged_aligned as u64).map_err(|_| errno!(ENOMEM))?;
187                let memory = MemoryObject::from(vmo).with_zx_name(b"starnix:ashmem");
188                Ok(Arc::new(memory))
189            })?
190            .clone();
191
192        let mapped_addr = current_task.mm()?.map_memory(
193            addr,
194            memory,
195            memory_offset,
196            length,
197            prot_flags,
198            mapping_options,
199            MappingName::Ashmem(state.name.clone().into()),
200        )?;
201
202        Ok(mapped_addr)
203    }
204
205    fn ioctl(
206        &self,
207        _file: &FileObject,
208        current_task: &CurrentTask,
209        request: u32,
210        arg: SyscallArg,
211    ) -> Result<SyscallResult, Errno> {
212        match request {
213            #[allow(unreachable_patterns)]
214            ASHMEM_SET_SIZE | starnix_uapi::arch32::ASHMEM_SET_SIZE => {
215                let mut state = self.state.lock();
216
217                if self.is_mapped() {
218                    return error!(EINVAL);
219                }
220                state.size = arg.into();
221                Ok(SUCCESS)
222            }
223            ASHMEM_GET_SIZE => Ok(self.state.lock().size.into()),
224            ASHMEM_SET_NAME => {
225                let mut state = self.state.lock();
226
227                if self.is_mapped() {
228                    return error!(EINVAL);
229                }
230                let mut name = current_task.read_c_string_to_vec(
231                    UserCString::new(current_task, arg),
232                    ASHMEM_NAME_LEN as usize,
233                )?;
234                name.push(0); // Add a null terminator
235
236                state.name = name.into();
237                Ok(SUCCESS)
238            }
239            ASHMEM_GET_NAME => {
240                let state = self.state.lock();
241                let name = &state.name[..];
242
243                current_task.write_memory(arg.into(), name)?;
244                Ok(SUCCESS)
245            }
246            #[allow(unreachable_patterns)]
247            ASHMEM_SET_PROT_MASK | starnix_uapi::arch32::ASHMEM_SET_PROT_MASK => {
248                let mut state = self.state.lock();
249                let prot_flags =
250                    ProtectionFlags::from_access_bits(arg.into()).ok_or_else(|| errno!(EINVAL))?;
251
252                // Do not allow protections to be increased
253                if !state.prot_flags.contains(prot_flags) {
254                    return error!(EINVAL);
255                }
256
257                state.prot_flags = prot_flags;
258                Ok(SUCCESS)
259            }
260            ASHMEM_GET_PROT_MASK => Ok(self.state.lock().prot_flags.bits().into()),
261            ASHMEM_PIN | ASHMEM_UNPIN | ASHMEM_GET_PIN_STATUS => {
262                let mut state = self.state.lock();
263
264                if !self.is_mapped() {
265                    return error!(EINVAL);
266                }
267
268                let user_ref = UserRef::<ashmem_pin>::new(arg.into());
269                let pin = current_task.read_object(user_ref)?;
270                let (lo, hi) =
271                    (pin.offset, pin.offset.checked_add(pin.len).ok_or_else(|| errno!(EFAULT))?);
272
273                // Bounds check
274                if (lo as usize) >= state.size || (hi as usize) > state.size {
275                    return error!(EINVAL);
276                }
277
278                // Aligned to page size
279                if (lo as u64) % *PAGE_SIZE != 0 || (hi as u64) % *PAGE_SIZE != 0 {
280                    return error!(EINVAL);
281                }
282
283                match request {
284                    ASHMEM_PIN => {
285                        for is_purged in state.unpinned.remove(lo..hi).iter() {
286                            if *is_purged {
287                                return Ok(ASHMEM_WAS_PURGED.into());
288                            }
289                        }
290
291                        return Ok(ASHMEM_NOT_PURGED.into());
292                    }
293                    ASHMEM_UNPIN => {
294                        // This method has must_use but we don't actually need to do any explicit
295                        // cleanup.
296                        let _ = state.unpinned.insert(lo..hi, false);
297                        return Ok(ASHMEM_IS_UNPINNED.into());
298                    }
299                    ASHMEM_GET_PIN_STATUS => {
300                        let mut intervals = state.unpinned.range(lo..hi);
301                        return match intervals.next() {
302                            Some(_) => Ok(ASHMEM_IS_UNPINNED.into()),
303                            None => Ok(ASHMEM_IS_PINNED.into()),
304                        };
305                    }
306                    _ => unreachable!(),
307                }
308            }
309            ASHMEM_PURGE_ALL_CACHES => {
310                let mut state = self.state.lock();
311                let memory = self.memory.get().ok_or_else(|| errno!(EINVAL))?;
312
313                if state.unpinned.is_empty() {
314                    return Ok(ASHMEM_IS_PINNED.into());
315                }
316                let unpinned: Vec<_> = state.unpinned.iter().map(|(k, _)| k.clone()).collect();
317                for range in unpinned.into_iter() {
318                    let (lo, hi) = (range.start as u64, range.end as u64);
319                    memory.op_range(zx::VmoOp::ZERO, lo, hi - lo).unwrap_or(());
320
321                    // This method has must_use but we don't actually need to do any explicit
322                    // cleanup.
323                    let _ = state.unpinned.insert(range, true);
324                }
325                return Ok(ASHMEM_IS_UNPINNED.into());
326            }
327            #[allow(unreachable_patterns)]
328            uapi::ASHMEM_GET_FILE_ID | uapi::arch32::ASHMEM_GET_FILE_ID => {
329                let state = self.state.lock();
330                current_task.write_object(arg.into(), &(state.id))?;
331                Ok(SUCCESS)
332            }
333            _ => error!(ENOTTY),
334        }
335    }
336}