Skip to main content

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//!     dynamic_binary_storage,
59//!     create_capability!(capabilities::MemoryAllocationCapability),
60//!     ).finalize(components::app_loader_component_static!(
61//!     DynamicBinaryStorage<'static>,
62//!     DynamicBinaryStorage<'static>,
63//!     DynamicBinaryStorage<'static>,
64//!     ));
65//!
66//! NOTE:
67//! 1. This capsule is not virtualized, and can only serve one app at a time.
68//! 2. This implementation currently only loads new apps. It does not update apps.
69//! ```
70
71use core::cell::Cell;
72use core::cmp;
73use core::num::NonZeroU32;
74
75use kernel::dynamic_binary_storage;
76use kernel::errorcode::into_statuscode;
77use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
78use kernel::process::{ProcessLoadError, ShortId};
79use kernel::processbuffer::ReadableProcessBuffer;
80use kernel::syscall::{CommandReturn, SyscallDriver};
81use kernel::utilities::cells::{OptionalCell, TakeCell};
82use kernel::utilities::leasable_buffer::SubSliceMut;
83use kernel::{ErrorCode, ProcessId};
84
85/// Syscall driver number.
86use capsules_core::driver;
87pub const DRIVER_NUM: usize = driver::NUM::AppLoader as usize;
88
89/// IDs for subscribed upcalls.
90mod upcall {
91    /// Setup Done callback
92    pub const SETUP_DONE: usize = 0;
93    /// Write done callback.
94    pub const WRITE_DONE: usize = 1;
95    /// Finalize done callback.
96    pub const FINALIZE_DONE: usize = 2;
97    /// Load done callback.
98    pub const LOAD_DONE: usize = 3;
99    /// Abort done callback.
100    pub const ABORT_DONE: usize = 4;
101    /// Unload done callback.
102    pub const UNLOAD_DONE: usize = 5;
103    /// Uninstall Done callback.
104    pub const UNINSTALL_DONE: usize = 6;
105    /// Number of upcalls.
106    pub const COUNT: u8 = 7;
107}
108
109// Ids for read-only allow buffers
110mod ro_allow {
111    /// Setup a buffer to write bytes to the nonvolatile storage.
112    pub const WRITE: usize = 0;
113    /// The number of allow buffers the kernel stores for this grant
114    pub const COUNT: u8 = 1;
115}
116
117// Discussion regarding this buffer size value
118// can be found at: https://github.com/tock/tock/pull/4520
119pub const BUF_LEN: usize = 4096;
120
121#[derive(Default)]
122pub struct App {
123    pending_command: bool,
124}
125
126pub struct AppLoader<
127    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
128    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
129    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
130    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
131> {
132    // The underlying driver for the process flashing and loading.
133    storage_driver: &'static S,
134    load_driver: &'static L,
135    unload_driver: &'static T,
136    uninstall_driver: &'static U,
137    // Per-app state.
138    apps: Grant<
139        App,
140        UpcallCount<{ upcall::COUNT }>,
141        AllowRoCount<{ ro_allow::COUNT }>,
142        AllowRwCount<0>,
143    >,
144
145    // Internal buffer for copying appslices into.
146    buffer: TakeCell<'static, [u8]>,
147    // What issued the currently executing call.
148    current_process: OptionalCell<ProcessId>,
149    new_app_length: Cell<usize>,
150}
151
152impl<
153    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
154    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
155    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
156    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
157> AppLoader<S, L, T, U>
158{
159    pub fn new(
160        grant: Grant<
161            App,
162            UpcallCount<{ upcall::COUNT }>,
163            AllowRoCount<{ ro_allow::COUNT }>,
164            AllowRwCount<0>,
165        >,
166        storage_driver: &'static S,
167        load_driver: &'static L,
168        unload_driver: &'static T,
169        uninstall_driver: &'static U,
170        buffer: &'static mut [u8],
171    ) -> AppLoader<S, L, T, U> {
172        AppLoader {
173            apps: grant,
174            storage_driver,
175            load_driver,
176            unload_driver,
177            uninstall_driver,
178            buffer: TakeCell::new(buffer),
179            current_process: OptionalCell::empty(),
180            new_app_length: Cell::new(0),
181        }
182    }
183
184    /// Copy data from the shared buffer with app and request kernel to
185    /// write the app data to flash.
186    fn write(&self, offset: usize, length: usize, processid: ProcessId) -> Result<(), ErrorCode> {
187        // Userspace sees memory that starts at address 0 even if it
188        // is offset in the physical memory.
189        match offset.checked_add(length) {
190            Some(result) => {
191                if result > self.new_app_length.get() {
192                    // this means the app is out of bounds
193                    return Err(ErrorCode::INVAL);
194                }
195            }
196            None => {
197                return Err(ErrorCode::INVAL);
198            }
199        }
200
201        self.apps
202            .enter(processid, |_app, kernel_data| {
203                let mut active_len = 0;
204
205                let result = kernel_data
206                    .get_readonly_processbuffer(ro_allow::WRITE)
207                    .and_then(|write| {
208                        write.enter(|app_buffer| {
209                            self.buffer
210                                .map(|kernel_buffer| {
211                                    // Get the length of the allowed buffer
212                                    let allow_buf_len = app_buffer.len();
213
214                                    // Check that the buffer length is not zero
215                                    if allow_buf_len == 0 {
216                                        return Err(ErrorCode::RESERVE);
217                                    }
218
219                                    // Shorten the length if the application did not give us
220                                    // enough bytes in the allowed buffer.
221                                    active_len = cmp::min(length, allow_buf_len);
222
223                                    // copy data into the kernel buffer!
224                                    let write_len = cmp::min(active_len, kernel_buffer.len());
225                                    let () = app_buffer[..write_len]
226                                        .copy_to_slice(&mut kernel_buffer[..write_len]);
227
228                                    Ok(())
229                                })
230                                .unwrap_or(Err(ErrorCode::RESERVE))
231                        })
232                    });
233
234                if result.is_err() {
235                    return Err(ErrorCode::RESERVE);
236                }
237
238                self.buffer
239                    .take()
240                    .map_or(Err(ErrorCode::RESERVE), |buffer| {
241                        let mut write_buffer = SubSliceMut::new(buffer);
242                        // should be the length supported by the app
243                        // (currently only powers of 2 work)
244                        write_buffer.slice(..length);
245                        let res = self.storage_driver.write(write_buffer, offset);
246                        match res {
247                            Ok(()) => Ok(()),
248                            Err((e, buffer)) => {
249                                self.buffer.replace(buffer.take());
250                                Err(e)
251                            }
252                        }
253                    })
254            })
255            .unwrap_or_else(|err| Err(err.into()))
256    }
257}
258
259impl<
260    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
261    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
262    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
263    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
264> dynamic_binary_storage::DynamicBinaryStoreClient for AppLoader<S, L, T, U>
265{
266    /// Let the requesting app know we are done setting up for the new app
267    fn setup_done(&self, result: Result<(), ErrorCode>) {
268        // Switch on which user of this capsule generated this callback.
269        self.current_process.map(|processid| {
270            let _ = self.apps.enter(processid, move |app, kernel_data| {
271                app.pending_command = false;
272                // Signal the app.
273                let _ = kernel_data
274                    .schedule_upcall(upcall::SETUP_DONE, (into_statuscode(result), 0, 0));
275            });
276        });
277    }
278
279    /// Let the app know we are done writing the block of data
280    fn write_done(&self, result: Result<(), ErrorCode>, buffer: &'static mut [u8], length: usize) {
281        // Switch on which user of this capsule generated this callback.
282        self.current_process.map(|processid| {
283            let _ = self.apps.enter(processid, move |app, kernel_data| {
284                // Replace the buffer we used to do this write.
285                self.buffer.replace(buffer);
286                app.pending_command = false;
287
288                // And then signal the app.
289                let _ = kernel_data
290                    .schedule_upcall(upcall::WRITE_DONE, (into_statuscode(result), length, 0));
291            });
292        });
293    }
294
295    /// Let the app know we are done finalizing, and are ready to load
296    fn finalize_done(&self, result: Result<(), ErrorCode>) {
297        self.current_process.map(|processid| {
298            let _ = self.apps.enter(processid, move |app, kernel_data| {
299                // And then signal the app.
300                app.pending_command = false;
301
302                self.current_process.take();
303                let _ = kernel_data
304                    .schedule_upcall(upcall::FINALIZE_DONE, (into_statuscode(result), 0, 0));
305            });
306        });
307    }
308
309    /// Let the app know we have aborted the new app writing process
310    fn abort_done(&self, result: Result<(), ErrorCode>) {
311        self.current_process.map(|processid| {
312            let _ = self.apps.enter(processid, move |app, kernel_data| {
313                // And then signal the app.
314                app.pending_command = false;
315
316                self.current_process.take();
317                let _ = kernel_data
318                    .schedule_upcall(upcall::ABORT_DONE, (into_statuscode(result), 0, 0));
319            });
320        });
321    }
322}
323
324impl<
325    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
326    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
327    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
328    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
329> dynamic_binary_storage::DynamicProcessLoadClient for AppLoader<S, L, T, U>
330{
331    /// Let the requesting app know we are done loading the new process
332    ///
333    /// Error Type Mapping.
334    ///
335    /// This method converts `ProcessLoadError` to `ErrorCode` so it can be
336    /// passed to userspace.
337    ///
338    /// Currently,
339    /// 1. ProcessLoadError::NotEnoughMemory       <==> ErrorCode::NOMEM
340    /// 2. ProcessLoadError::MpuInvalidFlashLength <==> ErrorCode::INVAL
341    /// 3. ProcessLoadError::InternalError         <==> ErrorCode::OFF
342    /// 4. All other ProcessLoadError types        <==> ErrorCode::FAIL
343    fn load_done(&self, result: Result<(), ProcessLoadError>) {
344        let status_code = match result {
345            Ok(()) => Ok(()),
346            Err(e) => match e {
347                ProcessLoadError::NotEnoughMemory => Err(ErrorCode::NOMEM),
348                ProcessLoadError::MpuInvalidFlashLength => Err(ErrorCode::INVAL),
349                ProcessLoadError::MpuConfigurationError => Err(ErrorCode::FAIL),
350                ProcessLoadError::MemoryAddressMismatch { .. } => Err(ErrorCode::FAIL),
351                ProcessLoadError::NoProcessSlot => Err(ErrorCode::FAIL),
352                ProcessLoadError::BinaryError(_) => Err(ErrorCode::FAIL),
353                ProcessLoadError::CheckError(_) => Err(ErrorCode::FAIL),
354                // This error is usually a result of bug in the kernel
355                // so we return Powered OFF error, because that is unlikely.
356                ProcessLoadError::InternalError => Err(ErrorCode::OFF),
357            },
358        };
359
360        self.current_process.map(|processid| {
361            let _ = self.apps.enter(processid, move |app, kernel_data| {
362                app.pending_command = false;
363                // Signal the app.
364                self.current_process.take();
365                let _ = kernel_data
366                    .schedule_upcall(upcall::LOAD_DONE, (into_statuscode(status_code), 0, 0));
367            });
368        });
369    }
370}
371
372impl<
373    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
374    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
375    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
376    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
377> dynamic_binary_storage::DynamicProcessUnloadClient for AppLoader<S, L, T, U>
378{
379    /// Let the app know we have unloaded the target process
380    /// and return an opaque identifier for the process binary
381    fn unload_done(&self, result: Result<(), ErrorCode>, app_handle: usize) {
382        self.current_process.map(|processid| {
383            let _ = self.apps.enter(processid, move |app, kernel_data| {
384                // And then signal the app.
385                app.pending_command = false;
386
387                self.current_process.take();
388                let _ = kernel_data.schedule_upcall(
389                    upcall::UNLOAD_DONE,
390                    (into_statuscode(result), app_handle, 0),
391                );
392            });
393        });
394    }
395}
396
397impl<
398    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
399    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
400    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
401    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
402> dynamic_binary_storage::DynamicProcessUninstallClient for AppLoader<S, L, T, U>
403{
404    /// Let the app know we have uninstalled the target application
405    /// binary.
406    fn uninstall_done(&self, result: Result<(), ErrorCode>) {
407        self.current_process.map(|processid| {
408            let _ = self.apps.enter(processid, move |app, kernel_data| {
409                // And then signal the app.
410                app.pending_command = false;
411
412                self.current_process.take();
413                let _ = kernel_data
414                    .schedule_upcall(upcall::UNINSTALL_DONE, (into_statuscode(result), 0, 0));
415            });
416        });
417    }
418}
419
420/// Provide an interface for userland.
421impl<
422    S: dynamic_binary_storage::DynamicBinaryStore + 'static,
423    L: dynamic_binary_storage::DynamicProcessLoad + 'static,
424    T: dynamic_binary_storage::DynamicProcessUnload + 'static,
425    U: dynamic_binary_storage::DynamicProcessUninstall + 'static,
426> SyscallDriver for AppLoader<S, L, T, U>
427{
428    /// Command interface.
429    ///
430    /// The driver returns ErrorCode::BUSY if:
431    /// - The kernel has already dedicated this driver to another process.
432    /// - The kernel is busy executing another command for this process.
433    ///
434    /// Currently, this capsule is not virtualized and can only be used by one
435    /// application at a time.
436    ///
437    /// Commands are selected by the lowest 8 bits of the first argument.
438    ///
439    /// ### `command_num`
440    ///
441    /// - `0`: Return Ok(()) if this driver is included on the platform.
442    /// - `1`: Request kernel to setup for loading app.
443    ///  - Returns appsize if the kernel has available space
444    ///  - Returns ErrorCode::FAIL if the kernel is unable to allocate space for
445    ///    the new app
446    /// - `2`: Request kernel to write app data to the nonvolatile_storage
447    ///  - Returns Ok(()) when write is successful
448    ///  - Returns ErrorCode::INVAL when the app is violating bounds
449    ///  - Returns ErrorCode::FAIL when the write fails
450    /// - `3`: Signal to the kernel that the writing is done.
451    ///  - Returns Ok(()) if the kernel successfully verified it and
452    ///    set the stage for `load()`.
453    ///  - Returns ErrorCode::FAIL if:
454    ///    a. The kernel needs to write a leading padding app but is unable to.
455    ///    b. The command is called during setup or load phases.
456    /// - `4`: Request kernel to load app.
457    ///  - Returns Ok(()) when the process is successfully loaded
458    ///  - Returns ErrorCode::FAIL if:
459    ///    a. The kernel is unable to create a process object for the application
460    /// - `5`: Request kernel to abort setup/write operation.
461    ///  - Returns Ok(()) when the operation is cancelled successfully
462    ///  - Returns ErrorCode::BUSY when the abort fails(due to padding app being
463    ///    unable to be written, so try again)
464    ///  - Returns ErrorCode::FAIL if the driver is not dedicated to this process
465    /// - `6`: Request kernel to unload a processs
466    ///  - Returns Ok(()) when the application is successfully scheduled for unload
467    ///  - Returns ErrorCode::FAIL when the unload fails
468    /// - `7`: Request kernel to uninstall an application binary
469    ///  - Returns Ok(()) when application is scheduled for uninstall
470    ///  - Returns ErrorCode::FAIL when uninstall fails.
471    ///
472    /// The driver returns ErrorCode::INVAL if any operation is called before the
473    /// preceeding operation was invoked. For example, `write()` cannot be called before
474    /// `setup()`, and `load()` cannot be called before `write()` (for this implementation).
475    fn command(
476        &self,
477        command_num: usize,
478        arg1: usize,
479        arg2: usize,
480        processid: ProcessId,
481    ) -> CommandReturn {
482        // Check if this driver is free, or already dedicated to this process.
483        let match_or_nonexistent = self.current_process.map_or(true, |current_process| {
484            self.apps
485                .enter(current_process, |_, _| current_process == processid)
486                .unwrap_or_else(|_e| {
487                    let _ = self.storage_driver.abort();
488                    self.new_app_length.set(0);
489                    self.current_process.take();
490                    false
491                })
492        });
493        if match_or_nonexistent {
494            self.current_process.set(processid);
495            let _ = self.apps.enter(processid, |app, _| {
496                if app.pending_command {
497                    CommandReturn::failure(ErrorCode::BUSY);
498                } else {
499                    app.pending_command = true;
500                }
501            });
502        } else {
503            return CommandReturn::failure(ErrorCode::BUSY);
504        }
505
506        match command_num {
507            0 => {
508                // Remove ownership from the current process so
509                // other processes can discover this driver
510                self.current_process.take();
511                CommandReturn::success()
512            }
513
514            1 => {
515                // Request kernel to allocate resources for
516                // an app with size passed via `arg1`.
517                let res = self.storage_driver.setup(arg1);
518                match res {
519                    Ok(app_len) => {
520                        self.new_app_length.set(app_len);
521                        CommandReturn::success()
522                    }
523                    Err(e) => {
524                        self.new_app_length.set(0);
525                        self.current_process.take();
526                        CommandReturn::failure(e)
527                    }
528                }
529            }
530
531            2 => {
532                // Request kernel to write app to flash.
533                let res = self.write(arg1, arg2, processid);
534                match res {
535                    Ok(()) => CommandReturn::success(),
536                    Err(e) => {
537                        if let Some(buffer) = self.buffer.take() {
538                            self.buffer.replace(buffer);
539                            self.new_app_length.set(0);
540                            self.current_process.take();
541                            CommandReturn::failure(e)
542                        } else {
543                            CommandReturn::failure(ErrorCode::RESERVE)
544                        }
545                    }
546                }
547            }
548
549            3 => {
550                // Signal to kernel writing is done.
551                let result = self.storage_driver.finalize();
552                match result {
553                    Ok(()) => CommandReturn::success(),
554                    Err(e) => {
555                        self.new_app_length.set(0);
556                        self.current_process.take();
557                        CommandReturn::failure(e)
558                    }
559                }
560            }
561
562            4 => {
563                // Request kernel to load the new app.
564                let res = self.load_driver.load();
565                match res {
566                    Ok(()) => {
567                        self.new_app_length.set(0);
568                        CommandReturn::success()
569                    }
570                    Err(e) => {
571                        self.new_app_length.set(0);
572                        self.current_process.take();
573                        CommandReturn::failure(e)
574                    }
575                }
576            }
577
578            5 => {
579                // Request kernel to abort setup/write operation.
580                let result = self.storage_driver.abort();
581                match result {
582                    Ok(()) => {
583                        self.new_app_length.set(0);
584                        CommandReturn::success()
585                    }
586                    Err(e) => {
587                        self.new_app_length.set(0);
588                        self.current_process.take();
589                        CommandReturn::failure(e)
590                    }
591                }
592            }
593            6 => {
594                // Request the kernel to unload a process
595                // by specifying its ShortId
596
597                // returns only the address of the active process (which is the latest version). we need to be able to uninstall any version
598                let shortid = match NonZeroU32::new(arg1 as u32) {
599                    Some(id) => ShortId::Fixed(id),
600                    None => return CommandReturn::failure(ErrorCode::INVAL),
601                };
602                let res = self.unload_driver.unload(shortid);
603                match res {
604                    Ok(()) => CommandReturn::success(),
605                    Err(e) => {
606                        self.current_process.take();
607                        CommandReturn::failure(e)
608                    }
609                }
610            }
611            7 => {
612                // Request the kernel to uninstall an application binary
613                // by specifying its `app_handle`
614                // (usually defined by the return value of `Unload`, but
615                // can be extensible).
616
617                let result = self.uninstall_driver.uninstall_with_app_handle(arg1);
618                match result {
619                    Ok(()) => CommandReturn::success(),
620                    Err(e) => {
621                        self.current_process.take();
622                        CommandReturn::failure(e)
623                    }
624                }
625            }
626            // Unsupported command numbers.
627            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
628        }
629    }
630
631    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
632        self.apps.enter(processid, |_, _| {})
633    }
634}