File: util.h

package info (click to toggle)
sheepdog 0.8.3-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,364 kB
  • ctags: 3,951
  • sloc: ansic: 30,552; sh: 3,573; perl: 2,924; asm: 453; makefile: 391; python: 192
file content (507 lines) | stat: -rw-r--r-- 11,690 bytes parent folder | download | duplicates (3)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#ifndef __UTIL_H__
#define __UTIL_H__

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <stdint.h>
#include <unistd.h>
#include <search.h>
#include <urcu/uatomic.h>
#include <pthread.h>
#include <errno.h>
#include <sys/param.h>

#include "logger.h"
#include "list.h"
#include "compiler.h"

#define SECTOR_SIZE (1U << 9)
#define BLOCK_SIZE (1U << 12)

#define round_up(x, y) roundup(x, y)
#define round_down(x, y) (((x) / (y)) * (y))

#if __BYTE_ORDER == __LITTLE_ENDIAN
#define __cpu_to_be16(x) bswap_16(x)
#define __cpu_to_be32(x) bswap_32(x)
#define __cpu_to_be64(x) bswap_64(x)
#define __be16_to_cpu(x) bswap_16(x)
#define __be32_to_cpu(x) bswap_32(x)
#define __be64_to_cpu(x) bswap_64(x)
#define __cpu_to_le32(x) (x)
#else
#define __cpu_to_be16(x) (x)
#define __cpu_to_be32(x) (x)
#define __cpu_to_be64(x) (x)
#define __be16_to_cpu(x) (x)
#define __be32_to_cpu(x) (x)
#define __be64_to_cpu(x) (x)
#define __cpu_to_le32(x) bswap_32(x)
#endif

#define uninitialized_var(x) x = x

static inline int before(uint32_t seq1, uint32_t seq2)
{
	return (int32_t)(seq1 - seq2) < 0;
}

static inline int after(uint32_t seq1, uint32_t seq2)
{
	return (int32_t)(seq2 - seq1) < 0;
}

#define min(x, y) ({ \
	typeof(x) _x = (x);	\
	typeof(y) _y = (y);	\
	(void) (&_x == &_y);		\
	_x < _y ? _x : _y; })

#define max(x, y) ({ \
	typeof(x) _x = (x);	\
	typeof(y) _y = (y);	\
	(void) (&_x == &_y);		\
	_x > _y ? _x : _y; })

static inline void *zalloc(size_t size)
{
	return calloc(1, size);
}

/*
 * Compares two integer values
 *
 * If the first argument is larger than the second one, intcmp() returns 1.  If
 * two members are equal, returns 0.  Otherwise, returns -1.
 */
#define intcmp(x, y) \
({					\
	typeof(x) _x = (x);		\
	typeof(y) _y = (y);		\
	(void) (&_x == &_y);		\
	_x < _y ? -1 : _x > _y ? 1 : 0;	\
})

typedef void (*try_to_free_t)(size_t);
try_to_free_t set_try_to_free_routine(try_to_free_t);

void *xmalloc(size_t size);
void *xzalloc(size_t size);
void *xrealloc(void *ptr, size_t size);
void *xcalloc(size_t nmemb, size_t size);
void *xvalloc(size_t size);
ssize_t xread(int fd, void *buf, size_t len);
ssize_t xwrite(int fd, const void *buf, size_t len);
ssize_t xpread(int fd, void *buf, size_t count, off_t offset);
ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset);
int xmkdir(const char *pathname, mode_t mode);
int xfallocate(int fd, int mode, off_t offset, off_t len);
int xftruncate(int fd, off_t length);
int eventfd_xread(int efd);
void eventfd_xwrite(int efd, int value);
void pstrcpy(char *buf, int buf_size, const char *str);
char *chomp(char *str);
int rmdir_r(const char *dir_path);
int purge_directory(const char *dir_path);
bool is_numeric(const char *p);
const char *data_to_str(void *data, size_t data_length);
int install_sighandler(int signum, void (*handler)(int), bool once);
int install_crash_handler(void (*handler)(int));
void reraise_crash_signal(int signo, int status);
pid_t gettid(void);
int tkill(int tid, int sig);
bool is_xattr_enabled(const char *path);
const char *my_exe_path(void);

int split_path(const char *path, size_t nr_segs, char **segs);
void make_path(char *path, size_t size, size_t nr_segs, const char **segs);

int atomic_create_and_write(const char *path, const char *buf, size_t len,
			    bool force_create);

/* a type safe version of qsort() */
#define xqsort(base, nmemb, compar)					\
({									\
	if (nmemb > 1) {						\
		qsort(base, nmemb, sizeof(*(base)),			\
		      (comparison_fn_t)compar);				\
		assert(compar(base, base + 1) <= 0);			\
	}								\
})

/* a type safe version of bsearch() */
#define xbsearch(key, base, nmemb, compar)				\
({									\
	typeof(&(base)[0]) __ret = NULL;				\
	if (nmemb > 0) {						\
		assert(compar(key, key) == 0);				\
		assert(compar(base, base) == 0);			\
		__ret = bsearch(key, base, nmemb, sizeof(*(base)),	\
				(comparison_fn_t)compar);		\
	}								\
	__ret;								\
})

/* a type safe version of lfind() */
#define xlfind(key, base, nmemb, compar)				\
({									\
	typeof(&(base)[0]) __ret = NULL;				\
	if (nmemb > 0) {						\
		size_t __n = nmemb;					\
		assert(compar(key, key) == 0);				\
		assert(compar(base, base) == 0);			\
		__ret = lfind(key, base, &__n, sizeof(*(base)),		\
			      (comparison_fn_t)compar);			\
	}								\
	__ret;								\
})

/*
 * Search 'key' in the array 'base' linearly and remove it if it found.
 *
 * If 'key' is found in 'base', this function increments *nmemb and returns
 * true.
 */
#define xlremove(key, base, nmemb, compar)				\
({									\
	bool __removed = false;						\
	typeof(&(base)[0]) __e;						\
									\
	__e = xlfind(key, base, *(nmemb), compar);			\
	if (__e != NULL) {						\
		(*(nmemb))--;						\
		memmove(__e, __e + 1,					\
			sizeof(*(base)) * (*(nmemb) - (__e - (base)))); \
		__removed = true;					\
	}								\
	__removed;							\
})

#ifdef assert
#error "Don't include assert.h, use util.h for assert()"
#endif

#ifndef NDEBUG
#define assert(expr)						\
({								\
	if (!(expr)) {						\
		sd_emerg("Asserting `%s' failed.", #expr);	\
		abort();					\
	}							\
})
#else
#define assert(expr) ((void)0)
#endif	/* NDEBUG */

#define SWAP(a, b) { typeof(a) tmp; tmp = a; a = b; b = tmp; }

/* urcu helpers */

/* Boolean data type which can be accessed by multiple threads */
typedef struct { unsigned long val; } uatomic_bool;

static inline bool uatomic_is_true(uatomic_bool *val)
{
	return uatomic_read(&val->val) == 1;
}

/* success if the old value is false */
static inline bool uatomic_set_true(uatomic_bool *val)
{
	return uatomic_cmpxchg(&val->val, 0, 1) == 0;
}

static inline void uatomic_set_false(uatomic_bool *val)
{
	uatomic_set(&val->val, 0);
}

/*
 * uatomic_xchg_ptr - uatomic_xchg for pointers
 *
 * Swaps the old value stored at location p with new value given by
 * val.  Returns old value.
 */
#define uatomic_xchg_ptr(p, val)			\
({							\
	uintptr_t ret;					\
	ret = uatomic_xchg((uintptr_t *)(p), (val));	\
	(typeof(*(p)))ret;				\
})

/*
 * refcnt_t: reference counter which can be manipulated by multiple threads
 * safely
 */

typedef struct {
	int val;
} refcnt_t;

static inline void refcount_set(refcnt_t *rc, int val)
{
	uatomic_set(&rc->val, val);
}

static inline int refcount_read(refcnt_t *rc)
{
	return uatomic_read(&rc->val);
}

static inline int refcount_inc(refcnt_t *rc)
{
	return uatomic_add_return(&rc->val, 1);
}

static inline int refcount_dec(refcnt_t *rc)
{
	assert(1 <= uatomic_read(&rc->val));
	return uatomic_sub_return(&rc->val, 1);
}

/* wrapper for pthread_mutex */

#define SD_MUTEX_INITIALIZER { .mutex = PTHREAD_MUTEX_INITIALIZER }

struct sd_mutex {
	pthread_mutex_t mutex;
};

static inline void sd_init_mutex(struct sd_mutex *mutex)
{
	int ret;

	do {
		ret = pthread_mutex_init(&mutex->mutex, NULL);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to initialize a lock, %s", strerror(ret));
}

static inline void sd_init_mutex_attr(struct sd_mutex *mutex,
				      pthread_mutexattr_t *attr)
{
	int ret;

	do {
		ret = pthread_mutex_init(&mutex->mutex, attr);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to initialize a lock with attr, %s",
		      strerror(ret));
}

static inline void sd_destroy_mutex(struct sd_mutex *mutex)
{
	int ret;

	do {
		ret = pthread_mutex_destroy(&mutex->mutex);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to destroy a lock, %s", strerror(ret));
}

static inline void sd_mutex_lock(struct sd_mutex *mutex)
{
	int ret;

	do {
		ret = pthread_mutex_lock(&mutex->mutex);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to lock for reading, %s", strerror(ret));
}

static inline int sd_mutex_trylock(struct sd_mutex *mutex)
{
	return pthread_mutex_trylock(&mutex->mutex);
}

static inline void sd_mutex_unlock(struct sd_mutex *mutex)
{
	int ret;

	do {
		ret = pthread_mutex_unlock(&mutex->mutex);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to unlock, %s", strerror(ret));
}

/* wrapper for pthread_cond */

#define SD_COND_INITIALIZER { .cond = PTHREAD_COND_INITIALIZER }

struct sd_cond {
	pthread_cond_t cond;
};

static inline void sd_cond_init(struct sd_cond *cond)
{
	int ret;

	do {
		ret = pthread_cond_init(&cond->cond, NULL);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to initialize a lock, %s", strerror(ret));

}

static inline void sd_destroy_cond(struct sd_cond *cond)
{
	int ret;

	do {
		ret = pthread_cond_destroy(&cond->cond);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to destroy a lock, %s", strerror(ret));
}

static inline int sd_cond_signal(struct sd_cond *cond)
{
	return pthread_cond_signal(&cond->cond);
}

static inline int sd_cond_wait(struct sd_cond *cond, struct sd_mutex *mutex)
{
	return pthread_cond_wait(&cond->cond, &mutex->mutex);
}

static inline int sd_cond_wait_timeout(struct sd_cond *cond,
				       struct sd_mutex *mutex, int second)
{
	struct timespec wait_time;
	wait_time.tv_sec = second;
	wait_time.tv_nsec = 0;
	return pthread_cond_timedwait(&cond->cond, &mutex->mutex, &wait_time);
}

static inline int sd_cond_broadcast(struct sd_cond *cond)
{
	return pthread_cond_broadcast(&cond->cond);
}

/* wrapper for pthread_rwlock */

#define SD_RW_LOCK_INITIALIZER { .rwlock = PTHREAD_RWLOCK_INITIALIZER }

struct sd_rw_lock {
	pthread_rwlock_t rwlock;
};

static inline void sd_init_rw_lock(struct sd_rw_lock *lock)
{
	int ret;

	do {
		ret = pthread_rwlock_init(&lock->rwlock, NULL);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to initialize a lock, %s", strerror(ret));
}

static inline void sd_destroy_rw_lock(struct sd_rw_lock *lock)
{
	int ret;

	do {
		ret = pthread_rwlock_destroy(&lock->rwlock);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to destroy a lock, %s", strerror(ret));
}

static inline void sd_read_lock(struct sd_rw_lock *lock)
{
	int ret;

	do {
		ret = pthread_rwlock_rdlock(&lock->rwlock);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to lock for reading, %s", strerror(ret));
}

/*
 * Even though POSIX manual it doesn't return EAGAIN, we indeed have met the
 * case that it returned EAGAIN
 */
static inline void sd_write_lock(struct sd_rw_lock *lock)
{
	int ret;

	do {
		ret = pthread_rwlock_wrlock(&lock->rwlock);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to lock for writing, %s", strerror(ret));
}

static inline void sd_rw_unlock(struct sd_rw_lock *lock)
{
	int ret;

	do {
		ret = pthread_rwlock_unlock(&lock->rwlock);
	} while (ret == EAGAIN);

	if (unlikely(ret != 0))
		panic("failed to unlock, %s", strerror(ret));
}

/* colors */
#define TEXT_NORMAL         "\033[0m"
#define TEXT_BOLD           "\033[1m"
#define TEXT_RED            "\033[0;31m"
#define TEXT_BOLD_RED       "\033[1;31m"
#define TEXT_GREEN          "\033[0;32m"
#define TEXT_BOLD_GREEN     "\033[1;32m"
#define TEXT_YELLOW         "\033[0;33m"
#define TEXT_BOLD_YELLOW    "\033[1;33m"
#define TEXT_BLUE           "\033[0;34m"
#define TEXT_BOLD_BLUE      "\033[1;34m"
#define TEXT_MAGENTA        "\033[0;35m"
#define TEXT_BOLD_MAGENTA   "\033[1;35m"
#define TEXT_CYAN           "\033[0;36m"
#define TEXT_BOLD_CYAN      "\033[1;36m"

#define CLEAR_SCREEN        "\033[2J"
#define RESET_CURSOR        "\033[1;1H"

static inline bool is_stdin_console(void)
{
	return isatty(STDIN_FILENO);
}

static inline bool is_stdout_console(void)
{
	return isatty(STDOUT_FILENO);
}

static inline void clear_screen(void)
{
	printf(CLEAR_SCREEN);
	printf(RESET_CURSOR);
}

extern mode_t sd_def_fmode;
extern mode_t sd_def_dmode;

#endif