1 /* 2 * Copyright 2005-2007, Ingo Weinhold, bonefish@users.sf.net. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef KERNEL_UTIL_AUTO_LOCKER_H 6 #define KERNEL_UTIL_AUTO_LOCKER_H 7 8 9 #include <KernelExport.h> 10 11 #include <shared/AutoLocker.h> 12 13 #include <int.h> 14 #include <lock.h> 15 16 17 namespace BPrivate { 18 19 // MutexLocking 20 class MutexLocking { 21 public: 22 inline bool Lock(mutex *lockable) 23 { 24 return mutex_lock(lockable) == B_OK; 25 } 26 27 inline void Unlock(mutex *lockable) 28 { 29 mutex_unlock(lockable); 30 } 31 }; 32 33 // MutexLocker 34 typedef AutoLocker<mutex, MutexLocking> MutexLocker; 35 36 // RecursiveLockLocking 37 class RecursiveLockLocking { 38 public: 39 inline bool Lock(recursive_lock *lockable) 40 { 41 return recursive_lock_lock(lockable) == B_OK; 42 } 43 44 inline void Unlock(recursive_lock *lockable) 45 { 46 recursive_lock_unlock(lockable); 47 } 48 }; 49 50 // RecursiveLocker 51 typedef AutoLocker<recursive_lock, RecursiveLockLocking> RecursiveLocker; 52 53 // InterruptsLocking 54 class InterruptsLocking { 55 public: 56 inline bool Lock(int* lockable) 57 { 58 *lockable = disable_interrupts(); 59 return true; 60 } 61 62 inline void Unlock(int* lockable) 63 { 64 restore_interrupts(*lockable); 65 } 66 }; 67 68 // InterruptsLocker 69 class InterruptsLocker : public AutoLocker<int, InterruptsLocking> { 70 public: 71 inline InterruptsLocker(bool alreadyLocked = false, 72 bool lockIfNotLocked = true) 73 : AutoLocker<int, InterruptsLocking>(&fState, alreadyLocked, 74 lockIfNotLocked) 75 { 76 } 77 78 private: 79 int fState; 80 }; 81 82 // SpinLocking 83 class SpinLocking { 84 public: 85 inline bool Lock(spinlock* lockable) 86 { 87 acquire_spinlock(lockable); 88 return true; 89 } 90 91 inline void Unlock(spinlock* lockable) 92 { 93 release_spinlock(lockable); 94 } 95 }; 96 97 // SpinLocker 98 typedef AutoLocker<spinlock, SpinLocking> SpinLocker; 99 100 // InterruptsSpinLocking 101 class InterruptsSpinLocking { 102 public: 103 struct State { 104 State(spinlock* lock) 105 : lock(lock) 106 { 107 } 108 109 int state; 110 spinlock* lock; 111 }; 112 113 inline bool Lock(spinlock* lockable) 114 { 115 fState = disable_interrupts(); 116 acquire_spinlock(lockable); 117 return true; 118 } 119 120 inline void Unlock(spinlock* lockable) 121 { 122 release_spinlock(lockable); 123 restore_interrupts(fState); 124 } 125 126 private: 127 int fState; 128 }; 129 130 // InterruptsSpinLocker 131 typedef AutoLocker<spinlock, InterruptsSpinLocking> InterruptsSpinLocker; 132 133 } // namespace BPrivate 134 135 using BPrivate::AutoLocker; 136 using BPrivate::MutexLocker; 137 using BPrivate::RecursiveLocker; 138 using BPrivate::InterruptsLocker; 139 using BPrivate::SpinLocker; 140 using BPrivate::InterruptsSpinLocker; 141 142 #endif // KERNEL_UTIL_AUTO_LOCKER_H 143