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        _filename: NamespaceNode,
167    ) -> Result<UserAddress, Errno> {
168        let state = self.state.lock();
169        let size_paged_aligned = round_up_to_increment(state.size, *PAGE_SIZE as usize)?;
170
171        // Filter protections
172        if !state.prot_flags.contains(prot_flags) {
173            return error!(EINVAL);
174        }
175        // Filter size
176        if size_paged_aligned < length {
177            return error!(EINVAL);
178        }
179
180        let memory = self
181            .memory
182            .get_or_try_init(|| {
183                if size_paged_aligned == 0 {
184                    return error!(EINVAL);
185                }
186                // Round up to page boundary
187                let vmo = zx::Vmo::create(size_paged_aligned as u64).map_err(|_| errno!(ENOMEM))?;
188                let memory = MemoryObject::from(vmo).with_zx_name(b"starnix:ashmem");
189                Ok(Arc::new(memory))
190            })?
191            .clone();
192
193        let mapped_addr = current_task.mm()?.map_memory(
194            addr,
195            memory,
196            memory_offset,
197            length,
198            prot_flags,
199            file.max_access_for_memory_mapping(),
200            mapping_options,
201            MappingName::Ashmem(state.name.clone().into()),
202        )?;
203
204        Ok(mapped_addr)
205    }
206
207    fn ioctl(
208        &self,
209        _file: &FileObject,
210        current_task: &CurrentTask,
211        request: u32,
212        arg: SyscallArg,
213    ) -> Result<SyscallResult, Errno> {
214        match request {
215            #[allow(unreachable_patterns)]
216            ASHMEM_SET_SIZE | starnix_uapi::arch32::ASHMEM_SET_SIZE => {
217                let mut state = self.state.lock();
218
219                if self.is_mapped() {
220                    return error!(EINVAL);
221                }
222                state.size = arg.into();
223                Ok(SUCCESS)
224            }
225            ASHMEM_GET_SIZE => Ok(self.state.lock().size.into()),
226            ASHMEM_SET_NAME => {
227                let mut state = self.state.lock();
228
229                if self.is_mapped() {
230                    return error!(EINVAL);
231                }
232                let mut name = current_task.read_c_string_to_vec(
233                    UserCString::new(current_task, arg),
234                    ASHMEM_NAME_LEN as usize,
235                )?;
236                name.push(0); // Add a null terminator
237
238                state.name = name.into();
239                Ok(SUCCESS)
240            }
241            ASHMEM_GET_NAME => {
242                let state = self.state.lock();
243                let name = &state.name[..];
244
245                current_task.write_memory(arg.into(), name)?;
246                Ok(SUCCESS)
247            }
248            #[allow(unreachable_patterns)]
249            ASHMEM_SET_PROT_MASK | starnix_uapi::arch32::ASHMEM_SET_PROT_MASK => {
250                let mut state = self.state.lock();
251                let prot_flags =
252                    ProtectionFlags::from_access_bits(arg.into()).ok_or_else(|| errno!(EINVAL))?;
253
254                // Do not allow protections to be increased
255                if !state.prot_flags.contains(prot_flags) {
256                    return error!(EINVAL);
257                }
258
259                state.prot_flags = prot_flags;
260                Ok(SUCCESS)
261            }
262            ASHMEM_GET_PROT_MASK => Ok(self.state.lock().prot_flags.bits().into()),
263            ASHMEM_PIN | ASHMEM_UNPIN | ASHMEM_GET_PIN_STATUS => {
264                let mut state = self.state.lock();
265
266                if !self.is_mapped() {
267                    return error!(EINVAL);
268                }
269
270                let user_ref = UserRef::<ashmem_pin>::new(arg.into());
271                let pin = current_task.read_object(user_ref)?;
272                let (lo, hi) =
273                    (pin.offset, pin.offset.checked_add(pin.len).ok_or_else(|| errno!(EFAULT))?);
274
275                // Bounds check
276                if (lo as usize) >= state.size || (hi as usize) > state.size {
277                    return error!(EINVAL);
278                }
279
280                // Aligned to page size
281                if (lo as u64) % *PAGE_SIZE != 0 || (hi as u64) % *PAGE_SIZE != 0 {
282                    return error!(EINVAL);
283                }
284
285                match request {
286                    ASHMEM_PIN => {
287                        for is_purged in state.unpinned.remove(lo..hi).iter() {
288                            if *is_purged {
289                                return Ok(ASHMEM_WAS_PURGED.into());
290                            }
291                        }
292
293                        return Ok(ASHMEM_NOT_PURGED.into());
294                    }
295                    ASHMEM_UNPIN => {
296                        // This method has must_use but we don't actually need to do any explicit
297                        // cleanup.
298                        let _ = state.unpinned.insert(lo..hi, false);
299                        return Ok(ASHMEM_IS_UNPINNED.into());
300                    }
301                    ASHMEM_GET_PIN_STATUS => {
302                        let mut intervals = state.unpinned.range(lo..hi);
303                        return match intervals.next() {
304                            Some(_) => Ok(ASHMEM_IS_UNPINNED.into()),
305                            None => Ok(ASHMEM_IS_PINNED.into()),
306                        };
307                    }
308                    _ => unreachable!(),
309                }
310            }
311            ASHMEM_PURGE_ALL_CACHES => {
312                let mut state = self.state.lock();
313                let memory = self.memory.get().ok_or_else(|| errno!(EINVAL))?;
314
315                if state.unpinned.is_empty() {
316                    return Ok(ASHMEM_IS_PINNED.into());
317                }
318                let unpinned: Vec<_> = state.unpinned.iter().map(|(k, _)| k.clone()).collect();
319                for range in unpinned.into_iter() {
320                    let (lo, hi) = (range.start as u64, range.end as u64);
321                    memory.op_range(zx::VmoOp::ZERO, lo, hi - lo).unwrap_or(());
322
323                    // This method has must_use but we don't actually need to do any explicit
324                    // cleanup.
325                    let _ = state.unpinned.insert(range, true);
326                }
327                return Ok(ASHMEM_IS_UNPINNED.into());
328            }
329            #[allow(unreachable_patterns)]
330            uapi::ASHMEM_GET_FILE_ID | uapi::arch32::ASHMEM_GET_FILE_ID => {
331                let state = self.state.lock();
332                current_task.write_object(arg.into(), &(state.id))?;
333                Ok(SUCCESS)
334            }
335            _ => error!(ENOTTY),
336        }
337    }
338}