| 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 | #define BITS_PER_BYTE CONFIG_BITS_PER_BYTE |
| 25 | #endif |
| 26 | |
| 27 | #define HBPB (BITS_PER_BYTE / 2) /* 4 */ |
| 28 | #define HMASK ((1 << HBPB) - 1) /* 0x0F */ |
| 29 | |
| 30 | /* for byte type */ |
| 31 | #define LOW_HALF(val) ((val) & HMASK) |
| 32 | #define LOW_HALF_INC 1 |
| 33 | |
| 34 | #define HIGH_HALF(val) ((val) & (HMASK << HBPB)) |
| 35 | #define HIGH_HALF_INC (1 << HBPB) |
| 36 | |
| 37 | byte lock = 0; |
| 38 | byte refcount = 0; |
| 39 | |
| 40 | inline spin_lock(lock, ticket) |
| 41 | { |
| 42 | atomic { |
| 43 | ticket = HIGH_HALF(lock) >> HBPB; |
| 44 | lock = lock + HIGH_HALF_INC; /* overflow expected */ |
| 45 | } |
| 46 | |
| 47 | do |
| 48 | :: 1 -> |
| 49 | if |
| 50 | :: (LOW_HALF(lock) == ticket) -> |
| 51 | break; |
| 52 | :: else -> |
| 53 | skip; |
| 54 | fi; |
| 55 | od; |
| 56 | } |
| 57 | |
| 58 | inline spin_unlock(lock) |
| 59 | { |
| 60 | lock = HIGH_HALF(lock) | LOW_HALF(lock + LOW_HALF_INC); |
| 61 | } |
| 62 | |
| 63 | proctype proc_X() |
| 64 | { |
| 65 | byte ticket; |
| 66 | |
| 67 | do |
| 68 | :: 1-> |
| 69 | spin_lock(lock, ticket); |
| 70 | refcount = refcount + 1; |
| 71 | refcount = refcount - 1; |
| 72 | spin_unlock(lock); |
| 73 | od; |
| 74 | } |
| 75 | |
| 76 | init |
| 77 | { |
| 78 | run proc_X(); |
| 79 | run proc_X(); |
| 80 | run proc_X(); |
| 81 | run proc_X(); |
| 82 | run proc_X(); |
| 83 | } |