From 7650fea5f2bed1c39a0ff6c5934709d316547a23 Mon Sep 17 00:00:00 2001
From: Dario Nieuwenhuis <dirbaio@dirbaio.net>
Date: Sat, 4 Mar 2023 05:37:13 +0100
Subject: [PATCH] nrf/buffered_uarte: add HIL tests.

---
 ci.sh                                   |   1 +
 embassy-nrf/src/buffered_uarte.rs       |   2 +-
 tests/nrf/.cargo/config.toml            |   9 +
 tests/nrf/Cargo.toml                    |  20 ++
 tests/nrf/build.rs                      |  16 ++
 tests/nrf/link_ram.x                    | 254 ++++++++++++++++++++++++
 tests/nrf/memory.x                      |   5 +
 tests/nrf/src/bin/buffered_uart.rs      |  74 +++++++
 tests/nrf/src/bin/buffered_uart_spam.rs |  86 ++++++++
 9 files changed, 466 insertions(+), 1 deletion(-)
 create mode 100644 tests/nrf/.cargo/config.toml
 create mode 100644 tests/nrf/Cargo.toml
 create mode 100644 tests/nrf/build.rs
 create mode 100644 tests/nrf/link_ram.x
 create mode 100644 tests/nrf/memory.x
 create mode 100644 tests/nrf/src/bin/buffered_uart.rs
 create mode 100644 tests/nrf/src/bin/buffered_uart_spam.rs

diff --git a/ci.sh b/ci.sh
index 417937d07..bbcb26bdb 100755
--- a/ci.sh
+++ b/ci.sh
@@ -133,6 +133,7 @@ cargo batch  \
     --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/nucleo-stm32wb55rg \
     --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/iot-stm32u585ai \
     --- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \
+    --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \
     $BUILD_EXTRA
 
 
diff --git a/embassy-nrf/src/buffered_uarte.rs b/embassy-nrf/src/buffered_uarte.rs
index 07f292c4a..ab639aeea 100644
--- a/embassy-nrf/src/buffered_uarte.rs
+++ b/embassy-nrf/src/buffered_uarte.rs
@@ -296,7 +296,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
         }
 
         // Received some bytes, wake task.
-        if r.inten.read().rxdrdy().bit_is_set() && r.events_rxdrdy.read().events_rxdrdy().bit_is_set() {
+        if r.inten.read().rxdrdy().bit_is_set() && r.events_rxdrdy.read().bits() != 0 {
             r.intenclr.write(|w| w.rxdrdy().clear());
             r.events_rxdrdy.reset();
             s.rx_waker.wake();
diff --git a/tests/nrf/.cargo/config.toml b/tests/nrf/.cargo/config.toml
new file mode 100644
index 000000000..4eec189d4
--- /dev/null
+++ b/tests/nrf/.cargo/config.toml
@@ -0,0 +1,9 @@
+[target.'cfg(all(target_arch = "arm", target_os = "none"))']
+#runner = "teleprobe local run --chip nRF52840_xxAA --elf"
+runner = "teleprobe client run --target nrf52840-dk --elf"
+
+[build]
+target = "thumbv7em-none-eabi"
+
+[env]
+DEFMT_LOG = "trace"
diff --git a/tests/nrf/Cargo.toml b/tests/nrf/Cargo.toml
new file mode 100644
index 000000000..2a4e8cf41
--- /dev/null
+++ b/tests/nrf/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+edition = "2021"
+name = "embassy-nrf-examples"
+version = "0.1.0"
+license = "MIT OR Apache-2.0"
+
+[dependencies]
+embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
+embassy-sync = { version = "0.1.0", path = "../../embassy-sync", features = ["defmt", "nightly"] }
+embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["defmt", "nightly", "integrated-timers"] }
+embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "nightly", "defmt-timestamp-uptime"] }
+embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nightly", "unstable-traits", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
+embedded-io = { version = "0.4.0", features = ["async"] }
+
+defmt = "0.3"
+defmt-rtt = "0.4"
+
+cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
+cortex-m-rt = "0.7.0"
+panic-probe = { version = "0.3", features = ["print-defmt"] }
\ No newline at end of file
diff --git a/tests/nrf/build.rs b/tests/nrf/build.rs
new file mode 100644
index 000000000..6f4872249
--- /dev/null
+++ b/tests/nrf/build.rs
@@ -0,0 +1,16 @@
+use std::error::Error;
+use std::path::PathBuf;
+use std::{env, fs};
+
+fn main() -> Result<(), Box<dyn Error>> {
+    let out = PathBuf::from(env::var("OUT_DIR").unwrap());
+    fs::write(out.join("link_ram.x"), include_bytes!("link_ram.x")).unwrap();
+    println!("cargo:rustc-link-search={}", out.display());
+    println!("cargo:rerun-if-changed=link_ram.x");
+
+    println!("cargo:rustc-link-arg-bins=--nmagic");
+    println!("cargo:rustc-link-arg-bins=-Tlink_ram.x");
+    println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
+
+    Ok(())
+}
diff --git a/tests/nrf/link_ram.x b/tests/nrf/link_ram.x
new file mode 100644
index 000000000..26da86baa
--- /dev/null
+++ b/tests/nrf/link_ram.x
@@ -0,0 +1,254 @@
+/* ##### EMBASSY NOTE
+    Originally from https://github.com/rust-embedded/cortex-m-rt/blob/master/link.x.in
+    Adjusted to put everything in RAM
+*/
+
+/* # Developer notes
+
+- Symbols that start with a double underscore (__) are considered "private"
+
+- Symbols that start with a single underscore (_) are considered "semi-public"; they can be
+  overridden in a user linker script, but should not be referred from user code (e.g. `extern "C" {
+  static mut __sbss }`).
+
+- `EXTERN` forces the linker to keep a symbol in the final binary. We use this to make sure a
+  symbol if not dropped if it appears in or near the front of the linker arguments and "it's not
+  needed" by any of the preceding objects (linker arguments)
+
+- `PROVIDE` is used to provide default values that can be overridden by a user linker script
+
+- On alignment: it's important for correctness that the VMA boundaries of both .bss and .data *and*
+  the LMA of .data are all 4-byte aligned. These alignments are assumed by the RAM initialization
+  routine. There's also a second benefit: 4-byte aligned boundaries means that you won't see
+  "Address (..) is out of bounds" in the disassembly produced by `objdump`.
+*/
+
+/* Provides information about the memory layout of the device */
+/* This will be provided by the user (see `memory.x`) or by a Board Support Crate */
+INCLUDE memory.x
+
+/* # Entry point = reset vector */
+EXTERN(__RESET_VECTOR);
+EXTERN(Reset);
+ENTRY(Reset);
+
+/* # Exception vectors */
+/* This is effectively weak aliasing at the linker level */
+/* The user can override any of these aliases by defining the corresponding symbol themselves (cf.
+   the `exception!` macro) */
+EXTERN(__EXCEPTIONS); /* depends on all the these PROVIDED symbols */
+
+EXTERN(DefaultHandler);
+
+PROVIDE(NonMaskableInt = DefaultHandler);
+EXTERN(HardFaultTrampoline);
+PROVIDE(MemoryManagement = DefaultHandler);
+PROVIDE(BusFault = DefaultHandler);
+PROVIDE(UsageFault = DefaultHandler);
+PROVIDE(SecureFault = DefaultHandler);
+PROVIDE(SVCall = DefaultHandler);
+PROVIDE(DebugMonitor = DefaultHandler);
+PROVIDE(PendSV = DefaultHandler);
+PROVIDE(SysTick = DefaultHandler);
+
+PROVIDE(DefaultHandler = DefaultHandler_);
+PROVIDE(HardFault = HardFault_);
+
+/* # Interrupt vectors */
+EXTERN(__INTERRUPTS); /* `static` variable similar to `__EXCEPTIONS` */
+
+/* # Pre-initialization function */
+/* If the user overrides this using the `pre_init!` macro or by creating a `__pre_init` function,
+   then the function this points to will be called before the RAM is initialized. */
+PROVIDE(__pre_init = DefaultPreInit);
+
+/* # Sections */
+SECTIONS
+{
+  PROVIDE(_stack_start = ORIGIN(RAM) + LENGTH(RAM));
+
+  /* ## Sections in RAM */
+  /* ### Vector table */
+  .vector_table ORIGIN(RAM) :
+  {
+    /* Initial Stack Pointer (SP) value */
+    LONG(_stack_start);
+
+    /* Reset vector */
+    KEEP(*(.vector_table.reset_vector)); /* this is the `__RESET_VECTOR` symbol */
+    __reset_vector = .;
+
+    /* Exceptions */
+    KEEP(*(.vector_table.exceptions)); /* this is the `__EXCEPTIONS` symbol */
+    __eexceptions = .;
+
+    /* Device specific interrupts */
+    KEEP(*(.vector_table.interrupts)); /* this is the `__INTERRUPTS` symbol */
+  } > RAM
+
+  PROVIDE(_stext = ADDR(.vector_table) + SIZEOF(.vector_table));
+
+  /* ### .text */
+  .text _stext :
+  {
+    __stext = .;
+    *(.Reset);
+
+    *(.text .text.*);
+
+    /* The HardFaultTrampoline uses the `b` instruction to enter `HardFault`,
+       so must be placed close to it. */
+    *(.HardFaultTrampoline);
+    *(.HardFault.*);
+
+    . = ALIGN(4); /* Pad .text to the alignment to workaround overlapping load section bug in old lld */
+    __etext = .;
+  } > RAM
+
+  /* ### .rodata */
+  .rodata : ALIGN(4)
+  {
+    . = ALIGN(4);
+    __srodata = .;
+    *(.rodata .rodata.*);
+
+    /* 4-byte align the end (VMA) of this section.
+       This is required by LLD to ensure the LMA of the following .data
+       section will have the correct alignment. */
+    . = ALIGN(4);
+    __erodata = .;
+  } > RAM
+
+  /* ## Sections in RAM */
+  /* ### .data */
+  .data : ALIGN(4)
+  {
+    . = ALIGN(4);
+    __sdata = .;
+    __edata = .;
+    *(.data .data.*);
+    . = ALIGN(4); /* 4-byte align the end (VMA) of this section */
+  } > RAM
+  /* Allow sections from user `memory.x` injected using `INSERT AFTER .data` to
+   * use the .data loading mechanism by pushing __edata. Note: do not change
+   * output region or load region in those user sections! */
+  . = ALIGN(4);
+
+  /* LMA of .data */
+  __sidata = LOADADDR(.data);
+
+  /* ### .gnu.sgstubs
+     This section contains the TrustZone-M veneers put there by the Arm GNU linker. */
+  /* Security Attribution Unit blocks must be 32 bytes aligned. */
+  /* Note that this pads the RAM usage to 32 byte alignment. */
+  .gnu.sgstubs : ALIGN(32)
+  {
+    . = ALIGN(32);
+    __veneer_base = .;
+    *(.gnu.sgstubs*)
+    . = ALIGN(32);
+    __veneer_limit = .;
+  } > RAM
+
+  /* ### .bss */
+  .bss (NOLOAD) : ALIGN(4)
+  {
+    . = ALIGN(4);
+    __sbss = .;
+    *(.bss .bss.*);
+    *(COMMON); /* Uninitialized C statics */
+    . = ALIGN(4); /* 4-byte align the end (VMA) of this section */
+  } > RAM
+  /* Allow sections from user `memory.x` injected using `INSERT AFTER .bss` to
+   * use the .bss zeroing mechanism by pushing __ebss. Note: do not change
+   * output region or load region in those user sections! */
+  . = ALIGN(4);
+  __ebss = .;
+
+  /* ### .uninit */
+  .uninit (NOLOAD) : ALIGN(4)
+  {
+    . = ALIGN(4);
+    __suninit = .;
+    *(.uninit .uninit.*);
+    . = ALIGN(4);
+    __euninit = .;
+  } > RAM
+
+  /* Place the heap right after `.uninit` in RAM */
+  PROVIDE(__sheap = __euninit);
+
+  /* ## .got */
+  /* Dynamic relocations are unsupported. This section is only used to detect relocatable code in
+     the input files and raise an error if relocatable code is found */
+  .got (NOLOAD) :
+  {
+    KEEP(*(.got .got.*));
+  }
+
+  /* ## Discarded sections */
+  /DISCARD/ :
+  {
+    /* Unused exception related info that only wastes space */
+    *(.ARM.exidx);
+    *(.ARM.exidx.*);
+    *(.ARM.extab.*);
+  }
+}
+
+/* Do not exceed this mark in the error messages below                                    | */
+/* # Alignment checks */
+ASSERT(ORIGIN(RAM) % 4 == 0, "
+ERROR(cortex-m-rt): the start of the RAM region must be 4-byte aligned");
+
+ASSERT(__sdata % 4 == 0 && __edata % 4 == 0, "
+BUG(cortex-m-rt): .data is not 4-byte aligned");
+
+ASSERT(__sidata % 4 == 0, "
+BUG(cortex-m-rt): the LMA of .data is not 4-byte aligned");
+
+ASSERT(__sbss % 4 == 0 && __ebss % 4 == 0, "
+BUG(cortex-m-rt): .bss is not 4-byte aligned");
+
+ASSERT(__sheap % 4 == 0, "
+BUG(cortex-m-rt): start of .heap is not 4-byte aligned");
+
+/* # Position checks */
+
+/* ## .vector_table */
+ASSERT(__reset_vector == ADDR(.vector_table) + 0x8, "
+BUG(cortex-m-rt): the reset vector is missing");
+
+ASSERT(__eexceptions == ADDR(.vector_table) + 0x40, "
+BUG(cortex-m-rt): the exception vectors are missing");
+
+ASSERT(SIZEOF(.vector_table) > 0x40, "
+ERROR(cortex-m-rt): The interrupt vectors are missing.
+Possible solutions, from most likely to less likely:
+- Link to a svd2rust generated device crate
+- Check that you actually use the device/hal/bsp crate in your code
+- Disable the 'device' feature of cortex-m-rt to build a generic application (a dependency
+may be enabling it)
+- Supply the interrupt handlers yourself. Check the documentation for details.");
+
+/* ## .text */
+ASSERT(ADDR(.vector_table) + SIZEOF(.vector_table) <= _stext, "
+ERROR(cortex-m-rt): The .text section can't be placed inside the .vector_table section
+Set _stext to an address greater than the end of .vector_table (See output of `nm`)");
+
+ASSERT(_stext + SIZEOF(.text) < ORIGIN(RAM) + LENGTH(RAM), "
+ERROR(cortex-m-rt): The .text section must be placed inside the RAM memory.
+Set _stext to an address smaller than 'ORIGIN(RAM) + LENGTH(RAM)'");
+
+/* # Other checks */
+ASSERT(SIZEOF(.got) == 0, "
+ERROR(cortex-m-rt): .got section detected in the input object files
+Dynamic relocations are not supported. If you are linking to C code compiled using
+the 'cc' crate then modify your build script to compile the C code _without_
+the -fPIC flag. See the documentation of the `cc::Build.pic` method for details.");
+/* Do not exceed this mark in the error messages above                                    | */
+
+
+/* Provides weak aliases (cf. PROVIDED) for device specific interrupt handlers */
+/* This will usually be provided by a device crate generated using svd2rust (see `device.x`) */
+INCLUDE device.x
\ No newline at end of file
diff --git a/tests/nrf/memory.x b/tests/nrf/memory.x
new file mode 100644
index 000000000..58900a7bd
--- /dev/null
+++ b/tests/nrf/memory.x
@@ -0,0 +1,5 @@
+MEMORY
+{
+  FLASH : ORIGIN = 0x00000000, LENGTH = 1024K
+  RAM : ORIGIN = 0x20000000, LENGTH = 256K
+}
diff --git a/tests/nrf/src/bin/buffered_uart.rs b/tests/nrf/src/bin/buffered_uart.rs
new file mode 100644
index 000000000..0550b0bb7
--- /dev/null
+++ b/tests/nrf/src/bin/buffered_uart.rs
@@ -0,0 +1,74 @@
+#![no_std]
+#![no_main]
+#![feature(type_alias_impl_trait)]
+
+use defmt::{assert_eq, *};
+use embassy_executor::Spawner;
+use embassy_futures::join::join;
+use embassy_nrf::buffered_uarte::BufferedUarte;
+use embassy_nrf::{interrupt, uarte};
+use {defmt_rtt as _, panic_probe as _};
+
+#[embassy_executor::main]
+async fn main(_spawner: Spawner) {
+    let p = embassy_nrf::init(Default::default());
+    let mut config = uarte::Config::default();
+    config.parity = uarte::Parity::EXCLUDED;
+    config.baudrate = uarte::Baudrate::BAUD1M;
+
+    let mut tx_buffer = [0u8; 1024];
+    let mut rx_buffer = [0u8; 1024];
+
+    let mut u = BufferedUarte::new(
+        p.UARTE0,
+        p.TIMER0,
+        p.PPI_CH0,
+        p.PPI_CH1,
+        p.PPI_GROUP0,
+        interrupt::take!(UARTE0_UART0),
+        p.P1_03,
+        p.P1_02,
+        config.clone(),
+        &mut rx_buffer,
+        &mut tx_buffer,
+    );
+
+    info!("uarte initialized!");
+
+    let (mut rx, mut tx) = u.split();
+
+    const COUNT: usize = 40_000;
+
+    let tx_fut = async {
+        let mut tx_buf = [0; 215];
+        let mut i = 0;
+        while i < COUNT {
+            let n = tx_buf.len().min(COUNT - i);
+            let tx_buf = &mut tx_buf[..n];
+            for (j, b) in tx_buf.iter_mut().enumerate() {
+                *b = (i + j) as u8;
+            }
+            let n = unwrap!(tx.write(tx_buf).await);
+            i += n;
+        }
+    };
+    let rx_fut = async {
+        let mut i = 0;
+        while i < COUNT {
+            let buf = unwrap!(rx.fill_buf().await);
+
+            for &b in buf {
+                assert_eq!(b, i as u8);
+                i = i + 1;
+            }
+
+            let n = buf.len();
+            rx.consume(n);
+        }
+    };
+
+    join(rx_fut, tx_fut).await;
+
+    info!("Test OK");
+    cortex_m::asm::bkpt();
+}
diff --git a/tests/nrf/src/bin/buffered_uart_spam.rs b/tests/nrf/src/bin/buffered_uart_spam.rs
new file mode 100644
index 000000000..57aaeca45
--- /dev/null
+++ b/tests/nrf/src/bin/buffered_uart_spam.rs
@@ -0,0 +1,86 @@
+#![no_std]
+#![no_main]
+#![feature(type_alias_impl_trait)]
+
+use core::mem;
+use core::ptr::NonNull;
+
+use defmt::{assert_eq, *};
+use embassy_executor::Spawner;
+use embassy_nrf::buffered_uarte::BufferedUarte;
+use embassy_nrf::gpio::{Level, Output, OutputDrive};
+use embassy_nrf::ppi::{Event, Ppi, Task};
+use embassy_nrf::uarte::Uarte;
+use embassy_nrf::{interrupt, pac, uarte};
+use embassy_time::{Duration, Timer};
+use {defmt_rtt as _, panic_probe as _};
+
+#[embassy_executor::main]
+async fn main(_spawner: Spawner) {
+    let mut p = embassy_nrf::init(Default::default());
+    let mut config = uarte::Config::default();
+    config.parity = uarte::Parity::EXCLUDED;
+    config.baudrate = uarte::Baudrate::BAUD1M;
+
+    let mut tx_buffer = [0u8; 1024];
+    let mut rx_buffer = [0u8; 1024];
+
+    mem::forget(Output::new(&mut p.P1_02, Level::High, OutputDrive::Standard));
+
+    let mut u = BufferedUarte::new(
+        p.UARTE0,
+        p.TIMER0,
+        p.PPI_CH0,
+        p.PPI_CH1,
+        p.PPI_GROUP0,
+        interrupt::take!(UARTE0_UART0),
+        p.P1_03,
+        p.P1_04,
+        config.clone(),
+        &mut rx_buffer,
+        &mut tx_buffer,
+    );
+
+    info!("uarte initialized!");
+
+    // uarte needs some quiet time to start rxing properly.
+    Timer::after(Duration::from_millis(10)).await;
+
+    // Tx spam in a loop.
+    const NSPAM: usize = 17;
+    static mut TX_BUF: [u8; NSPAM] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+    let _spam = Uarte::new(p.UARTE1, interrupt::take!(UARTE1), p.P1_01, p.P1_02, config.clone());
+    let spam_peri: pac::UARTE1 = unsafe { mem::transmute(()) };
+    let event = unsafe { Event::new_unchecked(NonNull::new_unchecked(&spam_peri.events_endtx as *const _ as _)) };
+    let task = unsafe { Task::new_unchecked(NonNull::new_unchecked(&spam_peri.tasks_starttx as *const _ as _)) };
+    let mut spam_ppi = Ppi::new_one_to_one(p.PPI_CH2, event, task);
+    spam_ppi.enable();
+    let p = unsafe { TX_BUF.as_mut_ptr() };
+    spam_peri.txd.ptr.write(|w| unsafe { w.ptr().bits(p as u32) });
+    spam_peri.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(NSPAM as _) });
+    spam_peri.tasks_starttx.write(|w| unsafe { w.bits(1) });
+
+    let mut i = 0;
+    let mut total = 0;
+    while total < 256 * 1024 {
+        let buf = unwrap!(u.fill_buf().await);
+        //info!("rx {}", buf);
+
+        for &b in buf {
+            assert_eq!(b, unsafe { TX_BUF[i] });
+
+            i = i + 1;
+            if i == NSPAM {
+                i = 0;
+            }
+        }
+
+        // Read bytes have to be explicitly consumed, otherwise fill_buf() will return them again
+        let n = buf.len();
+        u.consume(n);
+        total += n;
+    }
+
+    info!("Test OK");
+    cortex_m::asm::bkpt();
+}