capsules_core/low_level_debug/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Provides low-level debugging functionality to userspace. The system call
//! interface is documented in doc/syscalls/00008_low_level_debug.md.

mod fmt;

use core::cell::Cell;

use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
use kernel::hil::uart::{Transmit, TransmitClient};
use kernel::syscall::CommandReturn;
use kernel::{ErrorCode, ProcessId};

// LowLevelDebug requires a &mut [u8] buffer of length at least BUF_LEN.
pub use fmt::BUF_LEN;

pub const DRIVER_NUM: usize = crate::driver::NUM::LowLevelDebug as usize;

pub struct LowLevelDebug<'u, U: Transmit<'u>> {
    buffer: Cell<Option<&'static mut [u8]>>,
    grant: Grant<AppData, UpcallCount<0>, AllowRoCount<0>, AllowRwCount<0>>,
    // grant_failed is set to true when LowLevelDebug fails to allocate an app's
    // grant region. When it has a chance, LowLevelDebug will print a message
    // indicating a grant initialization has failed, then set this back to
    // false. Although LowLevelDebug cannot print an application ID without
    // using grant storage, it will at least output an error indicating some
    // application's message was dropped.
    grant_failed: Cell<bool>,
    uart: &'u U,
}

impl<'u, U: Transmit<'u>> LowLevelDebug<'u, U> {
    pub fn new(
        buffer: &'static mut [u8],
        uart: &'u U,
        grant: Grant<AppData, UpcallCount<0>, AllowRoCount<0>, AllowRwCount<0>>,
    ) -> LowLevelDebug<'u, U> {
        LowLevelDebug {
            buffer: Cell::new(Some(buffer)),
            grant,
            grant_failed: Cell::new(false),
            uart,
        }
    }
}

impl<'u, U: Transmit<'u>> kernel::syscall::SyscallDriver for LowLevelDebug<'u, U> {
    fn command(
        &self,
        minor_num: usize,
        r2: usize,
        r3: usize,
        caller_id: ProcessId,
    ) -> CommandReturn {
        match minor_num {
            0 => return CommandReturn::success(),
            1 => self.push_entry(DebugEntry::AlertCode(r2), caller_id),
            2 => self.push_entry(DebugEntry::Print1(r2), caller_id),
            3 => self.push_entry(DebugEntry::Print2(r2, r3), caller_id),
            _ => return CommandReturn::failure(ErrorCode::NOSUPPORT),
        }
        CommandReturn::success()
    }

    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
        self.grant.enter(processid, |_, _| {})
    }
}

impl<'u, U: Transmit<'u>> TransmitClient for LowLevelDebug<'u, U> {
    fn transmitted_buffer(
        &self,
        tx_buffer: &'static mut [u8],
        _tx_len: usize,
        _rval: Result<(), ErrorCode>,
    ) {
        // Identify and transmit the next queued entry. If there are no queued
        // entries remaining, store buffer.

        // Prioritize printing the "grant init failed" message over per-app
        // debug entries.
        if self.grant_failed.take() {
            const MESSAGE: &[u8] = b"LowLevelDebug: grant init failed\n";
            tx_buffer[..MESSAGE.len()].copy_from_slice(MESSAGE);

            let _ = self.uart.transmit_buffer(tx_buffer, MESSAGE.len()).map_err(
                |(_, returned_buffer)| {
                    self.buffer.set(Some(returned_buffer));
                },
            );
            return;
        }

        for process_grant in self.grant.iter() {
            let processid = process_grant.processid();
            let (app_num, first_entry) = process_grant.enter(|owned_app_data, _| {
                owned_app_data.queue.rotate_left(1);
                (processid.id(), owned_app_data.queue[QUEUE_SIZE - 1].take())
            });
            let to_print = match first_entry {
                None => continue,
                Some(to_print) => to_print,
            };
            self.transmit_entry(tx_buffer, app_num, to_print);
            return;
        }
        self.buffer.set(Some(tx_buffer));
    }
}

// -----------------------------------------------------------------------------
// Implementation details below
// -----------------------------------------------------------------------------

impl<'u, U: Transmit<'u>> LowLevelDebug<'u, U> {
    // If the UART is not busy (the buffer is available), transmits the entry.
    // Otherwise, adds it to the app's queue.
    fn push_entry(&self, entry: DebugEntry, processid: ProcessId) {
        use DebugEntry::Dropped;

        if let Some(buffer) = self.buffer.take() {
            self.transmit_entry(buffer, processid.id(), entry);
            return;
        }

        let result = self.grant.enter(processid, |borrow, _| {
            for queue_entry in &mut borrow.queue {
                if queue_entry.is_none() {
                    *queue_entry = Some(entry);
                    return;
                }
            }
            // The queue is full, so indicate some entries were dropped. If
            // there is not a drop entry, replace the last entry with a drop
            // counter. A new drop counter is initialized to two, as the
            // overwrite drops an entry plus we're dropping this entry.
            borrow.queue[QUEUE_SIZE - 1] = match borrow.queue[QUEUE_SIZE - 1] {
                Some(Dropped(count)) => Some(Dropped(count + 1)),
                _ => Some(Dropped(2)),
            };
        });

        // If we were unable to enter the grant region, schedule a diagnostic
        // message. This gives the user a chance of figuring out what happened
        // when LowLevelDebug fails.
        if result.is_err() {
            self.grant_failed.set(true);
        }
    }

    // Immediately prints the provided entry to the UART.
    fn transmit_entry(&self, buffer: &'static mut [u8], app_num: usize, entry: DebugEntry) {
        let msg_len = fmt::format_entry(app_num, entry, buffer);
        // The uart's error message is ignored because we cannot do anything if
        // it fails anyway.
        let _ = self
            .uart
            .transmit_buffer(buffer, msg_len)
            .map_err(|(_, returned_buffer)| {
                self.buffer.set(Some(returned_buffer));
            });
    }
}

// Length of the debug queue for each app. Each queue entry takes 3 words (tag
// and 2 usizes to print). The queue will be allocated in an app's grant region
// when that app first uses the debug driver.
const QUEUE_SIZE: usize = 4;

#[derive(Default)]
pub struct AppData {
    queue: [Option<DebugEntry>; QUEUE_SIZE],
}

#[derive(Clone, Copy)]
pub(crate) enum DebugEntry {
    Dropped(usize),       // Some debug messages were dropped
    AlertCode(usize),     // Display a predefined alert code
    Print1(usize),        // Print a single number
    Print2(usize, usize), // Print two numbers
}