Skip to main content

capsules_extra/
isolated_nonvolatile_storage_driver.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2025.
4
5//! This provides userspace access to nonvolatile storage.
6//!
7//! This driver provides isolation between individual userland applications.
8//! Each application only has access to its region of nonvolatile memory and
9//! cannot read/write to nonvolatile memory of other applications.
10//!
11//! Each app is assigned a fixed amount of nonvolatile memory. This amount is
12//! set at compile time.
13//!
14//! ## Storage Layout
15//!
16//! Example nonvolatile storage layout (note that `|` indicates bitwise
17//! concatenation):
18//!
19//! ```text
20//!     ╒════════ ← Start of nonvolatile region
21//!     ├──────── ← Start of App 1's region header
22//!     │ Region version number (8 bits) | Region length (24 bits)
23//!     │ App 1's ShortID (u32)
24//!     │ XOR of previous two u32 fields (u32)
25//!     ├──────── ← Start of App 1's Region          ═╗
26//!     │                                             ║
27//!     │
28//!     │                                            region 1
29//!     │                                            length
30//!     │
31//!     │                                             ║
32//!     │                                            ═╝
33//!     ├──────── ← Start of App 2's region header
34//!     │ Region version number (8 bits) | Region length (24 bits)
35//!     │ App 2's ShortID (u32)
36//!     │ XOR of previous two u32 fields (u32)
37//!     ├──────── ← Start of App 2's Region          ═╗
38//!     │                                             ║
39//!     │
40//!     │
41//!     │                                            region 2
42//!     │                                            length
43//!     │
44//!     │
45//!     │                                             ║
46//!     ...                                          ═╝
47//!     ╘════════ ← End of userspace region
48//! ```
49//!
50//! ## Storage Initialization
51//!
52//! This capsule caches the location of an application's storage region in
53//! grant. This cached location is set on the first usage of this capsule.
54//!
55//! Here is a general high-level overview of what happens when an app makes its
56//! first syscall:
57//! 1. App engages with the capsule by making any syscall.
58//! 2. Capsule searches through storage to see if that app has an existing
59//!    region.
60//! 3. After the search:
61//!    - If the capsule finds a matching region:
62//!      - Cache the app's region information in its grant.
63//!    - If the capsule DOESN'T find a matching region:
64//!      - Allocate a new region for that app.
65//!      - Erase the region's usable area.
66//! 4. Handle the syscall that the app originally made.
67//! 5. When the syscall finishes, notify the app via upcall.
68//!
69//! ## Example Software Stack
70//!
71//! Here is a diagram of the expected stack with this capsule: Boxes are
72//! components and between the boxes are the traits that are the interfaces
73//! between components. This capsule only provides a userspace interface.
74//!
75//! ```text
76//! +------------------------------------------------------------------------+
77//! |                                                                        |
78//! |                             userspace                                  |
79//! |                                                                        |
80//! +------------------------------------------------------------------------+
81//!                             kernel::Driver
82//! +------------------------------------------------------------------------+
83//! |                                                                        |
84//! | isolated_nonvolatile_storage_driver::IsolatedNonvolatileStorage (this) |
85//! |                                                                        |
86//! +------------------------------------------------------------------------+
87//!            hil::nonvolatile_storage::NonvolatileStorage
88//! +------------------------------------------------------------------------+
89//! |                                                                        |
90//! |               Physical nonvolatile storage driver                      |
91//! |                                                                        |
92//! +------------------------------------------------------------------------+
93//! ```
94//!
95
96use core::cmp;
97
98use kernel::errorcode::into_statuscode;
99use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
100use kernel::hil;
101use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
102use kernel::syscall::{CommandReturn, SyscallDriver};
103use kernel::utilities::cells::{OptionalCell, TakeCell};
104use kernel::utilities::copy_slice::CopyOrErr;
105use kernel::{ErrorCode, ProcessId};
106
107use capsules_core::driver;
108
109pub const DRIVER_NUM: usize = driver::NUM::IsolatedNvmStorage as usize;
110
111/// Recommended size for the buffer provided to this capsule.
112///
113/// This is enough space for a buffer to be used for reading/writing userspace
114/// data.
115pub const BUF_LEN: usize = 512;
116
117/// IDs for subscribed upcalls.
118mod upcall {
119    /// Get storage size done callback.
120    pub const GET_SIZE_DONE: usize = 0;
121    /// Read done callback.
122    pub const READ_DONE: usize = 1;
123    /// Write done callback.
124    pub const WRITE_DONE: usize = 2;
125    /// Number of upcalls.
126    pub const COUNT: u8 = 3;
127}
128
129/// Ids for read-only allow buffers
130mod ro_allow {
131    /// Setup a buffer to write bytes to the nonvolatile storage.
132    pub const WRITE: usize = 0;
133    /// The number of allow buffers the kernel stores for this grant
134    pub const COUNT: u8 = 1;
135}
136
137/// Ids for read-write allow buffers
138mod rw_allow {
139    /// Setup a buffer to read from the nonvolatile storage into.
140    pub const READ: usize = 0;
141    /// The number of allow buffers the kernel stores for this grant
142    pub const COUNT: u8 = 1;
143}
144
145#[derive(Clone, Copy, PartialEq, Debug)]
146#[repr(u8)]
147enum HeaderVersion {
148    V1 = 0x01,
149}
150
151// Current header version to allocate new regions with.
152const CURRENT_HEADER_VERSION: HeaderVersion = HeaderVersion::V1;
153
154/// Describes a region of nonvolatile memory that is assigned to a certain app.
155#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct AppRegion {
157    /// The version is based on the capsule version and layout format in use
158    /// when the region was created. This is set to a fixed value for all new
159    /// regions. An existing region may have been created with a newer or
160    /// earlier version of this capsule and therefore might have a different
161    /// version than what we currently initialize new regions with.
162    version: HeaderVersion,
163    /// Absolute address to describe where an app's nonvolatile region starts.
164    /// Note that this is the address FOLLOWING the region's header.
165    absolute_address: usize,
166    /// How many bytes allocated to a certain app. Note that this describes the
167    /// length of the usable storage region and does not include the region's
168    /// header.
169    length: usize,
170}
171
172// Metadata to be written before every app's region to describe the owner and
173// size of the region.
174#[derive(Clone, Copy, Debug)]
175struct AppRegionHeader {
176    /// An 8 bit version number concatenated with a 24 bit length value.
177    version_and_length: u32,
178    /// Unique per-app identifier. This comes from the Fixed variant of the
179    /// ShortID type.
180    shortid: u32,
181    /// xor between `version_and_length` and `shortid` fields. This serves as a
182    /// checksum.
183    xor: u32,
184}
185/// The size of the `AppRegionHeader` stored in the nonvolatile storage.
186const REGION_HEADER_LEN: usize = 3 * core::mem::size_of::<u32>();
187
188impl AppRegionHeader {
189    fn new(version: HeaderVersion, shortid: u32, length: usize) -> Option<Self> {
190        // check that length will fit in 3 bytes
191        if length > (2 << 23) {
192            return None;
193        }
194
195        let version_and_length = ((version as u8 as u32) << 24) | length as u32;
196
197        let xor = version_and_length ^ shortid;
198
199        Some(AppRegionHeader {
200            version_and_length,
201            shortid,
202            xor,
203        })
204    }
205
206    fn from_bytes(bytes: [u8; REGION_HEADER_LEN]) -> Option<Self> {
207        // first 4 bytes are split between a 8 bit version and 24 bit length
208        let version = bytes[0];
209        let length_slice = &bytes[1..4];
210        let version_and_length_slice = [version, length_slice[0], length_slice[1], length_slice[2]];
211        let version_and_length = u32::from_le_bytes(version_and_length_slice);
212
213        let shortid_slice = bytes[4..8].try_into().ok()?;
214        let shortid = u32::from_le_bytes(shortid_slice);
215
216        let xor_slice = bytes[8..12].try_into().ok()?;
217        let xor = u32::from_le_bytes(xor_slice);
218
219        Some(AppRegionHeader {
220            version_and_length,
221            shortid,
222            xor,
223        })
224    }
225
226    fn to_bytes(self) -> [u8; REGION_HEADER_LEN] {
227        let mut header_slice = [0; REGION_HEADER_LEN];
228
229        // copy version and length
230        let version_and_length_slice = u32::to_le_bytes(self.version_and_length);
231        let version_and_length_start_idx = 0;
232        let version_and_length_end_idx = version_and_length_slice.len();
233        header_slice[version_and_length_start_idx..version_and_length_end_idx]
234            .copy_from_slice(&version_and_length_slice);
235
236        // copy shortid
237        let shortid_slice = u32::to_le_bytes(self.shortid);
238        let shortid_start_idx = version_and_length_end_idx;
239        let shortid_end_idx = shortid_start_idx + shortid_slice.len();
240        header_slice[shortid_start_idx..shortid_end_idx].copy_from_slice(&shortid_slice);
241
242        // copy version and length
243        let xor_slice = u32::to_le_bytes(self.xor);
244        let xor_start_idx = shortid_end_idx;
245        let xor_end_idx = xor_start_idx + xor_slice.len();
246        header_slice[xor_start_idx..xor_end_idx].copy_from_slice(&xor_slice);
247
248        header_slice
249    }
250
251    fn is_valid(&self) -> bool {
252        self.version().is_some() && self.xor == (self.version_and_length ^ self.shortid)
253    }
254
255    fn version(&self) -> Option<HeaderVersion> {
256        // Need to do this since we can't pattern match against a method call.
257        const HEADER_V1: u8 = HeaderVersion::V1 as u8;
258
259        // Extract the 8 most significant bits from the concatenated version and
260        // length.
261        match (self.version_and_length >> 24) as u8 {
262            HEADER_V1 => Some(HeaderVersion::V1),
263            _ => None,
264        }
265    }
266
267    fn length(&self) -> u32 {
268        // Extract the 24 least significant bits from the concatenated version
269        // and length.
270        self.version_and_length & 0x00ffffff
271    }
272}
273
274/// Operation referencing a particular region.
275#[derive(Clone, Copy, PartialEq, Debug)]
276pub enum ManagerTask {
277    /// Read the contents of the header in the region. The `usize` is the
278    /// address of the start of the header.
279    DiscoverRegions(usize),
280    /// Write a valid header to the storage.
281    WriteHeader(ProcessId, AppRegion),
282    /// Erase the contents of a region. This supports using multiple nonvolatile
283    /// storage operations to complete the entire erase.
284    EraseRegion {
285        processid: ProcessId,
286        next_erase_start: usize,
287        remaining_bytes: usize,
288    },
289}
290
291/// What is currently using the underlying nonvolatile storage driver.
292#[derive(Clone, Copy, Debug)]
293pub enum User {
294    /// The operation is from a userspace process.
295    App { processid: ProcessId },
296    /// The operation is from this capsule.
297    RegionManager(ManagerTask),
298}
299
300/// The operation the process requested.
301#[derive(Clone, Copy, Debug)]
302pub enum NvmCommand {
303    GetSize,
304    Read { offset: usize },
305    Write { offset: usize },
306}
307
308impl NvmCommand {
309    fn offset(&self) -> usize {
310        match self {
311            NvmCommand::Read { offset } => *offset,
312            NvmCommand::Write { offset } => *offset,
313            NvmCommand::GetSize => 0,
314        }
315    }
316
317    fn upcall(&self) -> usize {
318        match self {
319            Self::GetSize => upcall::GET_SIZE_DONE,
320            Self::Write { offset: _ } => upcall::WRITE_DONE,
321            Self::Read { offset: _ } => upcall::READ_DONE,
322        }
323    }
324}
325
326/// State stored in the grant region on behalf of each app.
327#[derive(Default)]
328pub struct App {
329    /// Describe the location and size of an app's region (if it has been
330    /// initialized).
331    region: Option<AppRegion>,
332    /// Operation that will be handled once init sequence is complete.
333    pending_operation: Option<NvmCommand>,
334}
335
336/// Helper function to convert create a full, single usize value from two 32-bit
337/// values stored in usizes.
338///
339/// In C this would look like:
340///
341/// ```c
342/// size_t v = (hi << 32) | (uint32_t) lo;
343/// ```
344///
345/// This is useful when passing a machine-sized value (i.e. a `size_t`) via the
346/// system call interface in two 32-bit usize values. On a 32-bit machine this
347/// essentially has no effect; the full value is stored in the `lo` usize. On a
348/// 64-bit machine, this creates a usize by concatenating the hi and lo 32-bit
349/// values.
350///
351/// TODO
352/// ----
353///
354/// This can be more succinctly implemented using
355/// [`unbounded_shl()`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unbounded_shl).
356/// However, that method is currently a nightly-only feature.
357#[inline]
358pub const fn usize32s_to_usize(lo: usize, hi: usize) -> usize {
359    if usize::BITS <= 32 {
360        // Just return the lo value since it has the bits we need.
361        lo
362    } else {
363        // Create a 64-bit value.
364        (lo & 0xFFFFFFFF) | (hi << 32)
365    }
366}
367
368pub struct IsolatedNonvolatileStorage<'a, const APP_REGION_SIZE: usize> {
369    /// The underlying physical storage device.
370    driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'a>,
371    /// Per-app state.
372    apps: Grant<
373        App,
374        UpcallCount<{ upcall::COUNT }>,
375        AllowRoCount<{ ro_allow::COUNT }>,
376        AllowRwCount<{ rw_allow::COUNT }>,
377    >,
378
379    /// Internal buffer for copying appslices into.
380    buffer: TakeCell<'static, [u8]>,
381    /// What issued the currently executing call. This can be an app or the
382    /// kernel.
383    current_user: OptionalCell<User>,
384
385    /// The first byte that is accessible from userspace.
386    userspace_start_address: usize,
387    /// How many bytes allocated to userspace.
388    userspace_length: usize,
389
390    /// Absolute address of the header of the next region of userspace that's
391    /// not allocated to an app yet. Each time an app uses this capsule, a new
392    /// region of storage will be handed out and this address will point to the
393    /// header of a new unallocated region.
394    next_unallocated_region_header_address: OptionalCell<usize>,
395}
396
397impl<'a, const APP_REGION_SIZE: usize> IsolatedNonvolatileStorage<'a, APP_REGION_SIZE> {
398    pub fn new(
399        driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'a>,
400        grant: Grant<
401            App,
402            UpcallCount<{ upcall::COUNT }>,
403            AllowRoCount<{ ro_allow::COUNT }>,
404            AllowRwCount<{ rw_allow::COUNT }>,
405        >,
406        userspace_start_address: usize,
407        userspace_length: usize,
408        buffer: &'static mut [u8],
409    ) -> Self {
410        Self {
411            driver,
412            apps: grant,
413            buffer: TakeCell::new(buffer),
414            current_user: OptionalCell::empty(),
415            userspace_start_address,
416            userspace_length,
417            next_unallocated_region_header_address: OptionalCell::empty(),
418        }
419    }
420
421    // Start reading app region headers.
422    fn start_region_traversal(&self) -> Result<(), ErrorCode> {
423        if self.current_user.is_some() {
424            // Can't traverse the regions right now because the underlying
425            // driver is already in use.
426            return Err(ErrorCode::BUSY);
427        }
428
429        let res = self.read_region_header(self.userspace_start_address);
430        match res {
431            Ok(()) => {
432                // Mark that we started the discover operation.
433                self.current_user
434                    .set(User::RegionManager(ManagerTask::DiscoverRegions(
435                        self.userspace_start_address,
436                    )));
437                Ok(())
438            }
439            Err(e) => {
440                // We did not successfully start the discover, return the error.
441                Err(e)
442            }
443        }
444    }
445
446    fn allocate_app_region(&self, processid: ProcessId) -> Result<(), ErrorCode> {
447        // Can't allocate a region if we haven't previously traversed existing
448        // regions and found where they stop.
449        let new_header_addr = self
450            .next_unallocated_region_header_address
451            .get()
452            .ok_or(ErrorCode::FAIL)?;
453
454        // Get an app's write_id (same as ShortID) for saving to region header.
455        // Note that if an app doesn't have the valid permissions, it will be
456        // unable to create storage regions.
457        let write_id = processid
458            .get_storage_permissions()
459            .ok_or(ErrorCode::NOSUPPORT)?
460            .get_write_id()
461            .ok_or(ErrorCode::NOSUPPORT)?;
462
463        let region = AppRegion {
464            version: CURRENT_HEADER_VERSION,
465            // Have this region start where all the existing regions end.
466            // Note that the app's actual region starts after the region header.
467            absolute_address: new_header_addr + REGION_HEADER_LEN,
468            length: APP_REGION_SIZE,
469        };
470
471        // fail if new region is outside userspace area
472        if region.absolute_address > self.userspace_start_address + self.userspace_length
473            || region.absolute_address + region.length
474                > self.userspace_start_address + self.userspace_length
475        {
476            return Err(ErrorCode::NOMEM);
477        }
478
479        let Some(header) = AppRegionHeader::new(region.version, write_id, region.length) else {
480            return Err(ErrorCode::FAIL);
481        };
482
483        // Write this new region header to the end of the existing regions.
484        let res = self.write_region_header(&region, &header, new_header_addr);
485        match res {
486            Ok(()) => {
487                // Mark that we started the initialize region task.
488                self.current_user
489                    .set(User::RegionManager(ManagerTask::WriteHeader(
490                        processid, region,
491                    )));
492                Ok(())
493            }
494            Err(e) => {
495                // We did not successfully start the region initialization,
496                // return the error.
497                Err(e)
498            }
499        }
500    }
501
502    // Read the header of an app's storage region. The region_header_address
503    // argument describes the start of the **header** and not the usable region
504    // itself.
505    fn read_region_header(&self, region_header_address: usize) -> Result<(), ErrorCode> {
506        self.check_header_access(region_header_address, APP_REGION_SIZE)?;
507
508        self.buffer.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
509            self.driver
510                .read(buffer, region_header_address, REGION_HEADER_LEN)
511                .map_err(|(e, buf)| {
512                    self.buffer.replace(buf);
513                    e
514                })
515        })
516    }
517
518    // Write the header of an app's storage region. The region_header_address
519    // argument describes the start of the **header** and not the usable region
520    // itself.
521    fn write_region_header(
522        &self,
523        region: &AppRegion,
524        region_header: &AppRegionHeader,
525        region_header_address: usize,
526    ) -> Result<(), ErrorCode> {
527        self.check_header_access(region.absolute_address, region.length)?;
528
529        let header_slice = region_header.to_bytes();
530
531        self.buffer.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
532            let _ = buffer
533                .get_mut(0..REGION_HEADER_LEN)
534                .ok_or(ErrorCode::NOMEM)?
535                .copy_from_slice_or_err(
536                    header_slice
537                        .get(0..REGION_HEADER_LEN)
538                        .ok_or(ErrorCode::NOMEM)?,
539                );
540
541            self.driver
542                .write(buffer, region_header_address, REGION_HEADER_LEN)
543                .map_err(|(e, buf)| {
544                    self.buffer.replace(buf);
545                    e
546                })
547        })
548    }
549
550    fn erase_region_content(
551        &self,
552        offset: usize,
553        length: usize,
554    ) -> Result<(usize, usize), ErrorCode> {
555        self.check_header_access(offset, length)?;
556
557        self.buffer.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
558            let active_len = cmp::min(length, buffer.len());
559
560            // Clear the erase buffer in case there was any data
561            // remaining from a previous operation.
562            for c in buffer.iter_mut() {
563                *c = 0xFF;
564            }
565
566            // how many more bytes to erase after this operation
567            let remaining_len = if length > buffer.len() {
568                length - buffer.len()
569            } else {
570                0
571            };
572
573            let next_erase_start = offset + active_len;
574
575            self.driver
576                .write(buffer, offset, active_len)
577                .map(|()| (next_erase_start, remaining_len))
578                .map_err(|(e, buf)| {
579                    self.buffer.replace(buf);
580                    e
581                })
582        })
583    }
584
585    // Returns `Ok()` with the address of the next header to be read if a new
586    // header read was started.
587    fn header_read_done(&self, region_header_address: usize) -> Result<Option<usize>, ErrorCode> {
588        // Cases when a header read completes:
589        // 1. Read a valid header
590        //     - The valid header belongs to a Tock app (might not be currently
591        //       running).
592        //     - Search for the owner of the region within the apps.
593        //     - Find the owner of the region that has a matching shortid (from
594        //       the header).
595        //     - Then, startup another read operation to read the header of the
596        //       next storage region.
597        // 2. Read an invalid header
598        //     - We've reached the end of all previously allocated regions.
599        //     - Allocate new app region here.
600
601        let header = self.buffer.map_or(Err(ErrorCode::NOMEM), |buffer| {
602            // Need to copy over bytes since we need to convert a &[u8] into a
603            // [u8; REGION_HEADER_LEN]. The &[u8] refers to a slice of size
604            // BUF_LEN (which could be different than REGION_HEADER_LEN). Using
605            // buffer.try_into() will fail at runtime since the underlying
606            // buffer is not the same length as what we're trying to convert
607            // into.
608            let mut header_buffer = [0; REGION_HEADER_LEN];
609            header_buffer
610                .copy_from_slice_or_err(&buffer[..REGION_HEADER_LEN])
611                .or(Err(ErrorCode::FAIL))?;
612
613            // reconstruct header from bytes we just read
614            AppRegionHeader::from_bytes(header_buffer).ok_or(ErrorCode::FAIL)
615        })?;
616
617        if header.is_valid() {
618            // Find the app with the corresponding shortid.
619            for app in self.apps.iter() {
620                let processid = app.processid();
621                // Skip an app if it doesn't have the proper storage
622                // permissions.
623                let write_id = match processid.get_storage_permissions() {
624                    Some(perms) => match perms.get_write_id() {
625                        Some(write_id) => write_id,
626                        None => continue,
627                    },
628                    None => continue,
629                };
630                if write_id == header.shortid {
631                    app.enter(|app, _kernel_data| {
632                        if app.region.is_none() {
633                            let version = header.version().ok_or(ErrorCode::FAIL)?;
634                            let region = AppRegion {
635                                version,
636                                // The app's actual region starts after the
637                                // region header.
638                                absolute_address: region_header_address + REGION_HEADER_LEN,
639                                length: header.length() as usize,
640                            };
641                            app.region.replace(region);
642                        }
643                        Ok::<(), ErrorCode>(())
644                    })?;
645                    break;
646                }
647            }
648
649            let next_header_address =
650                region_header_address + REGION_HEADER_LEN + header.length() as usize;
651            // Kick off another read for the next region.
652            self.read_region_header(next_header_address)
653                .and(Ok(Some(next_header_address)))
654        } else {
655            // This is the end of the region traversal. If a header is invalid,
656            // we've reached the end of all previously allocated regions.
657
658            // Save this region header address so that we can allocate new
659            // regions here later.
660            self.next_unallocated_region_header_address
661                .set(region_header_address);
662
663            Ok(None)
664        }
665    }
666
667    fn check_userspace_perms(
668        &self,
669        processid: ProcessId,
670        command: NvmCommand,
671    ) -> Result<(), ErrorCode> {
672        let perms = processid
673            .get_storage_permissions()
674            .ok_or(ErrorCode::NOSUPPORT)?;
675        let write_id = perms.get_write_id().ok_or(ErrorCode::NOSUPPORT)?;
676        match command {
677            NvmCommand::Read { offset: _ } => perms
678                .check_read_permission(write_id)
679                .then_some(())
680                .ok_or(ErrorCode::NOSUPPORT),
681            NvmCommand::Write { offset: _ } => perms
682                .check_modify_permission(write_id)
683                .then_some(())
684                .ok_or(ErrorCode::NOSUPPORT),
685            NvmCommand::GetSize => {
686                // If we have a `write_id` then we can return the size.
687                Ok(())
688            }
689        }
690    }
691
692    fn check_userspace_access(
693        &self,
694        offset: usize,
695        length: usize,
696        region: &AppRegion,
697    ) -> Result<(), ErrorCode> {
698        // Check that access is within this app's isolated nonvolatile region.
699        // This is to prevent an app from reading/writing to another app's
700        // nonvolatile storage.
701
702        if offset >= region.length || length > region.length || offset + length > region.length {
703            return Err(ErrorCode::INVAL);
704        }
705
706        Ok(())
707    }
708
709    fn check_header_access(&self, offset: usize, length: usize) -> Result<(), ErrorCode> {
710        // Check that we're within the entire userspace region.
711        if offset < self.userspace_start_address
712            || offset >= self.userspace_start_address + self.userspace_length
713            || length > self.userspace_length
714            || offset + length >= self.userspace_start_address + self.userspace_length
715        {
716            return Err(ErrorCode::INVAL);
717        }
718
719        Ok(())
720    }
721
722    // Check so see if we are doing something. If not, go ahead and do this
723    // command. If so, this is queued and will be run when the pending command
724    // completes.
725    fn enqueue_userspace_command(
726        &self,
727        command: NvmCommand,
728        processid: ProcessId,
729    ) -> Result<(), ErrorCode> {
730        self.check_userspace_perms(processid, command)?;
731
732        self.apps
733            .enter(processid, |app, _kernel_data| {
734                if app.pending_operation.is_some() {
735                    return Err(ErrorCode::BUSY);
736                }
737                app.pending_operation = Some(command);
738                Ok(())
739            })
740            .unwrap_or_else(|err| Err(err.into()))?;
741
742        self.check_queue();
743        Ok(())
744    }
745
746    fn check_queue(&self) {
747        if self.current_user.is_some() {
748            // If the driver is busy we can't start a new operation and do not
749            // need to check the queue.
750            return;
751        }
752
753        // If this is none, we haven't traversed the existing regions yet.
754        if self.next_unallocated_region_header_address.is_none() {
755            match self.start_region_traversal() {
756                Ok(()) => {
757                    // We started an operation so we can return and let that
758                    // operation finish.
759                    return;
760                }
761                Err(_e) => {
762                    // We did not start the traversal which is a problem. This
763                    // shouldn't happen, but if it does then we could overwrite
764                    // existing regions.
765                    return;
766                }
767            }
768        }
769
770        // Iterate apps and run an operation if one is pending.
771        for app in self.apps.iter() {
772            let processid = app.processid();
773            let started = app.enter(|app, kernel_data| {
774                match app.pending_operation {
775                    Some(nvm_command) => {
776                        if app.region.is_none() {
777                            // This app needs its region allocated.
778                            self.allocate_app_region(processid).is_ok()
779                        } else {
780                            let res = self.handle_syscall(nvm_command, processid, app, kernel_data);
781                            match res {
782                                Ok(started_operation) => started_operation,
783                                Err(e) => {
784                                    app.pending_operation = None;
785                                    let _ = kernel_data.schedule_upcall(
786                                        nvm_command.upcall(),
787                                        (into_statuscode(Err(e)), 0, 0),
788                                    );
789
790                                    false
791                                }
792                            }
793                        }
794                    }
795                    None => false,
796                }
797            });
798            if started {
799                break;
800            }
801        }
802    }
803
804    fn handle_syscall(
805        &self,
806        command: NvmCommand,
807        processid: ProcessId,
808        app: &mut App,
809        kernel_data: &kernel::grant::GrantKernelData,
810    ) -> Result<bool, ErrorCode> {
811        match command {
812            NvmCommand::GetSize => {
813                match app.region {
814                    Some(region) => {
815                        // clear pending syscall
816                        app.pending_operation = None;
817                        // signal app with the result
818                        let _ = kernel_data.schedule_upcall(
819                            upcall::GET_SIZE_DONE,
820                            (into_statuscode(Ok(())), region.length, 0),
821                        );
822                        Ok(false)
823                    }
824                    None => Err(ErrorCode::NOMEM),
825                }
826            }
827
828            NvmCommand::Read { offset: _ } | NvmCommand::Write { offset: _ } => {
829                // Get the length of the correct allowed buffer.
830                let allow_buf_len = match command {
831                    NvmCommand::Read { offset: _ } => kernel_data
832                        .get_readwrite_processbuffer(rw_allow::READ)
833                        .map_or(0, |read| read.len()),
834                    NvmCommand::Write { offset: _ } => kernel_data
835                        .get_readonly_processbuffer(ro_allow::WRITE)
836                        .map_or(0, |read| read.len()),
837                    NvmCommand::GetSize => 0,
838                };
839
840                // Check that the matching allowed buffer exists.
841                if allow_buf_len == 0 {
842                    return Err(ErrorCode::RESERVE);
843                }
844
845                // Fail if the app doesn't have a region assigned to it.
846                let Some(app_region) = &app.region else {
847                    return Err(ErrorCode::NOMEM);
848                };
849
850                let command_offset = command.offset();
851
852                self.check_userspace_access(command_offset, allow_buf_len, app_region)?;
853
854                // Need to copy bytes if this is a write!
855                if let NvmCommand::Write { offset: _ } = command {
856                    let _ = kernel_data
857                        .get_readonly_processbuffer(ro_allow::WRITE)
858                        .and_then(|write| {
859                            write.enter(|app_buffer| {
860                                self.buffer.map(|kernel_buffer| {
861                                    // Check that the internal buffer and
862                                    // the buffer that was allowed are long
863                                    // enough.
864                                    let write_len = cmp::min(allow_buf_len, kernel_buffer.len());
865
866                                    let d = &app_buffer[0..write_len];
867                                    for (i, c) in kernel_buffer[0..write_len].iter_mut().enumerate()
868                                    {
869                                        *c = d[i].get();
870                                    }
871                                });
872                            })
873                        });
874                }
875
876                // Calculate where we want to actually read from in the
877                // physical storage. Note that the offset for this
878                // command is with respect to the app's region address
879                // space. This means that userspace accesses start at 0
880                // which is the start of the app's region.
881                let physical_address = app_region.absolute_address + command_offset;
882
883                let res = self
884                    .buffer
885                    .take()
886                    .map_or(Err(ErrorCode::RESERVE), |buffer| {
887                        // Check that the internal buffer and the buffer that was
888                        // allowed are long enough.
889                        let active_len_buf = cmp::min(allow_buf_len, buffer.len());
890
891                        match command {
892                            NvmCommand::Read { offset: _ } => self
893                                .driver
894                                .read(buffer, physical_address, active_len_buf)
895                                .map_err(|(_e, buf)| {
896                                    self.buffer.replace(buf);
897                                    ErrorCode::FAIL
898                                }),
899                            NvmCommand::Write { offset: _ } => self
900                                .driver
901                                .write(buffer, physical_address, active_len_buf)
902                                .map_err(|(_e, buf)| {
903                                    self.buffer.replace(buf);
904                                    ErrorCode::FAIL
905                                }),
906                            NvmCommand::GetSize => Err(ErrorCode::FAIL),
907                        }
908                    });
909                match res {
910                    Ok(()) => {
911                        self.current_user.set(User::App { processid });
912                        Ok(true)
913                    }
914                    Err(e) => Err(e),
915                }
916            }
917        }
918    }
919}
920
921/// This is the callback client for the underlying physical storage driver.
922impl<const APP_REGION_SIZE: usize> hil::nonvolatile_storage::NonvolatileStorageClient
923    for IsolatedNonvolatileStorage<'_, APP_REGION_SIZE>
924{
925    fn read_done(&self, buffer: &'static mut [u8], length: usize) {
926        // Switch on which user of this capsule generated this callback.
927        self.current_user.take().map(|user| {
928            match user {
929                User::RegionManager(state) => {
930                    self.buffer.replace(buffer);
931                    if let ManagerTask::DiscoverRegions(address) = state {
932                        let res = self.header_read_done(address);
933                        match res {
934                            Ok(addr) => match addr {
935                                Some(next_header_address) => {
936                                    self.current_user.set(User::RegionManager(
937                                        ManagerTask::DiscoverRegions(next_header_address),
938                                    ));
939                                }
940                                None => {
941                                    // We finished the scan of existing
942                                    // regions. Now we can check the queue
943                                    // to see if there is any work to be
944                                    // done.
945                                    self.check_queue();
946                                }
947                            },
948                            Err(_e) => {
949                                // Not clear what to do here.
950                                self.check_queue();
951                            }
952                        }
953                    }
954                }
955                User::App { processid } => {
956                    let _ = self.apps.enter(processid, move |app, kernel_data| {
957                        // Need to copy in the contents of the buffer
958                        let read_len = kernel_data
959                            .get_readwrite_processbuffer(rw_allow::READ)
960                            .and_then(|read| {
961                                read.mut_enter(|app_buffer| {
962                                    let read_len = cmp::min(app_buffer.len(), length);
963
964                                    let d = &app_buffer[0..read_len];
965                                    for (i, c) in buffer[0..read_len].iter().enumerate() {
966                                        d[i].set(*c);
967                                    }
968                                    read_len
969                                })
970                            })
971                            .unwrap_or(0);
972
973                        // Replace the buffer we used to do this read.
974                        self.buffer.replace(buffer);
975
976                        // clear pending syscall
977                        app.pending_operation = None;
978                        // And then signal the app.
979                        let _ = kernel_data.schedule_upcall(
980                            upcall::READ_DONE,
981                            (into_statuscode(Ok(())), read_len, 0),
982                        );
983                    });
984
985                    self.check_queue();
986                }
987            }
988        });
989    }
990
991    fn write_done(&self, buffer: &'static mut [u8], length: usize) {
992        // Replace the buffer we used to do this write.
993        self.buffer.replace(buffer);
994
995        // Switch on which user of this capsule generated this callback.
996        self.current_user.take().map(|user| {
997            match user {
998                User::RegionManager(state) => {
999                    match state {
1000                        ManagerTask::WriteHeader(processid, region) => {
1001                            // Now that we have written the header for the app
1002                            // we can store its region in its grant.
1003                            let _ = self.apps.enter(processid, |app, _kernel_data| {
1004                                // set region data in app's grant
1005                                app.region.replace(region);
1006                            });
1007
1008                            // Update our metadata about where the next
1009                            // unallocated region is.
1010                            let next_header_addr = region.absolute_address + region.length;
1011                            self.next_unallocated_region_header_address
1012                                .set(next_header_addr);
1013
1014                            // Erase the userspace accessible content of the region
1015                            // before handing it off to an app.
1016                            let res =
1017                                self.erase_region_content(region.absolute_address, region.length);
1018                            match res {
1019                                Ok((next_erase_start, remaining_bytes)) => {
1020                                    self.current_user.set(User::RegionManager(
1021                                        // need to pass on where the next erase should start
1022                                        // how long it should be.
1023                                        ManagerTask::EraseRegion {
1024                                            processid,
1025                                            next_erase_start,
1026                                            remaining_bytes,
1027                                        },
1028                                    ));
1029                                }
1030                                Err(_e) => {
1031                                    // Not clear what to do here.
1032                                    self.current_user.clear();
1033                                    self.check_queue();
1034                                }
1035                            }
1036                        }
1037                        ManagerTask::EraseRegion {
1038                            processid,
1039                            next_erase_start,
1040                            remaining_bytes,
1041                        } => {
1042                            if remaining_bytes > 0 {
1043                                // We still have more to erase, so kick off
1044                                // another one where we left off.
1045                                let res =
1046                                    self.erase_region_content(next_erase_start, remaining_bytes);
1047                                match res {
1048                                    Ok((next_erase_start, remaining_bytes)) => {
1049                                        self.current_user.set(User::RegionManager(
1050                                            ManagerTask::EraseRegion {
1051                                                processid,
1052                                                next_erase_start,
1053                                                remaining_bytes,
1054                                            },
1055                                        ));
1056                                    }
1057                                    Err(_e) => {
1058                                        // Not clear what to do here.
1059                                        self.current_user.clear();
1060                                        self.check_queue();
1061                                    }
1062                                }
1063                            } else {
1064                                // Done erasing entire region. Can go on with
1065                                // normal tasks.
1066                                self.current_user.clear();
1067                                self.check_queue();
1068                            }
1069                        }
1070                        _ => {}
1071                    }
1072                }
1073                User::App { processid } => {
1074                    let _ = self.apps.enter(processid, move |app, kernel_data| {
1075                        // clear pending syscall
1076                        app.pending_operation = None;
1077                        // Notify app that its write has completed.
1078                        let _ = kernel_data.schedule_upcall(
1079                            upcall::WRITE_DONE,
1080                            (into_statuscode(Ok(())), length, 0),
1081                        );
1082                    });
1083                    self.current_user.clear();
1084                    self.check_queue();
1085                }
1086            }
1087        });
1088    }
1089}
1090
1091/// Provide an interface for userland.
1092impl<const APP_REGION_SIZE: usize> SyscallDriver
1093    for IsolatedNonvolatileStorage<'_, APP_REGION_SIZE>
1094{
1095    /// Command interface.
1096    ///
1097    /// Commands are selected by the lowest 8 bits of the first argument.
1098    ///
1099    /// ### `command_num`
1100    ///
1101    /// - `0`: Return Ok(()) if this driver is included on the platform.
1102    /// - `1`: Return the number of bytes available to each app.
1103    /// - `2`: Start a read from the nonvolatile storage.
1104    /// - `3`: Start a write to the nonvolatile_storage.
1105    fn command(
1106        &self,
1107        command_num: usize,
1108        offset_lo: usize,
1109        offset_hi: usize,
1110        processid: ProcessId,
1111    ) -> CommandReturn {
1112        match command_num {
1113            0 => CommandReturn::success(),
1114
1115            // For the get_bytes, read, and write syscalls we need to first
1116            // initialize the app's isolated nonvolatile storage. This involves
1117            // searching the storage area for an existing region that belongs to
1118            // this app. If we don't find an existing region we allocate a new
1119            // one. Only once the initialization is complete, can we service the
1120            // original syscall. So, we can store the syscall data in the app's
1121            // grant and handle it when initialization finishes.
1122            1 | 2 | 3 => {
1123                // We want to handle both 64-bit and 32-bit platforms, but on
1124                // 32-bit platforms shifting `offset_hi` doesn't make sense.
1125                let offset: usize = usize32s_to_usize(offset_lo, offset_hi);
1126                let nvm_command = match command_num {
1127                    1 => NvmCommand::GetSize,
1128                    2 => NvmCommand::Read { offset },
1129                    3 => NvmCommand::Write { offset },
1130                    _ => return CommandReturn::failure(ErrorCode::NOSUPPORT),
1131                };
1132
1133                // Enqueue the operation for the app.
1134                let res = self.enqueue_userspace_command(nvm_command, processid);
1135                match res {
1136                    Ok(()) => CommandReturn::success(),
1137                    Err(e) => CommandReturn::failure(e),
1138                }
1139            }
1140            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
1141        }
1142    }
1143
1144    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
1145        self.apps.enter(processid, |_, _| {})
1146    }
1147}