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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// 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/.
//! The async runtime executor, plus inter-task communication tools.
//!
//! **Note:** for our purposes, a _task_ is an independent top-level future
//! managed by the executor polling loop. There is a fixed set of tasks,
//! provided to the executor at startup. This is distinct from the casual use
//! of "task" to mean a piece of code that runs concurrently with other code;
//! we'll use the term "concurrent process" for this. The fixed set of tasks
//! managed by the scheduler can execute an _arbitrary number_ of concurrent
//! processes using operations like `join` and `select`.
//!
//!
//! # Starting the executor / operating system
//!
//! The mechanism for "starting the OS" is [`run_tasks`]. That's the right
//! choice for most applications.
//!
//! `run_tasks` is a wrapper around fancier API, which you can use directly in
//! special circumstances:
//!
//! - If you need faster interrupt response, consider allowing some interrupts
//! to preempt task code using [`run_tasks_with_preemption`].
//! - If you need code to run when no other tasks are ready -- which can be
//! useful for putting the CPU into a low power state, or toggling a pin to
//! signal CPU load on a logic analyzer -- see [`run_tasks_with_idle`]
//! - Finally, if you want to turn on all the bells and whistles, you can use
//! [`run_tasks_with_preemption_and_idle`] which combines the previous two.
//!
//!
//! # Interrupts, wait, and notify
//!
//! So, you've given the OS an array of tasks that need to each be polled
//! forever. The OS could simply poll every task in a big loop (a pattern known
//! in embedded development as a "superloop"), but this has some problems:
//!
//! 1. By constantly checking whether each task can make progress, we keep the
//! CPU running full-tilt, burning power needlessly.
//!
//! 2. Because any given task may have to wait for *every other task* to be
//! polled before it gets control, the minimum response latency to events is
//! increased, possibly by a lot.
//!
//! We can do better.
//!
//! There are, in practice, two reasons why a task might yield.
//!
//! 1. Because it has more work to do immediately, but wants to leave room for
//! other tasks to execute during a long-running operation. In this case, we
//! actually *do* want to come right back and poll the task. (To do this, use
//! [`yield_cpu`].)
//!
//! 2. Because it is waiting for an event -- a particular timer tick, an
//! interrupt from a peripheral, a signal from another task, etc. In this
//! case, we don't need to poll the task again *until that event occurs.*
//!
//! The OS tracks a *wake bit* per task. When this bit is set, it means that
//! the task should be polled. Each time through the outer poll loop, the OS
//! will determine which tasks have their wake bits set, *clear the wake bits*,
//! and then poll the tasks.
//!
//! (Tasks might be polled even when their bit isn't set -- this is a waste of
//! energy, but is also something that Rust `Future`s are expected to tolerate.
//! Giving the OS some slack on this dramatically simplifies the implementation.
//! However, the OS tries to poll the smallest feasible set of tasks each time
//! it polls.)
//!
//! The need to set and check wake bits is embodied by the [`Notify`] type,
//! which provides a kind of event broadcast. Tasks can subscribe to a `Notify`,
//! and when it is signaled, all subscribed tasks get their wake bits set -- so
//! they will be polled at the next opportunity.
//!
//! `Notify` is very low level -- the more pleasant abstractions of
//! [`spsc::Queue`][crate::spsc], [`mutex`][crate::mutex], and even
//! [`sleep_until`][crate::time::sleep_until]/[`sleep_for`][crate::time::sleep_for]
//! are built on top of it. However, `Notify` is the only OS facility that's
//! safe to use from interrupt service routines, making it an ideal way to wake
//! tasks when hardware events occur. See the [`Notify`] docs for an example of
//! using this to handle events from a UART.
//!
//!
//! # Idle behavior
//!
//! When no tasks have their wake bits set, the default behavior is to idle the
//! processor using the `WFI` instruction. You can override this behavior by
//! starting the scheduler with [`run_tasks_with_idle`] or (if you're using
//! preemption, below) [`run_tasks_with_preemption_and_idle`], which let you
//! substitute a custom "idle hook" to execute when no tasks are ready.
//!
//! A common use for such an idle hook is to toggle a pin to indicate CPU usage
//! on a logic analyzer, enter a vendor-specific deep-sleep mode, or feed a
//! watchdog.
//!
//!
//! # Building your own task notification mechanism
//!
//! If `Notify` doesn't meet your needs, you can use the [`wake_task_by_index`]
//! and [`wake_tasks_by_mask`] functions to explicitly wake one or more tasks.
//! Because tasks are required to tolerate spurious wakeups, both of these
//! functions are safe: spamming tasks with wakeup requests merely wastes
//! energy and time.
//!
//! Both of these functions expose the fact that the scheduler tracks wake bits
//! in a single `usize`. When waking a task with index 0 (mask `1 << 0`), we're
//! actually waking any task where `index % 32 == 0`. Very complex systems with
//! greater than 32 top-level tasks will thus experience more spurious wakeups.
//! The advantage of this "lossy" technique is that wake bit manipulation is
//! very, very cheap, and can be done entirely with processor atomic operations.
//!
//! For an example of how to do this, read the source code for `Notify` -- it's
//! written entirely in terms of public API, so if you want to do something
//! similar that `Notify` itself doesn't support, you can start by copying it.
//!
//!
//! # Adding preemption
//!
//! By default, the scheduler does not preempt task code: task poll routines are
//! run cooperatively, and ISRs are allowed only in between polls. This
//! increases interrupt response latency, because if an event occurs while
//! polling tasks, all polling must complete before the ISR is run. However, it
//! makes the program much easier to reason about, because code is simply never
//! preempted.
//!
//! Applications can change this by starting the scheduler with
//! [`run_tasks_with_preemption`] or [`run_tasks_with_preemption_and_idle`].
//! These entry points let you set a _preemption policy_, which allows ISRs
//! above some priority level to preempt task code. (Tasks still cannot preempt
//! one another.)
//!
//! The more basic [`run_tasks`] operation is written in terms of
//! [`run_tasks_with_preemption_and_idle`], so if you would like to see how to
//! convert your use of `run_tasks` to the more complex form, start by copying
//! the code from `run_tasks`.
use Infallible;
use Future;
use mem;
use Pin;
use ;
use ;
use pin_project;
use crateCaptures;
// Despite the untangling of exec and time that happened in the 1.0 release, we
// still have some intimate dependencies between the modules. You'll see a few
// other cfg(feature = "systick") lines below.
cfg_if!
/// Accumulates bitmasks from wakers as they are invoked. The executor
/// atomically checks and clears this at each iteration.
static WAKE_BITS: AtomicUsize = new;
/// Computes the wake bit mask for the task with the given index, which is
/// equivalent to `1 << (index % USIZE_BITS)`.
const
/// VTable for our wakers. Our wakers store a task notification bitmask in their
/// "pointer" member, and atomically OR it into `WAKE_BITS` when invoked.
static VTABLE: RawWakerVTable = new;
/// Produces a `Waker` that will wake *at least* task `index` on invocation.
///
/// Technically, this will wake any task `n` where `n % 32 == index % 32`.
/// Exploits our known Waker structure to extract the notification mask from a
/// Waker.
///
/// If this is applied to a Waker that isn't from this executor (specifically,
/// one not generated by `waker_for_task`), this will cause spurious and almost
/// certainly incorrect wakeups. Currently I don't feel like that risk is great
/// enough to mark this unsafe -- it can't violate *memory* safety for certain.
///
/// In practice this function compiles down to a single inlined load
/// instruction.
/// Used to construct wakers do nothing, as a placeholder.
static NOOP_VTABLE: RawWakerVTable = new;
/// Returns a [`Waker`] that doesn't do anything and costs nothing to `clone`.
///
/// This is useful as a placeholder before a *real* `Waker` becomes available.
/// You probably don't need this unless you're building your own wake lists.
/// Polls `future` in a context where the `Waker` will signal the task with
/// index `index`.
/// Selects an interrupt control strategy for the scheduler.
///
/// This is used as an argument to [`run_tasks_with_preemption`] and
/// [`run_tasks_with_preemption_and_idle`].
/// Runs the given futures forever, sleeping when possible. Each future acts as
/// a task, in the sense of `core::task` -- that is, it is a top-level entity
/// that can wake up separately from the other tasks.
///
/// Task futures must not ever resolve/complete -- they need to be infinite
/// loops or equivalent. Due to limitations in the language, this requires their
/// return type to be [`Infallible`], which is an awkward way of writing `!`.
///
/// Not all tasks are polled every time through the loop. On the first
/// iteration, only the tasks with a corresponding bit set in `initial_mask` are
/// polled; on subsequent passes, only tasks awoken by the *previous* iteration
/// are called.
///
/// Any time polling completes with *no* tasks awoken, code will never run again
/// unless an interrupt handler wakes tasks using `Notify`. And so, when we
/// detect this condition, we use the `WFI` instruction to idle the processor
/// until an interrupt arrives. This has the advantages of using less power and
/// having more predictable response latency than spinning. If you'd like to
/// override this behavior, see [`run_tasks_with_idle`].
!
/// Extended version of `run_tasks` that replaces the default idle behavior
/// (sleeping until the next interrupt) with code of your choosing.
///
/// If you would like the processor to sleep when idle, you will need to call
/// WFI yourself from within the implementation of `idle_hook`.
///
/// See [`run_tasks`] for more details.
!
/// Extended version of `run_tasks` that configures the scheduler with a custom
/// interrupt policy.
///
/// Passing `Interrupts::Masked` here gets the same behavior as `run_tasks`.
///
/// Passing `Interrupts::Filtered(p)` causes the scheduler to only disable
/// interrupts with priority equal to or numerically greater than `p`. See the
/// docs for the [`Interrupts`] type for more details.
///
/// # Safety
///
/// This can be used safely as long as ISRs and task code that share data
/// structures use appropriate critical sections. If the only preemption you're
/// enabling is the OS's built-in SysTick ISR, it's intrinsically safe and you
/// can meet this contract trivially -- just make sure you've set the priority
/// levels for your other interrupts appropriately!
///
/// Note that none of the top-level functions in this module are safe to use
/// from a custom ISR. Only operations on types that are specifically described
/// as being ISR safe, such as `Notify::notify`, can be used from ISRs.
pub unsafe !
/// Extended version of `run_tasks` that configures the scheduler with a custom
/// interrupt policy and idle hook. See [`run_tasks`] for more information about
/// the basic behavior.
///
/// Passing `Interrupts::Masked` here gets the same behavior as
/// `run_tasks_with_idle`.
///
/// Passing `Interrupts::Filtered(p)` causes the scheduler to only disable
/// interrupts with priority equal to or numerically greater than `p`. This can
/// be used to ensure that the OS systick ISR (priority 0, by default) can
/// preempt long-running tasks.
///
/// # Safety
///
/// This can be used safely as long as ISRs and task code that share data
/// structures use appropriate critical sections. If the only preemption you're
/// enabling is the OS's built-in SysTick ISR, it's intrinsically safe and you
/// can meet this contract trivially -- just make sure you've set the priority
/// levels for your other interrupts appropriately!
///
/// Note that none of the top-level functions in this module are safe to use
/// from a custom ISR. Only operations on types that are specifically described
/// as being ISR safe, such as `Notify::notify`, can be used from ISRs.
pub unsafe !
/// This `static` variable is only written by the OS, and never read. It exists
/// to be observed from a debugger.
///
/// Without this, it's really hard to figure out where the official list of
/// tasks is. We don't put the list of tasks *itself* in a `static` because we
/// can't predict its size (it's up to the client). We don't use this `static`
/// as _our_ sense of the task list because, well, we don't have to.
///
/// The fact that we don't _read_ this variable dodges most lifetime/safety
/// issues.
///
/// Note that the `#[used]` annotation is load-bearing here -- without it the
/// compiler will happily throw the variable away, confusing the debugger.
static mut TASK_FUTURES: = None;
/// Constant that can be passed to `run_tasks` and `wake_tasks_by_mask` to mean
/// "all tasks."
pub const ALL_TASKS: usize = !0;
/// A lightweight task notification scheme that can be used to safely route
/// events from interrupt handlers to task code.
///
/// This is the lowest level inter-task communication type in `lilos`, and is
/// appropriate if you're building your own higher-level mechanism, or if you
/// want to signal events from interrupt service routines.
///
/// Any number of tasks can [`subscribe`][Notify::subscribe] to a `Notify`. When
/// [`notify`][Notify::notify] is called on it, all those tasks will be awoken
/// (i.e. their `Waker` will be triggered so that they become eligible for
/// polling), and their subscription is atomically ended. Because spurious wakes
/// are possible, the subscribed tasks may wake before `notify` is called. To
/// check if the desired condition has truly occurred, you'll generally want to
/// call [`until`][Notify::until] instead of using `subscribe` directly.
///
/// A `Notify` is very small (the size of a pointer), so feel free to create as
/// many as you like.
///
/// It is safe to call `notify` from an ISR, so this is the usual method by
/// which interrupt handlers inform task code of events. Normally a `Notify`
/// used in this way is stored in a `static`:
///
/// ```ignore
/// static EVENT: Notify = Notify::new();
/// ```
///
/// You can use that style of `static` `Notify` to sleep waiting for interrupt
/// conditions in async code. Here's an example for a made-up but typical UART
/// driver:
///
/// ```ignore
/// /// Event signal for waking task(s) when data arrives.
/// static RX_NOT_EMPTY: Notify = Notify::new();
///
/// /// UART interrupt handler.
/// #[interrupt]
/// fn UART() {
/// let uart = get_uart_peripheral_somehow();
///
/// let control = uart.control.read();
/// let status = uart.status.read();
///
/// if control.rx_irq_enabled() && status.rx_not_empty() {
/// // Shut off the interrupt source to keep this from reoccurring.
/// uart.control.modify(|_, w| w.rx_irq_enabled().clear());
/// // Wake up the task that requested this.
/// RX_NOT_EMPTY.notify();
/// }
/// }
///
/// async fn uart_recv(uart: &Uart) -> u8 {
/// // Enable the rx data interrupt so we get notified.
/// uart.control.modify(|_, w| w.rx_irq_enabled().set());
/// // Listen for data, using a predicate to filter out spurious wakes.
/// RX_NOT_EMPTY.until(|| uart.status.read().rx_not_empty()).await;
///
/// UART.data.read()
/// }
/// ```
///
/// # Waker coalescing
///
/// A `Notify` collects any number of task `Waker`s into a fixed-size structure
/// without heap allocation. It does this by coalescing the `Waker`s such that
/// they may become *imprecise*: firing the waker for task N may also spuriously
/// wake task M, if `M % 32 == N % 32`. (Implementation-wise, this is a matter
/// of collecting a wake bits mask from the wakers using secret knowledge.)
///
/// While this is often not the *ideal* strategy, it has the advantage that it
/// can be built up cheaply and torn down atomically from interrupt context.
/// (Contrast with e.g. a list of waiting tasks, which is more precise but
/// harder to get right and more expensive at runtime.)
///
/// For more nuanced use cases -- precisely waking a single task, waking tasks
/// in a particular order, waking groups of tasks together, etc. -- see the
/// [`list`][crate::list] module -- though note that `list` cannot be used from
/// an ISR.
/// Trait implemented by things that indicate success or failure, to be used
/// with [`Notify::until`] and friends.
///
/// In practice this is `bool` (if there's no output associated with success) or
/// `Option<T>` (if there is).
///
/// This is used by the various polling functions in this module.
/// Internal future type used to implement `Notify::until`. This makes it
/// much easier to recognize the future in a debugger.
/// Internal future type used to implement `Notify::until_racy`. This makes
/// it much easier to recognize the future in a debugger.
/// Notifies the executor that any tasks whose wake bits are set in `mask`
/// should be polled on the next iteration.
///
/// This is a very low-level operation and is rarely what you want to use. See
/// `Notify`.
/// Notifies the executor that the task with the given `index` should be polled
/// on the next iteration.
///
/// This operation isn't precise: it may wake other tasks, but it is guaranteed
/// to at least wake the desired task.
/// Tracks whether the timer list has been initialized.
static TIMER_LIST_READY: AtomicBool = new;
/// Storage for the timer list.
static mut TIMER_LIST: = uninit;
/// Panics if called from an interrupt service routine (ISR). This is used to
/// prevent OS features that are unavailable to ISRs from being used in ISRs.
/// Nabs a reference to the global timer list.
///
/// # Preconditions
///
/// - Must not be called from an interrupt.
/// - Must only be called once the timer list has been initialized, which is to
/// say, from within a task.
pub
/// Returns a future that will be pending exactly once before resolving.
///
/// This can be used to give up CPU to any other tasks that are currently ready
/// to run, and then take it back without waiting for an event.
///
/// # Cancellation
///
/// **Cancel safety:** Strict.
///
/// Dropping this future does nothing in particular.