diff --git a/.cargo/config.toml b/.cargo/config.toml index 80fc334..6b3df67 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,4 +1,25 @@ -[target.thumbv7m-none-eabi] +[build] +# Common embedded build targets +target = "thumbv7em-none-eabihf" +# target = "thumbv6m-none-eabi" + +[target.thumbv7em-none-eabihf] # used to run the qemu_test.rs example with QEMU -runner = "qemu-system-arm -cpu cortex-m3 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel" -rustflags = ["-C", "link-arg=-Tlink.x"] +runner = "./qemu-runner.sh --target thumbv7em-none-eabihf" +rustflags = [ + "-Clink-arg=-Tlink.x", + "-Clink-arg=-Tdefmt.x", + # Can be useful for debugging and to inspect where the heap memory is placed/linked. + # "-Clink-args=-Map=app.map" +] + +[target.thumbv6m-none-eabi] +# used to run the qemu_test.rs example with QEMU +runner = "./qemu-runner.sh --target thumbv6m-none-eabi" +rustflags = [ + "-Clink-arg=-Tlink.x", + "-Clink-arg=-Tdefmt.x", +] + +[env] +DEFMT_LOG="info" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c7a0f5e..cb4cd38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,9 @@ on: pull_request: # Run CI for PRs on any branch merge_group: # Run CI for the GitHub merge queue workflow_dispatch: # Run CI when manually requested + schedule: + # Run every week at 8am UTC Saturday + - cron: '0 8 * * SAT' name: Continuous integration @@ -13,7 +16,7 @@ jobs: matrix: target: - thumbv6m-none-eabi - - thumbv7m-none-eabi + - thumbv7em-none-eabihf toolchain: - stable - nightly @@ -27,6 +30,18 @@ jobs: - run: cargo check --target=${{ matrix.target }} --example global_alloc - if: ${{ matrix.toolchain == 'nightly' }} run: cargo check --target=${{ matrix.target }} --examples --all-features + - uses: imjohnbo/issue-bot@v3 + if: | + failure() + && github.event_name == 'schedule' + with: + title: CI Failure + labels: ci + body: | + Scheduled CI run failed. Details: + https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} test: runs-on: ubuntu-latest @@ -34,14 +49,15 @@ jobs: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: - targets: thumbv7m-none-eabi + targets: thumbv7em-none-eabihf toolchain: nightly - name: Install QEMU run: | sudo apt update sudo apt install qemu-system-arm - run: qemu-system-arm --version - - run: cargo run --target thumbv7m-none-eabi --example integration_test --all-features + - run: cargo +nightly run --target thumbv7em-none-eabihf --example llff_integration_test --all-features + - run: cargo +nightly run --target thumbv7em-none-eabihf --example tlsf_integration_test --all-features clippy: name: Clippy @@ -72,5 +88,8 @@ jobs: steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly + with: + targets: thumbv7em-none-eabihf + toolchain: nightly - name: rustdoc - run: cargo rustdoc --all-features + run: cargo +nightly rustdoc --all-features diff --git a/.github/workflows/cron.yml b/.github/workflows/cron.yml deleted file mode 100644 index ec46eb6..0000000 --- a/.github/workflows/cron.yml +++ /dev/null @@ -1,26 +0,0 @@ -on: - schedule: - # Run every week at 8am UTC Saturday. - - cron: '0 8 * * SAT' - -name: Cron CI - -jobs: - ci-cron: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: thumbv6m-none-eabi - - run: cargo check --examples --target thumbv6m-none-eabi - - uses: imjohnbo/issue-bot@v3 - if: failure() - with: - title: CI Failure - labels: ci - body: | - Scheduled CI run failed. Details: - https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c8bb34..0921f25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [Unreleased] + +### Added + +- Added a `init` macro to make initialization easier. + +### Changed + +- The `Heap::init` methods now panic if they're called more than once or with `size == 0`. + +## [v0.6.0] - 2024-09-01 + +### Added + +- Added a Two-Level Segregated Fit heap with the `tlsf` feature. + +### Changed + +- The `Heap` struct has been renamed to `LlffHeap` and requires the `llff` feature. +- Updated the rust edition from 2018 to 2021. + ## [v0.5.1] - 2023-11-04 ### Added @@ -120,7 +141,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Initial version of the allocator -[Unreleased]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.1...HEAD +[Unreleased]: https://github.com/rust-embedded/embedded-alloc/compare/v0.6.0...HEAD +[v0.6.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.1...v0.6.0 [v0.5.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.0...v0.5.1 [v0.5.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.3...v0.5.0 [v0.4.3]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.2...v0.4.3 diff --git a/Cargo.toml b/Cargo.toml index febf07f..57bd001 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ description = "A heap allocator for embedded systems" repository = "https://github.com/rust-embedded/embedded-alloc" documentation = "https://docs.rs/embedded-alloc" readme = "README.md" -edition = "2018" +edition = "2021" keywords = [ "allocator", @@ -21,20 +21,50 @@ keywords = [ ] license = "MIT OR Apache-2.0" name = "embedded-alloc" -version = "0.5.1" +version = "0.6.0" [features] +default = ["llff", "tlsf"] allocator_api = [] +# Use the Two-Level Segregated Fit allocator +tlsf = ["rlsf", "const-default"] +# Use the LinkedList first-fit allocator +llff = ["linked_list_allocator"] + [dependencies] critical-section = "1.0" - -[dependencies.linked_list_allocator] -default-features = false -version = "0.10.5" +linked_list_allocator = { version = "0.10.5", default-features = false, optional = true } +rlsf = { version = "0.2.1", default-features = false, optional = true } +const-default = { version = "1.0.0", default-features = false, optional = true } [dev-dependencies] cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } cortex-m-rt = "0.7" -cortex-m-semihosting = "0.5" -panic-semihosting = { version = "0.6", features = ["exit"] } +defmt = "1.0" +defmt-semihosting = "0.3.0" +semihosting = { version = "0.1.20", features = ["stdio"] } + +# thumbv6m-none-eabi only +[target.thumbv6m-none-eabi.dev-dependencies] +portable-atomic = { version = "1", features = ["unsafe-assume-single-core"] } + +# every other target gets the crate without the feature +[target.'cfg(not(target = "thumbv6m-none-eabi"))'.dev-dependencies] +portable-atomic = { version = "1" } + +[[example]] +name = "allocator_api" +required-features = ["allocator_api", "llff"] + +[[example]] +name = "llff_integration_test" +required-features = ["allocator_api", "llff"] + +[[example]] +name = "tlsf_integration_test" +required-features = ["allocator_api", "tlsf"] + +[[example]] +name = "global_alloc" +required-features = ["llff"] diff --git a/README.md b/README.md index 5fd93d7..868ae51 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Starting with Rust 1.68, this crate can be used as a global allocator on stable extern crate alloc; use cortex_m_rt::entry; -use embedded_alloc::Heap; +use embedded_alloc::LlffHeap as Heap; #[global_allocator] static HEAP: Heap = Heap::empty(); @@ -31,11 +31,15 @@ static HEAP: Heap = Heap::empty(); #[entry] fn main() -> ! { // Initialize the allocator BEFORE you use it + unsafe { + embedded_alloc::init!(HEAP, 1024); + } + // Alternatively, you can write the code directly to meet specific requirements. { use core::mem::MaybeUninit; const HEAP_SIZE: usize = 1024; static mut HEAP_MEM: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; - unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) } + unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) } } // now the allocator is ready types like Box, Vec can be used. @@ -48,9 +52,17 @@ For a full usage example, see [`examples/global_alloc.rs`](https://github.com/ru For this to work, an implementation of [`critical-section`](https://github.com/rust-embedded/critical-section) must be provided. -For simple use cases you may enable the `critical-section-single-core` feature in the [cortex-m](https://github.com/rust-embedded/cortex-m) crate. +For simple use cases with Cortex-M CPUs you may enable the `critical-section-single-core` feature in the [cortex-m](https://github.com/rust-embedded/cortex-m) crate. Please refer to the documentation of [`critical-section`](https://docs.rs/critical-section) for further guidance. +## Features + +There are two heaps available to use: + +* `llff`: Provides `LlffHeap`, a Linked List First Fit heap. +* `tlsf`: Provides `TlsfHeap`, a Two-Level Segregated Fit heap. + +The best heap to use will depend on your application, see [#78](https://github.com/rust-embedded/embedded-alloc/pull/78) for more discussion. ## License diff --git a/examples/allocator_api.rs b/examples/allocator_api.rs index 95ab702..cca48b3 100644 --- a/examples/allocator_api.rs +++ b/examples/allocator_api.rs @@ -1,14 +1,15 @@ +//! This examples requires nightly for the allocator API. #![feature(allocator_api)] #![no_std] #![no_main] extern crate alloc; -use alloc::vec::Vec; -use core::mem::MaybeUninit; -use core::panic::PanicInfo; +use core::{mem::MaybeUninit, panic::PanicInfo}; +use cortex_m as _; use cortex_m_rt::entry; -use embedded_alloc::Heap; +use defmt_semihosting as _; +use embedded_alloc::LlffHeap as Heap; // This is not used, but as of 2023-10-29 allocator_api cannot be used without // a global heap @@ -20,16 +21,18 @@ fn main() -> ! { const HEAP_SIZE: usize = 16; static mut HEAP_MEM: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; let heap: Heap = Heap::empty(); - unsafe { heap.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) } + unsafe { heap.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) } - let mut xs = Vec::new_in(heap); - xs.push(1); + let mut vec = alloc::vec::Vec::new_in(heap); + vec.push(1); - #[allow(clippy::empty_loop)] - loop { /* .. */ } + defmt::info!("Allocated vector: {:?}", vec.as_slice()); + + semihosting::process::exit(0); } #[panic_handler] -fn panic(_: &PanicInfo) -> ! { - loop {} +fn panic(info: &PanicInfo) -> ! { + defmt::error!("{}", info); + semihosting::process::exit(0); } diff --git a/examples/global_alloc.rs b/examples/global_alloc.rs index 812c9f1..9f1f723 100644 --- a/examples/global_alloc.rs +++ b/examples/global_alloc.rs @@ -3,10 +3,15 @@ extern crate alloc; -use alloc::vec::Vec; -use core::panic::PanicInfo; +use cortex_m as _; use cortex_m_rt::entry; -use embedded_alloc::Heap; +use defmt_semihosting as _; + +use core::panic::PanicInfo; +// Linked-List First Fit Heap allocator (feature = "llff") +use embedded_alloc::LlffHeap as Heap; +// Two-Level Segregated Fit Heap allocator (feature = "tlsf") +// use embedded_alloc::TlsfHeap as Heap; #[global_allocator] static HEAP: Heap = Heap::empty(); @@ -14,21 +19,23 @@ static HEAP: Heap = Heap::empty(); #[entry] fn main() -> ! { // Initialize the allocator BEFORE you use it - { - use core::mem::MaybeUninit; - const HEAP_SIZE: usize = 1024; - static mut HEAP_MEM: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; - unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) } + unsafe { + embedded_alloc::init!(HEAP, 1024); } - let mut xs = Vec::new(); - xs.push(1); + let vec = alloc::vec![1]; + + defmt::info!("Allocated vector: {:?}", vec.as_slice()); + + let string = alloc::string::String::from("Hello, world!"); + + defmt::info!("Allocated string: {:?}", string.as_str()); - #[allow(clippy::empty_loop)] - loop { /* .. */ } + semihosting::process::exit(0); } #[panic_handler] -fn panic(_: &PanicInfo) -> ! { - loop {} +fn panic(info: &PanicInfo) -> ! { + defmt::error!("{}", info); + semihosting::process::exit(0); } diff --git a/examples/integration_test.rs b/examples/llff_integration_test.rs similarity index 65% rename from examples/integration_test.rs rename to examples/llff_integration_test.rs index a45ba87..edf3220 100644 --- a/examples/integration_test.rs +++ b/examples/llff_integration_test.rs @@ -7,7 +7,7 @@ //! After toolchain installation this test can be run with: //! //! ```bash -//! cargo +nightly run --target thumbv7m-none-eabi --example integration_test --all-features +//! cargo +nightly run --target thumbv7m-none-eabi --example llff_integration_test --all-features //! ``` //! //! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html @@ -17,13 +17,16 @@ #![no_std] extern crate alloc; -extern crate panic_semihosting; use alloc::vec::Vec; -use core::mem::{size_of, MaybeUninit}; +use core::{ + mem::{size_of, MaybeUninit}, + panic::PanicInfo, +}; +use cortex_m as _; use cortex_m_rt::entry; -use cortex_m_semihosting::{debug, hprintln}; -use embedded_alloc::Heap; +use defmt_semihosting as _; +use embedded_alloc::LlffHeap as Heap; #[global_allocator] static HEAP: Heap = Heap::empty(); @@ -45,9 +48,9 @@ fn test_global_heap() { fn test_allocator_api() { // small local heap const HEAP_SIZE: usize = 16; - let heap_mem: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; + let mut heap_mem: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; let local_heap: Heap = Heap::empty(); - unsafe { local_heap.init(heap_mem.as_ptr() as usize, HEAP_SIZE) } + unsafe { local_heap.init(&raw mut heap_mem as usize, HEAP_SIZE) } assert_eq!(local_heap.used(), 0); @@ -61,28 +64,31 @@ fn test_allocator_api() { assert_eq!(v.as_slice(), &[0xCAFE, 0xDEAD, 0xFEED]); } +pub type TestTable<'a> = &'a [(fn() -> (), &'static str)]; + #[entry] fn main() -> ! { - { - const HEAP_SIZE: usize = 1024; - static mut HEAP_MEM: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; - unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) } + unsafe { + embedded_alloc::init!(HEAP, 1024); } - #[allow(clippy::type_complexity)] - let tests: &[(fn() -> (), &'static str)] = &[ + let tests: TestTable = &[ (test_global_heap, "test_global_heap"), (test_allocator_api, "test_allocator_api"), ]; for (test_fn, test_name) in tests { - hprintln!("{}: start", test_name); + defmt::info!("{}: start", test_name); test_fn(); - hprintln!("{}: pass", test_name); + defmt::info!("{}: pass", test_name); } // exit QEMU with a success status - debug::exit(debug::EXIT_SUCCESS); - #[allow(clippy::empty_loop)] - loop {} + semihosting::process::exit(0); +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + defmt::error!("{}", info); + semihosting::process::exit(-1); } diff --git a/examples/tlsf_integration_test.rs b/examples/tlsf_integration_test.rs new file mode 100644 index 0000000..5bf5601 --- /dev/null +++ b/examples/tlsf_integration_test.rs @@ -0,0 +1,109 @@ +//! This is a very basic smoke test that runs in QEMU +//! Reference the QEMU section of the [Embedded Rust Book] for more information +//! +//! This only tests integration of the allocator on an embedded target. +//! Comprehensive allocator tests are located in the allocator dependency. +//! +//! After toolchain installation this test can be run with: +//! +//! ```bash +//! cargo +nightly run --target thumbv7m-none-eabi --example tlsf_integration_test --all-features +//! ``` +//! +//! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html + +#![feature(allocator_api)] +#![no_main] +#![no_std] + +extern crate alloc; +use defmt_semihosting as _; + +use alloc::collections::LinkedList; +use core::{mem::MaybeUninit, panic::PanicInfo}; +use cortex_m as _; +use cortex_m_rt::entry; +use embedded_alloc::TlsfHeap as Heap; + +#[global_allocator] +static HEAP: Heap = Heap::empty(); +const HEAP_SIZE: usize = 30 * 1024; + +pub type TestTable<'a> = &'a [(fn() -> (), &'static str)]; + +fn test_global_heap() { + const ELEMS: usize = 250; + + let mut allocated = LinkedList::new(); + for _ in 0..ELEMS { + allocated.push_back(0); + } + for i in 0..ELEMS { + allocated.push_back(i as i32); + } + + assert_eq!(allocated.len(), 2 * ELEMS); + + for _ in 0..ELEMS { + allocated.pop_front(); + } + + for i in 0..ELEMS { + assert_eq!(allocated.pop_front().unwrap(), i as i32); + } +} + +fn test_allocator_api() { + // small local heap + const HEAP_SIZE: usize = 256; + let mut heap_mem: [MaybeUninit; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; + let local_heap: Heap = Heap::empty(); + unsafe { local_heap.init(heap_mem.as_mut_ptr() as usize, HEAP_SIZE) } + + const ELEMS: usize = 2; + + let mut allocated = LinkedList::new_in(local_heap); + for _ in 0..ELEMS { + allocated.push_back(0); + } + for i in 0..ELEMS { + allocated.push_back(i as i32); + } + + assert_eq!(allocated.len(), 2 * ELEMS); + + for _ in 0..ELEMS { + allocated.pop_front(); + } + + for i in 0..ELEMS { + assert_eq!(allocated.pop_front().unwrap(), i as i32); + } +} + +#[entry] +fn main() -> ! { + unsafe { + embedded_alloc::init!(HEAP, HEAP_SIZE); + } + + let tests: TestTable = &[ + (test_global_heap, "test_global_heap"), + (test_allocator_api, "test_allocator_api"), + ]; + + for (test_fn, test_name) in tests { + defmt::info!("{}: start", test_name); + test_fn(); + defmt::info!("{}: pass", test_name); + } + + // exit QEMU with a success status + semihosting::process::exit(0); +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + defmt::error!("{}", info); + semihosting::process::exit(-1); +} diff --git a/qemu-runner.sh b/qemu-runner.sh new file mode 100755 index 0000000..f0ffe99 --- /dev/null +++ b/qemu-runner.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# This requires you to previously run `cargo install defmt-print` + +# See https://ferroussystems.hackmd.io/@jonathanpallant/ryA1S6QDJx for a description of all the relevant QEMU machines +TARGET="" +ELF_BINARY="" + +# very small argument parser +while [[ $# -gt 0 ]]; do + case "$1" in + --target) TARGET="$2"; shift 2 ;; + *) ELF_BINARY="$1"; shift ;; + esac +done + +# default to the target cargo is currently building for +TARGET="${TARGET:-thumbv7em-none-eabihf}" + +case "$TARGET" in + thumbv6m-none-eabi) + MACHINE="-cpu cortex-m3 -machine mps2-an385" ;; + thumbv7em-none-eabihf) + # All suitable for thumbv7em-none-eabihf + MACHINE="-cpu cortex-m4 -machine mps2-an386" ;; + # MACHINE="-cpu cortex-m7 -machine mps2-387" ;; + # MACHINE="-cpu cortex-m7 -machine mps2-500" + *) + echo "Unsupported target: $TARGET" >&2 + exit 1 ;; +esac + +LOG_FORMAT='{[{L}]%bold} {s} {({ff}:{l:1})%dimmed}' + +echo "Running on '$MACHINE'..." +echo "------------------------------------------------------------------------" +qemu-system-arm $MACHINE -semihosting-config enable=on,target=native -nographic -kernel $ELF_BINARY | defmt-print -e $ELF_BINARY --log-format="$LOG_FORMAT" +echo "------------------------------------------------------------------------" diff --git a/src/lib.rs b/src/lib.rs index cc9fe1e..0b6bd29 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,114 +1,66 @@ #![doc = include_str!("../README.md")] #![no_std] #![cfg_attr(feature = "allocator_api", feature(allocator_api, alloc_layout_extra))] +#![warn(missing_docs)] -use core::alloc::{GlobalAlloc, Layout}; -use core::cell::RefCell; -use core::ptr::{self, NonNull}; +#[cfg(feature = "llff")] +mod llff; +#[cfg(feature = "tlsf")] +mod tlsf; -use critical_section::Mutex; -use linked_list_allocator::Heap as LLHeap; +#[cfg(feature = "llff")] +pub use llff::Heap as LlffHeap; +#[cfg(feature = "tlsf")] +pub use tlsf::Heap as TlsfHeap; -pub struct Heap { - heap: Mutex>, -} - -impl Heap { - /// Crate a new UNINITIALIZED heap allocator - /// - /// You must initialize this heap using the - /// [`init`](Self::init) method before using the allocator. - pub const fn empty() -> Heap { - Heap { - heap: Mutex::new(RefCell::new(LLHeap::empty())), - } - } - - /// Initializes the heap - /// - /// This function must be called BEFORE you run any code that makes use of the - /// allocator. - /// - /// `start_addr` is the address where the heap will be located. - /// - /// `size` is the size of the heap in bytes. - /// - /// Note that: - /// - /// - The heap grows "upwards", towards larger addresses. Thus `start_addr` will - /// be the smallest address used. - /// - /// - The largest address used is `start_addr + size - 1`, so if `start_addr` is - /// `0x1000` and `size` is `0x30000` then the allocator won't use memory at - /// addresses `0x31000` and larger. - /// - /// # Safety - /// - /// Obey these or Bad Stuff will happen. - /// - /// - This function must be called exactly ONCE. - /// - `size > 0` - pub unsafe fn init(&self, start_addr: usize, size: usize) { - critical_section::with(|cs| { - self.heap - .borrow(cs) - .borrow_mut() - .init(start_addr as *mut u8, size); - }); - } - - /// Returns an estimate of the amount of bytes in use. - pub fn used(&self) -> usize { - critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().used()) - } - - /// Returns an estimate of the amount of bytes available. - pub fn free(&self) -> usize { - critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().free()) - } - - fn alloc_first_fit(&self, layout: Layout) -> Result, ()> { - critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().allocate_first_fit(layout)) - } -} - -unsafe impl GlobalAlloc for Heap { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - self.alloc_first_fit(layout) - .ok() - .map_or(ptr::null_mut(), |allocation| allocation.as_ptr()) - } - - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - critical_section::with(|cs| { - self.heap - .borrow(cs) - .borrow_mut() - .deallocate(NonNull::new_unchecked(ptr), layout) - }); - } -} - -#[cfg(feature = "allocator_api")] -mod allocator_api { - use core::alloc::{AllocError, Allocator, GlobalAlloc, Layout}; - use core::ptr::NonNull; - - unsafe impl Allocator for crate::Heap { - fn allocate(&self, layout: Layout) -> Result, AllocError> { - match layout.size() { - 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), - size => self - .alloc_first_fit(layout) - .map(|allocation| NonNull::slice_from_raw_parts(allocation, size)) - .map_err(|_| AllocError), - } - } - - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - if layout.size() != 0 { - self.dealloc(ptr.as_ptr(), layout); - } - } - } +/// Initialize the global heap. +/// +/// This macro creates a static, uninitialized memory buffer of the specified size and +/// initializes the heap instance with that buffer. +/// +/// # Parameters +/// +/// - `$heap:ident`: The identifier of the global heap instance to initialize. +/// - `$size:expr`: An expression evaluating to a `usize` that specifies the size of the +/// static memory buffer in bytes. It must be **greater than zero**. +/// +/// # Safety +/// +/// This macro must be called first, before any operations on the heap, and **only once**. +/// It internally calls `Heap::init(...)` on the heap, +/// so `Heap::init(...)` should not be called directly if this macro is used. +/// +/// # Panics +/// +/// This macro will panic if either of the following are true: +/// +/// - this function is called more than ONCE. +/// - `size == 0`. +/// +/// # Example +/// +/// ```rust +/// use cortex_m_rt::entry; +/// use embedded_alloc::LlffHeap as Heap; +/// +/// #[global_allocator] +/// static HEAP: Heap = Heap::empty(); +/// +/// #[entry] +/// fn main() -> ! { +/// // Initialize the allocator BEFORE you use it +/// unsafe { +/// embedded_alloc::init!(HEAP, 1024); +/// } +/// let mut xs = Vec::new(); +/// // ... +/// } +/// ``` +#[macro_export] +macro_rules! init { + ($heap:ident, $size:expr) => { + static mut HEAP_MEM: [::core::mem::MaybeUninit; $size] = + [::core::mem::MaybeUninit::uninit(); $size]; + $heap.init(&raw mut HEAP_MEM as usize, $size) + }; } diff --git a/src/llff.rs b/src/llff.rs new file mode 100644 index 0000000..aae2485 --- /dev/null +++ b/src/llff.rs @@ -0,0 +1,127 @@ +use core::alloc::{GlobalAlloc, Layout}; +use core::cell::RefCell; +use core::ptr::{self, NonNull}; + +use critical_section::Mutex; +use linked_list_allocator::Heap as LLHeap; + +/// A linked list first fit heap. +pub struct Heap { + heap: Mutex>, +} + +impl Heap { + /// Create a new UNINITIALIZED heap allocator + /// + /// You must initialize this heap using the + /// [`init`](Self::init) method before using the allocator. + pub const fn empty() -> Heap { + Heap { + heap: Mutex::new(RefCell::new((LLHeap::empty(), false))), + } + } + + /// Initializes the heap + /// + /// This function must be called BEFORE you run any code that makes use of the + /// allocator. + /// + /// `start_addr` is the address where the heap will be located. + /// + /// `size` is the size of the heap in bytes. + /// + /// Note that: + /// + /// - The heap grows "upwards", towards larger addresses. Thus `start_addr` will + /// be the smallest address used. + /// + /// - The largest address used is `start_addr + size - 1`, so if `start_addr` is + /// `0x1000` and `size` is `0x30000` then the allocator won't use memory at + /// addresses `0x31000` and larger. + /// + /// # Safety + /// + /// This function is safe if the following invariants hold: + /// + /// - `start_addr` points to valid memory. + /// - `size` is correct. + /// + /// # Panics + /// + /// This function will panic if either of the following are true: + /// + /// - this function is called more than ONCE. + /// - `size == 0`. + pub unsafe fn init(&self, start_addr: usize, size: usize) { + assert!(size > 0); + critical_section::with(|cs| { + let mut heap = self.heap.borrow_ref_mut(cs); + assert!(!heap.1); + heap.1 = true; + heap.0.init(start_addr as *mut u8, size); + }); + } + + /// Returns an estimate of the amount of bytes in use. + pub fn used(&self) -> usize { + critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.used()) + } + + /// Returns an estimate of the amount of bytes available. + pub fn free(&self) -> usize { + critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.free()) + } + + fn alloc(&self, layout: Layout) -> Option> { + critical_section::with(|cs| { + self.heap + .borrow_ref_mut(cs) + .0 + .allocate_first_fit(layout) + .ok() + }) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + critical_section::with(|cs| { + self.heap + .borrow_ref_mut(cs) + .0 + .deallocate(NonNull::new_unchecked(ptr), layout) + }); + } +} + +unsafe impl GlobalAlloc for Heap { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + self.alloc(layout) + .map_or(ptr::null_mut(), |allocation| allocation.as_ptr()) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + self.dealloc(ptr, layout); + } +} + +#[cfg(feature = "allocator_api")] +mod allocator_api { + use super::*; + use core::alloc::{AllocError, Allocator}; + + unsafe impl Allocator for Heap { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + match layout.size() { + 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), + size => self.alloc(layout).map_or(Err(AllocError), |allocation| { + Ok(NonNull::slice_from_raw_parts(allocation, size)) + }), + } + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + if layout.size() != 0 { + self.dealloc(ptr.as_ptr(), layout); + } + } + } +} diff --git a/src/tlsf.rs b/src/tlsf.rs new file mode 100644 index 0000000..05664b9 --- /dev/null +++ b/src/tlsf.rs @@ -0,0 +1,116 @@ +use core::alloc::{GlobalAlloc, Layout}; +use core::cell::RefCell; +use core::ptr::{self, NonNull}; + +use const_default::ConstDefault; +use critical_section::Mutex; +use rlsf::Tlsf; + +type TlsfHeap = Tlsf<'static, usize, usize, { usize::BITS as usize }, { usize::BITS as usize }>; + +/// A two-Level segregated fit heap. +pub struct Heap { + heap: Mutex>, +} + +impl Heap { + /// Create a new UNINITIALIZED heap allocator + /// + /// You must initialize this heap using the + /// [`init`](Self::init) method before using the allocator. + pub const fn empty() -> Heap { + Heap { + heap: Mutex::new(RefCell::new((ConstDefault::DEFAULT, false))), + } + } + + /// Initializes the heap + /// + /// This function must be called BEFORE you run any code that makes use of the + /// allocator. + /// + /// `start_addr` is the address where the heap will be located. + /// + /// `size` is the size of the heap in bytes. + /// + /// Note that: + /// + /// - The heap grows "upwards", towards larger addresses. Thus `start_addr` will + /// be the smallest address used. + /// + /// - The largest address used is `start_addr + size - 1`, so if `start_addr` is + /// `0x1000` and `size` is `0x30000` then the allocator won't use memory at + /// addresses `0x31000` and larger. + /// + /// # Safety + /// + /// This function is safe if the following invariants hold: + /// + /// - `start_addr` points to valid memory. + /// - `size` is correct. + /// + /// # Panics + /// + /// This function will panic if either of the following are true: + /// + /// - this function is called more than ONCE. + /// - `size == 0`. + pub unsafe fn init(&self, start_addr: usize, size: usize) { + assert!(size > 0); + critical_section::with(|cs| { + let mut heap = self.heap.borrow_ref_mut(cs); + assert!(!heap.1); + heap.1 = true; + let block: NonNull<[u8]> = + NonNull::slice_from_raw_parts(NonNull::new_unchecked(start_addr as *mut u8), size); + heap.0.insert_free_block_ptr(block); + }); + } + + fn alloc(&self, layout: Layout) -> Option> { + critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.allocate(layout)) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + critical_section::with(|cs| { + self.heap + .borrow_ref_mut(cs) + .0 + .deallocate(NonNull::new_unchecked(ptr), layout.align()) + }) + } +} + +unsafe impl GlobalAlloc for Heap { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + self.alloc(layout) + .map_or(ptr::null_mut(), |allocation| allocation.as_ptr()) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + self.dealloc(ptr, layout) + } +} + +#[cfg(feature = "allocator_api")] +mod allocator_api { + use super::*; + use core::alloc::{AllocError, Allocator}; + + unsafe impl Allocator for Heap { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + match layout.size() { + 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), + size => self.alloc(layout).map_or(Err(AllocError), |allocation| { + Ok(NonNull::slice_from_raw_parts(allocation, size)) + }), + } + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + if layout.size() != 0 { + self.dealloc(ptr.as_ptr(), layout); + } + } + } +}