1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2007
5 * File locking support as required by Haskell 98
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
23 int readers; // >0 : readers, <0 : writers
26 // Two hash tables. The first maps objects (device/inode pairs) to
27 // Lock objects containing the number of active readers or writers. The
28 // second maps file descriptors to lock objects, so that we can unlock
29 // by FD without needing to fstat() again.
30 static HashTable *obj_hash;
31 static HashTable *fd_hash;
34 static Mutex file_lock_mutex;
37 static int cmpLocks(StgWord w1, StgWord w2)
39 Lock *l1 = (Lock *)w1;
40 Lock *l2 = (Lock *)w2;
41 return (l1->device == l2->device && l1->inode == l2->inode);
44 static int hashLock(HashTable *table, StgWord w)
47 // Just xor the dev_t with the ino_t, hope this is good enough.
48 return hashWord(table, (StgWord)l->inode ^ (StgWord)l->device);
54 obj_hash = allocHashTable_(hashLock, cmpLocks);
55 fd_hash = allocHashTable(); /* ordinary word-based table */
57 initMutex(&file_lock_mutex);
70 freeHashTable(obj_hash, freeLock);
71 freeHashTable(fd_hash, NULL);
73 closeMutex(&file_lock_mutex);
78 lockFile(int fd, dev_t dev, ino_t ino, int for_writing)
82 ACQUIRE_LOCK(&file_lock_mutex);
87 lock = lookupHashTable(obj_hash, (StgWord)&key);
91 lock = stgMallocBytes(sizeof(Lock), "lockFile");
94 lock->readers = for_writing ? -1 : 1;
95 insertHashTable(obj_hash, (StgWord)lock, (void *)lock);
96 insertHashTable(fd_hash, fd, lock);
97 RELEASE_LOCK(&file_lock_mutex);
102 // single-writer/multi-reader locking:
103 if (for_writing || lock->readers < 0) {
104 RELEASE_LOCK(&file_lock_mutex);
107 insertHashTable(fd_hash, fd, lock);
109 RELEASE_LOCK(&file_lock_mutex);
119 ACQUIRE_LOCK(&file_lock_mutex);
121 lock = lookupHashTable(fd_hash, fd);
123 // errorBelch("unlockFile: fd %d not found", fd);
124 // This is normal: we didn't know when calling unlockFile
125 // whether this FD referred to a locked file or not.
126 RELEASE_LOCK(&file_lock_mutex);
130 if (lock->readers < 0) {
136 if (lock->readers == 0) {
137 removeHashTable(obj_hash, (StgWord)lock, NULL);
140 removeHashTable(fd_hash, fd, NULL);
142 RELEASE_LOCK(&file_lock_mutex);