Git Product home page Git Product logo

r3's Introduction

R3 Real-Time Operating System

Experimental static component-oriented RTOS for deeply embedded systems

Try it on Repl.it

R3-OS (or simply R3) is an experimental static RTOS that utilizes Rust's compile-time function evaluation mechanism for static configuration (creation of kernel objects and memory allocation) and const traits to decouple kernel interfaces from implementation.

  • All kernel objects are defined statically for faster boot times, compile-time checking, predictable execution, reduced RAM consumption, no runtime allocation failures, and extra security.
  • A kernel and its configurator don't require an external build tool or a specialized procedural macro, maintaining transparency and inter-crate composability.
  • The kernel API is not tied to any specific kernel implementations. Kernels are provided as separate crates, one of which an application chooses and instantiates using the trait system.
  • Leverages Rust's type safety for access control of kernel objects. Safe code can't access an object that it doesn't own.

R3 API

  • Tasks are the standard way to spawn application threads. They are kernel objects encapsulating the associated threads' execution states and can be activated by application code or automatically at boot time. Tasks have dynamic priorities and can block to relinquish the processor for lower-priority tasks.

  • R3 provides a unified interface to control interrupt lines and register interrupt handlers. Some kernels (e.g., the Arm M-Profile port of the original kernel) support unmanaged interrupt lines, which aren't masked when the kernel is handling a system call and thus provide superior real-time performance.

  • R3 supports common synchronization primitives such as mutexes, semaphores, and event groups. The mutexes can use the priority ceiling protocol to avoid unbounded priority inversion and mutual deadlock. Tasks can park themselves.

  • The kernel timing mechanism drives software timers and a system-global clock with microsecond precision. The system clock can be rewound or fast-forwarded for drift compensation.

  • Bindings are a statically-defined storage with runtime initialization and configuration-time borrow checking. They can be bound to tasks and other objects to provide safe mutable access.

  • Procedural kernel configuration facilitates componentization. The utility library includes safe container types such as Mutex and RecursiveMutex, which are built upon low-level synchronization primitives.

The Kernel

The R3 original kernel is provided as a separate package r3_kernel.

  • Traditional uniprocessor tickless real-time kernel with preemptive scheduling

  • Implements a software-based scheduler supporting a customizable number of task priorities (up to 2¹⁵ levels on a 32-bit target, though the implementation is heavily optimized for a smaller number of priorities) and an unlimited number of tasks.

  • Provides a scalable kernel timing mechanism with a logarithmic time complexity. This implementation is robust against a large interrupt processing delay.

  • Supports Arm M-Profile (all versions shipped so far), Armv7-A (no FPU), RISC-V as well as the simulator port that runs on a host system.

Example

#![feature(const_refs_to_cell)]
#![feature(const_trait_impl)]
#![feature(naked_functions)]
#![feature(const_mut_refs)]
#![feature(asm_const)]
#![no_std]
#![no_main]

// ----------------------------------------------------------------

// Instantiate the Armv7-M port
use r3_port_arm_m as port;

type System = r3_kernel::System<SystemTraits>;
port::use_port!(unsafe struct SystemTraits);
port::use_rt!(unsafe SystemTraits);
port::use_systick_tickful!(unsafe impl PortTimer for SystemTraits);

impl port::ThreadingOptions for SystemTraits {}

impl port::SysTickOptions for SystemTraits {
    // STMF401 default clock configuration
    // SysTick = AHB/8, AHB = HSI (internal 16-MHz RC oscillator)
    const FREQUENCY: u64 = 2_000_000;
}

// ----------------------------------------------------------------

use r3::{bind::bind, kernel::StaticTask, prelude::*};

struct Objects {
    task: StaticTask<System>,
}

// Instantiate the kernel, allocate object IDs
const COTTAGE: Objects = r3_kernel::build!(SystemTraits, configure_app => Objects);

/// Root configuration
const fn configure_app(b: &mut r3_kernel::Cfg<SystemTraits>) -> Objects {
    System::configure_systick(b);

    // Runtime-initialized static storage
    let count = bind((), || 1u32).finish(b);

    Objects {
        // Create a task, giving the ownership of `count`
        task: StaticTask::define()
            .start_with_bind((count.borrow_mut(),), task_body)
            .priority(2)
            .active(true)
            .finish(b),
    }
}

fn task_body(count: &mut u32) {
    // ...
}

Explore the examples directory for example projects.

Prerequisites

You need a Nightly Rust compiler. This project is heavily reliant on unstable features, so it might or might not work with a newer compiler version. See the file rust-toolchain.toml to find out which compiler version this project is currently tested with.

You also need to install Rust's cross-compilation support for your target architecture. If it's not installed, you will see a compile error like this:

error[E0463]: can't find crate for `core`
  |
  = note: the `thumbv7m-none-eabi` target may not be installed

In this case, you need to run rustup target add thumbv7m-none-eabi.

r3's People

Contributors

rng-dynamics avatar yvt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

r3's Issues

Unsound `transmute` in `get` method for type `List`

impl<Head: 'static + Copy, Tail: ~const Bag> const Bag for List<Head, Tail> {
fn get<T: 'static>(&self) -> Option<&T> {
// Simulate specialization
if TypeId::of::<T>().eq(&TypeId::of::<Head>()) {
Some(unsafe { transmute::<&Head, &T>(&self.0) })
} else {
self.1.get()
}
}

The safe method get used transmute to make conversion from &Head to &T. Here are two problems:

  1. Copy trait bound is not sufficient for us to safely transmute from &Head. Suggest to use trait bound such as Pod.
  2. Transmute has an overloaded return type. If you do not specify the return type it may produce a surprising type to satisfy inference1.

Footnotes

  1. https://doc.rust-lang.org/nomicon/transmutes.html.

New nightly

Please note that with rust-lang/rust#94901 merged, ~const Drop bounds should be changed to ~const core::marker::Destruct. Sorry for the inconvenience.

Replace `Init` with `const Default` or something else

Having a local trait Init is problematic for a number of reasons:

  • Init is implemented on some external types, such as ArrayVec and TokenLock, for internal use. However, Init is also exposed to the user to allow for its use with r3::hunk::Hunk, giving access to these internal-use-only trait implementations. This means removing these trait implementations is a breaking change.
  • Implementing Init in an external crate requires a dependency on r3 even if the rest of r3 is not needed at all.

The best course of action is to replace Init with something else provided by an upstream crate or a language feature.

Replace `ZeroInit` with `bytemuck::Zeroable`

r3_core::utils::ZeroInit should be replaced by bytemuck::Zeroable. The latter is derivable (which helps us remove some unsafe impls) and has a better Rust ecosystem compatibility.

Zeroable is missing the following implementations:

  • core::atomic::Atomic{Bool,{U,I}{8,16,32,64,size},Ptr<impl Sized>} (Lokathor/bytemuck#74)
  • Option<fn(Args...) -> R>
  • Option<&[mut ]_>
  • UnsafeCell<impl Zeroable> (Lokathor/bytemuck#148)
  • [impl Zeroable + Sized] Zeroable requires Sized

Fix GitHub workflow badge

badges/shields#8671

r3/README.md

Line 10 in ecfb4e1

<img src="https://img.shields.io/github/workflow/status/r3-os/r3/CI/%F0%9F%A6%86?style=for-the-badge"> <img src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue?style=for-the-badge"> <a href="https://crates.io/crates/r3"><img src="https://img.shields.io/crates/v/r3?style=for-the-badge"></a> <a href="https://r3-os.github.io/r3/doc/r3/index.html"><img src="https://r3-os.github.io/r3/doc/badge.svg"></a>

Object names

Kernel objects should be able to have names for runtime inspection and to improve the configuration-time error reporting.

(It'd be ideal if we could also track their definition sites, but that would require std::backtrace::Backtrace::frames to be usable in const fn.)

Traitize: Remaining issues

Raw interface specificity:

  • Should the priority-based scheduling be enforced at API level? How should the test suite handle kernels without strict scheduling?
  • Some kernel implementations may prefer not returning BadId and causing an undefined behavior instead.

Raw interface extensibility:

  • MutexProtocol should be non_exhaustive? How is the kernel supposed to deal with unknown values?
  • The same goes for QueueOrder
  • Multi-processing
  • Some properties added to a Bag might be unsafe to ignore. How can we ensure the safety? What properties might fall under this criterion?

API design:

  • Implement object safety
  • The definer methods should be named define to make room for runtime construction.
  • r3::kernel::Cfg isn't a pretty name.
  • Kernel is not a raw trait. KernelMutex is a raw trait. But they are both in traits.
  • Is it really a good idea to require application code to use raw traits in trait bounds but use Kernel for global operations? Kernel being a kitchen sink is actually consistent with higher-level kernel object wrappers (like how Task::set_priority is bound by System: raw::KernelTaskSetPriority). But the real problem is that the raw traits are supposed to be bound by kernel-side semver guarantees.

r3_kernel:

  • r3_kernel::CfgBuilder is an awful name.

Documentation:

  • Update CHANGELOG.md
  • Define the versioning scheme

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.