From fd4d7c513914b6a58e13939442d09918b4eaa92d Mon Sep 17 00:00:00 2001 From: Jonathan 'theJPster' Pallant Date: Fri, 9 Nov 2018 15:40:05 +0000 Subject: [PATCH] Moved the start/registers.md content into peripherals/ --- src/peripherals/a-first-attempt.md | 180 ++++++++++++++++++----------- src/peripherals/peripherals.md | 17 ++- src/start/registers.md | 122 +------------------ 3 files changed, 125 insertions(+), 194 deletions(-) diff --git a/src/peripherals/a-first-attempt.md b/src/peripherals/a-first-attempt.md index 1c55952..12f55b0 100644 --- a/src/peripherals/a-first-attempt.md +++ b/src/peripherals/a-first-attempt.md @@ -1,97 +1,139 @@ # A First Attempt -## Arbitrary Memory Locations and Rust +## The Registers -Although Rust is capable of interacting with arbitrary memory locations, dereferencing any pointer is considered an `unsafe` operation. The most direct way to expose reading from or writing to a peripheral would look something like this: +Let's look at the 'SysTick' peripheral - a simple timer which comes with every Cortex-M processor core. Typically you'll be looking these up in the chip manufacturer's data sheet or *Technical Reference Manual*, but this example is common to all ARM Cortex-M cores, let's look in the [ARM reference manual]. We see there are four registers: + +[ARM reference manual]: http://infocenter.arm.com/help/topic/com.arm.doc.dui0553a/Babieigh.html + +| Offset | Name | Description | Width | +|--------|-------------|-----------------------------|--------| +| 0x00 | SYST_CSR | Control and Status Register | 32 bits| +| 0x04 | SYST_RVR | Reload Value Register | 32 bits| +| 0x08 | SYST_CVR | Current Value Register | 32 bits| +| 0x0C | SYST_CALIB | Calibration Value Register | 32 bits| + +## The C Approach + +In Rust, we can represent a collection of registers in exactly the same way as we do in C - with a `struct`. ```rust -use core::ptr; -const SER_PORT_SPEED_REG: *mut u32 = 0x4000_1000 as _; - -fn read_serial_port_speed() -> u32 { - unsafe { // <-- :( - ptr::read_volatile(SER_PORT_SPEED_REG) - } -} -fn write_serial_port_speed(val: u32) { - unsafe { // <-- :( - ptr::write_volatile(SER_PORT_SPEED_REG, val); - } +#[repr(C)] +struct SysTick { + pub csr: u32, + pub rvr: u32, + pub cvr: u32, + pub calib: u32, } ``` -Although this works, it is subjectively a little messy, so the first reaction might be to wrap these related things into a `struct` to better organize them. A second attempt could come up with something like this: +The qualifier `#[repr(C)]` tells the Rust compiler to lay this structure out like a C compiler would. That's very important, as Rust allows structure fields to be re-ordered, while C does not. You can imagine the debugging we'd have to do if these fields were silently re-arranged by the compiler! With this qualifier in place, we have our four 32-bit fields which correspond to the table above. But of course, this `struct` is of no use by itself - we need a variable. ```rust -use core::ptr; +let systick = 0xE000_E010 as *mut SysTick; +let time = unsafe { (*systick).cvr }; +``` -struct SerialPort; +## Volatile Accesses -impl SerialPort { - // Private Constants (addresses) - const SER_PORT_SPEED_REG: *mut u32 = 0x4000_1000 as _; +Now, there are a couple of problems with the approach above. - // Public Constants (enumerated values) - pub const SER_PORT_SPEED_8MBPS: u32 = 0x8000_0000; - pub const SER_PORT_SPEED_125KBPS: u32 = 0x0200_0000; +1. We have to use unsafe every time we want to access our Peripheral. +2. We've got no way of specifying which registers are read-only or read-write. +3. Any piece of code anywhere in your program could access the hardware + through this structure. +4. Most importantly, it doesn't actually work... - fn new() -> SerialPort { - SerialPort - } +Now, the problem is that compilers are clever. If you make two writes to the same piece of RAM, one after the other, the compiler can notice this and just skip the first write entirely. In C, we can mark variables as `volatile` to ensure that every read or write occurs as intended. In Rust, we instead mark the *accesses* as volatile, not the variable. - fn read_speed(&self) -> u32 { - unsafe { - ptr::read_volatile(Self::SER_PORT_SPEED_REG) +```rust +let systick = unsafe { &mut *(0xE000_E010 as *mut SysTick) }; +let time = unsafe { std::ptr::read_volatile(&mut systick.cvr) }; +``` + +So, we've fixed one of our four problems, but now we have even more `unsafe` code! Fortunately, there's a third party crate which can help - [`volatile_register`]. + +[`volatile_register`]: https://crates.io/crates/volatile_register + +```rust +use volatile_register::{RW, RO}; + +#[repr(C)] +struct SysTick { + pub csr: RW, + pub rvr: RW, + pub cvr: RW, + pub calib: RO, +} + +fn get_systick() -> &'static mut SysTick { + unsafe { &mut *(0xE000_E010 as *mut SysTick) } +} + +fn get_time() -> u32 { + let systick = get_systick(); + systick.cvr.read() +} +``` + +Now, the volatile accesses are performed automatically through the `read` and `write` methods. It's still `unsafe` to perform writes, but to be fair, hardware is a bunch of mutable state and there's no way for the compiler to know whether these writes are actually safe, so this is a good default position. + +## The Rusty Wrapper + +We need to wrap this `struct` up into a higher-layer API that is safe for our users to call. As the driver author, we manually verify the unsafe code is correct, and then present a safe API for our users so they don't have to worry about it (provided they trust us to get it right!). + +One example might be: + +```rust +use volatile_register::{RW, RO}; + +pub struct SystemTimer { + p: &'static mut RegisterBlock +} + +#[repr(C)] +struct RegisterBlock { + pub csr: RW, + pub rvr: RW, + pub cvr: RW, + pub calib: RO, +} + +impl SystemTimer { + pub fn new() -> SystemTimer { + SystemTimer { + p: unsafe { &mut *(0xE000_E010 as *mut RegisterBlock) } } } - fn write_speed(&mut self, val: u32) { - unsafe { - ptr::write_volatile(Self::SER_PORT_SPEED_REG, val); - } + pub fn get_time(&self) -> u32 { + self.p.cvr.read() + } + + pub fn set_reload(&mut self, reload_value: u32) { + unsafe { self.p.rvr.write(reload_value) } } } + +pub fn example_usage() -> String { + let mut st = SystemTimer::new(); + st.set_reload(0); + format!("Time is now 0x{:08x}", st.get_time()) +} ``` -And this is a little better! We've hidden that random looking memory address, and presented something that feels a little more rusty. We can even use our new interface: +Now, the problem with this approach is that the following code is perfectly acceptable to the compiler: ```rust -fn do_something() { - let mut serial = SerialPort::new(); +fn thread1() { + let mut st = SystemTimer::new(); + st.set_reload(2000); +} - let speed = serial.read_speed(); - // Do some work - serial.write_speed(speed * 2); +fn thread2() { + let mut st = SystemTimer::new(); + st.set_reload(1000); } ``` -But the problem with this is that our `SerialPort` struct could be created anywhere. By creating multiple instances of `SerialPort`, we would create aliased mutable pointers, which are typically avoided in Rust. - -Consider the following example: - -```rust -fn do_something() { - let mut serial = SerialPort::new(); - let speed = serial.read_speed(); - - // Be careful, we have to go slow! - if speed != SerialPort::SER_PORT_SPEED_LO { - serial.write_speed(SerialPort::SER_PORT_SPEED_LO) - } - // First, send some pre-data - something_else(); - // Okay, lets send some slow data - // ... -} - -fn something_else() { - let mut serial = SerialPort::new(); - // We gotta go fast for this! - serial.write_speed(SerialPort::SER_PORT_SPEED_HI); - // send some data... -} -``` - -In this case, if we were only looking at the code in `do_something()`, we would think that we are definitely sending our serial data slowly, and would be confused why our embedded code is not working as expected. - -In this case, it is easy to see where the error was introduced. However, once this code is spread out over multiple modules, drivers, developers, and days, it gets easier and easier to make these kinds of mistakes. +Our `&mut self` argument to the `set_reload` function checks that there are no other references to *that* particular `SystemTimer` struct, but they don't stop the user creating a second `SystemTimer` which points to the exact same peripheral! Code written in this fashion will work if the author is diligent enough to spot all of these 'duplicate' driver instances, but once the code is spread out over multiple modules, drivers, developers, and days, it gets easier and easier to make these kinds of mistakes. diff --git a/src/peripherals/peripherals.md b/src/peripherals/peripherals.md index 6762fe2..d423571 100644 --- a/src/peripherals/peripherals.md +++ b/src/peripherals/peripherals.md @@ -2,21 +2,30 @@ ## What are Peripherals? +Embedded systems can only get so far by executing normal Rust code and moving data around in RAM. If we want to get any information into or out of our system (be that blinking an LED, detecting a button press or communicating with an off-chip peripheral on some sort of bus) we're going to have to dip into the world of Peripherals and their 'memory mapped registers'. + Most Microcontrollers have more than just a CPU, RAM, or Flash Memory - they contain sections of silicon which are used for interacting with systems outside of the microcontroller, as well as directly and indirectly interacting with their surroundings in the world via sensors, motor controllers, or human interfaces such as a display or keyboard. These components are collectively known as Peripherals. These peripherals are useful because they allow a developer to offload processing to them, avoiding having to handle everything in software. Similar to how a desktop developer would offload graphics processing to a video card, embedded developers can offload some tasks to peripherals allowing the CPU to spend it's time doing something else important, or doing nothing in order to save power. +If you look at the main circuit board in an old-fashioned home computer from the 1970s or 1980s (and actually, the desktop PCs of yesterday are not so far removed from the embedded systems of today) you would expect to see: + +* A processor +* A RAM chip +* A ROM chip +* An I/O controller + +The RAM chip, ROM chip and I/O controller (the peripheral in this system) would be joined to the processor through a series of parallel traces known as a 'bus'. This bus carries address information, which selects which device on the bus the processor wishes to communicate with, and a data bus which carries the actual data. In our embedded microcontrollers, the same principles apply - it's just that everything is packed on to a single piece of silicon. + However, unlike graphics cards, which typically have a Software API like Vulkan, Metal, or OpenGL, peripherals are exposed to our Microcontroller with a hardware interface, which is mapped to a chunk of the memory. ## Linear and Real Memory Space -On a microcontroller, writing some data to an arbitrary address, such as `0x4000_0000` or `0x0000_0000`, may be a completely valid action. +On a microcontroller, writing some data to some other arbitrary address, such as `0x4000_0000` or `0x0000_0000`, may also be a completely valid action. On a desktop system, access to memory is tightly controlled by the MMU, or Memory Management Unit. This component has two major responsibilities: enforcing access permission to sections of memory (preventing one thread from reading or modifying the memory of another thread); and re-mapping segments of the physical memory to virtual memory ranges used in software. Microcontrollers do not typically have an MMU, and instead only use real physical addresses in software. -Although 32 bit microcontrollers have a real and linear address space from `0x0000_0000`, and `0xFFFF_FFFF`, they generally only use a few hundred kilobytes of that range for actual memory. This leaves a significant amount of address space remaining. - -Rather than ignore that remaining space, Microcontroller designers instead mapped the interface for peripherals in certain memory locations. This ends up looking something like this: +Although 32 bit microcontrollers have a real and linear address space from `0x0000_0000`, and `0xFFFF_FFFF`, they generally only use a few hundred kilobytes of that range for actual memory. This leaves a significant amount of address space remaining. In earlier chapters, we were talking about RAM being located at address `0x2000_0000`. If our RAM was 64 KiB long (i.e. with a maximum address of 0xFFFF) then addresses `0x2000_0000` to `0x2000_FFFF` would correspond to our RAM. When we write to a variable which lives at address `0x2000_1234`, what happens internally is that some logic detects the upper portion of the address (0x2000 in this example) and then activates the RAM so that it can act upon the lower portion of the address (0x1234 in this case). On a Cortex-M we also have our Flash ROM mapped in at address `0x0000_0000` up to, say, address `0x0007_FFFF` (if we have a 512 KiB Flash ROM). Rather than ignore all remaining space between these two regions, Microcontroller designers instead mapped the interface for peripherals in certain memory locations. This ends up looking something like this: ![](../assets/nrf52-memory-map.png) diff --git a/src/start/registers.md b/src/start/registers.md index cdbbe85..fcddcfe 100644 --- a/src/start/registers.md +++ b/src/start/registers.md @@ -1,35 +1,10 @@ # Memory-mapped Registers -Embedded systems can only get so far by executing normal Rust code and moving -data around in RAM. If we want to get any information into or out of our -system (be that blinking an LED, detecting a button press or communicating -with an off-chip peripheral on some sort of bus) we're going to have to dip -into the world of 'memory mapped registers'. -If you look at the main circuit board in an old-fashioned home computer from -the 1970s or 1980s (and actually, the desktop PCs of yesterday are not so far -removed from the embedded systems of today) you would expect to see: -* A processor -* A RAM chip -* A ROM chip -* An I/O controller -The RAM chip, ROM chip and I/O controller would be joined to the processor -through a series of parallel traces known as a 'bus'. This bus carries address -information, which selects which device on the bus the processor wishes to -communicate with, and a data bus which carries the actual data. In our -embedded microcontrollers, the same principles apply - it's just that -everything is packed on to a single piece of silicon. -In earlier chapters, we were talking about RAM being located at address -`0x2000_0000`. This is a 32-bit number because the ARM Cortex-M processor -cores have a 32-bit address bus. If our RAM was 64 KiB long (i.e. with a -maximum address of 0xFFFF) then addresses `0x2000_0000` to `0x2000_FFFF` would -correspond to our RAM. When we write to a variable which lives at address -`0x2000_1234`, what happens internally is that some logic detects the upper -portion of the address (0x2000 in this example) and then activates the RAM so -that it can act upon the lower portion of the address (0x1234 in this case). + Going back to our home computer example, our I/O controller needs to operate in the same fashion as the RAM, as it sits on the same bus. Here though, @@ -46,98 +21,3 @@ baud rate of our serial connection, one for data we wish to send over the serial connection and another which lets us read any buffered data that has been received. -Let's take the 'SysTick' peripheral - a simple timer which comes with every -Cortex-M processor core. Typically you'll be looking these up in the chip -manufacturer's data sheet or *Technical Reference Manual*, but this example is -common to all ARM Cortex-M cores, let's look in the [ARM reference manual]. we -see there are four registers: - -[ARM reference manual]: http://infocenter.arm.com/help/topic/com.arm.doc.dui0553a/Babieigh.html - -| Offset | Name | Description | Width | -|--------|-------------|-----------------------------|--------| -| 0x00 | SYST_CSR | Control and Status Register | 32 bits| -| 0x04 | SYST_RVR | Reload Value Register | 32 bits| -| 0x08 | SYST_CVR | Current Value Register | 32 bits| -| 0x0C | SYST_CALIB | Calibration Value Register | 32 bits| - -In Rust, we can represent a collection of registers in exactly the same way as we do in C - with a `struct`. - -```rust -#[repr(C)] -struct SysTick { - pub csr: u32, - pub rvr: u32, - pub cvr: u32, - pub calib: u32, -} -``` - -The qualifier `#[repr(C)]` tells the Rust compiler to lay this structure out -like a C compiler would. That's very important, as Rust allows structure -fields to be re-ordered, while C does not. You can imagine the debugging we'd -have to do if these fields were silently re-arranged by the compiler! We then -have our four 32-bit fields, which should correspond to the table above. But -of course, this `struct` is of no use by itself - we need a variable. - -```rust -let systick = 0xE000_E010 as *mut SysTick; -let time = unsafe { (*systick).cvr }; -``` - -Now, there are a couple of problems with this approach. - -1. We have to use unsafe every time we want to access our Peripheral. -2. We've got no way of specifying which registers are read-only or read-write. -3. Any piece of code anywhere in your program could access the hardware - through this structure. -4. Most importantly, it doesn't actually work... - -Now, the problem is that compilers are clever. If you make two writes to the -same piece of RAM, one after the other, the compiler can notice this and just -skip the first write entirely. In C, we can mark variables as `volatile` to -ensure that every read or write occurs as intended. In Rust, we instead mark -the *accesses* as volatile, not the variable. - -```rust -let systick = unsafe { &mut *(0xE000_E010 as *mut SysTick) }; -let time = unsafe { std::ptr::read_volatile(&mut systick.cvr) }; -``` - -So, we've fixed one of our four problems, but now we have even more `unsafe` -code! Fortunately, there's a third party crate which can help - -[`volatile_register`]. - -[`volatile_register`]: https://crates.io/crates/volatile_register - -```rust -use volatile_register::{RW, RO}; - -#[repr(C)] -struct SysTick { - pub csr: RW, - pub rvr: RW, - pub cvr: RW, - pub calib: RO, -} - -fn get_systick() -> &'static mut SysTick { - unsafe { &mut *(0xE000_E010 as *mut SysTick) } -} - -fn test() { - let systick = get_systick(); - let time = systick.cvr.read(); - unsafe { systick.rvr.write(time) }; -} -``` - -Now, the volatile accesses are performed automatically through the `read` and -`write` methods. It's still `unsafe` to perform writes, but to be fair, -hardware is a bunch of mutable state and there's no way for the compiler to -know whether these writes are actually safe, so this is a good default -position. We can always wrap this `struct` into a higher level API which -verifies when these writes are safe - more on that in the chapter on [Static -Guarantees]. - -[Static Guarantees]: ../static-guarantees/static-guarantees.md