Merge pull request #98 from fhars/nrf52-fix

fix nrf52 layout
diff --git a/.travis.yml b/.travis.yml
index 26f22ef..a8f2e6e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,14 +1,16 @@
 language: rust
 rust:
-  - nightly-2019-09-19
+  - nightly-2019-11-06
 
 os:
   - linux
+  - osx
 
 cache: rust
 
 install:
   - rustup target add thumbv7em-none-eabi
+  - rustup target add riscv32imc-unknown-none-elf
   - rustup component add rustfmt-preview
 
 script:
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..3b7a700
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,15 @@
+# Releases
+
+## 0.2.0 (WIP)
+
+- Many functions, including `main()` are asynchronous
+  - To retrieve the value of an asynchronous `value`, use `value.await`
+  - This is only possible within an `async fn`, so either
+    - Make the caller `fn` of `.await` an `async fn`
+    - Not recommended: Use `core::executor::block_on(value)` to retrieve the `value`
+- `syscalls::yieldk_for` is no longer available
+  - Yielding manually is discouraged as it conflicts with Rust's safety guarantees. If you need to wait for a condition, use `futures::wait_until` and `.await`.
+
+## a8bb4fa9be504517d5533511fd8e607ea61f1750 (0.1.0)
+
+- First and highly experimental `libtock-rs` API
\ No newline at end of file
diff --git a/Cargo.toml b/Cargo.toml
index e49e699..2f57f11 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,18 +1,20 @@
 [package]
 name = "libtock"
-version = "0.1.0"
+version = "0.2.0"
 authors = ["Tock Project Developers <tock-dev@googlegroups.com>"]
 license = "MIT/Apache-2.0"
 edition = "2018"
 
 [dependencies]
-linked_list_allocator = "0.6.3"
+core = { package = "async-support", path = "async-support" }
+linked_list_allocator = { version = "0.6.4", default-features = false }
 
 [dev-dependencies]
 corepack = { version = "0.4.0", default-features = false, features = ["alloc"] }
 # We pin the serde version because newer serde versions may not be compatible
 # with the nightly toolchain used by libtock-rs.
 serde = { version = "=1.0.84", default-features = false, features = ["derive"] }
+futures = { version = "0.3.1", default-features = false, features = ["unstable", "cfg-target-has-atomic"] }
 
 [profile.dev]
 panic = "abort"
diff --git a/README.md b/README.md
index 8ced327..4f60505 100644
--- a/README.md
+++ b/README.md
@@ -69,15 +69,12 @@
 ```rust
 #![no_std]
 
-extern crate tock;
-
-fn main() {
+async fn main() {
   // Your code
 }
 ```
 If you want to use heap based allocation you will have to add
 ```rust
-#![feature(alloc)]
 extern crate alloc;
 ```
 to the preamble.
diff --git a/async-support/Cargo.toml b/async-support/Cargo.toml
new file mode 100644
index 0000000..9287c6b
--- /dev/null
+++ b/async-support/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "async-support"
+version = "0.1.0"
+authors = ["Woyten <woyten.tielesch@online.de>"]
+edition = "2018"
+description = "`libtock` specific patch of `core` for `async`-`await` syntax in a `#![no_std]` environment. It implements the methods `core::future::poll_with_tls_context` and `core::future::from_generator` which are currently missing in `core`."
+
+[dependencies]
diff --git a/async-support/src/lib.rs b/async-support/src/lib.rs
new file mode 100644
index 0000000..7d36820
--- /dev/null
+++ b/async-support/src/lib.rs
@@ -0,0 +1,106 @@
+#![feature(generator_trait)]
+#![no_std]
+
+pub use core::*;
+
+pub mod future {
+    pub use core::future::Future;
+    use core::ops::Generator;
+    use core::pin::Pin;
+    use core::task::Poll;
+
+    pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
+    where
+        F: Future,
+    {
+        crate::executor::poll(f)
+    }
+
+    pub fn from_generator<G: Generator<Yield = ()>>(
+        generator: G,
+    ) -> impl Future<Output = G::Return> {
+        crate::executor::from_generator(generator)
+    }
+}
+
+pub mod executor {
+    use core::future::Future;
+    use core::ops::Generator;
+    use core::ops::GeneratorState;
+    use core::pin::Pin;
+    use core::ptr;
+    use core::task::Context;
+    use core::task::Poll;
+    use core::task::RawWaker;
+    use core::task::RawWakerVTable;
+    use core::task::Waker;
+
+    extern "Rust" {
+        #[link_name = "libtock::syscalls::yieldk"]
+        fn yieldk();
+    }
+
+    pub fn block_on<T>(mut future: impl Future<Output = T>) -> T {
+        // Contract described in the Rustdoc: "A value, once pinned, must remain pinned forever (...).".
+        // IOW calling Pin::new_unchecked is safe as long as no &mut future is leaked after pinning.
+        let mut pinned_future = unsafe { Pin::new_unchecked(&mut future) };
+
+        loop {
+            match poll(pinned_future.as_mut()) {
+                Poll::Pending => unsafe { yieldk() },
+                Poll::Ready(value) => {
+                    return value;
+                }
+            }
+        }
+    }
+
+    pub(crate) fn poll<F: Future>(pinned_future: Pin<&mut F>) -> Poll<F::Output> {
+        let waker = unsafe { Waker::from_raw(get_dummy_waker()) };
+        let mut context = Context::from_waker(&waker);
+        pinned_future.poll(&mut context)
+    }
+
+    // Since Tock OS comes with waking-up functionality built-in, we use dummy wakers that do nothing at all.
+    fn get_dummy_waker() -> RawWaker {
+        fn clone(_x: *const ()) -> RawWaker {
+            get_dummy_waker()
+        }
+
+        fn do_nothing(_x: *const ()) {}
+
+        // This vtable implements the methods required for managing the lifecycle of the wakers.
+        // Our wakers are dummies, so those functions don't do anything.
+        static DUMMY_WAKER_VTABLE: RawWakerVTable =
+            RawWakerVTable::new(clone, do_nothing, do_nothing, do_nothing);
+
+        // The wakers don't have any implementation, so the instance can simply be null.
+        RawWaker::new(ptr::null(), &DUMMY_WAKER_VTABLE)
+    }
+
+    pub(crate) fn from_generator<G: Generator<Yield = ()>>(
+        generator: G,
+    ) -> impl Future<Output = G::Return> {
+        GeneratorFuture { generator }
+    }
+
+    struct GeneratorFuture<G> {
+        generator: G,
+    }
+
+    impl<G: Generator<Yield = ()>> Future for GeneratorFuture<G> {
+        type Output = G::Return;
+
+        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+            // Pin::map_unchecked_mut is safe as long as the move and drop guarantees are propagated through the mapping.
+            // This is trivially satisfied since our future is only a newtype decorator of the generator.
+            let pinned_generator =
+                unsafe { self.map_unchecked_mut(|future| &mut future.generator) };
+
+            match pinned_generator.resume() {
+                GeneratorState::Yielded(()) => Poll::Pending,
+                GeneratorState::Complete(out) => Poll::Ready(out),
+            }
+        }
+    }
+}
diff --git a/build_examples.sh b/build_examples.sh
index af5057c..dbaeb56 100755
--- a/build_examples.sh
+++ b/build_examples.sh
@@ -3,3 +3,4 @@
 set -eux
 
 cargo build --release --target=thumbv7em-none-eabi --examples
+cargo build --release --target=riscv32imc-unknown-none-elf --examples # Important for tests: This target does not support atomics
diff --git a/examples/adc.rs b/examples/adc.rs
index 8ba602b..202270f 100644
--- a/examples/adc.rs
+++ b/examples/adc.rs
@@ -6,7 +6,7 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
     let mut with_callback = adc::with_callback(|channel: usize, value: usize| {
         writeln!(console, "channel: {}, value: {}", channel, value).unwrap();
@@ -16,6 +16,6 @@
 
     loop {
         adc.sample(0).unwrap();
-        timer::sleep(Duration::from_ms(2000));
+        timer::sleep(Duration::from_ms(2000)).await;
     }
 }
diff --git a/examples/adc_buffer.rs b/examples/adc_buffer.rs
index c313bde..a725804 100644
--- a/examples/adc_buffer.rs
+++ b/examples/adc_buffer.rs
@@ -7,7 +7,7 @@
 use libtock::syscalls;
 
 /// Reads a 128 byte sample into a buffer and prints the first value to the console.
-fn main() {
+async fn main() {
     let mut console = Console::new();
     let mut adc_buffer = AdcBuffer::new();
     let mut temp_buffer = [0; libtock::adc::BUFFER_SIZE];
diff --git a/examples/async.rs b/examples/async.rs
new file mode 100644
index 0000000..f4cc9e7
--- /dev/null
+++ b/examples/async.rs
@@ -0,0 +1,40 @@
+#![no_std]
+
+use futures::future;
+use libtock::buttons;
+use libtock::buttons::ButtonState;
+use libtock::futures as libtock_futures;
+use libtock::led;
+use libtock::timer;
+use libtock::timer::Duration;
+
+async fn main() {
+    future::join(blink_periodically(), blink_on_button_press()).await;
+}
+
+async fn blink_periodically() {
+    let led = led::get(0).unwrap();
+    loop {
+        timer::sleep(Duration::from_ms(250)).await;
+        led.on();
+        timer::sleep(Duration::from_ms(250)).await;
+        led.off();
+    }
+}
+
+async fn blink_on_button_press() {
+    let mut with_callback = buttons::with_callback(|_, _| {});
+    let mut buttons = with_callback.init().unwrap();
+    let mut button = buttons.iter_mut().next().unwrap();
+    let button = button.enable().unwrap();
+    let led = led::get(1).unwrap();
+
+    loop {
+        libtock_futures::wait_until(|| button.read() == ButtonState::Released).await;
+        libtock_futures::wait_until(|| button.read() == ButtonState::Pressed).await;
+        led.on();
+        libtock_futures::wait_until(|| button.read() == ButtonState::Released).await;
+        libtock_futures::wait_until(|| button.read() == ButtonState::Pressed).await;
+        led.off();
+    }
+}
diff --git a/examples/ble_scanning.rs b/examples/ble_scanning.rs
index 451953f..f32b7ec 100644
--- a/examples/ble_scanning.rs
+++ b/examples/ble_scanning.rs
@@ -16,7 +16,7 @@
 
 // Prevents the compiler from dropping the subscription too early.
 #[allow(unreachable_code)]
-fn main() {
+async fn main() {
     let mut shared_buffer = BleDriver::create_scan_buffer();
     let mut my_buffer = BleDriver::create_scan_buffer();
     let shared_memory = BleDriver::share_memory(&mut shared_buffer).unwrap();
diff --git a/examples/blink.rs b/examples/blink.rs
index 8e8980e..b731dd7 100644
--- a/examples/blink.rs
+++ b/examples/blink.rs
@@ -4,7 +4,7 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let num_leds = led::count();
 
     // Blink the LEDs in a binary count pattern and scale
@@ -21,6 +21,6 @@
         count = count.wrapping_add(1);
 
         // This delay uses an underlying timer in the kernel.
-        timer::sleep(Duration::from_ms(250));
+        timer::sleep(Duration::from_ms(250)).await;
     }
 }
diff --git a/examples/blink_random.rs b/examples/blink_random.rs
index d114d39..48bbf5f 100644
--- a/examples/blink_random.rs
+++ b/examples/blink_random.rs
@@ -5,20 +5,20 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let num_leds = led::count();
     // blink_nibble assumes 4 leds.
     assert_eq!(num_leds, 4);
 
     let mut buf = [0; 64];
     loop {
-        assert!(rng::fill_buffer(&mut buf));
+        assert!(rng::fill_buffer(&mut buf).await);
 
         for &x in buf.iter() {
             blink_nibble(x);
-            timer::sleep(Duration::from_ms(100));
+            timer::sleep(Duration::from_ms(100)).await;
             blink_nibble(x >> 4);
-            timer::sleep(Duration::from_ms(100));
+            timer::sleep(Duration::from_ms(100)).await;
         }
     }
 }
diff --git a/examples/button_leds.rs b/examples/button_leds.rs
index 2ab7615..bb85422 100644
--- a/examples/button_leds.rs
+++ b/examples/button_leds.rs
@@ -3,10 +3,9 @@
 use libtock::buttons;
 use libtock::buttons::ButtonState;
 use libtock::led;
-use libtock::timer;
-use libtock::timer::Duration;
+use libtock::syscalls;
 
-fn main() {
+async fn main() {
     let mut with_callback = buttons::with_callback(|button_num: usize, state| {
         let i = button_num as isize;
         match state {
@@ -22,6 +21,6 @@
     }
 
     loop {
-        timer::sleep(Duration::from_ms(500));
+        syscalls::yieldk();
     }
 }
diff --git a/examples/button_read.rs b/examples/button_read.rs
index 539fa6c..336955d 100644
--- a/examples/button_read.rs
+++ b/examples/button_read.rs
@@ -7,7 +7,7 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
     let mut with_callback = buttons::with_callback(|_, _| {});
     let mut buttons = with_callback.init().unwrap();
@@ -20,6 +20,6 @@
             ButtonState::Released => writeln!(console, "released"),
         }
         .unwrap();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/button_subscribe.rs b/examples/button_subscribe.rs
index 6644e8d..8616809 100644
--- a/examples/button_subscribe.rs
+++ b/examples/button_subscribe.rs
@@ -4,11 +4,10 @@
 use libtock::buttons;
 use libtock::buttons::ButtonState;
 use libtock::console::Console;
-use libtock::timer;
-use libtock::timer::Duration;
+use libtock::syscalls;
 
 // FIXME: Hangs up when buttons are pressed rapidly - problem in console?
-fn main() {
+async fn main() {
     let mut console = Console::new();
 
     let mut with_callback = buttons::with_callback(|button_num: usize, state| {
@@ -31,6 +30,6 @@
     }
 
     loop {
-        timer::sleep(Duration::from_ms(500));
+        syscalls::yieldk();
     }
 }
diff --git a/examples/gpio.rs b/examples/gpio.rs
index a09a2b2..4d5b9a4 100644
--- a/examples/gpio.rs
+++ b/examples/gpio.rs
@@ -5,14 +5,14 @@
 use libtock::timer::Duration;
 
 // Example works on P0.03
-fn main() {
+async fn main() {
     let pin = GpioPinUnitialized::new(0);
     let pin = pin.open_for_write().unwrap();
 
     loop {
         pin.set_high();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
         pin.set_low();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/gpio_read.rs b/examples/gpio_read.rs
index a5d7f5b..5c18f62 100644
--- a/examples/gpio_read.rs
+++ b/examples/gpio_read.rs
@@ -7,7 +7,7 @@
 use libtock::timer::Duration;
 
 // example works on p0.03
-fn main() {
+async fn main() {
     let mut console = Console::new();
     let pin = GpioPinUnitialized::new(0);
     let pin = pin.open_for_read(None, InputMode::PullDown).unwrap();
@@ -18,6 +18,6 @@
         } else {
             writeln!(console, "false").unwrap();
         }
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/hardware_test.rs b/examples/hardware_test.rs
index c224f58..a0f1bdb 100644
--- a/examples/hardware_test.rs
+++ b/examples/hardware_test.rs
@@ -29,7 +29,7 @@
     }
 }
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
     write!(console, "[test-results]\n").unwrap();
 
diff --git a/examples/hello.rs b/examples/hello.rs
index a1e30f2..c95bbd8 100644
--- a/examples/hello.rs
+++ b/examples/hello.rs
@@ -5,11 +5,11 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
 
     for i in 0.. {
         writeln!(console, "Hello world! {}", i).unwrap();
-        timer::sleep(Duration::from_ms(500))
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/panic.rs b/examples/panic.rs
index 4368415..8c58ac4 100644
--- a/examples/panic.rs
+++ b/examples/panic.rs
@@ -1,6 +1,6 @@
 #![no_std]
 
-fn main() {
+async fn main() {
     let _ = libtock::LibTock {};
     panic!("Bye world!");
 }
diff --git a/examples/sensors.rs b/examples/sensors.rs
index 7b3afd3..acd36e9 100644
--- a/examples/sensors.rs
+++ b/examples/sensors.rs
@@ -6,7 +6,7 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
     let mut humidity = HumiditySensor;
     let mut temperature = TemperatureSensor;
@@ -17,6 +17,6 @@
         writeln!(console, "Temperature: {}\n", temperature.read()).unwrap();
         writeln!(console, "Light:       {}\n", light.read()).unwrap();
         writeln!(console, "Accel:       {}\n", ninedof.read_acceleration()).unwrap();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/seven_segment.rs b/examples/seven_segment.rs
index 9f767e6..9e5752d 100644
--- a/examples/seven_segment.rs
+++ b/examples/seven_segment.rs
@@ -22,7 +22,7 @@
 }
 
 // Example works on a shift register on P0.03, P0.04, P0.28
-fn main() {
+async fn main() {
     let shift_register = ShiftRegister::new(
         GpioPinUnitialized::new(0).open_for_write().unwrap(),
         GpioPinUnitialized::new(1).open_for_write().unwrap(),
@@ -33,6 +33,6 @@
     loop {
         i = (i + 1) % 11;
         shift_register.write_bits(&number_to_bits(i));
-        timer::sleep(Duration::from_ms(200));
+        timer::sleep(Duration::from_ms(200)).await;
     }
 }
diff --git a/examples/simple_ble.rs b/examples/simple_ble.rs
index a467f97..e8ce3e8 100644
--- a/examples/simple_ble.rs
+++ b/examples/simple_ble.rs
@@ -15,7 +15,7 @@
 }
 
 #[allow(unused_variables)]
-fn main() {
+async fn main() {
     let led = led::get(0).unwrap();
 
     let uuid: [u8; 2] = [0x00, 0x18];
@@ -41,11 +41,10 @@
     gap_payload.add_service_payload([91, 79], &payload).unwrap();
 
     let handle = BleAdvertisingDriver::initialize(100, &gap_payload, &mut buffer).unwrap();
-
     loop {
         led.on();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
         led.off();
-        timer::sleep(Duration::from_ms(500));
+        timer::sleep(Duration::from_ms(500)).await;
     }
 }
diff --git a/examples/temperature.rs b/examples/temperature.rs
index 39290f8..5d7fd7f 100644
--- a/examples/temperature.rs
+++ b/examples/temperature.rs
@@ -2,19 +2,10 @@
 
 use core::fmt::Write;
 use libtock::console::Console;
-use libtock::syscalls;
 use libtock::temperature;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
-
-    let mut with_callback = temperature::with_callback(|result: isize| {
-        writeln!(console, "Temperature: {}", result).unwrap();
-    });
-
-    let _temperature = with_callback.start_measurement();
-
-    loop {
-        syscalls::yieldk();
-    }
+    let temperature = temperature::measure_temperature().await;
+    writeln!(console, "Temperature: {}", temperature).unwrap();
 }
diff --git a/examples/timer_subscribe.rs b/examples/timer_subscribe.rs
index 28148c6..77d7042 100644
--- a/examples/timer_subscribe.rs
+++ b/examples/timer_subscribe.rs
@@ -6,7 +6,7 @@
 use libtock::timer;
 use libtock::timer::Duration;
 
-fn main() {
+async fn main() {
     let mut console = Console::new();
 
     let mut with_callback = timer::with_callback(|_, _| {
diff --git a/riscv32_layout.ld b/riscv32_layout.ld
index 6a37365..b7067fd 100644
--- a/riscv32_layout.ld
+++ b/riscv32_layout.ld
@@ -1,7 +1,8 @@
 /* Layout for the RISC-V 32 boards, used by the examples in this repository. */
 
 MEMORY {
-  FLASH (rx) : ORIGIN = 0x20430000, LENGTH = 32M
+  /* The TBF header region is 32 bytes (0x20) */
+  FLASH (rx) : ORIGIN = 0x20430020, LENGTH = 32M
   SRAM (rwx) : ORIGIN = 0x80000000, LENGTH = 512K
 }
 
diff --git a/rust-toolchain b/rust-toolchain
index e304127..22e9048 100644
--- a/rust-toolchain
+++ b/rust-toolchain
@@ -1 +1 @@
-nightly-2019-09-19
+nightly-2019-11-06
diff --git a/src/buttons.rs b/src/buttons.rs
index 1bd29d3..916e052 100644
--- a/src/buttons.rs
+++ b/src/buttons.rs
@@ -78,7 +78,7 @@
     }
 }
 
-#[derive(Copy, Clone, Debug)]
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
 pub enum ButtonState {
     Pressed,
     Released,
diff --git a/src/console.rs b/src/console.rs
index ecd7ad1..7942fb7 100644
--- a/src/console.rs
+++ b/src/console.rs
@@ -1,5 +1,7 @@
+use crate::futures;
 use crate::syscalls;
 use core::cell::Cell;
+use core::executor;
 use core::fmt;
 
 const DRIVER_NUMBER: usize = 1;
@@ -65,7 +67,7 @@
             return;
         }
 
-        syscalls::yieldk_for(|| is_written.get());
+        executor::block_on(futures::wait_until(|| is_written.get()));
     }
 }
 
diff --git a/src/debug/low_level_debug.rs b/src/debug/low_level_debug.rs
new file mode 100644
index 0000000..06f2329
--- /dev/null
+++ b/src/debug/low_level_debug.rs
@@ -0,0 +1,40 @@
+//! Interface to the Low Level Debug capsule. This provides routines that are
+//! useful for toolchain issues. The capsule is documented at:
+//! https://github.com/tock/tock/blob/master/doc/syscalls/00008_low_level_debug.md
+
+use crate::syscalls::{command, command1_insecure};
+
+const DRIVER_NUMBER: usize = 8;
+
+mod command_nr {
+    pub const ALERT_CODE: usize = 1;
+    pub const PRINT1: usize = 2;
+    pub const PRINT2: usize = 3;
+}
+
+/// Use the LowLevelDebug capsule (if present) to indicate the given status
+/// code. If the capsule is not present, this is a no-op.
+#[inline(always)] // Improve reliability for relocation issues
+pub fn low_level_status_code(code: usize) {
+    unsafe {
+        command1_insecure(DRIVER_NUMBER, command_nr::ALERT_CODE, code);
+    }
+}
+
+/// Use the LowLevelDebug capsule (if present) to print a single number. If the
+/// capsule is not present, this is a no-op.
+#[inline(always)] // Improve reliability for relocation issues
+pub fn low_level_print1(value: usize) {
+    unsafe {
+        command1_insecure(DRIVER_NUMBER, command_nr::PRINT1, value);
+    }
+}
+
+/// Use the LowLevelDebug capsule (if present) to print two numbers. If the
+/// capsule is not present, this is a no-op.
+#[inline(always)] // Improve reliability for relocation issues
+pub fn low_level_print2(value1: usize, value2: usize) {
+    unsafe {
+        command(DRIVER_NUMBER, command_nr::PRINT2, value1, value2);
+    }
+}
diff --git a/src/debug.rs b/src/debug/mod.rs
similarity index 97%
rename from src/debug.rs
rename to src/debug/mod.rs
index c35a3b7..b05cf39 100644
--- a/src/debug.rs
+++ b/src/debug/mod.rs
@@ -1,5 +1,8 @@
 //! Heapless debugging functions for Tock troubleshooting
 
+mod low_level_debug;
+pub use low_level_debug::*;
+
 use crate::console::Console;
 
 pub fn println() {
diff --git a/src/entry_point.rs b/src/entry_point.rs
index e485bad..3b6028e 100644
--- a/src/entry_point.rs
+++ b/src/entry_point.rs
@@ -1,5 +1,5 @@
+use crate::memop;
 use crate::syscalls;
-use crate::ALLOCATOR;
 use core::intrinsics;
 use core::ptr;
 
@@ -84,8 +84,12 @@
         ldr r5, =.start   // r5 = address of .start
         cmp r4, r5
         beq .Lstack_init  // Jump to stack initialization if pc was correct
+        movw r0, #8       // LowLevelDebug driver number
+        movw r1, #1       // LowLevelDebug 'print status code' command
+        movw r2, #2       // LowLevelDebug relocation failed status code
+        svc 2             // command() syscall
         .Lyield_loop:
-        svc 0             // yield() syscall
+        svc 0             // yield() syscall (in infinite loop)
         b .Lyield_loop
 
         .Lstack_init:
@@ -208,6 +212,7 @@
     // Move arguments we need to keep over to callee-saved locations.
     mv   s0, a0             // s0 = void* app_start
     mv   s1, t0             // s1 = stack_top
+    mv   s2, a3             // s2 = app_heap_break
     //
     // Now we may want to move the stack pointer. If the kernel set the
     // `app_heap_break` larger than we need (and we are going to call `brk()`
@@ -254,7 +259,7 @@
     mv   a0, s0             // first arg is app_start
     mv   s0, sp             // Set the frame pointer to sp.
     mv   a1, s1             // second arg is stacktop
-    mv   a1, s1             // second arg is stackto
+    mv   a2, s2             // third arg is app_heap_break
     jal  rust_start"
     :                                                              // No output operands
     :
@@ -348,10 +353,10 @@
     let app_heap_start = app_heap_break;
     let app_heap_end = app_heap_break + HEAP_SIZE;
 
-    // tell the kernel the new app heap break
-    syscalls::memop(0, app_heap_end);
+    // Tell the kernel the new app heap break.
+    memop::set_brk(app_heap_end as *const u8);
 
-    ALLOCATOR.lock().init(app_heap_start, HEAP_SIZE);
+    HEAP.init(app_heap_start, HEAP_SIZE);
 
     main(0, ptr::null());
 
@@ -359,3 +364,27 @@
         syscalls::yieldk();
     }
 }
+
+use core::alloc::GlobalAlloc;
+use core::alloc::Layout;
+use core::ptr::NonNull;
+use linked_list_allocator::Heap;
+
+#[global_allocator]
+static ALLOCATOR: TockAllocator = TockAllocator;
+
+static mut HEAP: Heap = Heap::empty();
+
+struct TockAllocator;
+
+unsafe impl GlobalAlloc for TockAllocator {
+    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+        HEAP.allocate_first_fit(layout)
+            .ok()
+            .map_or(0 as *mut u8, |allocation| allocation.as_ptr())
+    }
+
+    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
+        HEAP.deallocate(NonNull::new_unchecked(ptr), layout)
+    }
+}
diff --git a/src/futures.rs b/src/futures.rs
new file mode 100644
index 0000000..0223507
--- /dev/null
+++ b/src/futures.rs
@@ -0,0 +1,29 @@
+use core::future::Future;
+use core::pin::Pin;
+use core::task::Context;
+use core::task::Poll;
+
+// TODO: Consider using FnMut
+pub async fn wait_until<F: Fn() -> bool>(condition: F) {
+    wait_for_value(move || if condition() { Some(()) } else { None }).await
+}
+
+pub async fn wait_for_value<T, F: Fn() -> Option<T>>(value_provider: F) -> T {
+    WaitForValue { value_provider }.await
+}
+
+struct WaitForValue<F> {
+    value_provider: F,
+}
+
+impl<T, F: Fn() -> Option<T>> Future for WaitForValue<F> {
+    type Output = T;
+
+    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+        if let Some(value) = (self.value_provider)() {
+            Poll::Ready(value)
+        } else {
+            Poll::Pending
+        }
+    }
+}
diff --git a/src/lang_items.rs b/src/lang_items.rs
index 6d91bb0..c27c549 100644
--- a/src/lang_items.rs
+++ b/src/lang_items.rs
@@ -22,6 +22,8 @@
 use crate::timer;
 use crate::timer::Duration;
 use core::alloc::Layout;
+use core::executor;
+use core::future::Future;
 use core::panic::PanicInfo;
 
 #[lang = "start"]
@@ -32,37 +34,54 @@
     main().report()
 }
 
+#[lang = "termination"]
 pub trait Termination {
     fn report(self) -> i32;
 }
 
-impl Termination for () {
+impl<T> Termination for T
+where
+    T: Future<Output = ()>,
+{
     fn report(self) -> i32 {
+        executor::block_on(self);
         0
     }
 }
 
 #[panic_handler]
-fn flash_all_leds(_info: &PanicInfo) -> ! {
-    loop {
-        for led in led::all() {
-            led.on();
+fn panic_handler(_info: &PanicInfo) -> ! {
+    // Signal a panic using the LowLevelDebug capsule (if available).
+    super::debug::low_level_status_code(1);
+
+    // Flash all LEDs (if available).
+    executor::block_on(async {
+        loop {
+            for led in led::all() {
+                led.on();
+            }
+            timer::sleep(Duration::from_ms(100)).await;
+            for led in led::all() {
+                led.off();
+            }
+            timer::sleep(Duration::from_ms(100)).await;
         }
-        timer::sleep(Duration::from_ms(100));
-        for led in led::all() {
-            led.off();
-        }
-        timer::sleep(Duration::from_ms(100));
-    }
+    });
+    // Never type is not supported for T in Future
+    unreachable!()
 }
 
 #[alloc_error_handler]
 fn cycle_leds(_: Layout) -> ! {
-    loop {
-        for led in led::all() {
-            led.on();
-            timer::sleep(Duration::from_ms(100));
-            led.off();
+    executor::block_on(async {
+        loop {
+            for led in led::all() {
+                led.on();
+                timer::sleep(Duration::from_ms(100)).await;
+                led.off();
+            }
         }
-    }
+    });
+    // Never type is not supported for T in Future
+    unreachable!()
 }
diff --git a/src/lib.rs b/src/lib.rs
index 3b24797..9b90ea0 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,11 @@
-#![feature(asm, alloc_error_handler, core_intrinsics, lang_items, naked_functions)]
+#![feature(
+    asm,
+    alloc_error_handler,
+    core_intrinsics,
+    lang_items,
+    naked_functions,
+    ptr_offset_from
+)]
 #![no_std]
 
 extern crate alloc;
@@ -12,8 +19,10 @@
 pub mod console;
 pub mod debug;
 pub mod electronics;
+pub mod futures;
 pub mod gpio;
 pub mod led;
+pub mod memop;
 pub mod result;
 pub mod rng;
 pub mod sensors;
@@ -36,10 +45,6 @@
 #[path = "syscalls_mock.rs"]
 mod syscalls;
 
-#[cfg(any(target_arch = "arm", target_arch = "riscv32"))]
-#[global_allocator]
-static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
-
 // Dummy structure to force importing the panic_handler and other no_std elements when nothing else
 // is imported.
 pub struct LibTock;
diff --git a/src/memop.rs b/src/memop.rs
new file mode 100644
index 0000000..4088f61
--- /dev/null
+++ b/src/memop.rs
@@ -0,0 +1,92 @@
+// Last updated for Tock 1.4.
+// See https://github.com/tock/tock/blob/master/doc/syscalls/memop.md
+use crate::syscalls;
+use core::slice;
+
+// Setting the break is marked as unsafe as it should only be called by the entry point to setup
+// the allocator. Updating the break afterwards can lead to allocated memory becoming unaccessible.
+//
+// Alternate allocator implementations may still find this useful in the future.
+pub unsafe fn set_brk(ptr: *const u8) -> bool {
+    syscalls::memop(0, ptr as usize) == 0
+}
+
+pub unsafe fn increment_brk(increment: usize) -> Option<*const u8> {
+    let result = syscalls::memop(1, increment);
+    if result >= 0 {
+        Some(result as *const u8)
+    } else {
+        None
+    }
+}
+
+pub fn get_brk() -> *const u8 {
+    unsafe { syscalls::memop(1, 0) as *const u8 }
+}
+
+pub fn get_mem_start() -> *const u8 {
+    unsafe { syscalls::memop(2, 0) as *const u8 }
+}
+
+pub fn get_mem_end() -> *const u8 {
+    unsafe { syscalls::memop(3, 0) as *const u8 }
+}
+
+pub fn get_flash_start() -> *const u8 {
+    unsafe { syscalls::memop(4, 0) as *const u8 }
+}
+
+pub fn get_flash_end() -> *const u8 {
+    unsafe { syscalls::memop(5, 0) as *const u8 }
+}
+
+pub fn get_grant_start() -> *const u8 {
+    unsafe { syscalls::memop(6, 0) as *const u8 }
+}
+
+pub fn get_flash_regions_count() -> usize {
+    unsafe { syscalls::memop(7, 0) as usize }
+}
+
+pub fn get_flash_region_start(i: usize) -> Option<*const u8> {
+    if i < get_flash_regions_count() {
+        Some(unsafe { syscalls::memop(8, i) as *const u8 })
+    } else {
+        None
+    }
+}
+
+pub fn get_flash_region_end(i: usize) -> Option<*const u8> {
+    if i < get_flash_regions_count() {
+        Some(unsafe { syscalls::memop(9, i) as *const u8 })
+    } else {
+        None
+    }
+}
+
+// It is safe to return a 'static immutable slice, as the Tock kernel doesn't change the layout of
+// flash regions during the application's lifetime.
+pub fn get_flash_region(i: usize) -> Option<&'static [u8]> {
+    if i < get_flash_regions_count() {
+        let start = unsafe { syscalls::memop(8, i) as *const u8 };
+        let end = unsafe { syscalls::memop(9, i) as *const u8 };
+        // This assumes that the kernel sends consistent results, i.e. start <= end.
+        let len = unsafe { end.offset_from(start) } as usize;
+        Some(unsafe { slice::from_raw_parts(start, len) })
+    } else {
+        None
+    }
+}
+
+// Setting the stack_top and heap_start addresses are marked as unsafe as they should only be called
+// by the entry point to setup the allocator. Updating these values afterwards can lead to incorrect
+// debug output from the kernel.
+//
+// Alternate allocator implementations may still find this useful in the future.
+pub unsafe fn set_stack_top(ptr: *const u8) {
+    let _ = syscalls::memop(10, ptr as usize);
+}
+
+pub unsafe fn set_heap_start(ptr: *const u8) {
+    let _ = syscalls::memop(11, ptr as usize);
+}
diff --git a/src/rng.rs b/src/rng.rs
index 411030e..955e273 100644
--- a/src/rng.rs
+++ b/src/rng.rs
@@ -1,3 +1,4 @@
+use crate::futures;
 use crate::syscalls;
 use core::cell::Cell;
 
@@ -15,7 +16,7 @@
     pub const SHARE_BUFFER: usize = 0;
 }
 
-pub fn fill_buffer(buf: &mut [u8]) -> bool {
+pub async fn fill_buffer(buf: &mut [u8]) -> bool {
     let buf_len = buf.len();
 
     let result = syscalls::allow(DRIVER_NUMBER, allow_nr::SHARE_BUFFER, buf);
@@ -40,6 +41,6 @@
         return false;
     }
 
-    syscalls::yieldk_for(|| is_filled.get());
-    return true;
+    futures::wait_until(|| is_filled.get()).await;
+    true
 }
diff --git a/src/sensors/mod.rs b/src/sensors/mod.rs
index f15a9db..7e62d8e 100644
--- a/src/sensors/mod.rs
+++ b/src/sensors/mod.rs
@@ -1,6 +1,8 @@
-use crate::syscalls::{self, yieldk_for};
+use crate::futures;
+use crate::syscalls;
 use core::cell::Cell;
 use core::convert::From;
+use core::executor;
 use core::fmt;
 use core::mem;
 
@@ -30,7 +32,7 @@
                 mem::transmute(&res),
             );
             syscalls::command(driver_num, 1, 0, 0);
-            yieldk_for(|| res.get().is_some());
+            executor::block_on(futures::wait_until(|| res.get().is_some()));
             res.get().unwrap()
         }
     }
diff --git a/src/sensors/ninedof.rs b/src/sensors/ninedof.rs
index a7a3a7e..7c347c8 100644
--- a/src/sensors/ninedof.rs
+++ b/src/sensors/ninedof.rs
@@ -1,5 +1,7 @@
-use crate::syscalls::{self, yieldk_for};
+use crate::futures;
+use crate::syscalls;
 use core::cell::Cell;
+use core::executor;
 use core::fmt;
 use core::mem;
 
@@ -36,7 +38,7 @@
         unsafe {
             subscribe(Self::cb, mem::transmute(&res));
             start_accel_reading();
-            yieldk_for(|| res.ready.get());
+            executor::block_on(futures::wait_until(|| res.ready.get()));
         }
         res.res.get()
     }
@@ -46,7 +48,7 @@
         unsafe {
             subscribe(Self::cb, mem::transmute(&res));
             start_magnetometer_reading();
-            yieldk_for(|| res.ready.get());
+            executor::block_on(futures::wait_until(|| res.ready.get()));
         }
         res.res.get()
     }
diff --git a/src/syscalls.rs b/src/syscalls.rs
index 049d102..0dad130 100644
--- a/src/syscalls.rs
+++ b/src/syscalls.rs
@@ -2,6 +2,11 @@
 use crate::callback::SubscribableCallback;
 use crate::shared_memory::SharedMemory;
 
+#[export_name = "libtock::syscalls::yieldk"]
+pub fn yieldk_c() {
+    yieldk()
+}
+
 #[cfg(target_arch = "arm")]
 pub fn yieldk() {
     // Note: A process stops yielding when there is a callback ready to run,
@@ -51,12 +56,6 @@
     }
 }
 
-pub fn yieldk_for<F: Fn() -> bool>(cond: F) {
-    while !cond() {
-        yieldk();
-    }
-}
-
 pub fn subscribe<CB: SubscribableCallback>(
     driver_number: usize,
     subscribe_number: usize,
@@ -113,14 +112,15 @@
     let res;
     asm!("li    a0, 1
           ecall"
-         : "=r" (res)
-         : "r" (major), "r" (minor), "r" (cb), "r" (ud)
+         : "={x10}" (res)
+         : "{x11}" (major), "{x12}" (minor), "{x13}" (cb), "{x14}" (ud)
          : "memory"
          : "volatile" );
     res
 }
 
 #[cfg(target_arch = "arm")]
+#[inline(always)]
 pub unsafe fn command(major: usize, minor: usize, arg1: usize, arg2: usize) -> isize {
     let res;
     asm!("svc 2" : "={r0}"(res)
@@ -131,12 +131,48 @@
 }
 
 #[cfg(target_arch = "riscv32")]
+#[inline(always)]
 pub unsafe fn command(major: usize, minor: usize, arg1: usize, arg2: usize) -> isize {
     let res;
     asm!("li    a0, 2
           ecall"
-         : "=r" (res)
-         : "r" (major), "r" (minor), "r" (arg1), "r" (arg2)
+         : "={x10}" (res)
+         : "{x11}" (major), "{x12}" (minor), "{x13}" (arg1), "{x14}" (arg2)
+         : "memory"
+         : "volatile");
+    res
+}
+
+// command1_insecure, is a variant of command() that only sets the first
+// argument in the system call interface. It has the benefit of generating
+// simpler assembly than command(), but it leaves the second argument's register
+// as-is which leaks it to the kernel driver being called. Prefer to use
+// command() instead of command1_insecure(), unless the benefit of generating
+// simpler assembly outweighs the drawbacks of potentially leaking arbitrary
+// information to the driver you are calling.
+//
+// At the moment, the only suitable use case for command1_insecure is the low
+// level debug interface.
+
+#[cfg(target_arch = "arm")]
+#[inline(always)]
+pub unsafe fn command1_insecure(major: usize, minor: usize, arg: usize) -> isize {
+    let res;
+    asm!("svc 2" : "={r0}"(res)
+                 : "{r0}"(major) "{r1}"(minor) "{r2}"(arg)
+                 : "memory"
+                 : "volatile");
+    res
+}
+
+#[cfg(target_arch = "riscv32")]
+#[inline(always)]
+pub unsafe fn command1_insecure(major: usize, minor: usize, arg: usize) -> isize {
+    let res;
+    asm!("li    a0, 2
+          ecall"
+         : "={x10}" (res)
+         : "{x11}" (major), "{x12}" (minor), "{x13}" (arg)
          : "memory"
          : "volatile");
     res
@@ -182,8 +218,8 @@
     let res;
     asm!("li    a0, 3
           ecall"
-         : "=r" (res)
-         : "r" (major), "r" (minor), "r" (slice), "r" (len)
+         : "={x10}" (res)
+         : "{x11}" (major), "{x12}" (minor), "{x13}" (slice), "{x14}" (len)
          : "memory"
          : "volatile");
     res
@@ -204,8 +240,8 @@
     let res;
     asm!("li    a0, 4
           ecall"
-         : "=r" (res)
-         : "r" (major), "r" (arg1)
+         : "={x10}" (res)
+         : "{x11}" (major), "{x12}" (arg1)
          : "memory"
          : "volatile");
     res
diff --git a/src/syscalls_mock.rs b/src/syscalls_mock.rs
index 8b60611..678bbb6 100644
--- a/src/syscalls_mock.rs
+++ b/src/syscalls_mock.rs
@@ -2,10 +2,6 @@
 use crate::callback::SubscribableCallback;
 use crate::shared_memory::SharedMemory;
 
-pub fn yieldk_for<F: Fn() -> bool>(_: F) {
-    unimplemented()
-}
-
 pub fn subscribe<CB: SubscribableCallback>(
     _: usize,
     _: usize,
@@ -27,6 +23,10 @@
     unimplemented()
 }
 
+pub unsafe fn command1_insecure(_: usize, _: usize, _: usize) -> isize {
+    unimplemented()
+}
+
 pub fn allow(_: usize, _: usize, _: &mut [u8]) -> Result<SharedMemory, isize> {
     unimplemented()
 }
@@ -35,6 +35,10 @@
     unimplemented()
 }
 
+pub unsafe fn memop(_: u32, _: usize) -> isize {
+    unimplemented()
+}
+
 fn unimplemented() -> ! {
     unimplemented!("Unimplemented for tests");
 }
diff --git a/src/temperature.rs b/src/temperature.rs
index 214fb78..fb67129 100644
--- a/src/temperature.rs
+++ b/src/temperature.rs
@@ -1,16 +1,18 @@
 use crate::callback::CallbackSubscription;
 use crate::callback::SubscribableCallback;
+use crate::futures;
 use crate::syscalls;
+use core::cell::Cell;
 
 const DRIVER_NUMBER: usize = 0x60000;
 const SUBSCRIBE_CALLBACK: usize = 0;
 const START_MEASUREMENT: usize = 1;
 
-pub fn with_callback<CB>(callback: CB) -> WithCallback<CB> {
+fn with_callback<CB>(callback: CB) -> WithCallback<CB> {
     WithCallback { callback }
 }
 
-pub struct WithCallback<CB> {
+struct WithCallback<CB> {
     callback: CB,
 }
 
@@ -24,9 +26,17 @@
 where
     Self: SubscribableCallback,
 {
-    pub fn start_measurement(&mut self) -> Result<CallbackSubscription, isize> {
+    fn start_measurement(&mut self) -> Result<CallbackSubscription, isize> {
         let subscription = syscalls::subscribe(DRIVER_NUMBER, SUBSCRIBE_CALLBACK, self)?;
         unsafe { syscalls::command(DRIVER_NUMBER, START_MEASUREMENT, 0, 0) };
         Ok(subscription)
     }
 }
+
+pub async fn measure_temperature() -> isize {
+    let temperature = Cell::<Option<isize>>::new(None);
+    let mut callback = |temp: isize| temperature.set(Some(temp));
+    let mut withcallback = with_callback(&mut callback);
+    let _subscription = withcallback.start_measurement();
+    futures::wait_for_value(|| temperature.get()).await
+}
diff --git a/src/timer.rs b/src/timer.rs
index 6634282..e40c32d 100644
--- a/src/timer.rs
+++ b/src/timer.rs
@@ -1,5 +1,6 @@
 use crate::callback::CallbackSubscription;
 use crate::callback::SubscribableCallback;
+use crate::futures;
 use crate::result;
 use crate::result::TockResult;
 use crate::result::TockValue;
@@ -22,14 +23,14 @@
     pub const SUBSCRIBE_CALLBACK: usize = 0;
 }
 
-pub fn sleep(duration: Duration<isize>) {
+pub async fn sleep(duration: Duration<isize>) {
     let expired = Cell::new(false);
     let mut with_callback = with_callback(|_, _| expired.set(true));
 
     let mut timer = with_callback.init().unwrap();
     timer.set_alarm(duration).unwrap();
 
-    syscalls::yieldk_for(|| expired.get());
+    futures::wait_until(|| expired.get()).await;
 }
 
 pub fn with_callback<CB>(callback: CB) -> WithCallback<CB> {
@@ -143,8 +144,27 @@
 
     pub fn set_alarm(&mut self, duration: Duration<isize>) -> TockResult<Alarm, SetAlarmError> {
         let now = self.get_current_clock();
-        let alarm_instant =
-            now.num_ticks() as usize + (duration.ms() as usize * self.clock_frequency.hz()) / 1000;
+        let freq = self.clock_frequency.hz();
+        let duration_ms = duration.ms() as usize;
+        let ticks = match duration_ms.checked_mul(freq) {
+            Some(x) => x / 1000,
+            None => {
+                // Divide the largest of the two operands by 1000, to improve precision of the
+                // result.
+                if duration_ms > freq {
+                    match (duration_ms / 1000).checked_mul(freq) {
+                        Some(y) => y,
+                        None => return Err(TockValue::Expected(SetAlarmError::DurationTooLong)),
+                    }
+                } else {
+                    match (freq / 1000).checked_mul(duration_ms) {
+                        Some(y) => y,
+                        None => return Err(TockValue::Expected(SetAlarmError::DurationTooLong)),
+                    }
+                }
+            }
+        };
+        let alarm_instant = now.num_ticks() as usize + ticks;
 
         let alarm_id =
             unsafe { syscalls::command(DRIVER_NUMBER, command_nr::SET_ALARM, alarm_instant, 0) };
@@ -212,6 +232,7 @@
 #[derive(Clone, Copy, Debug)]
 pub enum SetAlarmError {
     NoMemoryAvailable,
+    DurationTooLong,
 }
 
 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]