2 * Really simple exclusive file locking based on filename.
3 * No hash indexing, just a list, so only works well for < 100 files or
4 * so. But that's more than what fio needs, so should be fine.
19 struct fio_mutex lock;
20 struct flist_head list;
21 unsigned int references;
24 static struct flist_head *filelock_list;
25 static struct fio_mutex *filelock_lock;
27 int fio_filelock_init(void)
29 filelock_list = smalloc(sizeof(*filelock_list));
33 INIT_FLIST_HEAD(filelock_list);
34 filelock_lock = fio_mutex_init(FIO_MUTEX_UNLOCKED);
43 void fio_filelock_exit(void)
48 assert(flist_empty(filelock_list));
51 fio_mutex_remove(filelock_lock);
55 static struct fio_filelock *fio_hash_find(uint32_t hash)
57 struct flist_head *entry;
58 struct fio_filelock *ff;
60 flist_for_each(entry, filelock_list) {
61 ff = flist_entry(entry, struct fio_filelock, list);
69 static struct fio_filelock *fio_hash_get(uint32_t hash)
71 struct fio_filelock *ff;
73 ff = fio_hash_find(hash);
75 ff = smalloc(sizeof(*ff));
77 __fio_mutex_init(&ff->lock, FIO_MUTEX_UNLOCKED);
79 flist_add(&ff->list, filelock_list);
85 int fio_trylock_file(const char *fname)
87 struct fio_filelock *ff;
90 hash = jhash(fname, strlen(fname), 0);
92 fio_mutex_down(filelock_lock);
93 ff = fio_hash_get(hash);
95 fio_mutex_up(filelock_lock);
97 if (!fio_mutex_down_trylock(&ff->lock))
100 fio_mutex_down(filelock_lock);
103 * If we raced and the only reference to the lock is us, we can
106 if (ff->references != 1) {
111 fio_mutex_up(filelock_lock);
114 fio_mutex_down(&ff->lock);
121 void fio_lock_file(const char *fname)
123 struct fio_filelock *ff;
126 hash = jhash(fname, strlen(fname), 0);
128 fio_mutex_down(filelock_lock);
129 ff = fio_hash_get(hash);
131 fio_mutex_up(filelock_lock);
133 fio_mutex_down(&ff->lock);
136 void fio_unlock_file(const char *fname)
138 struct fio_filelock *ff;
141 hash = jhash(fname, strlen(fname), 0);
143 fio_mutex_down(filelock_lock);
145 ff = fio_hash_find(hash);
148 fio_mutex_up(&ff->lock);
149 if (!ff->references) {
150 flist_del(&ff->list);
154 log_err("fio: file not found for unlocking\n");
156 fio_mutex_up(filelock_lock);