Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / lib / lockfile.c
index 9bb7c6b..d157bc6 100644 (file)
@@ -1,4 +1,4 @@
- /* Copyright (c) 2008, 2009 Nicira Networks
+ /* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #include "coverage.h"
 #include "hash.h"
 #include "hmap.h"
+#include "ovs-thread.h"
 #include "timeval.h"
 #include "util.h"
-
-#define THIS_MODULE VLM_lockfile
 #include "vlog.h"
 
+VLOG_DEFINE_THIS_MODULE(lockfile);
+
+COVERAGE_DEFINE(lockfile_lock);
+COVERAGE_DEFINE(lockfile_error);
+COVERAGE_DEFINE(lockfile_unlock);
+
 struct lockfile {
     struct hmap_node hmap_node;
     char *name;
     dev_t device;
     ino_t inode;
     int fd;
+    HANDLE lock_handle;
 };
 
 /* Lock table.
@@ -47,77 +53,85 @@ struct lockfile {
  * descriptor for a file on which a process holds a lock drops *all* locks on
  * that file.  That means that we can't afford to open a lockfile more than
  * once. */
-static struct hmap lock_table = HMAP_INITIALIZER(&lock_table);
+static struct ovs_mutex lock_table_mutex = OVS_MUTEX_INITIALIZER;
+static struct hmap lock_table__ = HMAP_INITIALIZER(&lock_table__);
+static struct hmap *const lock_table OVS_GUARDED_BY(lock_table_mutex)
+    = &lock_table__;
 
 static void lockfile_unhash(struct lockfile *);
-static int lockfile_try_lock(const char *name, bool block,
-                             struct lockfile **lockfilep);
+static int lockfile_try_lock(const char *name, pid_t *pidp,
+                             struct lockfile **lockfilep)
+    OVS_REQUIRES(&lock_table_mutex);
+static void lockfile_do_unlock(struct lockfile * lockfile)
+    OVS_REQUIRES(&lock_table_mutex);
 
 /* Returns the name of the lockfile that would be created for locking a file
- * named 'file_name'.  The caller is responsible for freeing the returned
- * name, with free(), when it is no longer needed. */
+ * named 'filename_'.  The caller is responsible for freeing the returned name,
+ * with free(), when it is no longer needed. */
 char *
-lockfile_name(const char *file_name)
+lockfile_name(const char *filename_)
 {
-    const char *slash = strrchr(file_name, '/');
-    return (slash
-            ? xasprintf("%.*s/.%s.~lock~",
-                        (int) (slash - file_name), file_name, slash + 1)
-            : xasprintf(".%s.~lock~", file_name));
+    char *filename;
+    const char *slash;
+    char *lockname;
+
+    /* If 'filename_' is a symlink, base the name of the lockfile on the
+     * symlink's target rather than the name of the symlink.  That way, if a
+     * file is symlinked, but there is no symlink for its lockfile, then there
+     * is only a single lockfile for both the source and the target of the
+     * symlink, not one for each. */
+    filename = follow_symlinks(filename_);
+    slash = strrchr(filename, '/');
+    lockname = (slash
+                ? xasprintf("%.*s/.%s.~lock~",
+                            (int) (slash - filename), filename, slash + 1)
+                : xasprintf(".%s.~lock~", filename));
+    free(filename);
+
+    return lockname;
 }
 
 /* Locks the configuration file against modification by other processes and
  * re-reads it from disk.
  *
- * The 'timeout' specifies the maximum number of milliseconds to wait for the
- * config file to become free.  Use 0 to avoid waiting or INT_MAX to wait
- * forever.
- *
  * Returns 0 on success, otherwise a positive errno value.  On success,
  * '*lockfilep' is set to point to a new "struct lockfile *" that may be
  * unlocked with lockfile_unlock().  On failure, '*lockfilep' is set to
- * NULL. */
+ * NULL.  Will not block if the lock cannot be immediately acquired. */
 int
-lockfile_lock(const char *file, int timeout, struct lockfile **lockfilep)
+lockfile_lock(const char *file, struct lockfile **lockfilep)
 {
     /* Only exclusive ("write") locks are supported.  This is not a problem
      * because the Open vSwitch code that currently uses lock files does so in
      * stylized ways such that any number of readers may access a file while it
      * is being written. */
-    long long int start, elapsed;
     char *lock_name;
+    pid_t pid;
     int error;
 
     COVERAGE_INC(lockfile_lock);
 
     lock_name = lockfile_name(file);
-    time_refresh();
-    start = time_msec();
 
-    do {
-        error = lockfile_try_lock(lock_name, timeout > 0, lockfilep);
-        time_refresh();
-        elapsed = time_msec() - start;
-    } while (error == EINTR && (timeout == INT_MAX || elapsed < timeout));
+    ovs_mutex_lock(&lock_table_mutex);
+    error = lockfile_try_lock(lock_name, &pid, lockfilep);
+    ovs_mutex_unlock(&lock_table_mutex);
 
-    if (!error) {
-        if (elapsed) {
-            VLOG_WARN("%s: waited %lld ms for lock file",
-                      lock_name, elapsed);
-        }
-    } else if (error == EINTR) {
-        COVERAGE_INC(lockfile_timeout);
-        VLOG_WARN("%s: giving up on lock file after %lld ms",
-                  lock_name, elapsed);
-        error = ETIMEDOUT;
-    } else {
+    if (error) {
         COVERAGE_INC(lockfile_error);
         if (error == EACCES) {
             error = EAGAIN;
         }
-        VLOG_WARN("%s: failed to lock file "
-                  "(after %lld ms, with %d-ms timeout): %s",
-                  lock_name, elapsed, timeout, strerror(error));
+        if (pid == getpid()) {
+            VLOG_WARN("%s: cannot lock file because this process has already "
+                      "locked it", lock_name);
+        } else if (pid) {
+            VLOG_WARN("%s: cannot lock file because it is already locked by "
+                      "pid %ld", lock_name, (long int) pid);
+        } else {
+            VLOG_WARN("%s: failed to lock file: %s",
+                      lock_name, ovs_strerror(error));
+        }
     }
 
     free(lock_name);
@@ -130,8 +144,11 @@ void
 lockfile_unlock(struct lockfile *lockfile)
 {
     if (lockfile) {
+        ovs_mutex_lock(&lock_table_mutex);
+        lockfile_do_unlock(lockfile);
+        ovs_mutex_unlock(&lock_table_mutex);
+
         COVERAGE_INC(lockfile_unlock);
-        lockfile_unhash(lockfile);
         free(lockfile->name);
         free(lockfile);
     }
@@ -145,12 +162,14 @@ lockfile_postfork(void)
 {
     struct lockfile *lockfile;
 
-    HMAP_FOR_EACH (lockfile, struct lockfile, hmap_node, &lock_table) {
+    ovs_mutex_lock(&lock_table_mutex);
+    HMAP_FOR_EACH (lockfile, hmap_node, lock_table) {
         if (lockfile->fd >= 0) {
             VLOG_WARN("%s: child does not inherit lock", lockfile->name);
             lockfile_unhash(lockfile);
         }
     }
+    ovs_mutex_unlock(&lock_table_mutex);
 }
 \f
 static uint32_t
@@ -161,12 +180,12 @@ lockfile_hash(dev_t device, ino_t inode)
 }
 
 static struct lockfile *
-lockfile_find(dev_t device, ino_t inode)
+lockfile_find(dev_t device, ino_t inode) OVS_REQUIRES(&lock_table_mutex)
 {
     struct lockfile *lockfile;
 
-    HMAP_FOR_EACH_WITH_HASH (lockfile, struct lockfile, hmap_node,
-                             lockfile_hash(device, inode), &lock_table) {
+    HMAP_FOR_EACH_WITH_HASH (lockfile, hmap_node,
+                             lockfile_hash(device, inode), lock_table) {
         if (lockfile->device == device && lockfile->inode == inode) {
             return lockfile;
         }
@@ -175,17 +194,18 @@ lockfile_find(dev_t device, ino_t inode)
 }
 
 static void
-lockfile_unhash(struct lockfile *lockfile)
+lockfile_unhash(struct lockfile *lockfile) OVS_REQUIRES(&lock_table_mutex)
 {
     if (lockfile->fd >= 0) {
         close(lockfile->fd);
         lockfile->fd = -1;
-        hmap_remove(&lock_table, &lockfile->hmap_node);
+        hmap_remove(lock_table, &lockfile->hmap_node);
     }
 }
 
 static struct lockfile *
 lockfile_register(const char *name, dev_t device, ino_t inode, int fd)
+    OVS_REQUIRES(&lock_table_mutex)
 {
     struct lockfile *lockfile;
 
@@ -200,13 +220,84 @@ lockfile_register(const char *name, dev_t device, ino_t inode, int fd)
     lockfile->device = device;
     lockfile->inode = inode;
     lockfile->fd = fd;
-    hmap_insert(&lock_table, &lockfile->hmap_node,
+    hmap_insert(lock_table, &lockfile->hmap_node,
                 lockfile_hash(device, inode));
     return lockfile;
 }
 
+#ifdef _WIN32
+static void
+lockfile_do_unlock(struct lockfile *lockfile)
+    OVS_REQUIRES(&lock_table_mutex)
+{
+    if (lockfile->fd >= 0) {
+        OVERLAPPED overl;
+        overl.hEvent = 0;
+        overl.Offset = 0;
+        overl.OffsetHigh = 0;
+        UnlockFileEx(lockfile->lock_handle, 0, 1, 0, &overl);
+
+        close(lockfile->fd);
+        lockfile->fd = -1;
+    }
+}
+
 static int
-lockfile_try_lock(const char *name, bool block, struct lockfile **lockfilep)
+lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
+    OVS_REQUIRES(&lock_table_mutex)
+{
+    HANDLE lock_handle;
+    BOOL retval;
+    OVERLAPPED overl;
+    struct lockfile *lockfile;
+    int fd;
+
+    *pidp = 0;
+
+    fd = open(name, O_RDWR | O_CREAT, 0600);
+    if (fd < 0) {
+        VLOG_WARN("%s: failed to open lock file: %s",
+                   name, ovs_strerror(errno));
+        return errno;
+    }
+
+    lock_handle = (HANDLE)_get_osfhandle(fd);
+    if (lock_handle < 0) {
+        VLOG_WARN("%s: failed to get the file handle: %s",
+                   name, ovs_strerror(errno));
+        return errno;
+    }
+
+    /* Lock the file 'name' for the region that includes just the first
+     * byte. */
+    overl.hEvent = 0;
+    overl.Offset = 0;
+    overl.OffsetHigh = 0;
+    retval = LockFileEx(lock_handle, LOCKFILE_EXCLUSIVE_LOCK
+                        | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overl);
+    if (!retval) {
+        VLOG_WARN("Failed to lock file : %s", ovs_lasterror_to_string());
+        return EEXIST;
+    }
+
+    lockfile = xmalloc(sizeof *lockfile);
+    lockfile->name = xstrdup(name);
+    lockfile->fd = fd;
+    lockfile->lock_handle = lock_handle;
+
+    *lockfilep = lockfile;
+    return 0;
+}
+#else /* !_WIN32 */
+static void
+lockfile_do_unlock(struct lockfile *lockfile)
+{
+    lockfile_unhash(lockfile);
+}
+
+static int
+lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
+    OVS_REQUIRES(&lock_table_mutex)
 {
     struct flock l;
     struct stat s;
@@ -214,47 +305,32 @@ lockfile_try_lock(const char *name, bool block, struct lockfile **lockfilep)
     int fd;
 
     *lockfilep = NULL;
+    *pidp = 0;
 
-    /* Open the lock file, first creating it if necessary. */
-    for (;;) {
-        /* Check whether we've already got a lock on that file. */
-        if (!stat(name, &s)) {
-            if (lockfile_find(s.st_dev, s.st_ino)) {
-                return EDEADLK;
-            }
-        } else if (errno != ENOENT) {
-            VLOG_WARN("%s: failed to stat lock file: %s",
-                      name, strerror(errno));
-            return errno;
-        }
-
-        /* Try to open an existing lock file. */
-        fd = open(name, O_RDWR);
-        if (fd >= 0) {
-            break;
-        } else if (errno != ENOENT) {
-            VLOG_WARN("%s: failed to open lock file: %s",
-                      name, strerror(errno));
-            return errno;
-        }
-
-        /* Try to create a new lock file. */
-        VLOG_INFO("%s: lock file does not exist, creating", name);
-        fd = open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
-        if (fd >= 0) {
-            break;
-        } else if (errno != EEXIST) {
-            VLOG_WARN("%s: failed to create lock file: %s",
-                      name, strerror(errno));
-            return errno;
+    /* Check whether we've already got a lock on that file. */
+    if (!stat(name, &s)) {
+        if (lockfile_find(s.st_dev, s.st_ino)) {
+            *pidp = getpid();
+            return EDEADLK;
         }
+    } else if (errno != ENOENT) {
+        VLOG_WARN("%s: failed to stat lock file: %s",
+                  name, ovs_strerror(errno));
+        return errno;
+    }
 
-        /* Someone else created the lock file.  Try again. */
+    /* Open the lock file. */
+    fd = open(name, O_RDWR | O_CREAT, 0600);
+    if (fd < 0) {
+        VLOG_WARN("%s: failed to open lock file: %s",
+                  name, ovs_strerror(errno));
+        return errno;
     }
 
     /* Get the inode and device number for the lock table. */
     if (fstat(fd, &s)) {
-        VLOG_ERR("%s: failed to fstat lock file: %s", name, strerror(errno));
+        VLOG_ERR("%s: failed to fstat lock file: %s",
+                 name, ovs_strerror(errno));
         close(fd);
         return errno;
     }
@@ -266,15 +342,16 @@ lockfile_try_lock(const char *name, bool block, struct lockfile **lockfilep)
     l.l_start = 0;
     l.l_len = 0;
 
-    time_disable_restart();
-    error = fcntl(fd, block ? F_SETLKW : F_SETLK, &l) == -1 ? errno : 0;
-    time_enable_restart();
+    error = fcntl(fd, F_SETLK, &l) == -1 ? errno : 0;
 
     if (!error) {
         *lockfilep = lockfile_register(name, s.st_dev, s.st_ino, fd);
     } else {
+        if (!fcntl(fd, F_GETLK, &l) && l.l_type != F_UNLCK) {
+            *pidp = l.l_pid;
+        }
         close(fd);
     }
     return error;
 }
-
+#endif