Skip to main content

capsules_core/virtualizers/
virtual_rng.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// Virtualizer for the RNG
6use core::cell::Cell;
7use kernel::ErrorCode;
8use kernel::collections::list::{List, ListLink, ListNode};
9use kernel::hil::rng::{Client, Continue, Rng};
10use kernel::utilities::cells::OptionalCell;
11
12#[derive(Copy, Clone, PartialEq)]
13enum Op {
14    Idle,
15    Get,
16}
17
18// Struct to manage multiple rng requests
19pub struct MuxRngMaster<'a> {
20    rng: &'a dyn Rng<'a>,
21    devices: List<'a, VirtualRngMasterDevice<'a>>,
22    inflight: OptionalCell<&'a VirtualRngMasterDevice<'a>>,
23}
24
25impl<'a> MuxRngMaster<'a> {
26    pub const fn new(rng: &'a dyn Rng<'a>) -> MuxRngMaster<'a> {
27        MuxRngMaster {
28            rng,
29            devices: List::new(),
30            inflight: OptionalCell::empty(),
31        }
32    }
33
34    fn get_next_node(&self) -> Option<&'a VirtualRngMasterDevice<'a>> {
35        self.devices
36            .iter()
37            .find(|node| node.operation.get() != Op::Idle)
38    }
39
40    fn do_next_op(&self) -> Result<(), ErrorCode> {
41        if self.inflight.is_none() {
42            let mnode = self.get_next_node();
43            let return_code = mnode.map(|node| {
44                let op = node.operation.get();
45                let operation_code = match op {
46                    Op::Get => {
47                        let success_code = self.rng.get();
48
49                        // Only set inflight to node if we successfully initiated rng
50                        if success_code == Ok(()) {
51                            self.inflight.set(node);
52                        }
53                        success_code
54                    }
55                    Op::Idle => unreachable!("Attempted to run idle operation in virtual_rng!"), // Can't get here...
56                };
57
58                // Mark operation as done
59                node.operation.set(Op::Idle);
60                operation_code
61            });
62
63            // Check if return code has a value
64            if let Some(r) = return_code {
65                r
66            } else {
67                Err(ErrorCode::FAIL)
68            }
69        } else {
70            Ok(())
71        }
72    }
73}
74
75impl Client for MuxRngMaster<'_> {
76    fn randomness_available(
77        &self,
78        _randomness: &mut dyn Iterator<Item = u32>,
79        _error: Result<(), ErrorCode>,
80    ) -> Continue {
81        // Try find if randomness is available, or return done
82        let inflight = self.inflight.take();
83        inflight.map_or(Continue::Done, |device| {
84            let cont_code = device.randomness_available(_randomness, _error);
85            if let Some(mnode) = self.get_next_node() {
86                mnode.operation.set(Op::Idle);
87                self.inflight.set(mnode);
88                if cont_code == Continue::More {
89                    device.operation.set(Op::Get);
90                }
91                return Continue::More;
92            } else if cont_code == Continue::More {
93                self.inflight.set(device);
94            }
95
96            cont_code
97        })
98    }
99}
100
101// Struct for a single rng device
102pub struct VirtualRngMasterDevice<'a> {
103    //reference to the mux
104    mux: &'a MuxRngMaster<'a>,
105
106    // Pointer to next element in the list of devices
107    next: ListLink<'a, VirtualRngMasterDevice<'a>>,
108    client: OptionalCell<&'a dyn Client>,
109    operation: Cell<Op>,
110}
111
112// Implement ListNode trait for virtual rng device
113impl<'a> ListNode<'a, VirtualRngMasterDevice<'a>> for VirtualRngMasterDevice<'a> {
114    fn next(&self) -> &'a ListLink<'_, VirtualRngMasterDevice<'a>> {
115        &self.next
116    }
117}
118
119impl<'a> VirtualRngMasterDevice<'a> {
120    pub const fn new(mux: &'a MuxRngMaster<'a>) -> VirtualRngMasterDevice<'a> {
121        VirtualRngMasterDevice {
122            mux,
123            next: ListLink::empty(),
124            client: OptionalCell::empty(),
125            operation: Cell::new(Op::Idle),
126        }
127    }
128}
129
130impl<'a> PartialEq<VirtualRngMasterDevice<'a>> for VirtualRngMasterDevice<'a> {
131    fn eq(&self, other: &VirtualRngMasterDevice<'a>) -> bool {
132        // Check whether two rng devices point to the same device
133        core::ptr::eq(self, other)
134    }
135}
136
137impl<'a> Rng<'a> for VirtualRngMasterDevice<'a> {
138    fn get(&self) -> Result<(), ErrorCode> {
139        self.operation.set(Op::Get);
140        self.mux.do_next_op()
141    }
142
143    fn cancel(&self) -> Result<(), ErrorCode> {
144        // Set current device to idle
145        self.operation.set(Op::Idle);
146
147        self.mux.inflight.map_or_else(
148            || {
149                // If no node inflight, just set node to idle and return
150                Ok(())
151            },
152            |current_node| {
153                // Find if current device is the one in flight or not
154                if current_node == self {
155                    self.mux.inflight.take();
156                    if let Some(node) = self.mux.get_next_node() {
157                        self.mux.inflight.set(node);
158                        node.operation.set(Op::Idle);
159                        Ok(())
160                    } else {
161                        self.mux.rng.cancel()
162                    }
163                } else {
164                    Ok(())
165                }
166            },
167        )
168    }
169
170    fn set_client(&'a self, client: &'a dyn Client) {
171        self.mux.devices.push_head(self);
172
173        // Set client to handle callbacks for current device
174        self.client.set(client);
175
176        // Set client for rng to be current virtualizer
177        self.mux.rng.set_client(self.mux);
178    }
179}
180
181impl Client for VirtualRngMasterDevice<'_> {
182    fn randomness_available(
183        &self,
184        randomness: &mut dyn Iterator<Item = u32>,
185        error: Result<(), ErrorCode>,
186    ) -> Continue {
187        self.client.map_or(Continue::Done, move |client| {
188            client.randomness_available(randomness, error)
189        })
190    }
191}