blob: 325af7569858bc2ad1fdb4c1388a8feb94985875 [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
58#include "android.h"
59#include "flash.h"
60#include "ipc_lock.h"
61#include "locks.h"
62
63#define SLEEP_INTERVAL_MS 50
64
65static void msecs_to_timespec(int msecs, struct timespec *tmspec)
66{
67 tmspec->tv_sec = msecs / 1000;
68 tmspec->tv_nsec = (msecs % 1000) * 1000 * 1000;
69}
70
71static int lock_is_held(struct ipc_lock *lock)
72{
73 return lock->is_held;
74}
75
76static int file_lock_open_or_create(struct ipc_lock *lock)
77{
78 struct stat s;
79 char path[PATH_MAX];
80
81 if (in_android()) {
82 char *tmpdir;
83
84 tmpdir = android_tmpdir_path();
85 if (!tmpdir)
86 return -1;
87
88 if (snprintf(path, sizeof(path), "%s/%s",
89 tmpdir, lock->filename) < 0) {
90 return -1;
91 }
92 } else {
93 if (snprintf(path, sizeof(path), "%s", SYSTEM_LOCKFILE_DIR) < 0)
94 return -1;
95
96 if (lstat(path, &s) < 0) {
97 msg_gerr("Cannot stat %s", path);
98 return -1;
99 }
100
101 if (!S_ISDIR(s.st_mode)) {
102 msg_gerr("%s is not a directory.\n", path);
103 return -1;
104 }
105
106 if (strlen(path) + strlen(lock->filename) + 2 > PATH_MAX) {
107 msg_gerr("Lockfile path too long.\n");
108 return -1;
109 }
110 strcat(path, "/");
111 strcat(path, lock->filename);
112 }
113
114 lock->fd = open(path, O_RDWR | O_CREAT, 0600);
115 if (lock->fd < 0) {
116 msg_gerr("Cannot open lockfile %s", path);
117 return -1;
118 }
119
120 msg_gdbg("Opened file lock \"%s\"\n", path);
121 return 0;
122}
123
124static int file_lock_get(struct ipc_lock *lock, int timeout_msecs)
125{
126 int msecs_remaining = timeout_msecs;
127 struct timespec sleep_interval, rem;
128 int ret = -1;
129
130 if (timeout_msecs == 0)
131 return flock(lock->fd, LOCK_EX | LOCK_NB);
132
133 msecs_to_timespec(SLEEP_INTERVAL_MS, &sleep_interval);
134
135 while ((ret = flock(lock->fd, LOCK_EX | LOCK_NB)) != 0) {
136 if (errno != EWOULDBLOCK) {
137 msg_gerr("Error obtaining lock");
138 return -1;
139 }
140
141 if (msecs_remaining < SLEEP_INTERVAL_MS)
142 msecs_to_timespec(msecs_remaining, &sleep_interval);
143
144 while (nanosleep(&sleep_interval, &rem) != 0) {
145 if (errno == EINTR) {
146 sleep_interval = rem;
147 continue;
148 } else {
149 msg_gerr("nanosleep() failed");
150 return ret;
151 }
152 }
153
154 if (timeout_msecs < 0)
155 continue;
156
157 msecs_remaining -= SLEEP_INTERVAL_MS;
158 if (msecs_remaining < 0)
159 break;
160 }
161
162 if (ret != 0) {
163 msg_gerr("Timed out waiting for file lock.\n");
164 return -1;
165 }
166
167 return 0;
168}
169
170static int file_lock_write_pid(struct ipc_lock *lock)
171{
172 ssize_t len;
173 /* PIDs are usually 5 digits, but we'll reserve enough room for
174 a value of 2^32 (10 digits) out of paranoia. */
175 char pid_str[11];
176
177 if (ftruncate(lock->fd, 0) < 0) {
178 msg_gerr("Cannot truncate lockfile");
179 return -1;
180 }
181
182 snprintf(pid_str, sizeof(pid_str), "%lu", (unsigned long)getpid());
183 len = write(lock->fd, pid_str, strlen(pid_str));
184 if (len < 0) {
185 msg_gerr("Cannot write PID to lockfile");
186 return -1;
187 }
188
189 return 0;
190}
191
192static void file_lock_release(struct ipc_lock *lock)
193{
194 if (flock(lock->fd, LOCK_UN) < 0)
195 msg_gerr("Cannot release lock");
196
197 if (close(lock->fd) < 0)
198 msg_gerr("Cannot close lockfile");
199}
200
201/*
202 * timeout <0 = no timeout (try forever)
203 * timeout 0 = do not wait (return immediately)
204 * timeout >0 = wait up to $timeout milliseconds
205 *
206 * returns 0 to indicate lock acquired
207 * returns >0 to indicate lock was already held
208 * returns <0 to indicate failed to acquire lock
209 */
210int acquire_lock(struct ipc_lock *lock, int timeout_msecs)
211{
212 /* check if it is already held */
213 if (lock_is_held(lock))
214 return 1;
215
216 if (file_lock_open_or_create(lock))
217 return -1;
218
219 if (file_lock_get(lock, timeout_msecs)) {
220 lock->is_held = 0;
221 close(lock->fd);
222 return -1;
223 } else {
224 lock->is_held = 1;
225 }
226
227 /*
228 * Write PID to lockfile for debug purposes. Failure to write to
229 * the file should not be considered fatal. There might be something
230 * bad happening with the filesystem, but the lock has already been
231 * obtained and we may need our tools for diagnostics and repairs
232 * so we should continue anyway.
233 */
234 file_lock_write_pid(lock);
235 return 0;
236}
237
238/*
239 * returns 0 if lock was released successfully
240 * returns -1 if lock had not been held before the call
241 */
242int release_lock(struct ipc_lock *lock)
243{
244 if (lock_is_held(lock)) {
245 file_lock_release(lock);
246 lock->is_held = 0;
247 return 0;
248 }
249
250 msg_ginfo("%s called but lock was not held on %s.\n",
251 __func__, lock->filename);
252 return -1;
253}