Skip to content
This repository was archived by the owner on Jul 6, 2019. It is now read-only.

[WIP] Synchronization primitives #11

Merged
merged 7 commits into from
May 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions src/hal/cortex_m0/lock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use core::ty::Unsafe;
use core::option::{Option, Some, None};
use core::ops::Drop;
use core::kinds::Share;

/// A lock. Note that this disables interrupts. Consequently, a task
/// dying (e.g. by running out of stack space) while holding a lock
/// may cause a deadlock.
pub struct Lock {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a doc comment, mentioning that this lock works by disabling all the interrupts and thus is unsafe.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this mean it is unsafe? The lock routine will never loop with interrupts disabled so there shouldn't be any chance of deadlock. Am I missing something?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bump (github ate this).

locked: Unsafe<bool>
}

#[must_use]
pub struct Guard<'a>(&'a Lock);

pub static STATIC_LOCK: Lock = Lock { locked: Unsafe { value: false, marker1: InvariantType } };

impl Lock {
pub fn new() -> Lock {
Lock { locked: Unsafe::new(false) }
}

pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
unsafe {
let crit = NoInterrupts::new();
let locked = self.locked.get();
match *locked {
true => return None,
false => {
*locked = true;
return Some(Guard(self));
}
}
}
}

fn unlock<'a>(&'a self) {
unsafe {
let crit = NoInterrupts::new();
*self.locked.get() = false;
}
}
}

#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let &Guard(ref lock) = self;
lock.unlock();
}
}

impl Share for Lock { }
96 changes: 96 additions & 0 deletions src/hal/cortex_m3/lock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use core::ty::Unsafe;
use core::option::{Option, Some, None};
use core::ops::Drop;
use core::kinds::Share;
use core::kinds::marker::InvariantType;

/// A lock
pub struct Lock {
locked: Unsafe<u32>
}

#[must_use]
pub struct Guard<'a>(&'a Lock);

pub static STATIC_LOCK: Lock = Lock { locked: Unsafe { value: 0, marker1: InvariantType } };

#[inline(always)]
unsafe fn exclusive_load(addr: *u32) -> u32 {
let mut value: u32;
asm!("ldrex $0, [$1]"
: "=r"(value)
: "r"(addr)
:
: "volatile"
);
value
}

#[inline(always)]
unsafe fn exclusive_store(addr: *mut u32, value: u32) -> bool {
let mut success: u32;
asm!("strex $0, $2, [$1]"
: "=r"(success)
: "r"(addr), "r"(value)
:
: "volatile"
);
success == 0
}

impl Lock {
pub fn new() -> Lock {
Lock { locked: Unsafe::new(0) }
}

pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
unsafe {
let ptr: *mut u32 = self.locked.get();
let locked = exclusive_load(&*ptr) == 1;
let success = exclusive_store(ptr, 1);
if !locked && success {
return Some(Guard(self));
} else {
return None;
}
}
}

fn unlock<'a>(&'a self) {
unsafe {
loop {
let ptr: *mut u32 = self.locked.get();
let _locked = exclusive_load(&*ptr) == 1;
let success = exclusive_store(ptr, 0);
if success {
break;
}
}
}
}
}

#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let &Guard(ref lock) = self;
lock.unlock();
}
}

impl Share for Lock { }
1 change: 1 addition & 0 deletions src/hal/cortex_m3/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ pub mod scb;
pub mod nvic;
pub mod mpu;
#[cfg(cfg_multitasking)] pub mod sched;
#[cfg(cfg_multitasking)] pub mod lock;
52 changes: 52 additions & 0 deletions src/hal/cortex_m3/sched.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

//! Cortex-M3 specific support code for scheduler.

use core::ops::Drop;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please include core::... first, then zinc::.. separated by an empty line. Bonus points for keeping that sorted.

use core::intrinsics::abort;

use os::task::Task;
use super::scb;

Expand Down Expand Up @@ -75,7 +78,56 @@ impl SavedState {
}

// TODO(farcaller): this should actually kill the task.
// TODO(bgamari): It should also unlock anything the task holds
/// Default handler for task that tries to return.
unsafe fn task_finished() {
asm!("bkpt" :::: "volatile");
}

/// Phantom type to indicate that interrupts are disabled
pub struct NoInterrupts {
contents: ()
}

impl NoInterrupts {
pub fn new() -> NoInterrupts {
unsafe {
disable_irqs();
}
NoInterrupts { contents: () }
}
}

impl Drop for NoInterrupts {
fn drop(&mut self) {
unsafe {
enable_irqs();
}
}
}

static mut irq_level : uint = 0;

/// Disables all interrupts except Reset, HardFault, and NMI.
/// Note that this is reference counted: if `disable_irqs` is called
/// twice then interrupts will only be re-enabled upon the second call
/// to `enable_irqs`.
#[inline(always)]
unsafe fn disable_irqs() {
if irq_level == 0 {
asm!("cpsid i" :::: "volatile");
}
irq_level += 1;
}

/// Enables all interrupts except Reset, HardFault, and NMI.
#[inline(always)]
unsafe fn enable_irqs() {
if irq_level == 0 {
abort();
}
irq_level -= 1;
if irq_level == 0 {
asm!("cpsie i" :::: "volatile");
}
}
2 changes: 2 additions & 0 deletions src/lib/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@

pub mod strconv;
pub mod volatile_cell;
pub mod shared;
pub mod queue;
102 changes: 102 additions & 0 deletions src/lib/queue.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Rough structure taken from libsync's mpcs_intrusive
// all links are uint to allow for static initialization

//
// head tail
// | |--->| |--->| |--->| |--->| |
//

use core::ty::Unsafe;
use core::cmp::Ord;
use core::ops::Deref;
use core::ptr::RawPtr;
use core::option::{Option,Some,None};

use hal::cortex_m3::sched::NoInterrupts;

pub struct Node<T> {
pub next: Unsafe<*mut Node<T>>,
pub data: T
}

pub struct Queue<T> {
pub head: Unsafe<*mut Node<T>>,
pub tail: Unsafe<*mut Node<T>>
}

fn null_mut<T>() -> *mut T { 0 as *mut T }

impl<T> Queue<T> {
pub fn new() -> Queue<T> {
Queue {
head: Unsafe::new(null_mut()),
tail: Unsafe::new(null_mut())
}
}

/// Push to tail
pub unsafe fn push(&self, node: *mut Node<T>, _: &NoInterrupts) {
if (*self.head.get()).is_null() {
*self.head.get() = node;
}
let tail: *mut Node<T> = *self.tail.get();
*(*node).next.get() = null_mut();
if !tail.is_null() {
*(*tail).next.get() = node;
}
*self.tail.get() = node;
}

/// Peek at head
pub unsafe fn peek(&self) -> Option<*mut Node<T>> {
let head = self.head.get();
if (*head).is_null() {
None
} else {
Some(*head)
}
}

/// Pop off of head
pub unsafe fn pop(&self, _: &NoInterrupts) -> Option<*mut Node<T>> {
let head = self.head.get();
if (*head).is_null() {
None
} else {
*head = *(**head).next.get();
Some(*head)
}
}
}

impl<T: Ord> Queue<T> {
/// Priority insertion (higher ends up closer to head)
pub unsafe fn insert(&self, node: *mut Node<T>, _: &NoInterrupts) {
let mut next: &Unsafe<*mut Node<T>> = &self.head;
loop {
let i: *mut Node<T> = *next.get();
if i.is_null() {
break;
}
if (*i).data > (*node).data {
break;
}
next = &(*i).next;
}
*(*node).next.get() = *next.get();
*next.get() = node;
if (*(*node).next.get()).is_null() {
*self.tail.get() = node;
}
}
}

impl<T> Node<T> {
pub fn new(data: T) -> Node<T> {
Node { next: Unsafe::new(null_mut()), data: data }
}
}

impl<T> Deref<T> for Node<T> {
fn deref<'a>(&'a self) -> &'a T {&self.data}
}
Loading