Skip to main content

capsules_extra/
app_flash_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 2022.
4
5//! This allows multiple apps to write their own flash region.
6//!
7//! All write requests from userland are checked to ensure that they are only
8//! trying to write their own flash space, and not the TBF header either.
9//!
10//! This driver can handle non page aligned writes.
11//!
12//! Userland apps should allocate buffers in flash when they are compiled to
13//! ensure that there is room to write to. This should be accomplished by
14//! declaring `const` buffers.
15//!
16//! Usage
17//! -----
18//!
19//! ```rust,ignore
20//! # use kernel::static_init;
21//!
22//! let app_flash_buffer = static_init!([u8; 512], [0; 512]);
23//! let app_flash = static_init!(
24//!     capsules::app_flash_driver::AppFlash<'static>,
25//!     capsules::app_flash_driver::AppFlash::new(nv_to_page,
26//!         board_kernel.create_grant(&grant_cap), app_flash_buffer));
27//! ```
28
29use core::cmp;
30
31use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
32use kernel::hil;
33use kernel::processbuffer::ReadableProcessBuffer;
34use kernel::syscall::{CommandReturn, SyscallDriver};
35use kernel::utilities::cells::{OptionalCell, TakeCell};
36use kernel::{ErrorCode, ProcessId};
37
38/// Syscall driver number.
39use capsules_core::driver;
40pub const DRIVER_NUM: usize = driver::NUM::AppFlash as usize;
41
42/// IDs for subscribed upcalls.
43mod upcall {
44    /// `write_done` callback.
45    pub const WRITE_DONE: usize = 0;
46    /// Number of upcalls.
47    pub const COUNT: u8 = 1;
48}
49
50/// Ids for read-only allow buffers
51mod ro_allow {
52    /// Set write buffer. This entire buffer will be written to flash.
53    pub const BUFFER: usize = 0;
54    /// The number of allow buffers the kernel stores for this grant
55    pub const COUNT: u8 = 1;
56}
57
58#[derive(Default)]
59pub struct App {
60    pending_command: bool,
61    flash_address: usize,
62}
63
64pub struct AppFlash<'a> {
65    driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'a>,
66    apps: Grant<
67        App,
68        UpcallCount<{ upcall::COUNT }>,
69        AllowRoCount<{ ro_allow::COUNT }>,
70        AllowRwCount<0>,
71    >,
72    current_app: OptionalCell<ProcessId>,
73    buffer: TakeCell<'static, [u8]>,
74}
75
76impl<'a> AppFlash<'a> {
77    pub fn new(
78        driver: &'a dyn hil::nonvolatile_storage::NonvolatileStorage<'a>,
79        grant: Grant<
80            App,
81            UpcallCount<{ upcall::COUNT }>,
82            AllowRoCount<{ ro_allow::COUNT }>,
83            AllowRwCount<0>,
84        >,
85        buffer: &'static mut [u8],
86    ) -> AppFlash<'a> {
87        AppFlash {
88            driver,
89            apps: grant,
90            current_app: OptionalCell::empty(),
91            buffer: TakeCell::new(buffer),
92        }
93    }
94
95    // Check to see if we are doing something. If not, go ahead and do this
96    // command. If so, this is queued and will be run when the pending command
97    // completes.
98    fn enqueue_write(&self, flash_address: usize, processid: ProcessId) -> Result<(), ErrorCode> {
99        self.apps
100            .enter(processid, |app, kernel_data| {
101                // Check that this is a valid range in the app's flash.
102                let flash_length = kernel_data
103                    .get_readonly_processbuffer(ro_allow::BUFFER)
104                    .map_or(0, |buffer| buffer.len());
105                let (app_flash_start, app_flash_end) = processid.get_editable_flash_range();
106                if flash_address < app_flash_start
107                    || flash_address >= app_flash_end
108                    || flash_address + flash_length >= app_flash_end
109                {
110                    return Err(ErrorCode::INVAL);
111                }
112
113                if self.current_app.is_none() {
114                    self.current_app.set(processid);
115
116                    kernel_data
117                        .get_readonly_processbuffer(ro_allow::BUFFER)
118                        .and_then(|buffer| {
119                            buffer.enter(|app_buffer| {
120                                // Copy contents to internal buffer and write it.
121                                self.buffer
122                                    .take()
123                                    .map_or(Err(ErrorCode::RESERVE), |buffer| {
124                                        let length = cmp::min(buffer.len(), app_buffer.len());
125                                        let d = &app_buffer[0..length];
126                                        for (i, c) in buffer[0..length].iter_mut().enumerate() {
127                                            *c = d[i].get();
128                                        }
129
130                                        self.driver.write(buffer, flash_address, length).map_err(
131                                            |(e, buf)| {
132                                                self.buffer.replace(buf);
133                                                e
134                                            },
135                                        )
136                                    })
137                            })
138                        })
139                        .unwrap_or(Err(ErrorCode::RESERVE))
140                } else {
141                    // Queue this request for later.
142                    if app.pending_command {
143                        Err(ErrorCode::NOMEM)
144                    } else {
145                        app.pending_command = true;
146                        app.flash_address = flash_address;
147                        Ok(())
148                    }
149                }
150            })
151            .unwrap_or_else(|err| Err(err.into()))
152    }
153}
154
155impl hil::nonvolatile_storage::NonvolatileStorageClient for AppFlash<'_> {
156    fn read_done(&self, _buffer: &'static mut [u8], _length: usize) {}
157
158    fn write_done(&self, buffer: &'static mut [u8], _length: usize) {
159        // Put our write buffer back.
160        self.buffer.replace(buffer);
161
162        // Notify the current application that the command finished.
163        self.current_app.take().map(|processid| {
164            let _ = self.apps.enter(processid, |_app, upcalls| {
165                let _ = upcalls.schedule_upcall(upcall::WRITE_DONE, (0, 0, 0));
166            });
167        });
168
169        // Check if there are any pending events.
170        for cntr in self.apps.iter() {
171            let processid = cntr.processid();
172            let started_command = cntr.enter(|app, kernel_data| {
173                if app.pending_command {
174                    app.pending_command = false;
175                    self.current_app.set(processid);
176                    let flash_address = app.flash_address;
177
178                    kernel_data
179                        .get_readonly_processbuffer(ro_allow::BUFFER)
180                        .and_then(|buffer| {
181                            buffer.enter(|app_buffer| {
182                                self.buffer.take().is_some_and(|buffer| {
183                                    if app_buffer.len() != 512 {
184                                        false
185                                    } else {
186                                        // Copy contents to internal buffer and write it.
187                                        let length = cmp::min(buffer.len(), app_buffer.len());
188                                        let d = &app_buffer[0..length];
189                                        for (i, c) in buffer[0..length].iter_mut().enumerate() {
190                                            *c = d[i].get();
191                                        }
192
193                                        match self.driver.write(buffer, flash_address, length) {
194                                            Ok(()) => true,
195                                            Err((_e, buf)) => {
196                                                self.buffer.replace(buf);
197                                                false
198                                            }
199                                        }
200                                    }
201                                })
202                            })
203                        })
204                        .unwrap_or(false)
205                } else {
206                    false
207                }
208            });
209            if started_command {
210                break;
211            }
212        }
213    }
214}
215
216impl SyscallDriver for AppFlash<'_> {
217    /// App flash control.
218    ///
219    /// ### `command_num`
220    ///
221    /// - `0`: Driver existence check.
222    /// - `1`: Write the memory from the `allow` buffer to the address in flash.
223    fn command(
224        &self,
225        command_num: usize,
226        arg1: usize,
227        _: usize,
228        processid: ProcessId,
229    ) -> CommandReturn {
230        match command_num {
231            0 => CommandReturn::success(),
232
233            1 => {
234                // Write to flash from the allowed buffer
235                let flash_address = arg1;
236
237                let res = self.enqueue_write(flash_address, processid);
238
239                match res {
240                    Ok(()) => CommandReturn::success(),
241                    Err(e) => CommandReturn::failure(e),
242                }
243            }
244
245            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
246        }
247    }
248
249    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
250        self.apps.enter(processid, |_, _| {})
251    }
252}