blob: 30e2ffd9e1e930a07fc77b360ec7d3e9bdb21e63 [file] [log] [blame]
David Hendrickscb8ce142016-02-12 13:37:25 -08001/* Copyright 2016, Google Inc.
2 * All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following
12 * disclaimer in the documentation and/or other materials provided
13 * with the distribution.
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 * Alternatively, this software may be distributed under the terms of the
31 * GNU General Public License ("GPL") version 2 as published by the Free
32 * Software Foundation.
33 *
34 * file_lock.c: Implementation for a binary semaphore using a file lock.
35 *
36 * Warning: This relies on flock() which is known to be broken on NFS.
37 *
38 * The file will remain persistent once the lock has been used. Unfortunately,
39 * unlinking the file can introduce a race condition so we leave the file
40 * in place.
41 *
42 * The current process's PID will be written to the file for debug purposes.
43 */
44
45#include <errno.h>
46#include <fcntl.h>
47#include <inttypes.h>
48#include <limits.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52#include <time.h>
53#include <unistd.h>
54#include <sys/file.h>
55#include <sys/types.h>
56#include <sys/stat.h>
57
David Hendrickscb8ce142016-02-12 13:37:25 -080058#include "flash.h"
59#include "ipc_lock.h"
60#include "locks.h"
61
62#define SLEEP_INTERVAL_MS 50
63
64static void msecs_to_timespec(int msecs, struct timespec *tmspec)
65{
66 tmspec->tv_sec = msecs / 1000;
67 tmspec->tv_nsec = (msecs % 1000) * 1000 * 1000;
68}
69
70static int lock_is_held(struct ipc_lock *lock)
71{
72 return lock->is_held;
73}
74
David Hendricks467b8252016-06-01 15:49:53 -070075static int test_dir(const char *path)
David Hendrickscb8ce142016-02-12 13:37:25 -080076{
77 struct stat s;
David Hendricks467b8252016-06-01 15:49:53 -070078
79 if (lstat(path, &s) < 0) {
80 msg_gerr("Cannot stat %s.\n", path);
81 return -1;
82 }
83
84 if (!S_ISDIR(s.st_mode)) {
85 msg_gerr("%s is not a directory.\n", path);
86 return -1;
87 }
88
89 return 0;
90}
91
92static int file_lock_open_or_create(struct ipc_lock *lock)
93{
David Hendrickscb8ce142016-02-12 13:37:25 -080094 char path[PATH_MAX];
Jack Rosenthal124d9202019-12-09 17:15:47 -070095 const char *dir = SYSTEM_LOCKFILE_DIR;
96 const char fallback[] = "/tmp";
David Hendrickscb8ce142016-02-12 13:37:25 -080097
Jack Rosenthal124d9202019-12-09 17:15:47 -070098 if (test_dir(dir)) {
99 dir = fallback;
100 msg_gerr("Trying fallback directory: %s\n", dir);
101 if (test_dir(dir))
David Hendrickscb8ce142016-02-12 13:37:25 -0800102 return -1;
David Hendrickscb8ce142016-02-12 13:37:25 -0800103 }
104
Jack Rosenthal124d9202019-12-09 17:15:47 -0700105 if (snprintf(path, sizeof(path), "%s/%s", dir, lock->filename) < 0)
106 return -1;
107
David Hendrickscb8ce142016-02-12 13:37:25 -0800108 lock->fd = open(path, O_RDWR | O_CREAT, 0600);
109 if (lock->fd < 0) {
110 msg_gerr("Cannot open lockfile %s", path);
111 return -1;
112 }
113
114 msg_gdbg("Opened file lock \"%s\"\n", path);
115 return 0;
116}
117
118static int file_lock_get(struct ipc_lock *lock, int timeout_msecs)
119{
120 int msecs_remaining = timeout_msecs;
121 struct timespec sleep_interval, rem;
122 int ret = -1;
123
124 if (timeout_msecs == 0)
125 return flock(lock->fd, LOCK_EX | LOCK_NB);
126
127 msecs_to_timespec(SLEEP_INTERVAL_MS, &sleep_interval);
128
129 while ((ret = flock(lock->fd, LOCK_EX | LOCK_NB)) != 0) {
130 if (errno != EWOULDBLOCK) {
131 msg_gerr("Error obtaining lock");
132 return -1;
133 }
134
135 if (msecs_remaining < SLEEP_INTERVAL_MS)
136 msecs_to_timespec(msecs_remaining, &sleep_interval);
137
138 while (nanosleep(&sleep_interval, &rem) != 0) {
139 if (errno == EINTR) {
140 sleep_interval = rem;
141 continue;
142 } else {
143 msg_gerr("nanosleep() failed");
144 return ret;
145 }
146 }
147
148 if (timeout_msecs < 0)
149 continue;
150
151 msecs_remaining -= SLEEP_INTERVAL_MS;
152 if (msecs_remaining < 0)
153 break;
154 }
155
156 if (ret != 0) {
157 msg_gerr("Timed out waiting for file lock.\n");
158 return -1;
159 }
160
161 return 0;
162}
163
164static int file_lock_write_pid(struct ipc_lock *lock)
165{
166 ssize_t len;
167 /* PIDs are usually 5 digits, but we'll reserve enough room for
168 a value of 2^32 (10 digits) out of paranoia. */
169 char pid_str[11];
170
171 if (ftruncate(lock->fd, 0) < 0) {
172 msg_gerr("Cannot truncate lockfile");
173 return -1;
174 }
175
176 snprintf(pid_str, sizeof(pid_str), "%lu", (unsigned long)getpid());
177 len = write(lock->fd, pid_str, strlen(pid_str));
178 if (len < 0) {
179 msg_gerr("Cannot write PID to lockfile");
180 return -1;
181 }
182
183 return 0;
184}
185
186static void file_lock_release(struct ipc_lock *lock)
187{
188 if (flock(lock->fd, LOCK_UN) < 0)
189 msg_gerr("Cannot release lock");
190
191 if (close(lock->fd) < 0)
192 msg_gerr("Cannot close lockfile");
193}
194
195/*
196 * timeout <0 = no timeout (try forever)
197 * timeout 0 = do not wait (return immediately)
198 * timeout >0 = wait up to $timeout milliseconds
199 *
200 * returns 0 to indicate lock acquired
201 * returns >0 to indicate lock was already held
202 * returns <0 to indicate failed to acquire lock
203 */
204int acquire_lock(struct ipc_lock *lock, int timeout_msecs)
205{
206 /* check if it is already held */
207 if (lock_is_held(lock))
208 return 1;
209
210 if (file_lock_open_or_create(lock))
211 return -1;
212
213 if (file_lock_get(lock, timeout_msecs)) {
214 lock->is_held = 0;
215 close(lock->fd);
216 return -1;
217 } else {
218 lock->is_held = 1;
219 }
220
221 /*
222 * Write PID to lockfile for debug purposes. Failure to write to
223 * the file should not be considered fatal. There might be something
224 * bad happening with the filesystem, but the lock has already been
225 * obtained and we may need our tools for diagnostics and repairs
226 * so we should continue anyway.
227 */
228 file_lock_write_pid(lock);
229 return 0;
230}
231
232/*
233 * returns 0 if lock was released successfully
234 * returns -1 if lock had not been held before the call
235 */
236int release_lock(struct ipc_lock *lock)
237{
238 if (lock_is_held(lock)) {
239 file_lock_release(lock);
240 lock->is_held = 0;
241 return 0;
242 }
243
244 msg_ginfo("%s called but lock was not held on %s.\n",
245 __func__, lock->filename);
246 return -1;
247}