1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2007
5 * File locking support as required by Haskell 98
7 * ---------------------------------------------------------------------------*/
13 #include "OSThreads.h"
22 int readers; // >0 : readers, <0 : writers
25 // Two hash tables. The first maps objects (device/inode pairs) to
26 // Lock objects containing the number of active readers or writers. The
27 // second maps file descriptors to lock objects, so that we can unlock
28 // by FD without needing to fstat() again.
29 static HashTable *obj_hash;
30 static HashTable *fd_hash;
33 static Mutex file_lock_mutex;
36 static int cmpLocks(StgWord w1, StgWord w2)
38 Lock *l1 = (Lock *)w1;
39 Lock *l2 = (Lock *)w2;
40 return (l1->device == l2->device && l1->inode == l2->inode);
43 static int hashLock(HashTable *table, StgWord w)
46 // Just xor the dev_t with the ino_t, hope this is good enough.
47 return hashWord(table, (StgWord)l->inode ^ (StgWord)l->device);
53 obj_hash = allocHashTable_(hashLock, cmpLocks);
54 fd_hash = allocHashTable(); /* ordinary word-based table */
56 initMutex(&file_lock_mutex);
69 freeHashTable(obj_hash, freeLock);
70 freeHashTable(fd_hash, NULL);
72 closeMutex(&file_lock_mutex);
77 lockFile(int fd, dev_t dev, ino_t ino, int for_writing)
81 ACQUIRE_LOCK(&file_lock_mutex);
86 lock = lookupHashTable(obj_hash, (StgWord)&key);
90 lock = stgMallocBytes(sizeof(Lock), "lockFile");
93 lock->readers = for_writing ? -1 : 1;
94 insertHashTable(obj_hash, (StgWord)lock, (void *)lock);
95 insertHashTable(fd_hash, fd, lock);
96 RELEASE_LOCK(&file_lock_mutex);
101 // single-writer/multi-reader locking:
102 if (for_writing || lock->readers < 0) {
103 RELEASE_LOCK(&file_lock_mutex);
106 insertHashTable(fd_hash, fd, lock);
108 RELEASE_LOCK(&file_lock_mutex);
118 ACQUIRE_LOCK(&file_lock_mutex);
120 lock = lookupHashTable(fd_hash, fd);
122 // errorBelch("unlockFile: fd %d not found", fd);
123 // This is normal: we didn't know when calling unlockFile
124 // whether this FD referred to a locked file or not.
125 RELEASE_LOCK(&file_lock_mutex);
129 if (lock->readers < 0) {
135 if (lock->readers == 0) {
136 removeHashTable(obj_hash, (StgWord)lock, NULL);
139 removeHashTable(fd_hash, fd, NULL);
141 RELEASE_LOCK(&file_lock_mutex);