1 /* SPDX-License-Identifier: GPL-2.0 */
17 #include <sys/param.h>
20 #include "gcc-compat.h"
23 #include "gcc-compat.h"
27 #if (defined(__GNUC__) && defined(__i386__))
28 #define get16bits(d) (*((const uint16_t *) (d)))
30 #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
31 +(uint32_t)(((const uint8_t *)(d))[0]) )
35 * SuperFastHash, by Paul Hsieh.
36 * http://www.azillionmonkeys.com/qed/hash.html
38 static uint32_t super_fast_hash(const uint8_t *data, uint32_t len, uint32_t hash)
45 for (;len > 0; len--) {
46 hash += get16bits (data);
47 tmp = (get16bits (data+2) << 11) ^ hash;
48 hash = (hash << 16) ^ tmp;
49 data += 2*sizeof (uint16_t);
53 /* Handle end cases */
56 hash += get16bits (data);
58 hash ^= data[sizeof (uint16_t)] << 18;
62 hash += get16bits (data);
71 /* Force "avalanching" of final 127 bits */
81 static int get_key_or_die(const char *config_file)
88 if (stat(config_file, &statbuf) == 0) {
89 rpath = realpath(config_file, NULL);
91 DSS_EMERG_LOG(("could not resolve path %s: %m\n", config_file));
94 DSS_DEBUG_LOG(("resolved path: %s\n", rpath));
97 * This happens if the user did not specify a config file, and
98 * the default config file does not exist. Another (unlikely)
99 * possibility is that the config file was removed between
100 * startup and this call. We don't care about these corner
101 * cases too much and just use the unresolved path in this
104 rpath = dss_strdup(config_file);
105 ret = super_fast_hash((uint8_t *)rpath, strlen(rpath), 0) >> 1;
110 static int mutex_get(key_t key, int flags)
114 DSS_DEBUG_LOG(("getting semaphore 0x%lx\n", (long)key));
115 ret = semget(key, 2, flags);
117 return -ERRNO_TO_DSS_ERROR(errno);
121 static int do_semop(int id, struct sembuf *sops, int num)
125 DSS_DEBUG_LOG(("calling semop\n"));
127 ret = semop(id, sops, num);
130 } while (errno == EINTR);
131 return -ERRNO_TO_DSS_ERROR(errno);
134 static bool mutex_is_locked(int id)
139 DSS_DEBUG_LOG(("trying to lock\n"));
143 sops.sem_flg = SEM_UNDO | IPC_NOWAIT;
145 ret = do_semop(id, &sops, 1);
151 int lock_dss(char *config_file)
154 struct sembuf sops[4];
155 key_t key = get_key_or_die(config_file);
157 ret = mutex_get(key, IPC_CREAT | 0600);
164 sops[0].sem_flg = SEM_UNDO | IPC_NOWAIT;
168 sops[1].sem_flg = SEM_UNDO | IPC_NOWAIT;
172 sops[2].sem_flg = SEM_UNDO | IPC_NOWAIT;
176 sops[3].sem_flg = SEM_UNDO | IPC_NOWAIT;
178 return do_semop(id, sops, 4);
181 int get_dss_pid(char *config_file, pid_t *pid)
184 key_t key = get_key_or_die(config_file);
188 ret = mutex_get(key, 0);
190 return ret == -ERRNO_TO_DSS_ERROR(ENOENT)? -E_NOT_RUNNING : ret;
192 ret = semctl(semid, 1, GETPID);
194 return -E_NOT_RUNNING;
197 return mutex_is_locked(semid)? 1 : -E_NOT_RUNNING;