summaryrefslogtreecommitdiffstats
path: root/src/lib-index/mail-index-lock.c
blob: cdf62e4651fac6139fa3c6c06726615d2f27ad2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Copyright (c) 2003-2018 Dovecot authors, see the included COPYING file */

/*
   Locking should never fail or timeout. Exclusive locks must be kept as short
   time as possible. Shared locks can be long living, so if we can't get
   exclusive lock directly, we'll recreate the index. That means the shared
   lock holders can keep using the old file.

   lock_id is used to figure out if acquired lock is still valid. When index
   file is reopened, the lock_id can become invalid. It doesn't matter however,
   as no-one's going to modify the old file anymore.

   lock_id also tells us if we're referring to a shared or an exclusive lock.
   This allows us to drop back to shared locking once all exclusive locks
   are dropped. Shared locks have even numbers, exclusive locks have odd numbers.
   The number is increased by two every time the lock is dropped or index file
   is reopened.
*/

#include "lib.h"
#include "nfs-workarounds.h"
#include "mail-index-private.h"

#define MAIL_INDEX_SHARED_LOCK_TIMEOUT 120

int mail_index_lock_fd(struct mail_index *index, const char *path, int fd,
		       int lock_type, unsigned int timeout_secs,
		       struct file_lock **lock_r)
{
	const char *error;
	int ret;

	if (fd == -1) {
		i_assert(MAIL_INDEX_IS_IN_MEMORY(index));
		return 1;
	}

	struct file_lock_settings lock_set = {
		.lock_method = index->set.lock_method,
	};
	ret = file_wait_lock(fd, path, lock_type, &lock_set, timeout_secs,
			     lock_r, &error);
	if (ret < 0)
		e_error(index->event, "%s", error);
	return ret;
}

void mail_index_flush_read_cache(struct mail_index *index, const char *path,
				 int fd, bool locked)
{
	if ((index->flags & MAIL_INDEX_OPEN_FLAG_NFS_FLUSH) == 0)
		return;

	/* Assume flock() is emulated with fcntl(), because that's how most
	   OSes work nowadays. */
	if (locked &&
	    (index->set.lock_method == FILE_LOCK_METHOD_FCNTL ||
	     index->set.lock_method == FILE_LOCK_METHOD_FLOCK)) {
		nfs_flush_read_cache_locked(path, fd);
	} else {
		nfs_flush_read_cache_unlocked(path, fd);
	}
}