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 */
66 freeHashTable(obj_hash, freeLock);
67 freeHashTable(fd_hash, NULL);
71 lockFile(int fd, dev_t dev, ino_t ino, int for_writing)
75 ACQUIRE_LOCK(&file_lock_mutex);
80 lock = lookupHashTable(obj_hash, (StgWord)&key);
84 lock = stgMallocBytes(sizeof(Lock), "lockFile");
87 lock->readers = for_writing ? -1 : 1;
88 insertHashTable(obj_hash, (StgWord)lock, (void *)lock);
89 insertHashTable(fd_hash, fd, lock);
90 RELEASE_LOCK(&file_lock_mutex);
95 // single-writer/multi-reader locking:
96 if (for_writing || lock->readers < 0) {
97 RELEASE_LOCK(&file_lock_mutex);
100 insertHashTable(fd_hash, fd, lock);
102 RELEASE_LOCK(&file_lock_mutex);
112 ACQUIRE_LOCK(&file_lock_mutex);
114 lock = lookupHashTable(fd_hash, fd);
116 // errorBelch("unlockFile: fd %d not found", fd);
117 // This is normal: we didn't know when calling unlockFile
118 // whether this FD referred to a locked file or not.
119 RELEASE_LOCK(&file_lock_mutex);
123 if (lock->readers < 0) {
129 if (lock->readers == 0) {
130 removeHashTable(obj_hash, (StgWord)lock, NULL);
133 removeHashTable(fd_hash, fd, NULL);
135 RELEASE_LOCK(&file_lock_mutex);