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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! The public API: [`ObjShelf`], and the functions that use it through anything that locks one.
//! The engine behind it is in `memory`.
use String;
use Vec;
use Mutex;
use crate;
use crate;
use crate::;
/// Object memory on top of a storage [`Backend`], shared between RTIC tasks as a `#[shared]`
/// resource.
///
/// Objects have a name and a type. [`list`] returns the names, [`get`], [`insert`] and
/// [`get_or_insert_with`] return a typed [`Handle`], and every access to an object goes through a
/// closure given to [`with`] or [`with_mut`], so no reference to it escapes.
///
/// The functions take the memory as `mem`: anything that locks an `ObjShelf`, such as RTIC's
/// resource proxy (`&mut cx.shared.mem`). An owned `ObjShelf` is its own lock, so they also take
/// `&mut mem` directly, as in `init` before it is shared.
///
/// ```ignore
/// // in `init`: when the changes fill the RAM budget, the `save` task is spawned to flush them
/// let config = NorConfig { flash, range };
/// let mut mem = ObjShelf::<NorBackend<Flash>>::mount(config, 16 * 1024, || {
/// save::spawn().ok();
/// })?;
/// let handle: Handle<Settings> =
/// objshelf::get_or_insert_with(&mut mem, "settings", Settings::default)?.expect("fits");
///
/// // in a task with `shared = [mem]`: `None` means "not now, try again later"
/// let mem = &mut cx.shared.mem;
/// if let Some(brightness) = objshelf::with(mem, &handle, |s| s.brightness)? { /* ... */ }
/// if objshelf::with_mut(mem, &handle, |s| s.brightness = 3)?.is_none() { /* try again later */ }
///
/// // in the `save` task, of the lowest priority
/// objshelf::flush(&mut cx.shared.mem)?; // the changes go to the backend
/// ```
///
/// A whole app is in the repository: `examples/rtic_nor` with RTIC on an STM32F413 and SPI NOR,
/// and `examples/std_fs.rs`, the same app with threads and the file system backend.
///
/// # Writes
///
/// Only [`flush`], [`flush_object`] (which writes one object) and [`unmount`](Self::unmount) write
/// to the backend. Changes, [`insert`] and [`remove`] included, stay in RAM until then. A flush
/// runs in the caller's task: about 3 ms per small object on SPI NOR and 15 ms on an SSD, where
/// the file system backend syncs each file, and hundreds of ms when NOR garbage collection runs (a
/// sector erase can take 400 ms on SPI NOR). Call it from a task of the lowest priority, so that
/// every other task keeps running meanwhile.
///
/// # Locking
///
/// Each function takes the lock for short steps only: never wrap a call in `lock` yourself. Like
/// every RTIC lock, it blocks the tasks that share the memory and none of the others: tasks of a
/// higher priority that don't use it always keep running. The lock is held for:
///
/// - RAM work: names, changes, and the access to an object in RAM, with the closure given to
/// [`with`] or [`with_mut`] (keep closures short);
/// - the read of an object that is not in RAM: about 0.23 ms per 256-byte page on SPI NOR at
/// 25 MHz, with the driver of `examples/rtic_nor` (82 µs of it is the SPI transfer).
///
/// The writes of a flush run outside of it. Meanwhile the storage is busy.
///
/// # Not now: `Ok(None)`
///
/// No function waits, so any task can call any of them. Instead, [`with`], [`with_mut`],
/// [`insert`], [`get_or_insert_with`], [`flush`] and [`flush_object`] return `Ok(None)`, having
/// done nothing, when the call cannot be done now:
///
/// - Busy: a flush has the storage, and the call needs it. That is [`with`] and [`with_mut`] on an
/// object that is not in RAM, or is the one being written (it is out of RAM during its write),
/// and the flushes themselves. Objects in RAM keep working. Only a task that preempts the
/// flush, of a higher priority, can find the storage busy.
/// - Full: see [RAM budget](#ram-budget).
///
/// Try again later. Real errors still come as `Err`.
///
/// # RAM budget
///
/// Objects in RAM take about the `cache_bytes` given to [`mount`](Self::mount). Each one counts
/// its size, what it owns on the heap (measured with [`GetSize`](get_size2::GetSize), spare
/// capacity included), and its entry in the cache. Only the allocator's own overhead is not
/// counted.
///
/// - Over budget, the least recently used unmodified objects are dropped, with no I/O: they are
/// read again when needed. The object just used stays, even alone over budget.
/// - Modified objects stay until a flush. When an object would become modified and they would
/// then take more than `cache_bytes`, [`with_mut`] and [`insert`] call the `on_full` callback
/// given to [`mount`](Self::mount), to start a flush, and return `Ok(None)` without changing
/// anything. An object already modified can still change, and grow over the budget.
/// - An object that alone takes more than `cache_bytes` can never be inserted or become
/// modified, as no flush can make room for it: [`with_mut`] and [`insert`] return
/// [`Error::TooBig`]. It can still be read.
///
/// # Durability
///
/// Changes reach the backend on [`flush`], [`flush_object`] for that object, or
/// [`unmount`](Self::unmount): a reset loses the rest. Each object is stored with its name. A
/// power cut during a flush leaves each object either as it was or as written, with its name: an
/// object replaced by a new one of the same name ([`remove`], then [`insert`]) stays until the new
/// one is written, and the next mount keeps the newer one if both are left.
/// With exclusive access, nothing else can reach the memory: locking it is free.
/// Names of all the stored objects, in no particular order.
/// Handle to the object `name`.
///
/// `T` must be the type the object was inserted with: [`with`] and [`with_mut`] return
/// [`Error::WrongType`] otherwise. Returns [`Error::NotFound`] if there is no object with this
/// name.
/// Inserts a new object `name` and returns its handle. The object is in RAM, and reaches the
/// backend at the next [`flush`].
///
/// Returns [`Error::AlreadyExists`] if an object with this name exists, [`Error::NameTooLong`] if
/// `name` is longer than [`MAX_NAME_LEN`](crate::MAX_NAME_LEN) bytes, `Ok(None)` if the changes
/// not flushed yet leave no room for it, and [`Error::TooBig`] if it is bigger than the whole
/// budget (see [RAM budget](ObjShelf#ram-budget)).
/// Handle to the object `name`. If there is no object with this name (as on the first boot),
/// inserts the value returned by `f` first; `f` only runs in that case, and it fails as
/// [`insert`] does.
///
/// `T` must be the type the object was inserted with, as for [`get`].
/// Removes the object of `handle`. The removal reaches the backend at the next [`flush`].
///
/// Returns [`Error::NotFound`] if it is already removed.
/// Runs `f` on the object of `handle` and returns its result. Reads the object if it is not in
/// RAM, or returns `Ok(None)` without running `f` if a flush has the storage (see
/// [Not now](ObjShelf#not-now-oknone)).
/// Runs `f` on the object of `handle` with mutable access and returns its result. Reads the
/// object if it is not in RAM. The change is in RAM when this returns, and reaches the backend at
/// the next [`flush`].
///
/// Returns `Ok(None)` without running `f` if a flush has the storage and the object is not in
/// RAM, or if the changes not flushed yet leave no room for this object, and [`Error::TooBig`]
/// if it is bigger than the whole budget (see [RAM budget](ObjShelf#ram-budget)).
/// How the backend's space is used (see [`Usage`]), as of the last storage operation.
///
/// The changes not flushed yet are not counted: modified objects count with their stored size,
/// and new ones not at all.
/// How worn the backend's storage is (see [`Wear`]), as of the last storage operation. `None` if
/// the backend doesn't track it: its storage doesn't wear out, or something else handles it.
/// Writes the changes to the backend: the modified and new objects, each with its name, then the
/// removals. Returns `Ok(None)` if another flush has the storage (this one preempted it).
///
/// Each object modified when it starts is written once, so it ends even if an interrupt keeps
/// modifying objects. An object that fails to write stays in RAM for the next flush, and the
/// others and the removals are still done, so that one object failing at every flush does not
/// block them: the first error is returned at the end.
/// Writes the object of `handle` to the backend if it is modified, with its name. The other
/// changes, removals included, stay in RAM until [`flush`].
///
/// Returns [`Error::NotFound`] if the object is removed, and `Ok(None)` if another flush has the
/// storage, as [`flush`] does. Objects that must stay consistent with each other should be
/// flushed together, with [`flush`].