1 | ////////////////////////////////////////////////////////////////////////////////// |
---|
2 | // File : spin_lock.c |
---|
3 | // Date : 01/04/2012 |
---|
4 | // Author : alain greiner |
---|
5 | // Copyright (c) UPMC-LIP6 |
---|
6 | /////////////////////////////////////////////////////////////////////////////////// |
---|
7 | |
---|
8 | #include <spin_lock.h> |
---|
9 | #include <stdio.h> |
---|
10 | |
---|
11 | /////////////////////////////////////////////////////////////////////////////////// |
---|
12 | // lock_acquire() |
---|
13 | // This blocking function returns only when the lock has been taken. |
---|
14 | // If the lock is already taken a random delay is introduced before retry. |
---|
15 | /////////////////////////////////////////////////////////////////////////////////// |
---|
16 | void lock_acquire(giet_lock_t * lock) |
---|
17 | { |
---|
18 | unsigned int * plock = &lock->value; |
---|
19 | unsigned int delay = giet_rand(); |
---|
20 | |
---|
21 | if (delay == 0) delay++; |
---|
22 | |
---|
23 | asm volatile ( |
---|
24 | "giet_lock_try: \n" |
---|
25 | "ll $2, 0(%0) \n" /* $2 <= _ioc_lock current value */ |
---|
26 | "bnez $2, giet_lock_delay \n" /* delay if _ioc_lock already taken */ |
---|
27 | "li $3, 1 \n" /* $3 <= argument for sc */ |
---|
28 | "sc $3, 0(%0) \n" /* try to set _ioc_lock */ |
---|
29 | "bnez $3, giet_lock_ok \n" /* exit if atomic */ |
---|
30 | |
---|
31 | "giet_lock_delay: \n" |
---|
32 | "move $4, %1 \n" /* $4 <= delay */ |
---|
33 | |
---|
34 | "giet_lock_loop: \n" |
---|
35 | "addi $4, $4, -1 \n" /* $4 <= $4 - 1 */ |
---|
36 | "bnez $4, giet_lock_loop \n" /* test end delay */ |
---|
37 | "nop \n" |
---|
38 | "j giet_lock_try \n" /* retry */ |
---|
39 | "nop \n" |
---|
40 | |
---|
41 | "giet_lock_ok: \n" |
---|
42 | : |
---|
43 | :"r"(plock), "r"(delay) |
---|
44 | :"$2", "$3", "$4"); |
---|
45 | } |
---|
46 | |
---|
47 | |
---|
48 | ////////////////////////////////////////////////////////////////////////////// |
---|
49 | // lock_release() |
---|
50 | ////////////////////////////////////////////////////////////////////////////// |
---|
51 | void lock_release(giet_lock_t * lock) |
---|
52 | { |
---|
53 | unsigned int * plock = &lock->value; |
---|
54 | |
---|
55 | asm volatile ( "sync\n" ); // necessary because of the TSAR consistency model |
---|
56 | *plock = 0; |
---|
57 | } |
---|
58 | |
---|
59 | |
---|
60 | // Local Variables: |
---|
61 | // tab-width: 4 |
---|
62 | // c-basic-offset: 4 |
---|
63 | // c-file-offsets:((innamespace . 0)(inline-open . 0)) |
---|
64 | // indent-tabs-mode: nil |
---|
65 | // End: |
---|
66 | // vim: filetype=c:expandtab:shiftwidth=4:tabstop=4:softtabstop=4 |
---|
67 | |
---|