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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Timekeeping using the SysTick Timer.
//!
//! **Note:** this entire module is only available if the `systick` feature is
//! present; it is on by default.
//!
//! The OS uses the Cortex-M SysTick Timer to maintain a monotonic counter
//! recording the number of milliseconds ("ticks") since boot. This module
//! provides ways to read that timer, and also to arrange for tasks to be woken
//! at specific times (such as [`sleep_until`] and [`sleep_for`]).
//!
//! To use this facility in an application, you need to call
//! [`initialize_sys_tick`] to inform the OS of the system clock speed.
//! Otherwise, no operations in this module will work properly.
//!
//! You can get the value of tick counter using [`TickTime::now`].
//!
//! # Types for describing time
//!
//! This module uses three main types for describing time, in slightly different
//! roles.
//!
//! `TickTime` represents a specific point in time, measured as a number of
//! ticks since boot (or, really, since the executor was started). It's a
//! 64-bit count of milliseconds, which means it overflows every 584 million
//! years. This lets us ignore overflows in timestamps, making everything
//! simpler. `TickTime` is analogous to `std::time::Instant` from the Rust
//! standard library.
//!
//! `Millis` represents a relative time interval in milliseconds. This uses the
//! same representation as `TickTime`, so adding them together is cheap.
//!
//! `core::time::Duration` is similar to `Millis` but with a lot more bells and
//! whistles. It's the type used to measure time intervals in the Rust standard
//! library. It can be used with most time-related API in the OS, but you might
//! not want to do so on a smaller CPU: `Duration` uses a mixed-number-base
//! format internally that means almost all operations require a 64-bit multiply
//! or divide. On machines lacking such instructions, this can become quite
//! costly (in terms of both program size and time required).
//!
//! Cases where the OS won't accept `Duration` are mostly around things like
//! sleeps, where the operation will always be performed in units of whole
//! ticks, so being able to pass (say) nanoseconds is misleading.
//!
//! # Imposing a timeout on an operation
//!
//! If you want to stop a concurrent process if it's not done by a certain time,
//! see the [`with_deadline`] function (and its relative friend,
//! [`with_timeout`]). These let you impose a deadline on any future, such that
//! if it hasn't resolved by a certain time, it will be dropped (cancelled).
//!
//! # Fixing "lost ticks"
//!
//! If the longest sequence in your application between any two `await` points
//! takes less than a millisecond, the standard timer configuration will work
//! fine and keep reliable time.
//!
//! However, if you sometimes need to do more work than that -- or if you're
//! concerned you might do so by accident due to a bug -- the systick IRQ can be
//! configured to preempt task code. The OS is designed to handle this safely.
//! For more information, see
//! [`run_tasks_with_preemption`][crate::exec::run_tasks_with_preemption].
//!
//! # Getting higher precision
//!
//! For many applications, milliseconds are a fine unit of time, but sometimes
//! you need something more precise. Currently, the easiest way to do this is to
//! enlist a different hardware timer. The `time` module has no special
//! privileges that you can't make use of, and adding your own alternate
//! timekeeping module is explictly supported in the design (this is why the
//! `"systick"` feature exists).
//!
//! This can also be useful on processors like the Nordic nRF52 series, where
//! the best sleep mode to use when idling the CPU also stops the systick timer.
//! On platforms like that, the systick isn't useful as a monotonic clock, and
//! you'll want to use some other vendor-specific timer.
//!
//! Currently there's no example of how to do this in the repo. If you need
//! this, please file an issue.
use Future;
use ;
use Pin;
use ;
use ;
use Duration;
use ;
use exception;
use pin_project;
/// Bottom 32 bits of the tick counter. Updated by ISR.
static TICK: AtomicU32 = new;
/// Top 32 bits of the tick counter. Updated by ISR.
static EPOCH: AtomicU32 = new;
/// Sets up the tick counter for 1kHz operation, assuming a CPU core clock of
/// `clock_hz`.
///
/// If you use this module in your application, call this before
/// [`run_tasks`][crate::exec::run_tasks] (or a fancier version of `run_tasks`)
/// to set up the timer for monotonic operation.
/// Represents a moment in time by the value of the system tick counter.
/// System-specific analog of `std::time::Instant`.
;
/// Add a `Duration` to a `Ticks` with normal `+` overflow behavior (i.e.
/// checked in debug builds, optionally not checked in release builds).
/// A period of time measured in milliseconds.
///
/// This plays a role similar to `core::time::Duration` but is designed to be
/// cheaper to use. In particular, as of this writing, `Duration` insists on
/// converting times to and from a Unix-style (seconds, nanoseconds)
/// representation internally. This means that converting to or from any simple
/// monotonic time -- even in nanoseconds! -- requires a 64-bit division or
/// multiplication. Many useful processors, such as Cortex-M0, don't have 32-bit
/// division, much less 64-bit division.
///
/// `Millis` wraps a `u64` and records a number of milliseconds. Since
/// milliseconds are `lilos`'s unit used for internal timekeeping, this ensures
/// that a `Millis` can be used for any deadline or timeout computation without
/// any unit conversions or expensive arithmetic operations.
;
/// Adds a number of milliseconds to a `TickTime` with normal `+` overflow
/// behavior (i.e. checked in debug builds, optionally not checked in release
/// builds).
/// Adds a number of milliseconds to a `TickTime` with normal `+=` overflow
/// behavior (i.e. checked in debug builds, optionally not checked in release
/// builds).
/// Sleeps until the system time is equal to or greater than `deadline`.
///
/// More precisely, `sleep_until(d)` returns a `Future` that will poll as
/// `Pending` until `TickTime::now() >= deadline`; then it will poll `Ready`.
///
/// If `deadline` is already in the past, this will instantly become `Ready`.
///
/// Other tools you might consider:
///
/// - If you want to sleep for a relative time interval, consider [`sleep_for`].
/// - If you want to make an action periodic by sleeping in a loop,
/// [`PeriodicGate`] helps avoid common mistakes that cause timing drift and
/// jitter.
/// - If you want to impose a deadline/timeout on async code, see
/// [`with_deadline`].
///
/// # Preconditions
///
/// This can only be used within a task.
///
/// # Cancellation
///
/// **Cancel safety:** Strict.
///
/// Dropping this future does nothing in particular.
pub async
/// Sleeps until the system time has increased by `d`.
///
/// More precisely, `sleep_for(d)` captures the system time, `t`, and returns a
/// `Future` that will poll as `Pending` until `TickTime::now() >= t + d`; then
/// it will poll `Ready`.
///
/// If `d` is 0, this will instantly become `Ready`.
///
/// `d` can be any type that can be added to a `TickTime`, which in practice
/// means either [`Millis`] or [`Duration`].
///
/// This function is a thin wrapper around [`sleep_until`]. See that function's
/// docs for examples, details, and alternatives.
///
/// # Cancellation
///
/// **Cancel safety:** Strict.
///
/// Dropping this future does nothing in particular.
/// Alters a future to impose a deadline on its completion.
///
/// Concretely,
/// - The output type is changed from `T` to `Option<T>`.
/// - If the future resolves on any polling that starts before `deadline`, its
/// result will be produced, wrapped in `Some`.
/// - If poll is called at or after `deadline`, the future resolves to `None`.
///
/// The wrapped future is _not_ immediately dropped if the timeout expires. It
/// will be dropped when you drop the wrapped version. Under normal
/// circumstances this happens automatically, e.g. if you do:
///
/// ```ignore
/// with_deadline(MY_DEADLINE, some_operation()).await;
/// ```
///
/// In this case, `await` drops the future as soon as it resolves (as always),
/// which means the nested `some_operation()` future will be promptly dropped
/// when we notice that the deadline has been met or exceeded.
/// Alters a future to impose a timeout on its completion.
///
/// This is equivalent to [`with_deadline`] using a deadline of `TickTime::now()
/// \+ timeout`. That is, the current time is captured when `with_timeout` is
/// called (_not_ at first poll), the provided timeout is added, and that's used
/// as the deadline for the returned future.
///
/// See [`with_deadline`] for more details.
/// A future-wrapper that gates polling a future `B` on whether another
/// future `A` has resolved.
///
/// Once `A` resolved, `B` is no longer polled and the combined future
/// resolves to `None`. If `B` resolves first, its result is produced
/// wrapped in `Some`.
/// Helper for doing something periodically, accurately.
///
/// A `PeriodicGate` can be used to *gate* (pause) execution of a task until a
/// point in time arrives; that point in time is *periodic*, meaning it repeats
/// at regular intervals. For example, to call the function `f` every 30
/// milliseconds, you would write:
///
/// ```ignore
/// let mut gate = PeriodicGate::from(Millis(30));
/// loop {
/// f();
/// gate.next_time().await;
/// }
/// ```
///
/// This will maintain the 30-millisecond interval consistently, even if `f()`
/// takes several milliseconds to run, and even if `f()` is sometimes fast and
/// sometimes slow. (If `f` sometimes takes more than 30 milliseconds, the next
/// execution will happen later than normal -- there's not a lot we can do about
/// that. However, as soon as calls to `f` take less than 30 milliseconds, we'll
/// return to the normal periodic timing.)
///
/// This is often, but not always, what you want in a timing loop.
///
/// - `PeriodicGate` has "catch-up" behavior that might not be what you want: if
/// one execution takes (say) 5 times longer than the chosen period, it will
/// frantically run 4 more just after it to "catch up." This attempts to
/// maintain a constant number of executions per unit time, but that might not
/// be what you want. (Note that you can _detect_ the "catch-up" behavior by
/// calling [`PeriodicGate::is_lagging`].)
///
/// - [`sleep_for`] can ensure a minimum delay _between_ operations, which is
/// different from `PeriodicGate`'s behavior.
/// System tick ISR. Advances the tick counter. This doesn't wake any tasks; see
/// code in `exec` for that.