1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2007
5 * File locking support as required by Haskell 98
7 * ---------------------------------------------------------------------------*/
21 int readers; // >0 : readers, <0 : writers
24 // Two hash tables. The first maps objects (device/inode pairs) to
25 // Lock objects containing the number of active readers or writers. The
26 // second maps file descriptors to lock objects, so that we can unlock
27 // by FD without needing to fstat() again.
28 static HashTable *obj_hash;
29 static HashTable *fd_hash;
31 static int cmpLocks(StgWord w1, StgWord w2)
33 Lock *l1 = (Lock *)w1;
34 Lock *l2 = (Lock *)w2;
35 return (l1->device == l2->device && l1->inode == l2->inode);
38 static int hashLock(HashTable *table, StgWord w)
41 // Just xor the dev_t with the ino_t, hope this is good enough.
42 return hashWord(table, (StgWord)l->inode ^ (StgWord)l->device);
48 obj_hash = allocHashTable_(hashLock, cmpLocks);
49 fd_hash = allocHashTable(); /* ordinary word-based table */
61 freeHashTable(obj_hash, freeLock);
62 freeHashTable(fd_hash, NULL);
66 lockFile(int fd, dev_t dev, ino_t ino, int for_writing)
73 lock = lookupHashTable(obj_hash, (StgWord)&key);
77 lock = stgMallocBytes(sizeof(Lock), "lockFile");
80 lock->readers = for_writing ? -1 : 1;
81 insertHashTable(obj_hash, (StgWord)lock, (void *)lock);
82 insertHashTable(fd_hash, fd, lock);
87 // single-writer/multi-reader locking:
88 if (for_writing || lock->readers < 0) {
91 insertHashTable(fd_hash, fd, lock);
102 lock = lookupHashTable(fd_hash, fd);
104 // errorBelch("unlockFile: fd %d not found", fd);
105 // This is normal: we didn't know when calling unlockFile
106 // whether this FD referred to a locked file or not.
110 if (lock->readers < 0) {
116 if (lock->readers == 0) {
117 removeHashTable(obj_hash, (StgWord)lock, NULL);
120 removeHashTable(fd_hash, fd, NULL);