capsules_extra/app_loader.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 2024.
4
5//! This capsule provides an interface between a dynamic loading userspace
6//! app and the kernel.
7//!
8//! This is an initial implementation that gets the app size from the
9//! userspace app and sets up the flash region in which the app will be
10//! written. Then the app is actually written to flash. Finally, the
11//! the userspace app sends a request for the app to be loaded.
12//!
13//!
14//! Here is a diagram of the expected stack with this capsule:
15//! Boxes are components and between the boxes are the traits that are the
16//! interfaces between components.
17//!
18//! ```text
19//! +-----------------------------------------------------------------+
20//! | |
21//! | userspace |
22//! | |
23//! +-----------------------------------------------------------------+
24//! kernel::SyscallDriver
25//! +-----------------------------------------------------------------+
26//! | |
27//! | capsules::app_loader::AppLoader (this) |
28//! | |
29//! +-----------------------------------------------------------------+
30//! kernel::dynamic_binary_storage::DynamicBinaryStore
31//! kernel::dynamic_binary_storage::DynamicProcessLoad
32//! +-----------------------------------------------------------------+
33//! | | |
34//! | Physical Nonvolatile Storage | Kernel |
35//! | | |
36//! +-----------------------------------------------------------------+
37//! hil::nonvolatile_storage::NonvolatileStorage
38//! ```
39//!
40//! Example instantiation:
41//!
42//! ```rust, ignore
43//! # use kernel::static_init;
44//!
45//! type NonVolatilePages = components::dynamic_binary_storage::NVPages<nrf52840::nvmc::Nvmc>;
46//! type DynamicBinaryStorage<'a> = kernel::dynamic_binary_storage::SequentialDynamicBinaryStorage<
47//! 'static,
48//! nrf52840::chip::NRF52<'a, Nrf52840DefaultPeripherals<'a>>,
49//! kernel::process::ProcessStandardDebugFull,
50//! NonVolatilePages,
51//! >;
52//!
53//! let dynamic_app_loader = components::app_loader::AppLoaderComponent::new(
54//! board_kernel,
55//! capsules_extra::app_loader::DRIVER_NUM,
56//! dynamic_binary_storage,
57//! dynamic_binary_storage,
58//! ).finalize(components::app_loader_component_static!(
59//! DynamicBinaryStorage<'static>,
60//! DynamicBinaryStorage<'static>,
61//! ));
62//!
63//! NOTE:
64//! 1. This capsule is not virtualized, and can only serve one app at a time.
65//! 2. This implementation currently only loads new apps. It does not update apps.
66//! ```
67
68use core::cell::Cell;
69use core::cmp;
70
71use kernel::dynamic_binary_storage;
72use kernel::errorcode::into_statuscode;
73use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
74use kernel::process::ProcessLoadError;
75use kernel::processbuffer::ReadableProcessBuffer;
76use kernel::syscall::{CommandReturn, SyscallDriver};
77use kernel::utilities::cells::{OptionalCell, TakeCell};
78use kernel::utilities::leasable_buffer::SubSliceMut;
79use kernel::{ErrorCode, ProcessId};
80
81/// Syscall driver number.
82use capsules_core::driver;
83pub const DRIVER_NUM: usize = driver::NUM::AppLoader as usize;
84
85/// IDs for subscribed upcalls.
86mod upcall {
87 /// Setup Done callback
88 pub const SETUP_DONE: usize = 0;
89 /// Write done callback.
90 pub const WRITE_DONE: usize = 1;
91 /// Finalize done callback.
92 pub const FINALIZE_DONE: usize = 2;
93 /// Load done callback.
94 pub const LOAD_DONE: usize = 3;
95 /// Abort done callback.
96 pub const ABORT_DONE: usize = 4;
97 /// Number of upcalls.
98 pub const COUNT: u8 = 5;
99}
100
101// Ids for read-only allow buffers
102mod ro_allow {
103 /// Setup a buffer to write bytes to the nonvolatile storage.
104 pub const WRITE: usize = 0;
105 /// The number of allow buffers the kernel stores for this grant
106 pub const COUNT: u8 = 1;
107}
108
109// Discussion regarding this buffer size value
110// can be found at: https://github.com/tock/tock/pull/4520
111pub const BUF_LEN: usize = 4096;
112
113#[derive(Default)]
114pub struct App {
115 pending_command: bool,
116}
117
118pub struct AppLoader<
119 S: dynamic_binary_storage::DynamicBinaryStore + 'static,
120 L: dynamic_binary_storage::DynamicProcessLoad + 'static,
121> {
122 // The underlying driver for the process flashing and loading.
123 storage_driver: &'static S,
124 load_driver: &'static L,
125 // Per-app state.
126 apps: Grant<
127 App,
128 UpcallCount<{ upcall::COUNT }>,
129 AllowRoCount<{ ro_allow::COUNT }>,
130 AllowRwCount<0>,
131 >,
132
133 // Internal buffer for copying appslices into.
134 buffer: TakeCell<'static, [u8]>,
135 // What issued the currently executing call.
136 current_process: OptionalCell<ProcessId>,
137 new_app_length: Cell<usize>,
138}
139
140impl<
141 S: dynamic_binary_storage::DynamicBinaryStore + 'static,
142 L: dynamic_binary_storage::DynamicProcessLoad + 'static,
143 > AppLoader<S, L>
144{
145 pub fn new(
146 grant: Grant<
147 App,
148 UpcallCount<{ upcall::COUNT }>,
149 AllowRoCount<{ ro_allow::COUNT }>,
150 AllowRwCount<0>,
151 >,
152 storage_driver: &'static S,
153 load_driver: &'static L,
154 buffer: &'static mut [u8],
155 ) -> AppLoader<S, L> {
156 AppLoader {
157 apps: grant,
158 storage_driver,
159 load_driver,
160 buffer: TakeCell::new(buffer),
161 current_process: OptionalCell::empty(),
162 new_app_length: Cell::new(0),
163 }
164 }
165
166 /// Copy data from the shared buffer with app and request kernel to
167 /// write the app data to flash.
168 fn write(&self, offset: usize, length: usize, processid: ProcessId) -> Result<(), ErrorCode> {
169 // Userspace sees memory that starts at address 0 even if it
170 // is offset in the physical memory.
171 match offset.checked_add(length) {
172 Some(result) => {
173 if result > self.new_app_length.get() {
174 // this means the app is out of bounds
175 return Err(ErrorCode::INVAL);
176 }
177 }
178 None => {
179 return Err(ErrorCode::INVAL);
180 }
181 }
182
183 self.apps
184 .enter(processid, |_app, kernel_data| {
185 let mut active_len = 0;
186
187 let result = kernel_data
188 .get_readonly_processbuffer(ro_allow::WRITE)
189 .and_then(|write| {
190 write.enter(|app_buffer| {
191 self.buffer
192 .map(|kernel_buffer| {
193 // Get the length of the allowed buffer
194 let allow_buf_len = app_buffer.len();
195
196 // Check that the buffer length is not zero
197 if allow_buf_len == 0 {
198 return Err(ErrorCode::RESERVE);
199 }
200
201 // Shorten the length if the application did not give us
202 // enough bytes in the allowed buffer.
203 active_len = cmp::min(length, allow_buf_len);
204
205 // copy data into the kernel buffer!
206 let write_len = cmp::min(active_len, kernel_buffer.len());
207 let () = app_buffer[..write_len]
208 .copy_to_slice(&mut kernel_buffer[..write_len]);
209
210 Ok(())
211 })
212 .unwrap_or(Err(ErrorCode::RESERVE))
213 })
214 });
215
216 if result.is_err() {
217 return Err(ErrorCode::RESERVE);
218 }
219
220 self.buffer
221 .take()
222 .map_or(Err(ErrorCode::RESERVE), |buffer| {
223 let mut write_buffer = SubSliceMut::new(buffer);
224 // should be the length supported by the app
225 // (currently only powers of 2 work)
226 write_buffer.slice(..length);
227 let res = self.storage_driver.write(write_buffer, offset);
228 match res {
229 Ok(()) => Ok(()),
230 Err(e) => Err(e),
231 }
232 })
233 })
234 .unwrap_or_else(|err| Err(err.into()))
235 }
236}
237
238impl<
239 S: dynamic_binary_storage::DynamicBinaryStore + 'static,
240 L: dynamic_binary_storage::DynamicProcessLoad + 'static,
241 > dynamic_binary_storage::DynamicBinaryStoreClient for AppLoader<S, L>
242{
243 /// Let the requesting app know we are done setting up for the new app
244 fn setup_done(&self, result: Result<(), ErrorCode>) {
245 // Switch on which user of this capsule generated this callback.
246 self.current_process.map(|processid| {
247 let _ = self.apps.enter(processid, move |app, kernel_data| {
248 app.pending_command = false;
249 // Signal the app.
250 let _ = kernel_data
251 .schedule_upcall(upcall::SETUP_DONE, (into_statuscode(result), 0, 0));
252 });
253 });
254 }
255
256 /// Let the app know we are done writing the block of data
257 fn write_done(&self, result: Result<(), ErrorCode>, buffer: &'static mut [u8], length: usize) {
258 // Switch on which user of this capsule generated this callback.
259 self.current_process.map(|processid| {
260 let _ = self.apps.enter(processid, move |app, kernel_data| {
261 // Replace the buffer we used to do this write.
262 self.buffer.replace(buffer);
263 app.pending_command = false;
264
265 // And then signal the app.
266 let _ = kernel_data
267 .schedule_upcall(upcall::WRITE_DONE, (into_statuscode(result), length, 0));
268 });
269 });
270 }
271
272 /// Let the app know we are done finalizing, and are ready to load
273 fn finalize_done(&self, result: Result<(), ErrorCode>) {
274 self.current_process.map(|processid| {
275 let _ = self.apps.enter(processid, move |app, kernel_data| {
276 // And then signal the app.
277 app.pending_command = false;
278
279 self.current_process.take();
280 let _ = kernel_data
281 .schedule_upcall(upcall::FINALIZE_DONE, (into_statuscode(result), 0, 0));
282 });
283 });
284 }
285
286 /// Let the app know we have aborted the new app writing process
287 fn abort_done(&self, result: Result<(), ErrorCode>) {
288 self.current_process.map(|processid| {
289 let _ = self.apps.enter(processid, move |app, kernel_data| {
290 // And then signal the app.
291 app.pending_command = false;
292
293 self.current_process.take();
294 let _ = kernel_data
295 .schedule_upcall(upcall::ABORT_DONE, (into_statuscode(result), 0, 0));
296 });
297 });
298 }
299}
300
301impl<
302 S: dynamic_binary_storage::DynamicBinaryStore + 'static,
303 L: dynamic_binary_storage::DynamicProcessLoad + 'static,
304 > dynamic_binary_storage::DynamicProcessLoadClient for AppLoader<S, L>
305{
306 /// Let the requesting app know we are done loading the new process
307 ///
308 /// Error Type Mapping.
309 ///
310 /// This method converts `ProcessLoadError` to `ErrorCode` so it can be
311 /// passed to userspace.
312 ///
313 /// Currently,
314 /// 1. ProcessLoadError::NotEnoughMemory <==> ErrorCode::NOMEM
315 /// 2. ProcessLoadError::MpuInvalidFlashLength <==> ErrorCode::INVAL
316 /// 3. ProcessLoadError::InternalError <==> ErrorCode::OFF
317 /// 4. All other ProcessLoadError types <==> ErrorCode::FAIL
318
319 fn load_done(&self, result: Result<(), ProcessLoadError>) {
320 let status_code = match result {
321 Ok(()) => Ok(()),
322 Err(e) => match e {
323 ProcessLoadError::NotEnoughMemory => Err(ErrorCode::NOMEM),
324 ProcessLoadError::MpuInvalidFlashLength => Err(ErrorCode::INVAL),
325 ProcessLoadError::MpuConfigurationError => Err(ErrorCode::FAIL),
326 ProcessLoadError::MemoryAddressMismatch { .. } => Err(ErrorCode::FAIL),
327 ProcessLoadError::NoProcessSlot => Err(ErrorCode::FAIL),
328 ProcessLoadError::BinaryError(_) => Err(ErrorCode::FAIL),
329 ProcessLoadError::CheckError(_) => Err(ErrorCode::FAIL),
330 // This error is usually a result of bug in the kernel
331 // so we return Powered OFF error, because that is unlikely.
332 ProcessLoadError::InternalError => Err(ErrorCode::OFF),
333 },
334 };
335
336 self.current_process.map(|processid| {
337 let _ = self.apps.enter(processid, move |app, kernel_data| {
338 app.pending_command = false;
339 // Signal the app.
340 self.current_process.take();
341 let _ = kernel_data
342 .schedule_upcall(upcall::LOAD_DONE, (into_statuscode(status_code), 0, 0));
343 });
344 });
345 }
346}
347
348/// Provide an interface for userland.
349impl<
350 S: dynamic_binary_storage::DynamicBinaryStore + 'static,
351 L: dynamic_binary_storage::DynamicProcessLoad + 'static,
352 > SyscallDriver for AppLoader<S, L>
353{
354 /// Command interface.
355 ///
356 /// The driver returns ErrorCode::BUSY if:
357 /// - The kernel has already dedicated this driver to another process.
358 /// - The kernel is busy executing another command for this process.
359 ///
360 /// Currently, this capsule is not virtualized and can only be used by one
361 /// application at a time.
362 ///
363 /// Commands are selected by the lowest 8 bits of the first argument.
364 ///
365 /// ### `command_num`
366 ///
367 /// - `0`: Return Ok(()) if this driver is included on the platform.
368 /// - `1`: Request kernel to setup for loading app.
369 /// - Returns appsize if the kernel has available space
370 /// - Returns ErrorCode::FAIL if the kernel is unable to allocate space for the new app
371 /// - `2`: Request kernel to write app data to the nonvolatile_storage
372 /// - Returns Ok(()) when write is successful
373 /// - Returns ErrorCode::INVAL when the app is violating bounds
374 /// - Returns ErrorCode::FAIL when the write fails
375 /// - `3`: Signal to the kernel that the writing is done.
376 /// - Returns Ok(()) if the kernel successfully verified it and
377 /// set the stage for `load()`.
378 /// - Returns ErrorCode::FAIL if:
379 /// a. The kernel needs to write a leading padding app but is unable to.
380 /// b. The command is called during setup or load phases.
381 /// - `4`: Request kernel to load app.
382 /// - Returns Ok(()) when the process is successfully loaded
383 /// - Returns ErrorCode::FAIL if:
384 /// a. The kernel is unable to create a process object for the application
385 /// - `5`: Request kernel to abort setup/write operation.
386 /// - Returns Ok(()) when the operation is cancelled successfully
387 /// - Returns ErrorCode::BUSY when the abort fails
388 /// (due to padding app being unable to be written, so try again)
389 /// - Returns ErrorCode::FAIL if the driver is not dedicated to this process
390 ///
391 /// The driver returns ErrorCode::INVAL if any operation is called before the
392 /// preceeding operation was invoked. For example, `write()` cannot be called before
393 /// `setup()`, and `load()` cannot be called before `write()` (for this implementation).
394 fn command(
395 &self,
396 command_num: usize,
397 arg1: usize,
398 arg2: usize,
399 processid: ProcessId,
400 ) -> CommandReturn {
401 // Check if this driver is free, or already dedicated to this process.
402 let match_or_nonexistent = self.current_process.map_or(true, |current_process| {
403 self.apps
404 .enter(current_process, |_, _| current_process == processid)
405 .unwrap_or_else(|_e| {
406 let _ = self.storage_driver.abort();
407 self.new_app_length.set(0);
408 self.current_process.take();
409 false
410 })
411 });
412 if match_or_nonexistent {
413 self.current_process.set(processid);
414 let _ = self.apps.enter(processid, |app, _| {
415 if app.pending_command {
416 CommandReturn::failure(ErrorCode::BUSY);
417 } else {
418 app.pending_command = true;
419 }
420 });
421 } else {
422 return CommandReturn::failure(ErrorCode::BUSY);
423 }
424
425 match command_num {
426 0 => {
427 // Remove ownership from the current process so
428 // other processes can discover this driver
429 self.current_process.take();
430 CommandReturn::success()
431 }
432
433 1 => {
434 // Request kernel to allocate resources for
435 // an app with size passed via `arg1`.
436 let res = self.storage_driver.setup(arg1);
437 match res {
438 Ok(app_len) => {
439 self.new_app_length.set(app_len);
440 CommandReturn::success()
441 }
442 Err(e) => {
443 self.new_app_length.set(0);
444 self.current_process.take();
445 CommandReturn::failure(e)
446 }
447 }
448 }
449
450 2 => {
451 // Request kernel to write app to flash.
452 let res = self.write(arg1, arg2, processid);
453 match res {
454 Ok(()) => CommandReturn::success(),
455 Err(e) => {
456 let command_result = if let Some(buffer) = self.buffer.take() {
457 self.buffer.replace(buffer);
458 self.new_app_length.set(0);
459 self.current_process.take();
460 CommandReturn::failure(e)
461 } else {
462 CommandReturn::failure(ErrorCode::RESERVE)
463 };
464 command_result
465 }
466 }
467 }
468
469 3 => {
470 // Signal to kernel writing is done.
471 let result = self.storage_driver.finalize();
472 match result {
473 Ok(()) => CommandReturn::success(),
474 Err(e) => {
475 self.new_app_length.set(0);
476 self.current_process.take();
477 CommandReturn::failure(e)
478 }
479 }
480 }
481
482 4 => {
483 // Request kernel to load the new app.
484 let res = self.load_driver.load();
485 match res {
486 Ok(()) => {
487 self.new_app_length.set(0);
488 CommandReturn::success()
489 }
490 Err(e) => {
491 self.new_app_length.set(0);
492 self.current_process.take();
493 CommandReturn::failure(e)
494 }
495 }
496 }
497
498 5 => {
499 // Request kernel to abort setup/write operation.
500 let result = self.storage_driver.abort();
501 match result {
502 Ok(()) => {
503 self.new_app_length.set(0);
504 CommandReturn::success()
505 }
506 Err(e) => {
507 self.new_app_length.set(0);
508 self.current_process.take();
509 CommandReturn::failure(e)
510 }
511 }
512 }
513 // Unsupported command numbers.
514 _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
515 }
516 }
517
518 fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
519 self.apps.enter(processid, |_, _| {})
520 }
521}