| 1 | /* |
| 2 | * This program is free software; you can redistribute it and/or modify |
| 3 | * it under the terms of the GNU General Public License as published by |
| 4 | * the Free Software Foundation; either version 2 of the License, or |
| 5 | * (at your option) any later version. |
| 6 | * |
| 7 | * This program is distributed in the hope that it will be useful, |
| 8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 10 | * GNU General Public License for more details. |
| 11 | * |
| 12 | * You should have received a copy of the GNU General Public License |
| 13 | * along with this program; if not, write to the Free Software |
| 14 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 15 | * |
| 16 | * Copyright (c) 2009 Mathieu Desnoyers |
| 17 | */ |
| 18 | |
| 19 | /* 16 CPUs max (byte has 8 bits, divided in two) */ |
| 20 | |
| 21 | #ifndef CONFIG_BITS_PER_BYTE |
| 22 | #define BITS_PER_BYTE 8 |
| 23 | #else |
| 24 | // test progress failure with shorter byte size. Will fail with 5 proc. |
| 25 | #define BITS_PER_BYTE CONFIG_BITS_PER_BYTE |
| 26 | #endif |
| 27 | |
| 28 | #define HBPB (BITS_PER_BYTE / 2) /* 4 */ |
| 29 | #define HMASK ((1 << HBPB) - 1) /* 0x0F */ |
| 30 | |
| 31 | /* for byte type */ |
| 32 | #define LOW_HALF(val) ((val) & HMASK) |
| 33 | #define LOW_HALF_INC 1 |
| 34 | |
| 35 | #define HIGH_HALF(val) ((val) & (HMASK << HBPB)) |
| 36 | #define HIGH_HALF_INC (1 << HBPB) |
| 37 | |
| 38 | byte lock = 0; |
| 39 | byte refcount = 0; |
| 40 | |
| 41 | inline spin_lock(lock, ticket) |
| 42 | { |
| 43 | atomic { |
| 44 | ticket = HIGH_HALF(lock) >> HBPB; |
| 45 | lock = lock + HIGH_HALF_INC; /* overflow expected */ |
| 46 | } |
| 47 | |
| 48 | do |
| 49 | :: 1 -> |
| 50 | if |
| 51 | :: (LOW_HALF(lock) == ticket) -> |
| 52 | break; |
| 53 | :: else -> |
| 54 | skip; |
| 55 | fi; |
| 56 | od; |
| 57 | } |
| 58 | |
| 59 | inline spin_unlock(lock) |
| 60 | { |
| 61 | lock = HIGH_HALF(lock) | LOW_HALF(lock + LOW_HALF_INC); |
| 62 | } |
| 63 | |
| 64 | proctype proc_A() |
| 65 | { |
| 66 | byte ticket; |
| 67 | |
| 68 | do |
| 69 | :: 1 -> |
| 70 | progress_A: |
| 71 | spin_lock(lock, ticket); |
| 72 | refcount = refcount + 1; |
| 73 | refcount = refcount - 1; |
| 74 | spin_unlock(lock); |
| 75 | od; |
| 76 | } |
| 77 | |
| 78 | proctype proc_B() |
| 79 | { |
| 80 | byte ticket; |
| 81 | |
| 82 | do |
| 83 | :: 1 -> |
| 84 | spin_lock(lock, ticket); |
| 85 | refcount = refcount + 1; |
| 86 | refcount = refcount - 1; |
| 87 | spin_unlock(lock); |
| 88 | od; |
| 89 | } |
| 90 | |
| 91 | init |
| 92 | { |
| 93 | run proc_A(); |
| 94 | run proc_B(); |
| 95 | run proc_B(); |
| 96 | run proc_B(); |
| 97 | run proc_B(); |
| 98 | } |