repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/huge.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
void *huge_malloc(tsdn_t *tsdn, arena_t *arena, size_t usize, bool zero);
void *huge_palloc(tsdn_t *tsdn, arena_t *arena, size_t usize,
size_t alignment, bool zero);
bool huge_ralloc_no_move(tsdn_t *tsdn, void *ptr, size_t oldsize,
size_t usize_min, size_t usize_max, bool zero);
void *huge_ralloc(tsd_t *tsd, arena_t *arena, void *ptr, size_t oldsize,
size_t usize, size_t alignment, bool zero, tcache_t *tcache);
#ifdef JEMALLOC_JET
typedef void (huge_dalloc_junk_t)(void *, size_t);
extern huge_dalloc_junk_t *huge_dalloc_junk;
#endif
void huge_dalloc(tsdn_t *tsdn, void *ptr);
arena_t *huge_aalloc(const void *ptr);
size_t huge_salloc(tsdn_t *tsdn, const void *ptr);
prof_tctx_t *huge_prof_tctx_get(tsdn_t *tsdn, const void *ptr);
void huge_prof_tctx_set(tsdn_t *tsdn, const void *ptr, prof_tctx_t *tctx);
void huge_prof_tctx_reset(tsdn_t *tsdn, const void *ptr);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 1,518 | 41.194444 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/assert.h | /*
* Define a custom assert() in order to reduce the chances of deadlock during
* assertion failure.
*/
#ifndef assert
#define assert(e) do { \
if (unlikely(config_debug && !(e))) { \
malloc_printf( \
"<jemalloc>: %s:%d: Failed assertion: \"%s\"\n", \
__FILE__, __LINE__, #e); \
abort(); \
} \
} while (0)
#endif
#ifndef not_reached
#define not_reached() do { \
if (config_debug) { \
malloc_printf( \
"<jemalloc>: %s:%d: Unreachable code reached\n", \
__FILE__, __LINE__); \
abort(); \
} \
unreachable(); \
} while (0)
#endif
#ifndef not_implemented
#define not_implemented() do { \
if (config_debug) { \
malloc_printf("<jemalloc>: %s:%d: Not implemented\n", \
__FILE__, __LINE__); \
abort(); \
} \
} while (0)
#endif
#ifndef assert_not_implemented
#define assert_not_implemented(e) do { \
if (unlikely(config_debug && !(e))) \
not_implemented(); \
} while (0)
#endif
| 1,029 | 21.391304 | 77 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/atomic.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
#define atomic_read_uint64(p) atomic_add_uint64(p, 0)
#define atomic_read_uint32(p) atomic_add_uint32(p, 0)
#define atomic_read_p(p) atomic_add_p(p, NULL)
#define atomic_read_z(p) atomic_add_z(p, 0)
#define atomic_read_u(p) atomic_add_u(p, 0)
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
/*
* All arithmetic functions return the arithmetic result of the atomic
* operation. Some atomic operation APIs return the value prior to mutation, in
* which case the following functions must redundantly compute the result so
* that it can be returned. These functions are normally inlined, so the extra
* operations can be optimized away if the return values aren't used by the
* callers.
*
* <t> atomic_read_<t>(<t> *p) { return (*p); }
* <t> atomic_add_<t>(<t> *p, <t> x) { return (*p += x); }
* <t> atomic_sub_<t>(<t> *p, <t> x) { return (*p -= x); }
* bool atomic_cas_<t>(<t> *p, <t> c, <t> s)
* {
* if (*p != c)
* return (true);
* *p = s;
* return (false);
* }
* void atomic_write_<t>(<t> *p, <t> x) { *p = x; }
*/
#ifndef JEMALLOC_ENABLE_INLINE
uint64_t atomic_add_uint64(uint64_t *p, uint64_t x);
uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x);
bool atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s);
void atomic_write_uint64(uint64_t *p, uint64_t x);
uint32_t atomic_add_uint32(uint32_t *p, uint32_t x);
uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x);
bool atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s);
void atomic_write_uint32(uint32_t *p, uint32_t x);
void *atomic_add_p(void **p, void *x);
void *atomic_sub_p(void **p, void *x);
bool atomic_cas_p(void **p, void *c, void *s);
void atomic_write_p(void **p, const void *x);
size_t atomic_add_z(size_t *p, size_t x);
size_t atomic_sub_z(size_t *p, size_t x);
bool atomic_cas_z(size_t *p, size_t c, size_t s);
void atomic_write_z(size_t *p, size_t x);
unsigned atomic_add_u(unsigned *p, unsigned x);
unsigned atomic_sub_u(unsigned *p, unsigned x);
bool atomic_cas_u(unsigned *p, unsigned c, unsigned s);
void atomic_write_u(unsigned *p, unsigned x);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_ATOMIC_C_))
/******************************************************************************/
/* 64-bit operations. */
#if (LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
# if (defined(__amd64__) || defined(__x86_64__))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
uint64_t t = x;
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (t), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return (t + x);
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
uint64_t t;
x = (uint64_t)(-(int64_t)x);
t = x;
asm volatile (
"lock; xaddq %0, %1;"
: "+r" (t), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return (t + x);
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
uint8_t success;
asm volatile (
"lock; cmpxchgq %4, %0;"
"sete %1;"
: "=m" (*p), "=a" (success) /* Outputs. */
: "m" (*p), "a" (c), "r" (s) /* Inputs. */
: "memory" /* Clobbers. */
);
return (!(bool)success);
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
asm volatile (
"xchgq %1, %0;" /* Lock is implied by xchgq. */
: "=m" (*p), "+r" (x) /* Outputs. */
: "m" (*p) /* Inputs. */
: "memory" /* Clobbers. */
);
}
# elif (defined(JEMALLOC_C11ATOMICS))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
return (atomic_fetch_add(a, x) + x);
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
return (atomic_fetch_sub(a, x) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
return (!atomic_compare_exchange_strong(a, &c, s));
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
atomic_store(a, x);
}
# elif (defined(JEMALLOC_ATOMIC9))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
/*
* atomic_fetchadd_64() doesn't exist, but we only ever use this
* function on LP64 systems, so atomic_fetchadd_long() will do.
*/
assert(sizeof(uint64_t) == sizeof(unsigned long));
return (atomic_fetchadd_long(p, (unsigned long)x) + x);
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
assert(sizeof(uint64_t) == sizeof(unsigned long));
return (atomic_fetchadd_long(p, (unsigned long)(-(long)x)) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
assert(sizeof(uint64_t) == sizeof(unsigned long));
return (!atomic_cmpset_long(p, (unsigned long)c, (unsigned long)s));
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
assert(sizeof(uint64_t) == sizeof(unsigned long));
atomic_store_rel_long(p, x);
}
# elif (defined(JEMALLOC_OSATOMIC))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return (OSAtomicAdd64((int64_t)x, (int64_t *)p));
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return (OSAtomicAdd64(-((int64_t)x), (int64_t *)p));
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
return (!OSAtomicCompareAndSwap64(c, s, (int64_t *)p));
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
uint64_t o;
/*The documented OSAtomic*() API does not expose an atomic exchange. */
do {
o = atomic_read_uint64(p);
} while (atomic_cas_uint64(p, o, x));
}
# elif (defined(_MSC_VER))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return (InterlockedExchangeAdd64(p, x) + x);
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return (InterlockedExchangeAdd64(p, -((int64_t)x)) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
uint64_t o;
o = InterlockedCompareExchange64(p, s, c);
return (o != c);
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
InterlockedExchange64(p, x);
}
# elif (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) || \
defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_8))
JEMALLOC_INLINE uint64_t
atomic_add_uint64(uint64_t *p, uint64_t x)
{
return (__sync_add_and_fetch(p, x));
}
JEMALLOC_INLINE uint64_t
atomic_sub_uint64(uint64_t *p, uint64_t x)
{
return (__sync_sub_and_fetch(p, x));
}
JEMALLOC_INLINE bool
atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
{
return (!__sync_bool_compare_and_swap(p, c, s));
}
JEMALLOC_INLINE void
atomic_write_uint64(uint64_t *p, uint64_t x)
{
__sync_lock_test_and_set(p, x);
}
# else
# error "Missing implementation for 64-bit atomic operations"
# endif
#endif
/******************************************************************************/
/* 32-bit operations. */
#if (defined(__i386__) || defined(__amd64__) || defined(__x86_64__))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
uint32_t t = x;
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (t), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return (t + x);
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
uint32_t t;
x = (uint32_t)(-(int32_t)x);
t = x;
asm volatile (
"lock; xaddl %0, %1;"
: "+r" (t), "=m" (*p) /* Outputs. */
: "m" (*p) /* Inputs. */
);
return (t + x);
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
uint8_t success;
asm volatile (
"lock; cmpxchgl %4, %0;"
"sete %1;"
: "=m" (*p), "=a" (success) /* Outputs. */
: "m" (*p), "a" (c), "r" (s) /* Inputs. */
: "memory"
);
return (!(bool)success);
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
asm volatile (
"xchgl %1, %0;" /* Lock is implied by xchgl. */
: "=m" (*p), "+r" (x) /* Outputs. */
: "m" (*p) /* Inputs. */
: "memory" /* Clobbers. */
);
}
# elif (defined(JEMALLOC_C11ATOMICS))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
return (atomic_fetch_add(a, x) + x);
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
return (atomic_fetch_sub(a, x) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
return (!atomic_compare_exchange_strong(a, &c, s));
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
atomic_store(a, x);
}
#elif (defined(JEMALLOC_ATOMIC9))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return (atomic_fetchadd_32(p, x) + x);
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return (atomic_fetchadd_32(p, (uint32_t)(-(int32_t)x)) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
return (!atomic_cmpset_32(p, c, s));
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
atomic_store_rel_32(p, x);
}
#elif (defined(JEMALLOC_OSATOMIC))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return (OSAtomicAdd32((int32_t)x, (int32_t *)p));
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return (OSAtomicAdd32(-((int32_t)x), (int32_t *)p));
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
return (!OSAtomicCompareAndSwap32(c, s, (int32_t *)p));
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
uint32_t o;
/*The documented OSAtomic*() API does not expose an atomic exchange. */
do {
o = atomic_read_uint32(p);
} while (atomic_cas_uint32(p, o, x));
}
#elif (defined(_MSC_VER))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return (InterlockedExchangeAdd(p, x) + x);
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return (InterlockedExchangeAdd(p, -((int32_t)x)) - x);
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
uint32_t o;
o = InterlockedCompareExchange(p, s, c);
return (o != c);
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
InterlockedExchange(p, x);
}
#elif (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || \
defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_4))
JEMALLOC_INLINE uint32_t
atomic_add_uint32(uint32_t *p, uint32_t x)
{
return (__sync_add_and_fetch(p, x));
}
JEMALLOC_INLINE uint32_t
atomic_sub_uint32(uint32_t *p, uint32_t x)
{
return (__sync_sub_and_fetch(p, x));
}
JEMALLOC_INLINE bool
atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
{
return (!__sync_bool_compare_and_swap(p, c, s));
}
JEMALLOC_INLINE void
atomic_write_uint32(uint32_t *p, uint32_t x)
{
__sync_lock_test_and_set(p, x);
}
#else
# error "Missing implementation for 32-bit atomic operations"
#endif
/******************************************************************************/
/* Pointer operations. */
JEMALLOC_INLINE void *
atomic_add_p(void **p, void *x)
{
#if (LG_SIZEOF_PTR == 3)
return ((void *)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
#elif (LG_SIZEOF_PTR == 2)
return ((void *)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
#endif
}
JEMALLOC_INLINE void *
atomic_sub_p(void **p, void *x)
{
#if (LG_SIZEOF_PTR == 3)
return ((void *)atomic_add_uint64((uint64_t *)p,
(uint64_t)-((int64_t)x)));
#elif (LG_SIZEOF_PTR == 2)
return ((void *)atomic_add_uint32((uint32_t *)p,
(uint32_t)-((int32_t)x)));
#endif
}
JEMALLOC_INLINE bool
atomic_cas_p(void **p, void *c, void *s)
{
#if (LG_SIZEOF_PTR == 3)
return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
#elif (LG_SIZEOF_PTR == 2)
return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
#endif
}
JEMALLOC_INLINE void
atomic_write_p(void **p, const void *x)
{
#if (LG_SIZEOF_PTR == 3)
atomic_write_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_PTR == 2)
atomic_write_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
/******************************************************************************/
/* size_t operations. */
JEMALLOC_INLINE size_t
atomic_add_z(size_t *p, size_t x)
{
#if (LG_SIZEOF_PTR == 3)
return ((size_t)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
#elif (LG_SIZEOF_PTR == 2)
return ((size_t)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
#endif
}
JEMALLOC_INLINE size_t
atomic_sub_z(size_t *p, size_t x)
{
#if (LG_SIZEOF_PTR == 3)
return ((size_t)atomic_add_uint64((uint64_t *)p,
(uint64_t)-((int64_t)x)));
#elif (LG_SIZEOF_PTR == 2)
return ((size_t)atomic_add_uint32((uint32_t *)p,
(uint32_t)-((int32_t)x)));
#endif
}
JEMALLOC_INLINE bool
atomic_cas_z(size_t *p, size_t c, size_t s)
{
#if (LG_SIZEOF_PTR == 3)
return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
#elif (LG_SIZEOF_PTR == 2)
return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
#endif
}
JEMALLOC_INLINE void
atomic_write_z(size_t *p, size_t x)
{
#if (LG_SIZEOF_PTR == 3)
atomic_write_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_PTR == 2)
atomic_write_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
/******************************************************************************/
/* unsigned operations. */
JEMALLOC_INLINE unsigned
atomic_add_u(unsigned *p, unsigned x)
{
#if (LG_SIZEOF_INT == 3)
return ((unsigned)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
#elif (LG_SIZEOF_INT == 2)
return ((unsigned)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
#endif
}
JEMALLOC_INLINE unsigned
atomic_sub_u(unsigned *p, unsigned x)
{
#if (LG_SIZEOF_INT == 3)
return ((unsigned)atomic_add_uint64((uint64_t *)p,
(uint64_t)-((int64_t)x)));
#elif (LG_SIZEOF_INT == 2)
return ((unsigned)atomic_add_uint32((uint32_t *)p,
(uint32_t)-((int32_t)x)));
#endif
}
JEMALLOC_INLINE bool
atomic_cas_u(unsigned *p, unsigned c, unsigned s)
{
#if (LG_SIZEOF_INT == 3)
return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
#elif (LG_SIZEOF_INT == 2)
return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
#endif
}
JEMALLOC_INLINE void
atomic_write_u(unsigned *p, unsigned x)
{
#if (LG_SIZEOF_INT == 3)
atomic_write_uint64((uint64_t *)p, (uint64_t)x);
#elif (LG_SIZEOF_INT == 2)
atomic_write_uint32((uint32_t *)p, (uint32_t)x);
#endif
}
/******************************************************************************/
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 15,441 | 22.684049 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/jemalloc_internal_decls.h | #ifndef JEMALLOC_INTERNAL_DECLS_H
#define JEMALLOC_INTERNAL_DECLS_H
#include <math.h>
#ifdef _WIN32
# include <windows.h>
# include "msvc_compat/windows_extra.h"
#else
# include <sys/param.h>
# include <sys/mman.h>
# if !defined(__pnacl__) && !defined(__native_client__)
# include <sys/syscall.h>
# if !defined(SYS_write) && defined(__NR_write)
# define SYS_write __NR_write
# endif
# include <sys/uio.h>
# endif
# include <pthread.h>
# ifdef JEMALLOC_OS_UNFAIR_LOCK
# include <os/lock.h>
# endif
# ifdef JEMALLOC_GLIBC_MALLOC_HOOK
# include <sched.h>
# endif
# include <errno.h>
# include <sys/time.h>
# include <time.h>
# ifdef JEMALLOC_HAVE_MACH_ABSOLUTE_TIME
# include <mach/mach_time.h>
# endif
#endif
#include <sys/types.h>
#include <limits.h>
#ifndef SIZE_T_MAX
# define SIZE_T_MAX SIZE_MAX
#endif
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#ifndef offsetof
# define offsetof(type, member) ((size_t)&(((type *)NULL)->member))
#endif
#include <string.h>
#include <strings.h>
#include <ctype.h>
#ifdef _MSC_VER
# include <io.h>
typedef intptr_t ssize_t;
# define PATH_MAX 1024
# define STDERR_FILENO 2
# define __func__ __FUNCTION__
# ifdef JEMALLOC_HAS_RESTRICT
# define restrict __restrict
# endif
/* Disable warnings about deprecated system functions. */
# pragma warning(disable: 4996)
#if _MSC_VER < 1800
static int
isblank(int c)
{
return (c == '\t' || c == ' ');
}
#endif
#else
# include <unistd.h>
#endif
#include <fcntl.h>
#endif /* JEMALLOC_INTERNAL_H */
| 1,608 | 20.171053 | 68 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/mb.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
void mb_write(void);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MB_C_))
#ifdef __i386__
/*
* According to the Intel Architecture Software Developer's Manual, current
* processors execute instructions in order from the perspective of other
* processors in a multiprocessor system, but 1) Intel reserves the right to
* change that, and 2) the compiler's optimizer could re-order instructions if
* there weren't some form of barrier. Therefore, even if running on an
* architecture that does not need memory barriers (everything through at least
* i686), an "optimizer barrier" is necessary.
*/
JEMALLOC_INLINE void
mb_write(void)
{
# if 0
/* This is a true memory barrier. */
asm volatile ("pusha;"
"xor %%eax,%%eax;"
"cpuid;"
"popa;"
: /* Outputs. */
: /* Inputs. */
: "memory" /* Clobbers. */
);
# else
/*
* This is hopefully enough to keep the compiler from reordering
* instructions around this one.
*/
asm volatile ("nop;"
: /* Outputs. */
: /* Inputs. */
: "memory" /* Clobbers. */
);
# endif
}
#elif (defined(__amd64__) || defined(__x86_64__))
JEMALLOC_INLINE void
mb_write(void)
{
asm volatile ("sfence"
: /* Outputs. */
: /* Inputs. */
: "memory" /* Clobbers. */
);
}
#elif defined(__powerpc__)
JEMALLOC_INLINE void
mb_write(void)
{
asm volatile ("eieio"
: /* Outputs. */
: /* Inputs. */
: "memory" /* Clobbers. */
);
}
#elif defined(__sparc64__)
JEMALLOC_INLINE void
mb_write(void)
{
asm volatile ("membar #StoreStore"
: /* Outputs. */
: /* Inputs. */
: "memory" /* Clobbers. */
);
}
#elif defined(__tile__)
JEMALLOC_INLINE void
mb_write(void)
{
__sync_synchronize();
}
#else
/*
* This is much slower than a simple memory barrier, but the semantics of mutex
* unlock make this work.
*/
JEMALLOC_INLINE void
mb_write(void)
{
malloc_mutex_t mtx;
malloc_mutex_init(&mtx, "mb", WITNESS_RANK_OMIT);
malloc_mutex_lock(TSDN_NULL, &mtx);
malloc_mutex_unlock(TSDN_NULL, &mtx);
}
#endif
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 2,738 | 22.612069 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/quarantine.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
typedef struct quarantine_obj_s quarantine_obj_t;
typedef struct quarantine_s quarantine_t;
/* Default per thread quarantine size if valgrind is enabled. */
#define JEMALLOC_VALGRIND_QUARANTINE_DEFAULT (ZU(1) << 24)
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
struct quarantine_obj_s {
void *ptr;
size_t usize;
};
struct quarantine_s {
size_t curbytes;
size_t curobjs;
size_t first;
#define LG_MAXOBJS_INIT 10
size_t lg_maxobjs;
quarantine_obj_t objs[1]; /* Dynamically sized ring buffer. */
};
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
void quarantine_alloc_hook_work(tsd_t *tsd);
void quarantine(tsd_t *tsd, void *ptr);
void quarantine_cleanup(tsd_t *tsd);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
void quarantine_alloc_hook(void);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_QUARANTINE_C_))
JEMALLOC_ALWAYS_INLINE void
quarantine_alloc_hook(void)
{
tsd_t *tsd;
assert(config_fill && opt_quarantine);
tsd = tsd_fetch();
if (tsd_quarantine_get(tsd) == NULL)
quarantine_alloc_hook_work(tsd);
}
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 1,593 | 25.131148 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/valgrind.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#ifdef JEMALLOC_VALGRIND
#include <valgrind/valgrind.h>
/*
* The size that is reported to Valgrind must be consistent through a chain of
* malloc..realloc..realloc calls. Request size isn't recorded anywhere in
* jemalloc, so it is critical that all callers of these macros provide usize
* rather than request size. As a result, buffer overflow detection is
* technically weakened for the standard API, though it is generally accepted
* practice to consider any extra bytes reported by malloc_usable_size() as
* usable space.
*/
#define JEMALLOC_VALGRIND_MAKE_MEM_NOACCESS(ptr, usize) do { \
if (unlikely(in_valgrind)) \
valgrind_make_mem_noaccess(ptr, usize); \
} while (0)
#define JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ptr, usize) do { \
if (unlikely(in_valgrind)) \
valgrind_make_mem_undefined(ptr, usize); \
} while (0)
#define JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ptr, usize) do { \
if (unlikely(in_valgrind)) \
valgrind_make_mem_defined(ptr, usize); \
} while (0)
/*
* The VALGRIND_MALLOCLIKE_BLOCK() and VALGRIND_RESIZEINPLACE_BLOCK() macro
* calls must be embedded in macros rather than in functions so that when
* Valgrind reports errors, there are no extra stack frames in the backtraces.
*/
#define JEMALLOC_VALGRIND_MALLOC(cond, tsdn, ptr, usize, zero) do { \
if (unlikely(in_valgrind && cond)) { \
VALGRIND_MALLOCLIKE_BLOCK(ptr, usize, p2rz(tsdn, ptr), \
zero); \
} \
} while (0)
#define JEMALLOC_VALGRIND_REALLOC_MOVED_no(ptr, old_ptr) \
(false)
#define JEMALLOC_VALGRIND_REALLOC_MOVED_maybe(ptr, old_ptr) \
((ptr) != (old_ptr))
#define JEMALLOC_VALGRIND_REALLOC_PTR_NULL_no(ptr) \
(false)
#define JEMALLOC_VALGRIND_REALLOC_PTR_NULL_maybe(ptr) \
(ptr == NULL)
#define JEMALLOC_VALGRIND_REALLOC_OLD_PTR_NULL_no(old_ptr) \
(false)
#define JEMALLOC_VALGRIND_REALLOC_OLD_PTR_NULL_maybe(old_ptr) \
(old_ptr == NULL)
#define JEMALLOC_VALGRIND_REALLOC(moved, tsdn, ptr, usize, ptr_null, \
old_ptr, old_usize, old_rzsize, old_ptr_null, zero) do { \
if (unlikely(in_valgrind)) { \
size_t rzsize = p2rz(tsdn, ptr); \
\
if (!JEMALLOC_VALGRIND_REALLOC_MOVED_##moved(ptr, \
old_ptr)) { \
VALGRIND_RESIZEINPLACE_BLOCK(ptr, old_usize, \
usize, rzsize); \
if (zero && old_usize < usize) { \
valgrind_make_mem_defined( \
(void *)((uintptr_t)ptr + \
old_usize), usize - old_usize); \
} \
} else { \
if (!JEMALLOC_VALGRIND_REALLOC_OLD_PTR_NULL_## \
old_ptr_null(old_ptr)) { \
valgrind_freelike_block(old_ptr, \
old_rzsize); \
} \
if (!JEMALLOC_VALGRIND_REALLOC_PTR_NULL_## \
ptr_null(ptr)) { \
size_t copy_size = (old_usize < usize) \
? old_usize : usize; \
size_t tail_size = usize - copy_size; \
VALGRIND_MALLOCLIKE_BLOCK(ptr, usize, \
rzsize, false); \
if (copy_size > 0) { \
valgrind_make_mem_defined(ptr, \
copy_size); \
} \
if (zero && tail_size > 0) { \
valgrind_make_mem_defined( \
(void *)((uintptr_t)ptr + \
copy_size), tail_size); \
} \
} \
} \
} \
} while (0)
#define JEMALLOC_VALGRIND_FREE(ptr, rzsize) do { \
if (unlikely(in_valgrind)) \
valgrind_freelike_block(ptr, rzsize); \
} while (0)
#else
#define RUNNING_ON_VALGRIND ((unsigned)0)
#define JEMALLOC_VALGRIND_MAKE_MEM_NOACCESS(ptr, usize) do {} while (0)
#define JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ptr, usize) do {} while (0)
#define JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ptr, usize) do {} while (0)
#define JEMALLOC_VALGRIND_MALLOC(cond, tsdn, ptr, usize, zero) do {} while (0)
#define JEMALLOC_VALGRIND_REALLOC(maybe_moved, tsdn, ptr, usize, \
ptr_maybe_null, old_ptr, old_usize, old_rzsize, old_ptr_maybe_null, \
zero) do {} while (0)
#define JEMALLOC_VALGRIND_FREE(ptr, rzsize) do {} while (0)
#endif
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
#ifdef JEMALLOC_VALGRIND
void valgrind_make_mem_noaccess(void *ptr, size_t usize);
void valgrind_make_mem_undefined(void *ptr, size_t usize);
void valgrind_make_mem_defined(void *ptr, size_t usize);
void valgrind_freelike_block(void *ptr, size_t usize);
#endif
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 4,841 | 36.534884 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/extent.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
typedef struct extent_node_s extent_node_t;
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
/* Tree of extents. Use accessor functions for en_* fields. */
struct extent_node_s {
/* Arena from which this extent came, if any. */
arena_t *en_arena;
/* Pointer to the extent that this tree node is responsible for. */
void *en_addr;
/* Total region size. */
size_t en_size;
/*
* Serial number (potentially non-unique).
*
* In principle serial numbers can wrap around on 32-bit systems if
* JEMALLOC_MUNMAP is defined, but as long as comparison functions fall
* back on address comparison for equal serial numbers, stable (if
* imperfect) ordering is maintained.
*
* Serial numbers may not be unique even in the absence of wrap-around,
* e.g. when splitting an extent and assigning the same serial number to
* both resulting adjacent extents.
*/
size_t en_sn;
/*
* The zeroed flag is used by chunk recycling code to track whether
* memory is zero-filled.
*/
bool en_zeroed;
/*
* True if physical memory is committed to the extent, whether
* explicitly or implicitly as on a system that overcommits and
* satisfies physical memory needs on demand via soft page faults.
*/
bool en_committed;
/*
* The achunk flag is used to validate that huge allocation lookups
* don't return arena chunks.
*/
bool en_achunk;
/* Profile counters, used for huge objects. */
prof_tctx_t *en_prof_tctx;
/* Linkage for arena's runs_dirty and chunks_cache rings. */
arena_runs_dirty_link_t rd;
qr(extent_node_t) cc_link;
union {
/* Linkage for the size/sn/address-ordered tree. */
rb_node(extent_node_t) szsnad_link;
/* Linkage for arena's achunks, huge, and node_cache lists. */
ql_elm(extent_node_t) ql_link;
};
/* Linkage for the address-ordered tree. */
rb_node(extent_node_t) ad_link;
};
typedef rb_tree(extent_node_t) extent_tree_t;
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
rb_proto(, extent_tree_szsnad_, extent_tree_t, extent_node_t)
rb_proto(, extent_tree_ad_, extent_tree_t, extent_node_t)
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
arena_t *extent_node_arena_get(const extent_node_t *node);
void *extent_node_addr_get(const extent_node_t *node);
size_t extent_node_size_get(const extent_node_t *node);
size_t extent_node_sn_get(const extent_node_t *node);
bool extent_node_zeroed_get(const extent_node_t *node);
bool extent_node_committed_get(const extent_node_t *node);
bool extent_node_achunk_get(const extent_node_t *node);
prof_tctx_t *extent_node_prof_tctx_get(const extent_node_t *node);
void extent_node_arena_set(extent_node_t *node, arena_t *arena);
void extent_node_addr_set(extent_node_t *node, void *addr);
void extent_node_size_set(extent_node_t *node, size_t size);
void extent_node_sn_set(extent_node_t *node, size_t sn);
void extent_node_zeroed_set(extent_node_t *node, bool zeroed);
void extent_node_committed_set(extent_node_t *node, bool committed);
void extent_node_achunk_set(extent_node_t *node, bool achunk);
void extent_node_prof_tctx_set(extent_node_t *node, prof_tctx_t *tctx);
void extent_node_init(extent_node_t *node, arena_t *arena, void *addr,
size_t size, size_t sn, bool zeroed, bool committed);
void extent_node_dirty_linkage_init(extent_node_t *node);
void extent_node_dirty_insert(extent_node_t *node,
arena_runs_dirty_link_t *runs_dirty, extent_node_t *chunks_dirty);
void extent_node_dirty_remove(extent_node_t *node);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_EXTENT_C_))
JEMALLOC_INLINE arena_t *
extent_node_arena_get(const extent_node_t *node)
{
return (node->en_arena);
}
JEMALLOC_INLINE void *
extent_node_addr_get(const extent_node_t *node)
{
return (node->en_addr);
}
JEMALLOC_INLINE size_t
extent_node_size_get(const extent_node_t *node)
{
return (node->en_size);
}
JEMALLOC_INLINE size_t
extent_node_sn_get(const extent_node_t *node)
{
return (node->en_sn);
}
JEMALLOC_INLINE bool
extent_node_zeroed_get(const extent_node_t *node)
{
return (node->en_zeroed);
}
JEMALLOC_INLINE bool
extent_node_committed_get(const extent_node_t *node)
{
assert(!node->en_achunk);
return (node->en_committed);
}
JEMALLOC_INLINE bool
extent_node_achunk_get(const extent_node_t *node)
{
return (node->en_achunk);
}
JEMALLOC_INLINE prof_tctx_t *
extent_node_prof_tctx_get(const extent_node_t *node)
{
return (node->en_prof_tctx);
}
JEMALLOC_INLINE void
extent_node_arena_set(extent_node_t *node, arena_t *arena)
{
node->en_arena = arena;
}
JEMALLOC_INLINE void
extent_node_addr_set(extent_node_t *node, void *addr)
{
node->en_addr = addr;
}
JEMALLOC_INLINE void
extent_node_size_set(extent_node_t *node, size_t size)
{
node->en_size = size;
}
JEMALLOC_INLINE void
extent_node_sn_set(extent_node_t *node, size_t sn)
{
node->en_sn = sn;
}
JEMALLOC_INLINE void
extent_node_zeroed_set(extent_node_t *node, bool zeroed)
{
node->en_zeroed = zeroed;
}
JEMALLOC_INLINE void
extent_node_committed_set(extent_node_t *node, bool committed)
{
node->en_committed = committed;
}
JEMALLOC_INLINE void
extent_node_achunk_set(extent_node_t *node, bool achunk)
{
node->en_achunk = achunk;
}
JEMALLOC_INLINE void
extent_node_prof_tctx_set(extent_node_t *node, prof_tctx_t *tctx)
{
node->en_prof_tctx = tctx;
}
JEMALLOC_INLINE void
extent_node_init(extent_node_t *node, arena_t *arena, void *addr, size_t size,
size_t sn, bool zeroed, bool committed)
{
extent_node_arena_set(node, arena);
extent_node_addr_set(node, addr);
extent_node_size_set(node, size);
extent_node_sn_set(node, sn);
extent_node_zeroed_set(node, zeroed);
extent_node_committed_set(node, committed);
extent_node_achunk_set(node, false);
if (config_prof)
extent_node_prof_tctx_set(node, NULL);
}
JEMALLOC_INLINE void
extent_node_dirty_linkage_init(extent_node_t *node)
{
qr_new(&node->rd, rd_link);
qr_new(node, cc_link);
}
JEMALLOC_INLINE void
extent_node_dirty_insert(extent_node_t *node,
arena_runs_dirty_link_t *runs_dirty, extent_node_t *chunks_dirty)
{
qr_meld(runs_dirty, &node->rd, rd_link);
qr_meld(chunks_dirty, node, cc_link);
}
JEMALLOC_INLINE void
extent_node_dirty_remove(extent_node_t *node)
{
qr_remove(&node->rd, rd_link);
qr_remove(node, cc_link);
}
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 6,787 | 24.04797 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/chunk_dss.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
typedef enum {
dss_prec_disabled = 0,
dss_prec_primary = 1,
dss_prec_secondary = 2,
dss_prec_limit = 3
} dss_prec_t;
#define DSS_PREC_DEFAULT dss_prec_secondary
#define DSS_DEFAULT "secondary"
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
extern const char *dss_prec_names[];
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
dss_prec_t chunk_dss_prec_get(void);
bool chunk_dss_prec_set(dss_prec_t dss_prec);
void *chunk_alloc_dss(tsdn_t *tsdn, arena_t *arena, void *new_addr,
size_t size, size_t alignment, bool *zero, bool *commit);
bool chunk_in_dss(void *chunk);
bool chunk_dss_mergeable(void *chunk_a, void *chunk_b);
void chunk_dss_boot(void);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 1,211 | 30.894737 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/jemalloc_internal_macros.h | /*
* JEMALLOC_ALWAYS_INLINE and JEMALLOC_INLINE are used within header files for
* functions that are static inline functions if inlining is enabled, and
* single-definition library-private functions if inlining is disabled.
*
* JEMALLOC_ALWAYS_INLINE_C and JEMALLOC_INLINE_C are for use in .c files, in
* which case the denoted functions are always static, regardless of whether
* inlining is enabled.
*/
#if defined(JEMALLOC_DEBUG) || defined(JEMALLOC_CODE_COVERAGE)
/* Disable inlining to make debugging/profiling easier. */
# define JEMALLOC_ALWAYS_INLINE
# define JEMALLOC_ALWAYS_INLINE_C static
# define JEMALLOC_INLINE
# define JEMALLOC_INLINE_C static
# define inline
#else
# define JEMALLOC_ENABLE_INLINE
# ifdef JEMALLOC_HAVE_ATTR
# define JEMALLOC_ALWAYS_INLINE \
static inline JEMALLOC_ATTR(unused) JEMALLOC_ATTR(always_inline)
# define JEMALLOC_ALWAYS_INLINE_C \
static inline JEMALLOC_ATTR(always_inline)
# else
# define JEMALLOC_ALWAYS_INLINE static inline
# define JEMALLOC_ALWAYS_INLINE_C static inline
# endif
# define JEMALLOC_INLINE static inline
# define JEMALLOC_INLINE_C static inline
# ifdef _MSC_VER
# define inline _inline
# endif
#endif
#ifdef JEMALLOC_CC_SILENCE
# define UNUSED JEMALLOC_ATTR(unused)
#else
# define UNUSED
#endif
#define ZU(z) ((size_t)z)
#define ZI(z) ((ssize_t)z)
#define QU(q) ((uint64_t)q)
#define QI(q) ((int64_t)q)
#define KZU(z) ZU(z##ULL)
#define KZI(z) ZI(z##LL)
#define KQU(q) QU(q##ULL)
#define KQI(q) QI(q##LL)
#ifndef __DECONST
# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
#endif
#ifndef JEMALLOC_HAS_RESTRICT
# define restrict
#endif
| 1,669 | 27.793103 | 78 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/pages.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
void *pages_map(void *addr, size_t size, bool *commit);
void pages_unmap(void *addr, size_t size);
void *pages_trim(void *addr, size_t alloc_size, size_t leadsize,
size_t size, bool *commit);
bool pages_commit(void *addr, size_t size);
bool pages_decommit(void *addr, size_t size);
bool pages_purge(void *addr, size_t size);
bool pages_huge(void *addr, size_t size);
bool pages_nohuge(void *addr, size_t size);
void pages_boot(void);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 1,077 | 34.933333 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/prof.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
typedef struct prof_bt_s prof_bt_t;
typedef struct prof_cnt_s prof_cnt_t;
typedef struct prof_tctx_s prof_tctx_t;
typedef struct prof_gctx_s prof_gctx_t;
typedef struct prof_tdata_s prof_tdata_t;
/* Option defaults. */
#ifdef JEMALLOC_PROF
# define PROF_PREFIX_DEFAULT "jeprof"
#else
# define PROF_PREFIX_DEFAULT ""
#endif
#define LG_PROF_SAMPLE_DEFAULT 19
#define LG_PROF_INTERVAL_DEFAULT -1
/*
* Hard limit on stack backtrace depth. The version of prof_backtrace() that
* is based on __builtin_return_address() necessarily has a hard-coded number
* of backtrace frame handlers, and should be kept in sync with this setting.
*/
#define PROF_BT_MAX 128
/* Initial hash table size. */
#define PROF_CKH_MINITEMS 64
/* Size of memory buffer to use when writing dump files. */
#define PROF_DUMP_BUFSIZE 65536
/* Size of stack-allocated buffer used by prof_printf(). */
#define PROF_PRINTF_BUFSIZE 128
/*
* Number of mutexes shared among all gctx's. No space is allocated for these
* unless profiling is enabled, so it's okay to over-provision.
*/
#define PROF_NCTX_LOCKS 1024
/*
* Number of mutexes shared among all tdata's. No space is allocated for these
* unless profiling is enabled, so it's okay to over-provision.
*/
#define PROF_NTDATA_LOCKS 256
/*
* prof_tdata pointers close to NULL are used to encode state information that
* is used for cleaning up during thread shutdown.
*/
#define PROF_TDATA_STATE_REINCARNATED ((prof_tdata_t *)(uintptr_t)1)
#define PROF_TDATA_STATE_PURGATORY ((prof_tdata_t *)(uintptr_t)2)
#define PROF_TDATA_STATE_MAX PROF_TDATA_STATE_PURGATORY
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
struct prof_bt_s {
/* Backtrace, stored as len program counters. */
void **vec;
unsigned len;
};
#ifdef JEMALLOC_PROF_LIBGCC
/* Data structure passed to libgcc _Unwind_Backtrace() callback functions. */
typedef struct {
prof_bt_t *bt;
unsigned max;
} prof_unwind_data_t;
#endif
struct prof_cnt_s {
/* Profiling counters. */
uint64_t curobjs;
uint64_t curbytes;
uint64_t accumobjs;
uint64_t accumbytes;
};
typedef enum {
prof_tctx_state_initializing,
prof_tctx_state_nominal,
prof_tctx_state_dumping,
prof_tctx_state_purgatory /* Dumper must finish destroying. */
} prof_tctx_state_t;
struct prof_tctx_s {
/* Thread data for thread that performed the allocation. */
prof_tdata_t *tdata;
/*
* Copy of tdata->thr_{uid,discrim}, necessary because tdata may be
* defunct during teardown.
*/
uint64_t thr_uid;
uint64_t thr_discrim;
/* Profiling counters, protected by tdata->lock. */
prof_cnt_t cnts;
/* Associated global context. */
prof_gctx_t *gctx;
/*
* UID that distinguishes multiple tctx's created by the same thread,
* but coexisting in gctx->tctxs. There are two ways that such
* coexistence can occur:
* - A dumper thread can cause a tctx to be retained in the purgatory
* state.
* - Although a single "producer" thread must create all tctx's which
* share the same thr_uid, multiple "consumers" can each concurrently
* execute portions of prof_tctx_destroy(). prof_tctx_destroy() only
* gets called once each time cnts.cur{objs,bytes} drop to 0, but this
* threshold can be hit again before the first consumer finishes
* executing prof_tctx_destroy().
*/
uint64_t tctx_uid;
/* Linkage into gctx's tctxs. */
rb_node(prof_tctx_t) tctx_link;
/*
* True during prof_alloc_prep()..prof_malloc_sample_object(), prevents
* sample vs destroy race.
*/
bool prepared;
/* Current dump-related state, protected by gctx->lock. */
prof_tctx_state_t state;
/*
* Copy of cnts snapshotted during early dump phase, protected by
* dump_mtx.
*/
prof_cnt_t dump_cnts;
};
typedef rb_tree(prof_tctx_t) prof_tctx_tree_t;
struct prof_gctx_s {
/* Protects nlimbo, cnt_summed, and tctxs. */
malloc_mutex_t *lock;
/*
* Number of threads that currently cause this gctx to be in a state of
* limbo due to one of:
* - Initializing this gctx.
* - Initializing per thread counters associated with this gctx.
* - Preparing to destroy this gctx.
* - Dumping a heap profile that includes this gctx.
* nlimbo must be 1 (single destroyer) in order to safely destroy the
* gctx.
*/
unsigned nlimbo;
/*
* Tree of profile counters, one for each thread that has allocated in
* this context.
*/
prof_tctx_tree_t tctxs;
/* Linkage for tree of contexts to be dumped. */
rb_node(prof_gctx_t) dump_link;
/* Temporary storage for summation during dump. */
prof_cnt_t cnt_summed;
/* Associated backtrace. */
prof_bt_t bt;
/* Backtrace vector, variable size, referred to by bt. */
void *vec[1];
};
typedef rb_tree(prof_gctx_t) prof_gctx_tree_t;
struct prof_tdata_s {
malloc_mutex_t *lock;
/* Monotonically increasing unique thread identifier. */
uint64_t thr_uid;
/*
* Monotonically increasing discriminator among tdata structures
* associated with the same thr_uid.
*/
uint64_t thr_discrim;
/* Included in heap profile dumps if non-NULL. */
char *thread_name;
bool attached;
bool expired;
rb_node(prof_tdata_t) tdata_link;
/*
* Counter used to initialize prof_tctx_t's tctx_uid. No locking is
* necessary when incrementing this field, because only one thread ever
* does so.
*/
uint64_t tctx_uid_next;
/*
* Hash of (prof_bt_t *)-->(prof_tctx_t *). Each thread tracks
* backtraces for which it has non-zero allocation/deallocation counters
* associated with thread-specific prof_tctx_t objects. Other threads
* may write to prof_tctx_t contents when freeing associated objects.
*/
ckh_t bt2tctx;
/* Sampling state. */
uint64_t prng_state;
uint64_t bytes_until_sample;
/* State used to avoid dumping while operating on prof internals. */
bool enq;
bool enq_idump;
bool enq_gdump;
/*
* Set to true during an early dump phase for tdata's which are
* currently being dumped. New threads' tdata's have this initialized
* to false so that they aren't accidentally included in later dump
* phases.
*/
bool dumping;
/*
* True if profiling is active for this tdata's thread
* (thread.prof.active mallctl).
*/
bool active;
/* Temporary storage for summation during dump. */
prof_cnt_t cnt_summed;
/* Backtrace vector, used for calls to prof_backtrace(). */
void *vec[PROF_BT_MAX];
};
typedef rb_tree(prof_tdata_t) prof_tdata_tree_t;
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
extern bool opt_prof;
extern bool opt_prof_active;
extern bool opt_prof_thread_active_init;
extern size_t opt_lg_prof_sample; /* Mean bytes between samples. */
extern ssize_t opt_lg_prof_interval; /* lg(prof_interval). */
extern bool opt_prof_gdump; /* High-water memory dumping. */
extern bool opt_prof_final; /* Final profile dumping. */
extern bool opt_prof_leak; /* Dump leak summary at exit. */
extern bool opt_prof_accum; /* Report cumulative bytes. */
extern char opt_prof_prefix[
/* Minimize memory bloat for non-prof builds. */
#ifdef JEMALLOC_PROF
PATH_MAX +
#endif
1];
/* Accessed via prof_active_[gs]et{_unlocked,}(). */
extern bool prof_active;
/* Accessed via prof_gdump_[gs]et{_unlocked,}(). */
extern bool prof_gdump_val;
/*
* Profile dump interval, measured in bytes allocated. Each arena triggers a
* profile dump when it reaches this threshold. The effect is that the
* interval between profile dumps averages prof_interval, though the actual
* interval between dumps will tend to be sporadic, and the interval will be a
* maximum of approximately (prof_interval * narenas).
*/
extern uint64_t prof_interval;
/*
* Initialized as opt_lg_prof_sample, and potentially modified during profiling
* resets.
*/
extern size_t lg_prof_sample;
void prof_alloc_rollback(tsd_t *tsd, prof_tctx_t *tctx, bool updated);
void prof_malloc_sample_object(tsdn_t *tsdn, const void *ptr, size_t usize,
prof_tctx_t *tctx);
void prof_free_sampled_object(tsd_t *tsd, size_t usize, prof_tctx_t *tctx);
void bt_init(prof_bt_t *bt, void **vec);
void prof_backtrace(prof_bt_t *bt);
prof_tctx_t *prof_lookup(tsd_t *tsd, prof_bt_t *bt);
#ifdef JEMALLOC_JET
size_t prof_tdata_count(void);
size_t prof_bt_count(void);
const prof_cnt_t *prof_cnt_all(void);
typedef int (prof_dump_open_t)(bool, const char *);
extern prof_dump_open_t *prof_dump_open;
typedef bool (prof_dump_header_t)(tsdn_t *, bool, const prof_cnt_t *);
extern prof_dump_header_t *prof_dump_header;
#endif
void prof_idump(tsdn_t *tsdn);
bool prof_mdump(tsd_t *tsd, const char *filename);
void prof_gdump(tsdn_t *tsdn);
prof_tdata_t *prof_tdata_init(tsd_t *tsd);
prof_tdata_t *prof_tdata_reinit(tsd_t *tsd, prof_tdata_t *tdata);
void prof_reset(tsd_t *tsd, size_t lg_sample);
void prof_tdata_cleanup(tsd_t *tsd);
bool prof_active_get(tsdn_t *tsdn);
bool prof_active_set(tsdn_t *tsdn, bool active);
const char *prof_thread_name_get(tsd_t *tsd);
int prof_thread_name_set(tsd_t *tsd, const char *thread_name);
bool prof_thread_active_get(tsd_t *tsd);
bool prof_thread_active_set(tsd_t *tsd, bool active);
bool prof_thread_active_init_get(tsdn_t *tsdn);
bool prof_thread_active_init_set(tsdn_t *tsdn, bool active_init);
bool prof_gdump_get(tsdn_t *tsdn);
bool prof_gdump_set(tsdn_t *tsdn, bool active);
void prof_boot0(void);
void prof_boot1(void);
bool prof_boot2(tsd_t *tsd);
void prof_prefork0(tsdn_t *tsdn);
void prof_prefork1(tsdn_t *tsdn);
void prof_postfork_parent(tsdn_t *tsdn);
void prof_postfork_child(tsdn_t *tsdn);
void prof_sample_threshold_update(prof_tdata_t *tdata);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
bool prof_active_get_unlocked(void);
bool prof_gdump_get_unlocked(void);
prof_tdata_t *prof_tdata_get(tsd_t *tsd, bool create);
prof_tctx_t *prof_tctx_get(tsdn_t *tsdn, const void *ptr);
void prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize,
prof_tctx_t *tctx);
void prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize,
const void *old_ptr, prof_tctx_t *tctx);
bool prof_sample_accum_update(tsd_t *tsd, size_t usize, bool commit,
prof_tdata_t **tdata_out);
prof_tctx_t *prof_alloc_prep(tsd_t *tsd, size_t usize, bool prof_active,
bool update);
void prof_malloc(tsdn_t *tsdn, const void *ptr, size_t usize,
prof_tctx_t *tctx);
void prof_realloc(tsd_t *tsd, const void *ptr, size_t usize,
prof_tctx_t *tctx, bool prof_active, bool updated, const void *old_ptr,
size_t old_usize, prof_tctx_t *old_tctx);
void prof_free(tsd_t *tsd, const void *ptr, size_t usize);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_PROF_C_))
JEMALLOC_ALWAYS_INLINE bool
prof_active_get_unlocked(void)
{
/*
* Even if opt_prof is true, sampling can be temporarily disabled by
* setting prof_active to false. No locking is used when reading
* prof_active in the fast path, so there are no guarantees regarding
* how long it will take for all threads to notice state changes.
*/
return (prof_active);
}
JEMALLOC_ALWAYS_INLINE bool
prof_gdump_get_unlocked(void)
{
/*
* No locking is used when reading prof_gdump_val in the fast path, so
* there are no guarantees regarding how long it will take for all
* threads to notice state changes.
*/
return (prof_gdump_val);
}
JEMALLOC_ALWAYS_INLINE prof_tdata_t *
prof_tdata_get(tsd_t *tsd, bool create)
{
prof_tdata_t *tdata;
cassert(config_prof);
tdata = tsd_prof_tdata_get(tsd);
if (create) {
if (unlikely(tdata == NULL)) {
if (tsd_nominal(tsd)) {
tdata = prof_tdata_init(tsd);
tsd_prof_tdata_set(tsd, tdata);
}
} else if (unlikely(tdata->expired)) {
tdata = prof_tdata_reinit(tsd, tdata);
tsd_prof_tdata_set(tsd, tdata);
}
assert(tdata == NULL || tdata->attached);
}
return (tdata);
}
JEMALLOC_ALWAYS_INLINE prof_tctx_t *
prof_tctx_get(tsdn_t *tsdn, const void *ptr)
{
cassert(config_prof);
assert(ptr != NULL);
return (arena_prof_tctx_get(tsdn, ptr));
}
JEMALLOC_ALWAYS_INLINE void
prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize, prof_tctx_t *tctx)
{
cassert(config_prof);
assert(ptr != NULL);
arena_prof_tctx_set(tsdn, ptr, usize, tctx);
}
JEMALLOC_ALWAYS_INLINE void
prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize, const void *old_ptr,
prof_tctx_t *old_tctx)
{
cassert(config_prof);
assert(ptr != NULL);
arena_prof_tctx_reset(tsdn, ptr, usize, old_ptr, old_tctx);
}
JEMALLOC_ALWAYS_INLINE bool
prof_sample_accum_update(tsd_t *tsd, size_t usize, bool update,
prof_tdata_t **tdata_out)
{
prof_tdata_t *tdata;
cassert(config_prof);
tdata = prof_tdata_get(tsd, true);
if (unlikely((uintptr_t)tdata <= (uintptr_t)PROF_TDATA_STATE_MAX))
tdata = NULL;
if (tdata_out != NULL)
*tdata_out = tdata;
if (unlikely(tdata == NULL))
return (true);
if (likely(tdata->bytes_until_sample >= usize)) {
if (update)
tdata->bytes_until_sample -= usize;
return (true);
} else {
/* Compute new sample threshold. */
if (update)
prof_sample_threshold_update(tdata);
return (!tdata->active);
}
}
JEMALLOC_ALWAYS_INLINE prof_tctx_t *
prof_alloc_prep(tsd_t *tsd, size_t usize, bool prof_active, bool update)
{
prof_tctx_t *ret;
prof_tdata_t *tdata;
prof_bt_t bt;
assert(usize == s2u(usize));
if (!prof_active || likely(prof_sample_accum_update(tsd, usize, update,
&tdata)))
ret = (prof_tctx_t *)(uintptr_t)1U;
else {
bt_init(&bt, tdata->vec);
prof_backtrace(&bt);
ret = prof_lookup(tsd, &bt);
}
return (ret);
}
JEMALLOC_ALWAYS_INLINE void
prof_malloc(tsdn_t *tsdn, const void *ptr, size_t usize, prof_tctx_t *tctx)
{
cassert(config_prof);
assert(ptr != NULL);
assert(usize == isalloc(tsdn, ptr, true));
if (unlikely((uintptr_t)tctx > (uintptr_t)1U))
prof_malloc_sample_object(tsdn, ptr, usize, tctx);
else
prof_tctx_set(tsdn, ptr, usize, (prof_tctx_t *)(uintptr_t)1U);
}
JEMALLOC_ALWAYS_INLINE void
prof_realloc(tsd_t *tsd, const void *ptr, size_t usize, prof_tctx_t *tctx,
bool prof_active, bool updated, const void *old_ptr, size_t old_usize,
prof_tctx_t *old_tctx)
{
bool sampled, old_sampled;
cassert(config_prof);
assert(ptr != NULL || (uintptr_t)tctx <= (uintptr_t)1U);
if (prof_active && !updated && ptr != NULL) {
assert(usize == isalloc(tsd_tsdn(tsd), ptr, true));
if (prof_sample_accum_update(tsd, usize, true, NULL)) {
/*
* Don't sample. The usize passed to prof_alloc_prep()
* was larger than what actually got allocated, so a
* backtrace was captured for this allocation, even
* though its actual usize was insufficient to cross the
* sample threshold.
*/
prof_alloc_rollback(tsd, tctx, true);
tctx = (prof_tctx_t *)(uintptr_t)1U;
}
}
sampled = ((uintptr_t)tctx > (uintptr_t)1U);
old_sampled = ((uintptr_t)old_tctx > (uintptr_t)1U);
if (unlikely(sampled))
prof_malloc_sample_object(tsd_tsdn(tsd), ptr, usize, tctx);
else
prof_tctx_reset(tsd_tsdn(tsd), ptr, usize, old_ptr, old_tctx);
if (unlikely(old_sampled))
prof_free_sampled_object(tsd, old_usize, old_tctx);
}
JEMALLOC_ALWAYS_INLINE void
prof_free(tsd_t *tsd, const void *ptr, size_t usize)
{
prof_tctx_t *tctx = prof_tctx_get(tsd_tsdn(tsd), ptr);
cassert(config_prof);
assert(usize == isalloc(tsd_tsdn(tsd), ptr, true));
if (unlikely((uintptr_t)tctx > (uintptr_t)1U))
prof_free_sampled_object(tsd, usize, tctx);
}
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 15,844 | 27.914234 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/hash.h | /*
* The following hash function is based on MurmurHash3, placed into the public
* domain by Austin Appleby. See https://github.com/aappleby/smhasher for
* details.
*/
/******************************************************************************/
#ifdef JEMALLOC_H_TYPES
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
uint32_t hash_x86_32(const void *key, int len, uint32_t seed);
void hash_x86_128(const void *key, const int len, uint32_t seed,
uint64_t r_out[2]);
void hash_x64_128(const void *key, const int len, const uint32_t seed,
uint64_t r_out[2]);
void hash(const void *key, size_t len, const uint32_t seed,
size_t r_hash[2]);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_HASH_C_))
/******************************************************************************/
/* Internal implementation. */
JEMALLOC_INLINE uint32_t
hash_rotl_32(uint32_t x, int8_t r)
{
return ((x << r) | (x >> (32 - r)));
}
JEMALLOC_INLINE uint64_t
hash_rotl_64(uint64_t x, int8_t r)
{
return ((x << r) | (x >> (64 - r)));
}
JEMALLOC_INLINE uint32_t
hash_get_block_32(const uint32_t *p, int i)
{
/* Handle unaligned read. */
if (unlikely((uintptr_t)p & (sizeof(uint32_t)-1)) != 0) {
uint32_t ret;
memcpy(&ret, (uint8_t *)(p + i), sizeof(uint32_t));
return (ret);
}
return (p[i]);
}
JEMALLOC_INLINE uint64_t
hash_get_block_64(const uint64_t *p, int i)
{
/* Handle unaligned read. */
if (unlikely((uintptr_t)p & (sizeof(uint64_t)-1)) != 0) {
uint64_t ret;
memcpy(&ret, (uint8_t *)(p + i), sizeof(uint64_t));
return (ret);
}
return (p[i]);
}
JEMALLOC_INLINE uint32_t
hash_fmix_32(uint32_t h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return (h);
}
JEMALLOC_INLINE uint64_t
hash_fmix_64(uint64_t k)
{
k ^= k >> 33;
k *= KQU(0xff51afd7ed558ccd);
k ^= k >> 33;
k *= KQU(0xc4ceb9fe1a85ec53);
k ^= k >> 33;
return (k);
}
JEMALLOC_INLINE uint32_t
hash_x86_32(const void *key, int len, uint32_t seed)
{
const uint8_t *data = (const uint8_t *) key;
const int nblocks = len / 4;
uint32_t h1 = seed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
/* body */
{
const uint32_t *blocks = (const uint32_t *) (data + nblocks*4);
int i;
for (i = -nblocks; i; i++) {
uint32_t k1 = hash_get_block_32(blocks, i);
k1 *= c1;
k1 = hash_rotl_32(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = hash_rotl_32(h1, 13);
h1 = h1*5 + 0xe6546b64;
}
}
/* tail */
{
const uint8_t *tail = (const uint8_t *) (data + nblocks*4);
uint32_t k1 = 0;
switch (len & 3) {
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0]; k1 *= c1; k1 = hash_rotl_32(k1, 15);
k1 *= c2; h1 ^= k1;
}
}
/* finalization */
h1 ^= len;
h1 = hash_fmix_32(h1);
return (h1);
}
UNUSED JEMALLOC_INLINE void
hash_x86_128(const void *key, const int len, uint32_t seed,
uint64_t r_out[2])
{
const uint8_t * data = (const uint8_t *) key;
const int nblocks = len / 16;
uint32_t h1 = seed;
uint32_t h2 = seed;
uint32_t h3 = seed;
uint32_t h4 = seed;
const uint32_t c1 = 0x239b961b;
const uint32_t c2 = 0xab0e9789;
const uint32_t c3 = 0x38b34ae5;
const uint32_t c4 = 0xa1e38b93;
/* body */
{
const uint32_t *blocks = (const uint32_t *) (data + nblocks*16);
int i;
for (i = -nblocks; i; i++) {
uint32_t k1 = hash_get_block_32(blocks, i*4 + 0);
uint32_t k2 = hash_get_block_32(blocks, i*4 + 1);
uint32_t k3 = hash_get_block_32(blocks, i*4 + 2);
uint32_t k4 = hash_get_block_32(blocks, i*4 + 3);
k1 *= c1; k1 = hash_rotl_32(k1, 15); k1 *= c2; h1 ^= k1;
h1 = hash_rotl_32(h1, 19); h1 += h2;
h1 = h1*5 + 0x561ccd1b;
k2 *= c2; k2 = hash_rotl_32(k2, 16); k2 *= c3; h2 ^= k2;
h2 = hash_rotl_32(h2, 17); h2 += h3;
h2 = h2*5 + 0x0bcaa747;
k3 *= c3; k3 = hash_rotl_32(k3, 17); k3 *= c4; h3 ^= k3;
h3 = hash_rotl_32(h3, 15); h3 += h4;
h3 = h3*5 + 0x96cd1c35;
k4 *= c4; k4 = hash_rotl_32(k4, 18); k4 *= c1; h4 ^= k4;
h4 = hash_rotl_32(h4, 13); h4 += h1;
h4 = h4*5 + 0x32ac3b17;
}
}
/* tail */
{
const uint8_t *tail = (const uint8_t *) (data + nblocks*16);
uint32_t k1 = 0;
uint32_t k2 = 0;
uint32_t k3 = 0;
uint32_t k4 = 0;
switch (len & 15) {
case 15: k4 ^= tail[14] << 16;
case 14: k4 ^= tail[13] << 8;
case 13: k4 ^= tail[12] << 0;
k4 *= c4; k4 = hash_rotl_32(k4, 18); k4 *= c1; h4 ^= k4;
case 12: k3 ^= tail[11] << 24;
case 11: k3 ^= tail[10] << 16;
case 10: k3 ^= tail[ 9] << 8;
case 9: k3 ^= tail[ 8] << 0;
k3 *= c3; k3 = hash_rotl_32(k3, 17); k3 *= c4; h3 ^= k3;
case 8: k2 ^= tail[ 7] << 24;
case 7: k2 ^= tail[ 6] << 16;
case 6: k2 ^= tail[ 5] << 8;
case 5: k2 ^= tail[ 4] << 0;
k2 *= c2; k2 = hash_rotl_32(k2, 16); k2 *= c3; h2 ^= k2;
case 4: k1 ^= tail[ 3] << 24;
case 3: k1 ^= tail[ 2] << 16;
case 2: k1 ^= tail[ 1] << 8;
case 1: k1 ^= tail[ 0] << 0;
k1 *= c1; k1 = hash_rotl_32(k1, 15); k1 *= c2; h1 ^= k1;
}
}
/* finalization */
h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len;
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
h1 = hash_fmix_32(h1);
h2 = hash_fmix_32(h2);
h3 = hash_fmix_32(h3);
h4 = hash_fmix_32(h4);
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
r_out[0] = (((uint64_t) h2) << 32) | h1;
r_out[1] = (((uint64_t) h4) << 32) | h3;
}
UNUSED JEMALLOC_INLINE void
hash_x64_128(const void *key, const int len, const uint32_t seed,
uint64_t r_out[2])
{
const uint8_t *data = (const uint8_t *) key;
const int nblocks = len / 16;
uint64_t h1 = seed;
uint64_t h2 = seed;
const uint64_t c1 = KQU(0x87c37b91114253d5);
const uint64_t c2 = KQU(0x4cf5ad432745937f);
/* body */
{
const uint64_t *blocks = (const uint64_t *) (data);
int i;
for (i = 0; i < nblocks; i++) {
uint64_t k1 = hash_get_block_64(blocks, i*2 + 0);
uint64_t k2 = hash_get_block_64(blocks, i*2 + 1);
k1 *= c1; k1 = hash_rotl_64(k1, 31); k1 *= c2; h1 ^= k1;
h1 = hash_rotl_64(h1, 27); h1 += h2;
h1 = h1*5 + 0x52dce729;
k2 *= c2; k2 = hash_rotl_64(k2, 33); k2 *= c1; h2 ^= k2;
h2 = hash_rotl_64(h2, 31); h2 += h1;
h2 = h2*5 + 0x38495ab5;
}
}
/* tail */
{
const uint8_t *tail = (const uint8_t*)(data + nblocks*16);
uint64_t k1 = 0;
uint64_t k2 = 0;
switch (len & 15) {
case 15: k2 ^= ((uint64_t)(tail[14])) << 48;
case 14: k2 ^= ((uint64_t)(tail[13])) << 40;
case 13: k2 ^= ((uint64_t)(tail[12])) << 32;
case 12: k2 ^= ((uint64_t)(tail[11])) << 24;
case 11: k2 ^= ((uint64_t)(tail[10])) << 16;
case 10: k2 ^= ((uint64_t)(tail[ 9])) << 8;
case 9: k2 ^= ((uint64_t)(tail[ 8])) << 0;
k2 *= c2; k2 = hash_rotl_64(k2, 33); k2 *= c1; h2 ^= k2;
case 8: k1 ^= ((uint64_t)(tail[ 7])) << 56;
case 7: k1 ^= ((uint64_t)(tail[ 6])) << 48;
case 6: k1 ^= ((uint64_t)(tail[ 5])) << 40;
case 5: k1 ^= ((uint64_t)(tail[ 4])) << 32;
case 4: k1 ^= ((uint64_t)(tail[ 3])) << 24;
case 3: k1 ^= ((uint64_t)(tail[ 2])) << 16;
case 2: k1 ^= ((uint64_t)(tail[ 1])) << 8;
case 1: k1 ^= ((uint64_t)(tail[ 0])) << 0;
k1 *= c1; k1 = hash_rotl_64(k1, 31); k1 *= c2; h1 ^= k1;
}
}
/* finalization */
h1 ^= len; h2 ^= len;
h1 += h2;
h2 += h1;
h1 = hash_fmix_64(h1);
h2 = hash_fmix_64(h2);
h1 += h2;
h2 += h1;
r_out[0] = h1;
r_out[1] = h2;
}
/******************************************************************************/
/* API. */
JEMALLOC_INLINE void
hash(const void *key, size_t len, const uint32_t seed, size_t r_hash[2])
{
assert(len <= INT_MAX); /* Unfortunate implementation limitation. */
#if (LG_SIZEOF_PTR == 3 && !defined(JEMALLOC_BIG_ENDIAN))
hash_x64_128(key, (int)len, seed, (uint64_t *)r_hash);
#else
{
uint64_t hashes[2];
hash_x86_128(key, (int)len, seed, hashes);
r_hash[0] = (size_t)hashes[0];
r_hash[1] = (size_t)hashes[1];
}
#endif
}
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 8,394 | 22.449721 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/jemalloc/include/jemalloc/internal/tsd.h | /******************************************************************************/
#ifdef JEMALLOC_H_TYPES
/* Maximum number of malloc_tsd users with cleanup functions. */
#define MALLOC_TSD_CLEANUPS_MAX 2
typedef bool (*malloc_tsd_cleanup_t)(void);
#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
!defined(_WIN32))
typedef struct tsd_init_block_s tsd_init_block_t;
typedef struct tsd_init_head_s tsd_init_head_t;
#endif
typedef struct tsd_s tsd_t;
typedef struct tsdn_s tsdn_t;
#define TSDN_NULL ((tsdn_t *)0)
typedef enum {
tsd_state_uninitialized,
tsd_state_nominal,
tsd_state_purgatory,
tsd_state_reincarnated
} tsd_state_t;
/*
* TLS/TSD-agnostic macro-based implementation of thread-specific data. There
* are five macros that support (at least) three use cases: file-private,
* library-private, and library-private inlined. Following is an example
* library-private tsd variable:
*
* In example.h:
* typedef struct {
* int x;
* int y;
* } example_t;
* #define EX_INITIALIZER JEMALLOC_CONCAT({0, 0})
* malloc_tsd_types(example_, example_t)
* malloc_tsd_protos(, example_, example_t)
* malloc_tsd_externs(example_, example_t)
* In example.c:
* malloc_tsd_data(, example_, example_t, EX_INITIALIZER)
* malloc_tsd_funcs(, example_, example_t, EX_INITIALIZER,
* example_tsd_cleanup)
*
* The result is a set of generated functions, e.g.:
*
* bool example_tsd_boot(void) {...}
* bool example_tsd_booted_get(void) {...}
* example_t *example_tsd_get(bool init) {...}
* void example_tsd_set(example_t *val) {...}
*
* Note that all of the functions deal in terms of (a_type *) rather than
* (a_type) so that it is possible to support non-pointer types (unlike
* pthreads TSD). example_tsd_cleanup() is passed an (a_type *) pointer that is
* cast to (void *). This means that the cleanup function needs to cast the
* function argument to (a_type *), then dereference the resulting pointer to
* access fields, e.g.
*
* void
* example_tsd_cleanup(void *arg)
* {
* example_t *example = (example_t *)arg;
*
* example->x = 42;
* [...]
* if ([want the cleanup function to be called again])
* example_tsd_set(example);
* }
*
* If example_tsd_set() is called within example_tsd_cleanup(), it will be
* called again. This is similar to how pthreads TSD destruction works, except
* that pthreads only calls the cleanup function again if the value was set to
* non-NULL.
*/
/* malloc_tsd_types(). */
#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
#define malloc_tsd_types(a_name, a_type)
#elif (defined(JEMALLOC_TLS))
#define malloc_tsd_types(a_name, a_type)
#elif (defined(_WIN32))
#define malloc_tsd_types(a_name, a_type) \
typedef struct { \
bool initialized; \
a_type val; \
} a_name##tsd_wrapper_t;
#else
#define malloc_tsd_types(a_name, a_type) \
typedef struct { \
bool initialized; \
a_type val; \
} a_name##tsd_wrapper_t;
#endif
/* malloc_tsd_protos(). */
#define malloc_tsd_protos(a_attr, a_name, a_type) \
a_attr bool \
a_name##tsd_boot0(void); \
a_attr void \
a_name##tsd_boot1(void); \
a_attr bool \
a_name##tsd_boot(void); \
a_attr bool \
a_name##tsd_booted_get(void); \
a_attr a_type * \
a_name##tsd_get(bool init); \
a_attr void \
a_name##tsd_set(a_type *val);
/* malloc_tsd_externs(). */
#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
#define malloc_tsd_externs(a_name, a_type) \
extern __thread a_type a_name##tsd_tls; \
extern __thread bool a_name##tsd_initialized; \
extern bool a_name##tsd_booted;
#elif (defined(JEMALLOC_TLS))
#define malloc_tsd_externs(a_name, a_type) \
extern __thread a_type a_name##tsd_tls; \
extern pthread_key_t a_name##tsd_tsd; \
extern bool a_name##tsd_booted;
#elif (defined(_WIN32))
#define malloc_tsd_externs(a_name, a_type) \
extern DWORD a_name##tsd_tsd; \
extern a_name##tsd_wrapper_t a_name##tsd_boot_wrapper; \
extern bool a_name##tsd_booted;
#else
#define malloc_tsd_externs(a_name, a_type) \
extern pthread_key_t a_name##tsd_tsd; \
extern tsd_init_head_t a_name##tsd_init_head; \
extern a_name##tsd_wrapper_t a_name##tsd_boot_wrapper; \
extern bool a_name##tsd_booted;
#endif
/* malloc_tsd_data(). */
#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
a_attr __thread a_type JEMALLOC_TLS_MODEL \
a_name##tsd_tls = a_initializer; \
a_attr __thread bool JEMALLOC_TLS_MODEL \
a_name##tsd_initialized = false; \
a_attr bool a_name##tsd_booted = false;
#elif (defined(JEMALLOC_TLS))
#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
a_attr __thread a_type JEMALLOC_TLS_MODEL \
a_name##tsd_tls = a_initializer; \
a_attr pthread_key_t a_name##tsd_tsd; \
a_attr bool a_name##tsd_booted = false;
#elif (defined(_WIN32))
#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
a_attr DWORD a_name##tsd_tsd; \
a_attr a_name##tsd_wrapper_t a_name##tsd_boot_wrapper = { \
false, \
a_initializer \
}; \
a_attr bool a_name##tsd_booted = false;
#else
#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
a_attr pthread_key_t a_name##tsd_tsd; \
a_attr tsd_init_head_t a_name##tsd_init_head = { \
ql_head_initializer(blocks), \
MALLOC_MUTEX_INITIALIZER \
}; \
a_attr a_name##tsd_wrapper_t a_name##tsd_boot_wrapper = { \
false, \
a_initializer \
}; \
a_attr bool a_name##tsd_booted = false;
#endif
/* malloc_tsd_funcs(). */
#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
a_cleanup) \
/* Initialization/cleanup. */ \
a_attr bool \
a_name##tsd_cleanup_wrapper(void) \
{ \
\
if (a_name##tsd_initialized) { \
a_name##tsd_initialized = false; \
a_cleanup(&a_name##tsd_tls); \
} \
return (a_name##tsd_initialized); \
} \
a_attr bool \
a_name##tsd_boot0(void) \
{ \
\
if (a_cleanup != malloc_tsd_no_cleanup) { \
malloc_tsd_cleanup_register( \
&a_name##tsd_cleanup_wrapper); \
} \
a_name##tsd_booted = true; \
return (false); \
} \
a_attr void \
a_name##tsd_boot1(void) \
{ \
\
/* Do nothing. */ \
} \
a_attr bool \
a_name##tsd_boot(void) \
{ \
\
return (a_name##tsd_boot0()); \
} \
a_attr bool \
a_name##tsd_booted_get(void) \
{ \
\
return (a_name##tsd_booted); \
} \
a_attr bool \
a_name##tsd_get_allocates(void) \
{ \
\
return (false); \
} \
/* Get/set. */ \
a_attr a_type * \
a_name##tsd_get(bool init) \
{ \
\
assert(a_name##tsd_booted); \
return (&a_name##tsd_tls); \
} \
a_attr void \
a_name##tsd_set(a_type *val) \
{ \
\
assert(a_name##tsd_booted); \
a_name##tsd_tls = (*val); \
if (a_cleanup != malloc_tsd_no_cleanup) \
a_name##tsd_initialized = true; \
}
#elif (defined(JEMALLOC_TLS))
#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
a_cleanup) \
/* Initialization/cleanup. */ \
a_attr bool \
a_name##tsd_boot0(void) \
{ \
\
if (a_cleanup != malloc_tsd_no_cleanup) { \
if (pthread_key_create(&a_name##tsd_tsd, a_cleanup) != \
0) \
return (true); \
} \
a_name##tsd_booted = true; \
return (false); \
} \
a_attr void \
a_name##tsd_boot1(void) \
{ \
\
/* Do nothing. */ \
} \
a_attr bool \
a_name##tsd_boot(void) \
{ \
\
return (a_name##tsd_boot0()); \
} \
a_attr bool \
a_name##tsd_booted_get(void) \
{ \
\
return (a_name##tsd_booted); \
} \
a_attr bool \
a_name##tsd_get_allocates(void) \
{ \
\
return (false); \
} \
/* Get/set. */ \
a_attr a_type * \
a_name##tsd_get(bool init) \
{ \
\
assert(a_name##tsd_booted); \
return (&a_name##tsd_tls); \
} \
a_attr void \
a_name##tsd_set(a_type *val) \
{ \
\
assert(a_name##tsd_booted); \
a_name##tsd_tls = (*val); \
if (a_cleanup != malloc_tsd_no_cleanup) { \
if (pthread_setspecific(a_name##tsd_tsd, \
(void *)(&a_name##tsd_tls))) { \
malloc_write("<jemalloc>: Error" \
" setting TSD for "#a_name"\n"); \
if (opt_abort) \
abort(); \
} \
} \
}
#elif (defined(_WIN32))
#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
a_cleanup) \
/* Initialization/cleanup. */ \
a_attr bool \
a_name##tsd_cleanup_wrapper(void) \
{ \
DWORD error = GetLastError(); \
a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
TlsGetValue(a_name##tsd_tsd); \
SetLastError(error); \
\
if (wrapper == NULL) \
return (false); \
if (a_cleanup != malloc_tsd_no_cleanup && \
wrapper->initialized) { \
wrapper->initialized = false; \
a_cleanup(&wrapper->val); \
if (wrapper->initialized) { \
/* Trigger another cleanup round. */ \
return (true); \
} \
} \
malloc_tsd_dalloc(wrapper); \
return (false); \
} \
a_attr void \
a_name##tsd_wrapper_set(a_name##tsd_wrapper_t *wrapper) \
{ \
\
if (!TlsSetValue(a_name##tsd_tsd, (void *)wrapper)) { \
malloc_write("<jemalloc>: Error setting" \
" TSD for "#a_name"\n"); \
abort(); \
} \
} \
a_attr a_name##tsd_wrapper_t * \
a_name##tsd_wrapper_get(bool init) \
{ \
DWORD error = GetLastError(); \
a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
TlsGetValue(a_name##tsd_tsd); \
SetLastError(error); \
\
if (init && unlikely(wrapper == NULL)) { \
wrapper = (a_name##tsd_wrapper_t *) \
malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
if (wrapper == NULL) { \
malloc_write("<jemalloc>: Error allocating" \
" TSD for "#a_name"\n"); \
abort(); \
} else { \
wrapper->initialized = false; \
wrapper->val = a_initializer; \
} \
a_name##tsd_wrapper_set(wrapper); \
} \
return (wrapper); \
} \
a_attr bool \
a_name##tsd_boot0(void) \
{ \
\
a_name##tsd_tsd = TlsAlloc(); \
if (a_name##tsd_tsd == TLS_OUT_OF_INDEXES) \
return (true); \
if (a_cleanup != malloc_tsd_no_cleanup) { \
malloc_tsd_cleanup_register( \
&a_name##tsd_cleanup_wrapper); \
} \
a_name##tsd_wrapper_set(&a_name##tsd_boot_wrapper); \
a_name##tsd_booted = true; \
return (false); \
} \
a_attr void \
a_name##tsd_boot1(void) \
{ \
a_name##tsd_wrapper_t *wrapper; \
wrapper = (a_name##tsd_wrapper_t *) \
malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
if (wrapper == NULL) { \
malloc_write("<jemalloc>: Error allocating" \
" TSD for "#a_name"\n"); \
abort(); \
} \
memcpy(wrapper, &a_name##tsd_boot_wrapper, \
sizeof(a_name##tsd_wrapper_t)); \
a_name##tsd_wrapper_set(wrapper); \
} \
a_attr bool \
a_name##tsd_boot(void) \
{ \
\
if (a_name##tsd_boot0()) \
return (true); \
a_name##tsd_boot1(); \
return (false); \
} \
a_attr bool \
a_name##tsd_booted_get(void) \
{ \
\
return (a_name##tsd_booted); \
} \
a_attr bool \
a_name##tsd_get_allocates(void) \
{ \
\
return (true); \
} \
/* Get/set. */ \
a_attr a_type * \
a_name##tsd_get(bool init) \
{ \
a_name##tsd_wrapper_t *wrapper; \
\
assert(a_name##tsd_booted); \
wrapper = a_name##tsd_wrapper_get(init); \
if (a_name##tsd_get_allocates() && !init && wrapper == NULL) \
return (NULL); \
return (&wrapper->val); \
} \
a_attr void \
a_name##tsd_set(a_type *val) \
{ \
a_name##tsd_wrapper_t *wrapper; \
\
assert(a_name##tsd_booted); \
wrapper = a_name##tsd_wrapper_get(true); \
wrapper->val = *(val); \
if (a_cleanup != malloc_tsd_no_cleanup) \
wrapper->initialized = true; \
}
#else
#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
a_cleanup) \
/* Initialization/cleanup. */ \
a_attr void \
a_name##tsd_cleanup_wrapper(void *arg) \
{ \
a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *)arg; \
\
if (a_cleanup != malloc_tsd_no_cleanup && \
wrapper->initialized) { \
wrapper->initialized = false; \
a_cleanup(&wrapper->val); \
if (wrapper->initialized) { \
/* Trigger another cleanup round. */ \
if (pthread_setspecific(a_name##tsd_tsd, \
(void *)wrapper)) { \
malloc_write("<jemalloc>: Error" \
" setting TSD for "#a_name"\n"); \
if (opt_abort) \
abort(); \
} \
return; \
} \
} \
malloc_tsd_dalloc(wrapper); \
} \
a_attr void \
a_name##tsd_wrapper_set(a_name##tsd_wrapper_t *wrapper) \
{ \
\
if (pthread_setspecific(a_name##tsd_tsd, \
(void *)wrapper)) { \
malloc_write("<jemalloc>: Error setting" \
" TSD for "#a_name"\n"); \
abort(); \
} \
} \
a_attr a_name##tsd_wrapper_t * \
a_name##tsd_wrapper_get(bool init) \
{ \
a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
pthread_getspecific(a_name##tsd_tsd); \
\
if (init && unlikely(wrapper == NULL)) { \
tsd_init_block_t block; \
wrapper = tsd_init_check_recursion( \
&a_name##tsd_init_head, &block); \
if (wrapper) \
return (wrapper); \
wrapper = (a_name##tsd_wrapper_t *) \
malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
block.data = wrapper; \
if (wrapper == NULL) { \
malloc_write("<jemalloc>: Error allocating" \
" TSD for "#a_name"\n"); \
abort(); \
} else { \
wrapper->initialized = false; \
wrapper->val = a_initializer; \
} \
a_name##tsd_wrapper_set(wrapper); \
tsd_init_finish(&a_name##tsd_init_head, &block); \
} \
return (wrapper); \
} \
a_attr bool \
a_name##tsd_boot0(void) \
{ \
\
if (pthread_key_create(&a_name##tsd_tsd, \
a_name##tsd_cleanup_wrapper) != 0) \
return (true); \
a_name##tsd_wrapper_set(&a_name##tsd_boot_wrapper); \
a_name##tsd_booted = true; \
return (false); \
} \
a_attr void \
a_name##tsd_boot1(void) \
{ \
a_name##tsd_wrapper_t *wrapper; \
wrapper = (a_name##tsd_wrapper_t *) \
malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
if (wrapper == NULL) { \
malloc_write("<jemalloc>: Error allocating" \
" TSD for "#a_name"\n"); \
abort(); \
} \
memcpy(wrapper, &a_name##tsd_boot_wrapper, \
sizeof(a_name##tsd_wrapper_t)); \
a_name##tsd_wrapper_set(wrapper); \
} \
a_attr bool \
a_name##tsd_boot(void) \
{ \
\
if (a_name##tsd_boot0()) \
return (true); \
a_name##tsd_boot1(); \
return (false); \
} \
a_attr bool \
a_name##tsd_booted_get(void) \
{ \
\
return (a_name##tsd_booted); \
} \
a_attr bool \
a_name##tsd_get_allocates(void) \
{ \
\
return (true); \
} \
/* Get/set. */ \
a_attr a_type * \
a_name##tsd_get(bool init) \
{ \
a_name##tsd_wrapper_t *wrapper; \
\
assert(a_name##tsd_booted); \
wrapper = a_name##tsd_wrapper_get(init); \
if (a_name##tsd_get_allocates() && !init && wrapper == NULL) \
return (NULL); \
return (&wrapper->val); \
} \
a_attr void \
a_name##tsd_set(a_type *val) \
{ \
a_name##tsd_wrapper_t *wrapper; \
\
assert(a_name##tsd_booted); \
wrapper = a_name##tsd_wrapper_get(true); \
wrapper->val = *(val); \
if (a_cleanup != malloc_tsd_no_cleanup) \
wrapper->initialized = true; \
}
#endif
#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS
#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
!defined(_WIN32))
struct tsd_init_block_s {
ql_elm(tsd_init_block_t) link;
pthread_t thread;
void *data;
};
struct tsd_init_head_s {
ql_head(tsd_init_block_t) blocks;
malloc_mutex_t lock;
};
#endif
#define MALLOC_TSD \
/* O(name, type) */ \
O(tcache, tcache_t *) \
O(thread_allocated, uint64_t) \
O(thread_deallocated, uint64_t) \
O(prof_tdata, prof_tdata_t *) \
O(iarena, arena_t *) \
O(arena, arena_t *) \
O(arenas_tdata, arena_tdata_t *) \
O(narenas_tdata, unsigned) \
O(arenas_tdata_bypass, bool) \
O(tcache_enabled, tcache_enabled_t) \
O(quarantine, quarantine_t *) \
O(witnesses, witness_list_t) \
O(witness_fork, bool) \
#define TSD_INITIALIZER { \
tsd_state_uninitialized, \
NULL, \
0, \
0, \
NULL, \
NULL, \
NULL, \
NULL, \
0, \
false, \
tcache_enabled_default, \
NULL, \
ql_head_initializer(witnesses), \
false \
}
struct tsd_s {
tsd_state_t state;
#define O(n, t) \
t n;
MALLOC_TSD
#undef O
};
/*
* Wrapper around tsd_t that makes it possible to avoid implicit conversion
* between tsd_t and tsdn_t, where tsdn_t is "nullable" and has to be
* explicitly converted to tsd_t, which is non-nullable.
*/
struct tsdn_s {
tsd_t tsd;
};
static const tsd_t tsd_initializer = TSD_INITIALIZER;
malloc_tsd_types(, tsd_t)
#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS
void *malloc_tsd_malloc(size_t size);
void malloc_tsd_dalloc(void *wrapper);
void malloc_tsd_no_cleanup(void *arg);
void malloc_tsd_cleanup_register(bool (*f)(void));
tsd_t *malloc_tsd_boot0(void);
void malloc_tsd_boot1(void);
#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
!defined(_WIN32))
void *tsd_init_check_recursion(tsd_init_head_t *head,
tsd_init_block_t *block);
void tsd_init_finish(tsd_init_head_t *head, tsd_init_block_t *block);
#endif
void tsd_cleanup(void *arg);
#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES
#ifndef JEMALLOC_ENABLE_INLINE
malloc_tsd_protos(JEMALLOC_ATTR(unused), , tsd_t)
tsd_t *tsd_fetch_impl(bool init);
tsd_t *tsd_fetch(void);
tsdn_t *tsd_tsdn(tsd_t *tsd);
bool tsd_nominal(tsd_t *tsd);
#define O(n, t) \
t *tsd_##n##p_get(tsd_t *tsd); \
t tsd_##n##_get(tsd_t *tsd); \
void tsd_##n##_set(tsd_t *tsd, t n);
MALLOC_TSD
#undef O
tsdn_t *tsdn_fetch(void);
bool tsdn_null(const tsdn_t *tsdn);
tsd_t *tsdn_tsd(tsdn_t *tsdn);
#endif
#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TSD_C_))
malloc_tsd_externs(, tsd_t)
malloc_tsd_funcs(JEMALLOC_ALWAYS_INLINE, , tsd_t, tsd_initializer, tsd_cleanup)
JEMALLOC_ALWAYS_INLINE tsd_t *
tsd_fetch_impl(bool init)
{
tsd_t *tsd = tsd_get(init);
if (!init && tsd_get_allocates() && tsd == NULL)
return (NULL);
assert(tsd != NULL);
if (unlikely(tsd->state != tsd_state_nominal)) {
if (tsd->state == tsd_state_uninitialized) {
tsd->state = tsd_state_nominal;
/* Trigger cleanup handler registration. */
tsd_set(tsd);
} else if (tsd->state == tsd_state_purgatory) {
tsd->state = tsd_state_reincarnated;
tsd_set(tsd);
} else
assert(tsd->state == tsd_state_reincarnated);
}
return (tsd);
}
JEMALLOC_ALWAYS_INLINE tsd_t *
tsd_fetch(void)
{
return (tsd_fetch_impl(true));
}
JEMALLOC_ALWAYS_INLINE tsdn_t *
tsd_tsdn(tsd_t *tsd)
{
return ((tsdn_t *)tsd);
}
JEMALLOC_INLINE bool
tsd_nominal(tsd_t *tsd)
{
return (tsd->state == tsd_state_nominal);
}
#define O(n, t) \
JEMALLOC_ALWAYS_INLINE t * \
tsd_##n##p_get(tsd_t *tsd) \
{ \
\
return (&tsd->n); \
} \
\
JEMALLOC_ALWAYS_INLINE t \
tsd_##n##_get(tsd_t *tsd) \
{ \
\
return (*tsd_##n##p_get(tsd)); \
} \
\
JEMALLOC_ALWAYS_INLINE void \
tsd_##n##_set(tsd_t *tsd, t n) \
{ \
\
assert(tsd->state == tsd_state_nominal); \
tsd->n = n; \
}
MALLOC_TSD
#undef O
JEMALLOC_ALWAYS_INLINE tsdn_t *
tsdn_fetch(void)
{
if (!tsd_booted_get())
return (NULL);
return (tsd_tsdn(tsd_fetch_impl(false)));
}
JEMALLOC_ALWAYS_INLINE bool
tsdn_null(const tsdn_t *tsdn)
{
return (tsdn == NULL);
}
JEMALLOC_ALWAYS_INLINE tsd_t *
tsdn_tsd(tsdn_t *tsdn)
{
assert(!tsdn_null(tsdn));
return (&tsdn->tsd);
}
#endif
#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/
| 21,743 | 26.593909 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/geohash-int/geohash.h | /*
* Copyright (c) 2013-2014, yinqiwen <[email protected]>
* Copyright (c) 2014, Matt Stancliff <[email protected]>.
* Copyright (c) 2015, Salvatore Sanfilippo <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GEOHASH_H_
#define GEOHASH_H_
#include <stddef.h>
#include <stdint.h>
#include <stdint.h>
#if defined(__cplusplus)
extern "C" {
#endif
#define HASHISZERO(r) (!(r).bits && !(r).step)
#define RANGEISZERO(r) (!(r).max && !(r).min)
#define RANGEPISZERO(r) (r == NULL || RANGEISZERO(*r))
#define GEO_STEP_MAX 26 /* 26*2 = 52 bits. */
/* Limits from EPSG:900913 / EPSG:3785 / OSGEO:41001 */
#define GEO_LAT_MIN -85.05112878
#define GEO_LAT_MAX 85.05112878
#define GEO_LONG_MIN -180
#define GEO_LONG_MAX 180
typedef enum {
GEOHASH_NORTH = 0,
GEOHASH_EAST,
GEOHASH_WEST,
GEOHASH_SOUTH,
GEOHASH_SOUTH_WEST,
GEOHASH_SOUTH_EAST,
GEOHASH_NORT_WEST,
GEOHASH_NORT_EAST
} GeoDirection;
typedef struct {
uint64_t bits;
uint8_t step;
} GeoHashBits;
typedef struct {
double min;
double max;
} GeoHashRange;
typedef struct {
GeoHashBits hash;
GeoHashRange longitude;
GeoHashRange latitude;
} GeoHashArea;
typedef struct {
GeoHashBits north;
GeoHashBits east;
GeoHashBits west;
GeoHashBits south;
GeoHashBits north_east;
GeoHashBits south_east;
GeoHashBits north_west;
GeoHashBits south_west;
} GeoHashNeighbors;
/*
* 0:success
* -1:failed
*/
void geohashGetCoordRange(GeoHashRange *long_range, GeoHashRange *lat_range);
int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range,
double longitude, double latitude, uint8_t step,
GeoHashBits *hash);
int geohashEncodeType(double longitude, double latitude,
uint8_t step, GeoHashBits *hash);
int geohashEncodeWGS84(double longitude, double latitude, uint8_t step,
GeoHashBits *hash);
int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range,
const GeoHashBits hash, GeoHashArea *area);
int geohashDecodeType(const GeoHashBits hash, GeoHashArea *area);
int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea *area);
int geohashDecodeAreaToLongLat(const GeoHashArea *area, double *xy);
int geohashDecodeToLongLatType(const GeoHashBits hash, double *xy);
int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double *xy);
int geohashDecodeToLongLatMercator(const GeoHashBits hash, double *xy);
void geohashNeighbors(const GeoHashBits *hash, GeoHashNeighbors *neighbors);
#if defined(__cplusplus)
}
#endif
#endif /* GEOHASH_H_ */
| 4,124 | 33.663866 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/geohash-int/geohash_helper.h | /*
* Copyright (c) 2013-2014, yinqiwen <[email protected]>
* Copyright (c) 2014, Matt Stancliff <[email protected]>.
* Copyright (c) 2015, Salvatore Sanfilippo <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GEOHASH_HELPER_HPP_
#define GEOHASH_HELPER_HPP_
#include <math.h>
#include "geohash.h"
#define GZERO(s) s.bits = s.step = 0;
#define GISZERO(s) (!s.bits && !s.step)
#define GISNOTZERO(s) (s.bits || s.step)
typedef uint64_t GeoHashFix52Bits;
typedef uint64_t GeoHashVarBits;
typedef struct {
GeoHashBits hash;
GeoHashArea area;
GeoHashNeighbors neighbors;
} GeoHashRadius;
int GeoHashBitsComparator(const GeoHashBits *a, const GeoHashBits *b);
uint8_t geohashEstimateStepsByRadius(double range_meters, double lat);
int geohashBoundingBox(double longitude, double latitude, double radius_meters,
double *bounds);
GeoHashRadius geohashGetAreasByRadius(double longitude,
double latitude, double radius_meters);
GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude,
double radius_meters);
GeoHashRadius geohashGetAreasByRadiusMercator(double longitude, double latitude,
double radius_meters);
GeoHashFix52Bits geohashAlign52Bits(const GeoHashBits hash);
double geohashGetDistance(double lon1d, double lat1d,
double lon2d, double lat2d);
int geohashGetDistanceIfInRadius(double x1, double y1,
double x2, double y2, double radius,
double *distance);
int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2,
double y2, double radius,
double *distance);
#endif /* GEOHASH_HELPER_HPP_ */
| 3,368 | 45.791667 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/install_server.sh | #!/bin/sh
# Copyright 2011 Dvir Volk <dvirsk at gmail dot com>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL Dvir Volk OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
#
# Interactive service installer for redis server
# this generates a redis config file and an /etc/init.d script, and installs them
# this scripts should be run as root
die () {
echo "ERROR: $1. Aborting!"
exit 1
}
#Absolute path to this script
SCRIPT=$(readlink -f $0)
#Absolute path this script is in
SCRIPTPATH=$(dirname $SCRIPT)
#Initial defaults
_REDIS_PORT=6379
echo "Welcome to the redis service installer"
echo "This script will help you easily set up a running redis server"
echo
#check for root user
if [ "$(id -u)" -ne 0 ] ; then
echo "You must run this script as root. Sorry!"
exit 1
fi
#Read the redis port
read -p "Please select the redis port for this instance: [$_REDIS_PORT] " REDIS_PORT
if ! echo $REDIS_PORT | egrep -q '^[0-9]+$' ; then
echo "Selecting default: $_REDIS_PORT"
REDIS_PORT=$_REDIS_PORT
fi
#read the redis config file
_REDIS_CONFIG_FILE="/etc/redis/$REDIS_PORT.conf"
read -p "Please select the redis config file name [$_REDIS_CONFIG_FILE] " REDIS_CONFIG_FILE
if [ -z "$REDIS_CONFIG_FILE" ] ; then
REDIS_CONFIG_FILE=$_REDIS_CONFIG_FILE
echo "Selected default - $REDIS_CONFIG_FILE"
fi
#read the redis log file path
_REDIS_LOG_FILE="/var/log/redis_$REDIS_PORT.log"
read -p "Please select the redis log file name [$_REDIS_LOG_FILE] " REDIS_LOG_FILE
if [ -z "$REDIS_LOG_FILE" ] ; then
REDIS_LOG_FILE=$_REDIS_LOG_FILE
echo "Selected default - $REDIS_LOG_FILE"
fi
#get the redis data directory
_REDIS_DATA_DIR="/var/lib/redis/$REDIS_PORT"
read -p "Please select the data directory for this instance [$_REDIS_DATA_DIR] " REDIS_DATA_DIR
if [ -z "$REDIS_DATA_DIR" ] ; then
REDIS_DATA_DIR=$_REDIS_DATA_DIR
echo "Selected default - $REDIS_DATA_DIR"
fi
#get the redis executable path
_REDIS_EXECUTABLE=`command -v redis-server`
read -p "Please select the redis executable path [$_REDIS_EXECUTABLE] " REDIS_EXECUTABLE
if [ ! -x "$REDIS_EXECUTABLE" ] ; then
REDIS_EXECUTABLE=$_REDIS_EXECUTABLE
if [ ! -x "$REDIS_EXECUTABLE" ] ; then
echo "Mmmmm... it seems like you don't have a redis executable. Did you run make install yet?"
exit 1
fi
fi
#check the default for redis cli
CLI_EXEC=`command -v redis-cli`
if [ -z "$CLI_EXEC" ] ; then
CLI_EXEC=`dirname $REDIS_EXECUTABLE`"/redis-cli"
fi
echo "Selected config:"
echo "Port : $REDIS_PORT"
echo "Config file : $REDIS_CONFIG_FILE"
echo "Log file : $REDIS_LOG_FILE"
echo "Data dir : $REDIS_DATA_DIR"
echo "Executable : $REDIS_EXECUTABLE"
echo "Cli Executable : $CLI_EXEC"
read -p "Is this ok? Then press ENTER to go on or Ctrl-C to abort." _UNUSED_
mkdir -p `dirname "$REDIS_CONFIG_FILE"` || die "Could not create redis config directory"
mkdir -p `dirname "$REDIS_LOG_FILE"` || die "Could not create redis log dir"
mkdir -p "$REDIS_DATA_DIR" || die "Could not create redis data directory"
#render the templates
TMP_FILE="/tmp/${REDIS_PORT}.conf"
DEFAULT_CONFIG="${SCRIPTPATH}/../redis.conf"
INIT_TPL_FILE="${SCRIPTPATH}/redis_init_script.tpl"
INIT_SCRIPT_DEST="/etc/init.d/redis_${REDIS_PORT}"
PIDFILE="/var/run/redis_${REDIS_PORT}.pid"
if [ ! -f "$DEFAULT_CONFIG" ]; then
echo "Mmmmm... the default config is missing. Did you switch to the utils directory?"
exit 1
fi
#Generate config file from the default config file as template
#changing only the stuff we're controlling from this script
echo "## Generated by install_server.sh ##" > $TMP_FILE
read -r SED_EXPR <<-EOF
s#^port [0-9]{4}\$#port ${REDIS_PORT}#; \
s#^logfile .+\$#logfile ${REDIS_LOG_FILE}#; \
s#^dir .+\$#dir ${REDIS_DATA_DIR}#; \
s#^pidfile .+\$#pidfile ${PIDFILE}#; \
s#^daemonize no\$#daemonize yes#;
EOF
sed -r "$SED_EXPR" $DEFAULT_CONFIG >> $TMP_FILE
#cat $TPL_FILE | while read line; do eval "echo \"$line\"" >> $TMP_FILE; done
cp $TMP_FILE $REDIS_CONFIG_FILE || die "Could not write redis config file $REDIS_CONFIG_FILE"
#Generate sample script from template file
rm -f $TMP_FILE
#we hard code the configs here to avoid issues with templates containing env vars
#kinda lame but works!
REDIS_INIT_HEADER=\
"#!/bin/sh\n
#Configurations injected by install_server below....\n\n
EXEC=$REDIS_EXECUTABLE\n
CLIEXEC=$CLI_EXEC\n
PIDFILE=\"$PIDFILE\"\n
CONF=\"$REDIS_CONFIG_FILE\"\n\n
REDISPORT=\"$REDIS_PORT\"\n\n
###############\n\n"
REDIS_CHKCONFIG_INFO=\
"# REDHAT chkconfig header\n\n
# chkconfig: - 58 74\n
# description: redis_${REDIS_PORT} is the redis daemon.\n
### BEGIN INIT INFO\n
# Provides: redis_6379\n
# Required-Start: \$network \$local_fs \$remote_fs\n
# Required-Stop: \$network \$local_fs \$remote_fs\n
# Default-Start: 2 3 4 5\n
# Default-Stop: 0 1 6\n
# Should-Start: \$syslog \$named\n
# Should-Stop: \$syslog \$named\n
# Short-Description: start and stop redis_${REDIS_PORT}\n
# Description: Redis daemon\n
### END INIT INFO\n\n"
if command -v chkconfig >/dev/null; then
#if we're a box with chkconfig on it we want to include info for chkconfig
echo "$REDIS_INIT_HEADER" "$REDIS_CHKCONFIG_INFO" > $TMP_FILE && cat $INIT_TPL_FILE >> $TMP_FILE || die "Could not write init script to $TMP_FILE"
else
#combine the header and the template (which is actually a static footer)
echo "$REDIS_INIT_HEADER" > $TMP_FILE && cat $INIT_TPL_FILE >> $TMP_FILE || die "Could not write init script to $TMP_FILE"
fi
###
# Generate sample script from template file
# - No need to check which system we are on. The init info are comments and
# do not interfere with update_rc.d systems. Additionally:
# Ubuntu/debian by default does not come with chkconfig, but does issue a
# warning if init info is not available.
cat > ${TMP_FILE} <<EOT
#!/bin/sh
#Configurations injected by install_server below....
EXEC=$REDIS_EXECUTABLE
CLIEXEC=$CLI_EXEC
PIDFILE=$PIDFILE
CONF="$REDIS_CONFIG_FILE"
REDISPORT="$REDIS_PORT"
###############
# SysV Init Information
# chkconfig: - 58 74
# description: redis_${REDIS_PORT} is the redis daemon.
### BEGIN INIT INFO
# Provides: redis_${REDIS_PORT}
# Required-Start: \$network \$local_fs \$remote_fs
# Required-Stop: \$network \$local_fs \$remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Should-Start: \$syslog \$named
# Should-Stop: \$syslog \$named
# Short-Description: start and stop redis_${REDIS_PORT}
# Description: Redis daemon
### END INIT INFO
EOT
cat ${INIT_TPL_FILE} >> ${TMP_FILE}
#copy to /etc/init.d
cp $TMP_FILE $INIT_SCRIPT_DEST && \
chmod +x $INIT_SCRIPT_DEST || die "Could not copy redis init script to $INIT_SCRIPT_DEST"
echo "Copied $TMP_FILE => $INIT_SCRIPT_DEST"
#Install the service
echo "Installing service..."
if command -v chkconfig >/dev/null 2>&1; then
# we're chkconfig, so lets add to chkconfig and put in runlevel 345
chkconfig --add redis_${REDIS_PORT} && echo "Successfully added to chkconfig!"
chkconfig --level 345 redis_${REDIS_PORT} on && echo "Successfully added to runlevels 345!"
elif command -v update-rc.d >/dev/null 2>&1; then
#if we're not a chkconfig box assume we're able to use update-rc.d
update-rc.d redis_${REDIS_PORT} defaults && echo "Success!"
else
echo "No supported init tool found."
fi
/etc/init.d/redis_$REDIS_PORT start || die "Failed starting service..."
#tada
echo "Installation successful!"
exit 0
| 8,545 | 33.739837 | 147 | sh |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/whatisdoing.sh | # This script is from http://poormansprofiler.org/
#
# NOTE: Instead of using this script, you should use the Redis
# Software Watchdog, which provides a similar functionality but in
# a more reliable / easy to use way.
#
# Check http://redis.io/topics/latency for more information.
#!/bin/bash
nsamples=1
sleeptime=0
pid=$(ps auxww | grep '[r]edis-server' | awk '{print $2}')
for x in $(seq 1 $nsamples)
do
gdb -ex "set pagination 0" -ex "thread apply all bt" -batch -p $pid
sleep $sleeptime
done | \
awk '
BEGIN { s = ""; }
/Thread/ { print s; s = ""; }
/^\#/ { if (s != "" ) { s = s "," $4} else { s = $4 } }
END { print s }' | \
sort | uniq -c | sort -r -n -k 1,1
| 693 | 26.76 | 71 | sh |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/releasetools/02_upload_tarball.sh | #!/bin/bash
echo "Uploading..."
scp /tmp/redis-${1}.tar.gz [email protected]:/var/virtual/download.redis.io/httpdocs/releases/
echo "Updating web site... (press any key if it is a stable release, or Ctrl+C)"
read x
ssh [email protected] "cd /var/virtual/download.redis.io/httpdocs; ./update.sh ${1}"
| 304 | 42.571429 | 96 | sh |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/releasetools/04_release_hash.sh | #!/bin/bash
SHA=$(curl -s http://download.redis.io/releases/redis-${1}.tar.gz | shasum | cut -f 1 -d' ')
ENTRY="hash redis-${1}.tar.gz sha1 $SHA http://download.redis.io/releases/redis-${1}.tar.gz"
echo $ENTRY >> ~/hack/redis-hashes/README
vi ~/hack/redis-hashes/README
echo "Press any key to commit, Ctrl-C to abort)."
read yes
(cd ~/hack/redis-hashes; git commit -a -m "${1} hash."; git push)
| 395 | 43 | 92 | sh |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/releasetools/03_test_release.sh | #!/bin/sh
if [ $# != "1" ]
then
echo "Usage: ${0} <git-ref>"
exit 1
fi
TAG=$1
TARNAME="redis-${TAG}.tar.gz"
DOWNLOADURL="http://download.redis.io/releases/${TARNAME}"
ssh antirez@metal "export TERM=xterm;
cd /tmp;
rm -rf test_release_tmp_dir;
cd test_release_tmp_dir;
wget $DOWNLOADURL;
tar xvzf $TARNAME;
cd redis-${TAG};
make;
./runtest;
./runtest-sentinel;
if [ -x runtest-cluster ]; then
./runtest-cluster;
fi"
| 657 | 25.32 | 58 | sh |
null | NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/utils/releasetools/01_create_tarball.sh | #!/bin/sh
if [ $# != "1" ]
then
echo "Usage: ./mkrelease.sh <git-ref>"
exit 1
fi
TAG=$1
TARNAME="redis-${TAG}.tar"
echo "Generating /tmp/${TARNAME}"
cd ~/hack/redis
git archive $TAG --prefix redis-${TAG}/ > /tmp/$TARNAME || exit 1
echo "Gizipping the archive"
rm -f /tmp/$TARNAME.gz
gzip -9 /tmp/$TARNAME
| 314 | 18.6875 | 65 | sh |
null | NearPMSW-main/nearpm/checkpointing/TATP_CP/tatp_db.h | /*
Author: Vaibhav Gogte <[email protected]>
Aasheesh Kolli <[email protected]>
This file declares the TATP data base and the different transactions supported by
the database.
*/
#include <cstdint>
//#include <atomic>
#include <pthread.h>
#include "tableEntries.h"
#include "../include/txopt.h"
class TATP_DB{
private:
long total_subscribers; // Holds the number of subscribers
int num_threads;
subscriber_entry* subscriber_table; // Pointer to the subscriber table
access_info_entry* access_info_table; // Pointer to the access info table
special_facility_entry* special_facility_table; // Pointer to the special facility table
call_forwarding_entry* call_forwarding_table; // Pointer to the call forwarding table
pthread_mutex_t* lock_; // Lock per subscriber to protect the update
//std::atomic<long>** txCounts; // Array of tx counts, success and fails
unsigned long* subscriber_rndm_seeds;
unsigned long* vlr_rndm_seeds;
unsigned long* rndm_seeds;
public:
TATP_DB(unsigned num_subscribers); // Constructs and sizes tables as per num_subscribers
~TATP_DB();
void initialize(unsigned num_subscribers, int n);
void populate_tables(unsigned num_subscribers); // Populates the various tables
void fill_subscriber_entry(unsigned _s_id); // Fills subscriber table entry given subscriber id
void fill_access_info_entry(unsigned _s_id, short _ai_type); // Fills access info table entry given subscriber id and ai_type
void fill_special_facility_entry(unsigned _s_id, short _sf_type); // Fills special facility table entry given subscriber id and sf_type
void fill_call_forwarding_entry(unsigned _s_id, short _sf_type, short _start_time); // Fills call forwarding table entry given subscriber id, sf_type and start type
void convert_to_string(unsigned number, int num_digits, char* string_ptr);
void make_upper_case_string(char* string_ptr, int num_chars);
void update_subscriber_data(int threadId); // Tx: updates a random subscriber data
void update_location(int threadId, int num_ops); // Tx: updates location for a random subscriber
void insert_call_forwarding(int threadId); // Tx: Inserts into call forwarding table for a random user
void delete_call_forwarding(int threadId); // Tx: Deletes call forwarding for a random user
unsigned long get_random(int thread_id, int min, int max);
unsigned long get_random(int thread_id);
unsigned long get_random_s_id(int thread_id);
unsigned long get_random_vlr(int thread_id);
void print_results();
};
//DS for logging info to recover from a failed update_subscriber_data Tx
struct recovery_update_subscriber_data {
char txType; // will be '0'
unsigned s_id; // the subscriber id being updated
short sf_type; // the sf_type being modified
short bit_1; // the old bit_! value
short data_a; // the old data_a value
char padding[5];
};
struct recovery_update_location {
char txType; // will be '1'
unsigned s_id; // the subcriber whose location is being updated
unsigned vlr_location; // the old vlr location
char padding[7];
};
| 3,135 | 39.727273 | 168 | h |
null | NearPMSW-main/nearpm/checkpointing/TATP_CP/tatp_db.cc | /*
Author: Vaibhav Gogte <[email protected]>
Aasheesh Kolli <[email protected]>
This file defines the various transactions in TATP.
*/
#include "tatp_db.h"
#include <cstdlib> // For rand
#include <iostream>
#include <libpmem.h>
#include <sys/mman.h>
//#include <queue>
//#include <iostream>
#define NUM_RNDM_SEEDS 1280
subscriber_entry * subscriber_table_entry_backup;
uint64_t * subscriber_table_entry_backup_valid;
extern void * device;
static void setpage(void * addr){
uint64_t pageNo = ((uint64_t)addr)/4096;
unsigned long * pageStart = (unsigned long *)(pageNo*4096);
mprotect(pageStart, 4096, PROT_READ);
return;
}
extern void * checkpoint_start;
int getRand() {
return rand();
}
TATP_DB::TATP_DB(unsigned num_subscribers) {}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::initialize(unsigned num_subscribers, int n) {
total_subscribers = num_subscribers;
num_threads = n;
size_t mapped_len;
int is_pmem;
void * pmemstart;
int totsize = num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long) + sizeof(subscriber_entry) + sizeof(uint64_t);
if ((pmemstart = pmem_map_file("/mnt/mem/tatp", totsize,
PMEM_FILE_CREATE, 0666, &mapped_len, &is_pmem)) == NULL) {
fprintf(stderr, "pmem_map_file failed\n");
exit(0);
}
if ((checkpoint_start = pmem_map_file("/mnt/mem/checkpoint", 4096*50,
PMEM_FILE_CREATE, 0666, &mapped_len, &is_pmem)) == NULL) {
fprintf(stderr, "pmem_map_file failed\n");
exit(0);
}
subscriber_table = (subscriber_entry*) pmemstart;
// A max of 4 access info entries per subscriber
access_info_table = (access_info_entry*) (pmemstart + num_subscribers*sizeof(subscriber_entry));
// A max of 4 access info entries per subscriber
special_facility_table = (special_facility_entry*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry));
// A max of 3 call forwarding entries per "special facility entry"
call_forwarding_table= (call_forwarding_entry*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry));
//Korakit
//removed for single thread version
/*
lock_ = (pthread_mutex_t *)malloc(n*sizeof(pthread_mutex_t));
for(int i=0; i<num_threads; i++) {
pthread_mutex_init(&lock_[i], NULL);
}
*/
for(int i=0; i<4*num_subscribers; i++) {
access_info_table[i].valid = false;
special_facility_table[i].valid = false;
for(int j=0; j<3; j++) {
call_forwarding_table[3*i+j].valid = false;
// printf("%d\n",j);
}
// printf("%d %d %d\n", i, 4*num_subscribers, totsize);
}
//printf("ab\n");
//rndm_seeds = new std::atomic<unsigned long>[NUM_RNDM_SEEDS];
//rndm_seeds = (std::atomic<unsigned long>*) malloc(NUM_RNDM_SEEDS*sizeof(std::atomic<unsigned long>));
subscriber_rndm_seeds = (unsigned long*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry));
vlr_rndm_seeds = (unsigned long*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry) + NUM_RNDM_SEEDS*sizeof(unsigned long));
rndm_seeds = (unsigned long*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long));
subscriber_table_entry_backup = (subscriber_entry*) (pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long));
subscriber_table_entry_backup_valid = (uint64_t*)(pmemstart + num_subscribers*sizeof(subscriber_entry) + 4*num_subscribers*sizeof(access_info_entry) + 4*num_subscribers*sizeof(special_facility_entry) + 3*4*num_subscribers*sizeof(call_forwarding_entry) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long) + NUM_RNDM_SEEDS*sizeof(unsigned long) + sizeof(subscriber_entry) );
//sgetRand();
for(int i=0; i<NUM_RNDM_SEEDS; i++) {
subscriber_rndm_seeds[i] = getRand()%(NUM_RNDM_SEEDS*10)+1;
vlr_rndm_seeds[i] = getRand()%(NUM_RNDM_SEEDS*10)+1;
rndm_seeds[i] = getRand()%(NUM_RNDM_SEEDS*10)+1;
//std::cout<<i<<" "<<rndm_seeds[i]<<std::endl;
}
}
TATP_DB::~TATP_DB(){
free(subscriber_rndm_seeds);
free(vlr_rndm_seeds);
free(rndm_seeds);
}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::populate_tables(unsigned num_subscribers) {
for(int i=0; i<num_subscribers; i++) {
fill_subscriber_entry(i);
int num_ai_types = getRand()%4 + 1; // num_ai_types varies from 1->4
for(int j=1; j<=num_ai_types; j++) {
fill_access_info_entry(i,j);
}
int num_sf_types = getRand()%4 + 1; // num_sf_types varies from 1->4
for(int k=1; k<=num_sf_types; k++) {
fill_special_facility_entry(i,k);
int num_call_forwards = getRand()%4; // num_call_forwards varies from 0->3
for(int p=0; p<num_call_forwards; p++) {
fill_call_forwarding_entry(i,k,8*p);
}
}
}
}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::fill_subscriber_entry(unsigned _s_id) {
subscriber_table[_s_id].s_id = _s_id;
convert_to_string(_s_id, 15, subscriber_table[_s_id].sub_nbr);
subscriber_table[_s_id].bit_1 = (short) (getRand()%2);
subscriber_table[_s_id].bit_2 = (short) (getRand()%2);
subscriber_table[_s_id].bit_3 = (short) (getRand()%2);
subscriber_table[_s_id].bit_4 = (short) (getRand()%2);
subscriber_table[_s_id].bit_5 = (short) (getRand()%2);
subscriber_table[_s_id].bit_6 = (short) (getRand()%2);
subscriber_table[_s_id].bit_7 = (short) (getRand()%2);
subscriber_table[_s_id].bit_8 = (short) (getRand()%2);
subscriber_table[_s_id].bit_9 = (short) (getRand()%2);
subscriber_table[_s_id].bit_10 = (short) (getRand()%2);
subscriber_table[_s_id].hex_1 = (short) (getRand()%16);
subscriber_table[_s_id].hex_2 = (short) (getRand()%16);
subscriber_table[_s_id].hex_3 = (short) (getRand()%16);
subscriber_table[_s_id].hex_4 = (short) (getRand()%16);
subscriber_table[_s_id].hex_5 = (short) (getRand()%16);
subscriber_table[_s_id].hex_6 = (short) (getRand()%16);
subscriber_table[_s_id].hex_7 = (short) (getRand()%16);
subscriber_table[_s_id].hex_8 = (short) (getRand()%16);
subscriber_table[_s_id].hex_9 = (short) (getRand()%16);
subscriber_table[_s_id].hex_10 = (short) (getRand()%16);
subscriber_table[_s_id].byte2_1 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_2 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_3 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_4 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_5 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_6 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_7 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_8 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_9 = (short) (getRand()%256);
subscriber_table[_s_id].byte2_10 = (short) (getRand()%256);
subscriber_table[_s_id].msc_location = getRand()%(2^32 - 1) + 1;
subscriber_table[_s_id].vlr_location = getRand()%(2^32 - 1) + 1;
}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::fill_access_info_entry(unsigned _s_id, short _ai_type) {
int tab_indx = 4*_s_id + _ai_type - 1;
access_info_table[tab_indx].s_id = _s_id;
access_info_table[tab_indx].ai_type = _ai_type;
access_info_table[tab_indx].data_1 = getRand()%256;
access_info_table[tab_indx].data_2 = getRand()%256;
make_upper_case_string(access_info_table[tab_indx].data_3, 3);
make_upper_case_string(access_info_table[tab_indx].data_4, 5);
access_info_table[tab_indx].valid = true;
}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::fill_special_facility_entry(unsigned _s_id, short _sf_type) {
int tab_indx = 4*_s_id + _sf_type - 1;
special_facility_table[tab_indx].s_id = _s_id;
special_facility_table[tab_indx].sf_type = _sf_type;
special_facility_table[tab_indx].is_active = ((getRand()%100 < 85) ? 1 : 0);
special_facility_table[tab_indx].error_cntrl = getRand()%256;
special_facility_table[tab_indx].data_a = getRand()%256;
make_upper_case_string(special_facility_table[tab_indx].data_b, 5);
special_facility_table[tab_indx].valid = true;
}
//Korakit
//this function is used in setup phase, no need to provide crash consistency
void TATP_DB::fill_call_forwarding_entry(unsigned _s_id, short _sf_type, short _start_time) {
if(_start_time == 0)
return;
int tab_indx = 12*_s_id + 3*(_sf_type-1) + (_start_time-8)/8;
call_forwarding_table[tab_indx].s_id = _s_id;
call_forwarding_table[tab_indx].sf_type = _sf_type;
call_forwarding_table[tab_indx].start_time = _start_time - 8;
call_forwarding_table[tab_indx].end_time = (_start_time - 8) + getRand()%8 + 1;
convert_to_string(getRand()%1000, 15, call_forwarding_table[tab_indx].numberx);
}
void TATP_DB::convert_to_string(unsigned number, int num_digits, char* string_ptr) {
char digits[10] = {'0','1','2','3','4','5','6','7','8','9'};
int quotient = number;
int reminder = 0;
int num_digits_converted=0;
int divider = 1;
while((quotient != 0) && (num_digits_converted<num_digits)) {
divider = 10^(num_digits_converted+1);
reminder = quotient%divider; quotient = quotient/divider;
string_ptr[num_digits-1 - num_digits_converted] = digits[reminder];
num_digits_converted++;
}
if(num_digits_converted < num_digits) {
string_ptr[num_digits-1 - num_digits_converted] = digits[0];
num_digits_converted++;
}
return;
}
void TATP_DB::make_upper_case_string(char* string_ptr, int num_chars) {
char alphabets[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
for(int i=0; i<num_chars; i++) {
string_ptr[i] = alphabets[getRand()%26];
}
return;
}
void TATP_DB::update_subscriber_data(int threadId) {
unsigned rndm_s_id = getRand() % total_subscribers;
short rndm_sf_type = getRand() % 4 + 1;
unsigned special_facility_tab_indx = 4*rndm_s_id + rndm_sf_type -1;
if(special_facility_table[special_facility_tab_indx].valid) {
//FIXME: There is a potential data race here, do not use this function yet
//Korakit
//removed for single thread version
//pthread_mutex_lock(&lock_[rndm_s_id]);
subscriber_table[rndm_s_id].bit_1 = getRand()%2;
special_facility_table[special_facility_tab_indx].data_a = getRand()%256;
//Korakit
//removed for single thread version
//pthread_mutex_unlock(&lock_[rndm_s_id]);
}
return;
}
//subscriber_entry subscriber_table_entry_backup;
//uint64_t subscriber_table_entry_backup_valid;
void TATP_DB::update_location(int threadId, int num_ops) {
long rndm_s_id;
rndm_s_id = get_random_s_id(threadId)-1;
rndm_s_id /=total_subscribers;
//Korakit
//removed for single thread version
//pthread_mutex_lock(&lock_[rndm_s_id]);
//create backup
//*subscriber_table_entry_backup = subscriber_table[rndm_s_id];
//move_data(&subscriber_table_entry_backup, &subscriber_table[rndm_s_id],sizeof(subscriber_table_entry_backup));
//s_fence();
//*subscriber_table_entry_backup_valid = 1;
//s_fence();
setpage(&subscriber_table[rndm_s_id].vlr_location);
subscriber_table[rndm_s_id].vlr_location = get_random_vlr(threadId);
pmem_persist(&subscriber_table[rndm_s_id], sizeof(subscriber_table[rndm_s_id]));
//*subscriber_table_entry_backup_valid = 0;
//s_fence();
//Korakit
//removed for single thread version
//pthread_mutex_unlock(&lock_[rndm_s_id]);
return;
}
void TATP_DB::insert_call_forwarding(int threadId) {
return;
}
void TATP_DB::delete_call_forwarding(int threadId) {
return;
}
void TATP_DB::print_results() {
//std::cout<<"TxType:0 successful txs = "<<txCounts[0][0]<<std::endl;
//std::cout<<"TxType:0 failed txs = "<<txCounts[0][1]<<std::endl;
//std::cout<<"TxType:1 successful txs = "<<txCounts[1][0]<<std::endl;
//std::cout<<"TxType:1 failed txs = "<<txCounts[1][1]<<std::endl;
//std::cout<<"TxType:2 successful txs = "<<txCounts[2][0]<<std::endl;
//std::cout<<"TxType:2 failed txs = "<<txCounts[2][1]<<std::endl;
//std::cout<<"TxType:3 successful txs = "<<txCounts[3][0]<<std::endl;
//std::cout<<"TxType:3 failed txs = "<<txCounts[3][1]<<std::endl;
}
unsigned long TATP_DB::get_random(int thread_id) {
//return (getRand()%65536 | min + getRand()%(max - min + 1)) % (max - min + 1) + min;
unsigned long tmp;
tmp = rndm_seeds[thread_id*10] = (rndm_seeds[thread_id*10] * 16807) % 2147483647;
return tmp;
}
unsigned long TATP_DB::get_random(int thread_id, int min, int max) {
//return (getRand()%65536 | min + getRand()%(max - min + 1)) % (max - min + 1) + min;
unsigned long tmp;
tmp = rndm_seeds[thread_id*10] = (rndm_seeds[thread_id*10] * 16807) % 2147483647;
return (min+tmp%(max-min+1));
}
unsigned long TATP_DB::get_random_s_id(int thread_id) {
unsigned long tmp;
tmp = subscriber_rndm_seeds[thread_id*10] = (subscriber_rndm_seeds[thread_id*10] * 16807) % 2147483647;
return (1 + tmp%(total_subscribers));
}
unsigned long TATP_DB::get_random_vlr(int thread_id) {
unsigned long tmp;
tmp = vlr_rndm_seeds[thread_id*10] = (vlr_rndm_seeds[thread_id*10] * 16807)%2147483647;
return (1 + tmp%(2^32));
}
| 14,363 | 39.235294 | 402 | cc |
null | NearPMSW-main/nearpm/checkpointing/TATP_CP/run.sh | #!/usr/bin/env bash
sudo rm -rf /mnt/mem/*
sudo ./tatp_nvm > out
tot=$(grep "tottime" out)
grep "cp" out > time
cp=$(awk '{sum+= $2;} END{print sum;}' time)
echo $1$tot
echo $1'cp' $cp
| 187 | 16.090909 | 44 | sh |
null | NearPMSW-main/nearpm/checkpointing/TATP_CP/tatp_nvm.cc | /*
Author: Vaibhav Gogte <[email protected]>
Aasheesh Kolli <[email protected]>
This file is the TATP benchmark, performs various transactions as per the specifications.
*/
#include "tatp_db.h"
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstdint>
#include <assert.h>
#include <sys/time.h>
#include <string>
#include <fstream>
#include <libpmem.h>
#include <cstring>
//Korakit
//might need to change parameters
#define NUM_SUBSCRIBERS 100000 //100000
#define NUM_OPS_PER_CS 2
#define NUM_OPS 30000 //10000000
#define NUM_THREADS 1
TATP_DB* my_tatp_db;
//#include "../DCT/rdtsc.h"
void init_db() {
unsigned num_subscribers = NUM_SUBSCRIBERS;
my_tatp_db = (TATP_DB *)malloc(sizeof(TATP_DB));
my_tatp_db->initialize(num_subscribers,NUM_THREADS);
fprintf(stderr, "Created tatp db at %p\n", (void *)my_tatp_db);
}
void* update_locations(void* args) {
int thread_id = *((int*)args);
for(int i=0; i<NUM_OPS/NUM_THREADS; i++) {
my_tatp_db->update_location(thread_id,NUM_OPS_PER_CS);
}
return 0;
}
/////////////////Page fault handling/////////////////
#include <bits/types/sig_atomic_t.h>
#include <bits/types/sigset_t.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#define SIGSTKSZ 8192
#define SA_SIGINFO 4
#define SA_ONSTACK 0x08000000 /* Use signal stack by using `sa_restorer'. */
#define SA_RESTART 0x10000000 /* Restart syscall on signal return. */
#define SA_NODEFER 0x40000000 /* Don't automatically block the signal when*/
stack_t _sigstk;
int updated_page_count = 0;
int all_updates = 0;
void * checkpoint_start;
void * page[50];
void * device;
double totTimeCP = 0;
static inline uint64_t getCycle(){
uint32_t cycles_high, cycles_low, pid;
asm volatile ("RDTSCP\n\t" // rdtscp into eax and edx
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"mov %%ecx, %2\n\t"
:"=r" (cycles_high), "=r" (cycles_low), "=r" (pid) //store in vars
:// no input
:"%eax", "%edx", "%ecx" // clobbered by rdtscp
);
return((uint64_t)cycles_high << 32) | cycles_low;
}
#define GRANULARITY 2048
void cmd_issue( uint32_t opcode,
uint32_t TXID,
uint32_t TID,
uint32_t OID,
uint64_t data_addr,
uint32_t data_size,
void * ptr){
//command with thread id encoded as first 8 bits of each word
uint32_t issue_cmd[7];
issue_cmd[0] = (TID<<24)|(opcode<<16)|(TXID<<8)|TID;
issue_cmd[1] = (TID<<24)|(OID<<16)|(data_addr>>48);
issue_cmd[2] = (TID<<24)|((data_addr & 0x0000FFFFFFFFFFFF)>>24);
issue_cmd[3] = (TID<<24)|(data_addr & 0x0000000000FFFFFF);
issue_cmd[4] = (TID<<24)|(data_size<<8);
issue_cmd[5] = (TID<<24)|(0X00FFFFFF>>16);
issue_cmd[6] = (TID<<24)|((0X00FFFFFF & 0x0000FFFF)<<8);
for(int i=0;i<7;i++){
// printf("%08x\n",issue_cmd[i]);
*((u_int32_t *) ptr) = issue_cmd[i];
}
}
static void segvHandle(int signum, siginfo_t * siginfo, void * context) {
#define CPTIME
#ifdef CPTIME
uint64_t endCycles, startCycles,totalCycles;
startCycles = getCycle();
#endif
void * addr = siginfo->si_addr; // address of access
uint64_t pageNo = ((uint64_t)addr)/4096;
unsigned long * pageStart = (unsigned long *)(pageNo*4096);
// Check if this was a SEGV that we are supposed to trap.
if (siginfo->si_code == SEGV_ACCERR) {
mprotect(pageStart, 4096, PROT_READ|PROT_WRITE);
if(all_updates >=5 || updated_page_count == 50){
for(int i=0;i<updated_page_count;i++){
//memcpy(checkpoint_start + 4096, pageStart, 4096);
//pmem_persist(checkpoint_start + 4096, 4096);
cmd_issue(2,0,0,0, (uint64_t)pageStart,4096,device);
/* *((uint64_t*)device) = (uint64_t)(checkpoint_start + 4096);
*((uint64_t*)(device)+1) = 00;
*((uint64_t*)(device)+2) = (uint64_t)0.320580;
*((uint64_t*)(device)+3) = ((uint64_t)(((0) << 16)| 6) << 32) | 4096;
*(((uint32_t*)(device))+255) = (uint32_t)(((0) << 16)| 6);
*/
page[updated_page_count] = 0;
}
updated_page_count = 0;
all_updates = 0;
}
all_updates ++;
for(int i=0; i<updated_page_count; i++){
if(page[i] == pageStart){
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
#endif
return;}
}
page[updated_page_count] = pageStart;
//printf("test1 %lx %d %d\n",page[updated_page_count],updated_page_count,all_updates);
updated_page_count++;
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
#endif
//*((int *)checkpoint_start) = 10;
//test++;
//printf("test1 %lx %d\n",updated_page_count);
} else if (siginfo->si_code == SEGV_MAPERR) {
fprintf (stderr, "%d : map error with addr %p!\n", getpid(), addr);
abort();
} else {
fprintf (stderr, "%d : other access error with addr %p.\n", getpid(), addr);
abort();
}
}
static void installSignalHandler(void) {
// Set up an alternate signal stack.
printf("page fault handler initialized!!\n");
_sigstk.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
_sigstk.ss_size = SIGSTKSZ;
_sigstk.ss_flags = 0;
sigaltstack(&_sigstk, (stack_t *) 0);
// Now set up a signal handler for SIGSEGV events.
struct sigaction siga;
sigemptyset(&siga.sa_mask);
// Set the following signals to a set
sigaddset(&siga.sa_mask, SIGSEGV);
sigaddset(&siga.sa_mask, SIGALRM);
sigprocmask(SIG_BLOCK, &siga.sa_mask, NULL);
// Point to the handler function.
siga.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART | SA_NODEFER;
siga.sa_sigaction = segvHandle;
if (sigaction(SIGSEGV, &siga, NULL) == -1) {
perror("sigaction(SIGSEGV)");
exit(-1);
}
sigprocmask(SIG_UNBLOCK, &siga.sa_mask, NULL);
return;
}
void* open_device(const char* pathname)
{
//int fd = os_open("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0",O_RDWR|O_SYNC);
int fd = open(pathname,O_RDWR|O_SYNC);
if(fd == -1)
{
printf("Couldnt opene file!!\n");
exit(0);
}
void * ptr = mmap(0,4096,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);
if(ptr == (void *)-1)
{
printf("Could not map memory!!\n");
exit(0);
}
printf("opened device without error!!\n");
return ptr;
}
///////////////////////////////////////////////////////////////////
void installSignalHandler (void) __attribute__ ((constructor));
int main(int argc, char* argv[]) {
//printf("in main\n");
//struct timeval tv_start;
//struct timeval tv_end;
//std::ofstream fexec;
//fexec.open("exec.csv",std::ios_base::app);
// Korakit: move to the init
// LIU
device = open_device("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0");
uint64_t* tmp = (uint64_t*)device;
*tmp = 0xdeadbeefdeadbeef;
pmem_persist(tmp,64);
*tmp = (uint64_t)tmp;
pmem_persist(tmp,64);
uint32_t tid;
tid = 0;//gettid();
tid = tid & 0x3f;
tid = (tid<< 4)| 0;//pop->run_id;
//printf("%d %d\n",tid, pop->run_id);
*tmp = tid;
pmem_persist(tmp,64);
init_db();
// LIU: remove output
//std::cout<<"done with initialization"<<std::endl;
my_tatp_db->populate_tables(NUM_SUBSCRIBERS);
// LIU: remove output
//std::cout<<"done with populating tables"<<std::endl;
pthread_t threads[NUM_THREADS];
int id[NUM_THREADS];
//Korakit
//exit to count instructions after initialization
//we use memory trace from the beginning to this to test the compression ratio
//as update locations(the actual test) only do one update
// LIU
// gettimeofday(&tv_start, NULL);
//CounterAtomic::initCounterCache();
uint64_t endCycles, startCycles,totalCycles;
startCycles = getCycle();
for(int i=0; i<NUM_THREADS; i++) {
id[i] = i;
update_locations((void*)&id[i]);
}
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("tottime %f\ndata movement time %f\n", totTime, totTimeCP);
//Korakit
//Not necessary for single threaded version
/*
for(int i=0; i<NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
*/
// LIU: remove the output
/*
gettimeofday(&tv_end, NULL);
fprintf(stderr, "time elapsed %ld us\n",
tv_end.tv_usec - tv_start.tv_usec +
(tv_end.tv_sec - tv_start.tv_sec) * 1000000);
fexec << "TATP" << ", " << std::to_string((tv_end.tv_usec - tv_start.tv_usec) + (tv_end.tv_sec - tv_start.tv_sec) * 1000000) << std::endl;
fexec.close();
free(my_tatp_db);
std::cout<<"done with threads"<<std::endl;
*/
return 0;
}
| 8,797 | 25.5 | 140 | cc |
null | NearPMSW-main/nearpm/checkpointing/TATP_CP/tableEntries.h | /*
Author: Vaibhav Gogte <[email protected]>
Aasheesh Kolli <[email protected]>
This file defines the table entries used by TATP.
*/
struct subscriber_entry {
unsigned s_id; // Subscriber id
char sub_nbr[15]; // Subscriber number, s_id in 15 digit string, zeros padded
short bit_1, bit_2, bit_3, bit_4, bit_5, bit_6, bit_7, bit_8, bit_9, bit_10; // randomly generated values 0/1
short hex_1, hex_2, hex_3, hex_4, hex_5, hex_6, hex_7, hex_8, hex_9, hex_10; // randomly generated values 0->15
short byte2_1, byte2_2, byte2_3, byte2_4, byte2_5, byte2_6, byte2_7, byte2_8, byte2_9, byte2_10; // randomly generated values 0->255
unsigned msc_location; // Randomly generated value 1->((2^32)-1)
unsigned vlr_location; // Randomly generated value 1->((2^32)-1)
char padding[40];
};
struct access_info_entry {
unsigned s_id; //Subscriber id
short ai_type; // Random value 1->4. A subscriber can have a max of 4 and all unique
short data_1, data_2; // Randomly generated values 0->255
char data_3[3]; // random 3 char string. All upper case alphabets
char data_4[5]; // random 5 char string. All upper case alphabets
bool valid;
bool padding_1[7];
char padding_2[4+32];
};
struct special_facility_entry {
unsigned s_id; //Subscriber id
short sf_type; // Random value 1->4. A subscriber can have a max of 4 and all unique
short is_active; // 0(15%)/1(85%)
short error_cntrl; // Randomly generated values 0->255
short data_a; // Randomly generated values 0->255
char data_b[5]; // random 5 char string. All upper case alphabets
char padding_1[7];
bool valid;
bool padding_2[4+32];
};
struct call_forwarding_entry {
unsigned s_id; // Subscriber id from special facility
short sf_type; // sf_type from special facility table
int start_time; // 0 or 8 or 16
int end_time; // start_time+N, N randomly generated 1->8
char numberx[15]; // randomly generated 15 digit string
char padding_1[7];
bool valid;
bool padding_2[24];
};
| 1,993 | 35.254545 | 134 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/run.sh | sudo mount -o dax /dev/pmem0 /mnt/pmem
sudo rm -rf /mnt/mem/*
sudo chown oem /mnt/pmem
#./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1
#sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --num=10000 --engine=cmap --benchmarks=fillseq,fillrandom,overwrite > out
make bench
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --num=10000 --engine=cmap --benchmarks=fillrandom > out
#grep "timecp" out > time
#awk '{sum+= $3;} END{print sum;}' time
grep "cp" out > time
log=$(awk '{sum+= $2;} END{print sum;}' time)
echo ""
echo $1'cp' $log
tottime=$(tail -1 out | awk '{print $NF}' | cut -d "," -f10|awk '{print $1/100}')
echo $1'tottime' $tottime
| 674 | 41.1875 | 135 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/runtest.sh | sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillrandom
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,overwrite
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,readseq
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,readrandom
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,readmissing
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,deleteseq
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,deleterandom
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,readwhilewriting
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,readrandomwriterandom
sudo ./pmemkv_bench --db=/mnt/pmem/pmemkv --db_size_in_gb=1 --engine=tree3 --benchmarks=fillseq,txfillrandom
| 1,176 | 89.538462 | 117 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/setup.sh | sudo mkfs.ext4 /dev/pmem0
sudo mount -o dax /dev/pmem0 /mnt/pmem
sudo chown oem /mnt/pmem
#cd Research/Research/pmdk/src/examples/libpmemobj/map/
#cat run.sh
| 159 | 25.666667 | 55 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/entrypoint.sh | #!/bin/sh -l
#
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021, Intel Corporation
set -e
set -x
echo "$1"
project_dir=${WORKDIR:-/pmemkv-bench}
echo "run basic test"
pytest-3 -v ${project_dir}/tests/test.py
| 219 | 12.75 | 40 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/db_bench.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 License
// (found in the LICENSE file in the root directory).
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017-2021, Intel Corporation
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <inttypes.h>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <vector>
#include "csv.h"
#include "histogram.h"
#include "leveldb/env.h"
#include "libpmemkv.hpp"
#include "libpmempool.h"
#include "mutexlock.h"
#include "port/port_posix.h"
#include "random.h"
#include "testutil.h"
static const std::string USAGE =
"pmemkv_bench\n"
"--engine=<name> (storage engine name, default: cmap)\n"
"--db=<location> (path to persistent pool, default: /dev/shm/pmemkv)\n"
" (note: file on DAX filesystem, DAX device, or poolset file)\n"
"--db_size_in_gb=<integer> (size of persistent pool to create in GB, default: 0)\n"
" (note: for existing poolset or device DAX configs use 0 or leave default value)\n"
" (note: when pool path is non-existing, value should be > 0)\n"
"--histogram=<0|1> (show histograms when reporting latencies)\n"
"--num=<integer> (number of keys to place in database, default: 1000000)\n"
"--reads=<integer> (number of read operations, default: 1000000)\n"
"--threads=<integer> (number of concurrent threads, default: 1)\n"
"--key_size=<integer> (size of keys in bytes, default: 16)\n"
"--value_size=<integer> (size of values in bytes, default: 100)\n"
"--readwritepercent=<integer> (Ratio of reads to reads/writes (expressed "
"as percentage) for the ReadRandomWriteRandom workload. The default value "
"90 means 90% operations out of all reads and writes operations are reads. "
"In other words, 9 gets for every 1 put.) type: int32 default: 90\n"
"--tx_size=<integer> (number of elements to insert in a single tx, there will be"
"num/tx_size transactions per thread in total, the last tx might be smaller, default: 10)\n"
"--disjoint=<0|1> (specifies whether each thread works on disjoint set of keys. "
"0 means that all threads read/write to the db using any key between 0 and `num`, so that "
"number of ops is `threads` * `num`. 1 means that each thread performs reads/writes using "
"only [`thread_id` * `num` / `threads`, (`thread_id` + 1) * `num` / `threads`) subset of keys, "
"so that total number of ops is `num`. The default value is 0.)\n"
"--benchmarks=<name>, (comma-separated list of benchmarks to run)\n"
" fillseq (load N values in sequential key order)\n"
" fillrandom (load N values in random key order)\n"
" overwrite (replace N values in random key order)\n"
" readseq (read N values in sequential key order)\n"
" readrandom (read N values in random key order)\n"
" readmissing (read N missing values in random key order)\n"
" deleteseq (delete N values in sequential key order)\n"
" deleterandom (delete N values in random key order)\n"
" readwhilewriting (1 writer, N threads doing random reads)\n"
" readrandomwriterandom (N threads doing random-read, random-write)\n"
" txfillrandom (load N values in random key order transactionally)\n";
// Number of key/values to place in database
static int FLAGS_num = 1000000;
static bool FLAGS_disjoint = false;
// Number of read operations to do. If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;
// Number of concurrent threads to run.
static int FLAGS_threads = 1;
static int FLAGS_key_size = 16;
// Size of each value
static int FLAGS_value_size = 100;
// Print histogram of operation timings
static bool FLAGS_histogram = false;
// Use the db with the following name.
static const char *FLAGS_db = "/dev/shm/pmemkv";
// Use following size when opening the database.
static int FLAGS_db_size_in_gb = 0;
static const double FLAGS_compression_ratio = 1.0;
static const int FLAGS_ops_between_duration_checks = 1000;
static const int FLAGS_duration = 0;
static int FLAGS_readwritepercent = 90;
static int FLAGS_tx_size = 10;
using namespace leveldb;
leveldb::Env *g_env = NULL;
#if defined(__linux)
static Slice TrimSpace(Slice s)
{
size_t start = 0;
while (start < s.size() && isspace(s[start])) {
start++;
}
size_t limit = s.size();
while (limit > start && isspace(s[limit - 1])) {
limit--;
}
return Slice(s.data() + start, limit - start);
}
#endif
// Helper for quickly generating random data.
class RandomGenerator {
private:
std::string data_;
unsigned int pos_;
public:
RandomGenerator()
{
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
// large enough to serve all typical value sizes we want to write.
Random rnd(301);
std::string piece;
while (data_.size() < (unsigned)std::max(1048576, FLAGS_value_size)) {
// Add a short fragment that is as compressible as specified
// by FLAGS_compression_ratio.
test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
data_.append(piece);
}
pos_ = 0;
}
Slice Generate(unsigned int len)
{
assert(len <= data_.size());
if (pos_ + len > data_.size()) {
pos_ = 0;
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
Slice GenerateWithTTL(unsigned int len)
{
assert(len <= data_.size());
if (pos_ + len > data_.size()) {
pos_ = 0;
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
};
static void AppendWithSpace(std::string *str, Slice msg)
{
if (msg.empty())
return;
if (!str->empty()) {
str->push_back(' ');
}
str->append(msg.data(), msg.size());
}
enum OperationType : unsigned char {
kRead = 0,
kWrite,
kDelete,
kSeek,
kMerge,
kUpdate,
};
class BenchmarkLogger {
private:
struct hist {
int id;
std::string name;
std::string histogram;
};
int id = 0;
std::vector<hist> histograms;
CSV<int> csv = CSV<int>("id");
public:
void insert(std::string name, Histogram histogram)
{
histograms.push_back({id, name, histogram.ToString()});
std::vector<double> percentiles = {50, 75, 90, 99.9, 99.99};
for (double &percentile : percentiles) {
csv.insert(id, "Percentilie P" + std::to_string(percentile) + " [micros/op]",
histogram.Percentile(percentile));
}
csv.insert(id, "Median [micros/op]", histogram.Median());
}
template <typename T>
void insert(std::string column, T data)
{
csv.insert(id, column, data);
}
void insert(std::string column, std::time_t time)
{
std::ostringstream time_stream;
time_stream << std::put_time(std::localtime(&time), "%D %T");
insert(column, time_stream.str());
}
void print_histogram()
{
std::cout << "------------------------------------------------" << std::endl;
for (auto &histogram : histograms) {
std::cout << "benchmark: " << histogram.id << ", " << histogram.name << std::endl
<< histogram.histogram << std::endl;
}
}
void print()
{
csv.print();
}
void next_benchmark()
{
id++;
}
};
class Stats {
private:
double start_;
double finish_;
double seconds_;
int done_;
int next_report_;
int64_t bytes_;
double last_op_finish_;
Histogram hist_;
std::string message_;
bool exclude_from_merge_;
public:
Stats()
{
Start();
}
void Start()
{
next_report_ = 100;
last_op_finish_ = start_;
hist_.Clear();
done_ = 0;
bytes_ = 0;
seconds_ = 0;
start_ = g_env->NowMicros();
finish_ = start_;
message_.clear();
// When set, stats from this thread won't be merged with others.
exclude_from_merge_ = false;
}
void Merge(const Stats &other)
{
if (other.exclude_from_merge_)
return;
hist_.Merge(other.hist_);
done_ += other.done_;
bytes_ += other.bytes_;
seconds_ += other.seconds_;
if (other.start_ < start_)
start_ = other.start_;
if (other.finish_ > finish_)
finish_ = other.finish_;
// Just keep the messages from one thread
if (message_.empty())
message_ = other.message_;
}
void Stop()
{
finish_ = g_env->NowMicros();
seconds_ = (finish_ - start_) * 1e-6;
}
void AddMessage(Slice msg)
{
AppendWithSpace(&message_, msg);
}
void SetExcludeFromMerge()
{
exclude_from_merge_ = true;
}
void FinishedSingleOp()
{
if (FLAGS_histogram) {
double now = g_env->NowMicros();
double micros = now - last_op_finish_;
hist_.Add(micros);
if (micros > 20000) {
fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
fflush(stderr);
}
last_op_finish_ = now;
}
done_++;
if (done_ >= next_report_) {
if (next_report_ < 1000)
next_report_ += 100;
else if (next_report_ < 5000)
next_report_ += 500;
else if (next_report_ < 10000)
next_report_ += 1000;
else if (next_report_ < 50000)
next_report_ += 5000;
else if (next_report_ < 100000)
next_report_ += 10000;
else if (next_report_ < 500000)
next_report_ += 50000;
else
next_report_ += 100000;
fprintf(stderr, "... finished %d ops%30s\r", done_, "");
fflush(stderr);
}
}
void AddBytes(int64_t n)
{
bytes_ += n;
}
float get_micros_per_op()
{
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1)
done_ = 1;
return seconds_ * 1e6 / done_;
}
float get_ops_per_sec()
{
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1)
done_ = 1;
double elapsed = (finish_ - start_) * 1e-6;
return done_ / elapsed;
}
float get_throughput()
{
// Rate and ops/sec is computed on actual elapsed time, not the sum of per-thread
// elapsed times.
double elapsed = (finish_ - start_) * 1e-6;
return (bytes_ / 1048576.0) / elapsed;
}
std::string get_extra_data()
{
return message_;
}
Histogram &get_histogram()
{
return hist_;
}
};
// State shared by all concurrent executions of the same benchmark.
struct SharedState {
port::Mutex mu;
port::CondVar cv;
int total;
// Each thread goes through the following states:
// (1) initializing
// (2) waiting for others to be initialized
// (3) running
// (4) done
int num_initialized;
int num_done;
bool start;
SharedState() : cv(&mu)
{
}
};
// Per-thread state for concurrent executions of the same benchmark.
struct ThreadState {
int tid; // 0..n-1 when running in n threads
Random rand; // Has different seeds for different threads
Stats stats;
SharedState *shared;
ThreadState(int index) : tid(index), rand(1000 + index)
{
}
};
class Duration {
typedef std::chrono::high_resolution_clock::time_point time_point;
public:
Duration(uint64_t max_seconds, int64_t max_ops, int64_t ops_per_stage = 0)
{
max_seconds_ = max_seconds;
max_ops_ = max_ops;
ops_per_stage_ = (ops_per_stage > 0) ? ops_per_stage : max_ops;
ops_ = 0;
start_at_ = std::chrono::high_resolution_clock::now();
}
int64_t GetStage()
{
return std::min(ops_, max_ops_ - 1) / ops_per_stage_;
}
bool Done(int64_t increment)
{
if (increment <= 0)
increment = 1; // avoid Done(0) and infinite loops
ops_ += increment;
if (max_seconds_) {
// Recheck every appx 1000 ops (exact iff increment is factor of 1000)
auto granularity = FLAGS_ops_between_duration_checks;
if ((ops_ / granularity) != ((ops_ - increment) / granularity)) {
time_point now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now - start_at_)
.count() >= max_seconds_;
} else {
return false;
}
} else {
return ops_ > max_ops_;
}
}
private:
uint64_t max_seconds_;
int64_t max_ops_;
int64_t ops_per_stage_;
int64_t ops_;
time_point start_at_;
};
class Benchmark {
private:
pmem::kv::db *kv_;
int num_;
int tx_size_;
int value_size_;
int key_size_;
int reads_;
int64_t readwrites_;
BenchmarkLogger &logger;
Slice name;
int n;
const char *engine;
void (Benchmark::*method)(ThreadState *) = NULL;
void PrintHeader()
{
PrintEnvironment();
logger.insert("Path", FLAGS_db);
logger.insert("Engine", engine);
logger.insert("Keys [bytes each]", FLAGS_key_size);
logger.insert("Values [bytes each]", FLAGS_value_size);
logger.insert("Entries", num_);
logger.insert("RawSize [MB (estimated)]",
((static_cast<int64_t>(FLAGS_key_size + FLAGS_value_size) * num_) / 1048576.0));
PrintWarnings();
}
void PrintWarnings()
{
#if defined(__GNUC__) && !defined(__OPTIMIZE__)
fprintf(stdout, "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
#endif
#ifndef NDEBUG
fprintf(stdout, "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
#endif
}
void PrintEnvironment()
{
#if defined(__linux)
auto now = std::time(NULL);
logger.insert("Date:", now);
FILE *cpuinfo = fopen("/proc/cpuinfo", "r");
if (cpuinfo != NULL) {
char line[1000];
int num_cpus = 0;
std::string cpu_type;
std::string cache_size;
while (fgets(line, sizeof(line), cpuinfo) != NULL) {
const char *sep = strchr(line, ':');
if (sep == NULL) {
continue;
}
Slice key = TrimSpace(Slice(line, sep - 1 - line));
Slice val = TrimSpace(Slice(sep + 1));
if (key == "model name") {
++num_cpus;
cpu_type = val.ToString();
} else if (key == "cache size") {
cache_size = val.ToString();
}
}
fclose(cpuinfo);
logger.insert("CPU", std::to_string(num_cpus));
logger.insert("CPU model", cpu_type);
logger.insert("CPUCache", cache_size);
}
#endif
}
public:
Benchmark(Slice name, pmem::kv::db *&kv, int num_threads, const char *engine, BenchmarkLogger &logger)
: kv_(kv), num_(FLAGS_num), tx_size_(FLAGS_tx_size), value_size_(FLAGS_value_size),
key_size_(FLAGS_key_size), reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
readwrites_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads), logger(logger), n(num_threads),
name(name), engine(engine)
{
fprintf(stderr, "running %s \n", name.ToString().c_str());
bool fresh_db = false;
if (name == Slice("fillseq")) {
fresh_db = true;
method = &Benchmark::WriteSeq;
} else if (name == Slice("fillrandom")) {
fresh_db = true;
method = &Benchmark::WriteRandom;
} else if (name == Slice("txfillrandom")) {
fresh_db = true;
method = &Benchmark::TxFillRandom;
} else if (name == Slice("overwrite")) {
method = &Benchmark::WriteRandom;
} else if (name == Slice("readseq")) {
method = &Benchmark::ReadSeq;
} else if (name == Slice("readrandom")) {
method = &Benchmark::ReadRandom;
} else if (name == Slice("readmissing")) {
method = &Benchmark::ReadMissing;
} else if (name == Slice("deleteseq")) {
method = &Benchmark::DeleteSeq;
} else if (name == Slice("deleterandom")) {
method = &Benchmark::DeleteRandom;
} else if (name == Slice("readwhilewriting")) {
++num_threads;
method = &Benchmark::ReadWhileWriting;
} else if (name == Slice("readrandomwriterandom")) {
method = &Benchmark::ReadRandomWriteRandom;
} else {
throw std::runtime_error("unknown benchmark: " + name.ToString());
}
logger.next_benchmark();
logger.insert("Benchmark", name.ToString());
PrintHeader();
if (fresh_db) {
if (kv_ != nullptr) {
kv_->close();
delete kv_;
kv_ = nullptr;
}
Create(name.ToString());
kv = kv_;
}
}
Slice AllocateKey(std::unique_ptr<const char[]> &key_guard)
{
const char *tmp = new char[key_size_];
key_guard.reset(tmp);
return Slice(key_guard.get(), key_size_);
}
void GenerateKeyFromInt(uint64_t v, int64_t num_keys, Slice *key, bool missing = false)
{
char *start = const_cast<char *>(key->data());
char *pos = start;
int bytes_to_fill = std::min(key_size_, 8);
if (missing) {
int64_t v1 = -v;
memcpy(pos, static_cast<void *>(&v1), bytes_to_fill);
} else
memcpy(pos, static_cast<void *>(&v), bytes_to_fill);
pos += bytes_to_fill;
if (key_size_ > pos - start) {
memset(pos, '0', key_size_ - (pos - start));
}
}
void Run()
{
SharedState shared;
shared.total = n;
shared.num_initialized = 0;
shared.num_done = 0;
shared.start = false;
ThreadArg *arg = new ThreadArg[n];
for (int i = 0; i < n; i++) {
arg[i].bm = this;
arg[i].method = method;
arg[i].shared = &shared;
arg[i].thread = new ThreadState(i);
arg[i].thread->shared = &shared;
g_env->StartThread(ThreadBody, &arg[i]);
}
shared.mu.Lock();
while (shared.num_initialized < n) {
shared.cv.Wait();
}
shared.start = true;
shared.cv.SignalAll();
while (shared.num_done < n) {
shared.cv.Wait();
}
shared.mu.Unlock();
for (int i = 1; i < n; i++) {
arg[0].thread->stats.Merge(arg[i].thread->stats);
}
auto thread_stats = arg[0].thread->stats;
logger.insert("micros/op (avarage)", thread_stats.get_micros_per_op());
logger.insert("ops/sec", thread_stats.get_ops_per_sec());
logger.insert("throughput [MB/s]", thread_stats.get_throughput());
logger.insert("extra_data", thread_stats.get_extra_data());
if (FLAGS_histogram) {
logger.insert(name.ToString(), thread_stats.get_histogram());
}
for (int i = 0; i < n; i++) {
delete arg[i].thread;
}
delete[] arg;
}
private:
struct ThreadArg {
Benchmark *bm;
SharedState *shared;
ThreadState *thread;
void (Benchmark::*method)(ThreadState *);
};
struct DbInserter {
DbInserter(pmem::kv::db *db) : db(db)
{
}
pmem::kv::status put(pmem::kv::string_view key, pmem::kv::string_view value)
{
return db->put(key, value);
}
pmem::kv::status commit()
{
return pmem::kv::status::OK;
}
private:
pmem::kv::db *db;
};
struct TxInserter {
TxInserter(pmem::kv::db *db) : tx(db->tx_begin().get_value())
{
}
pmem::kv::status put(pmem::kv::string_view key, pmem::kv::string_view value)
{
return tx.put(key, value);
}
pmem::kv::status commit()
{
return tx.commit();
}
private:
pmem::kv::tx tx;
};
static void ThreadBody(void *v)
{
ThreadArg *arg = reinterpret_cast<ThreadArg *>(v);
SharedState *shared = arg->shared;
ThreadState *thread = arg->thread;
{
MutexLock l(&shared->mu);
shared->num_initialized++;
if (shared->num_initialized >= shared->total) {
shared->cv.SignalAll();
}
while (!shared->start) {
shared->cv.Wait();
}
}
thread->stats.Start();
(arg->bm->*(arg->method))(thread);
thread->stats.Stop();
{
MutexLock l(&shared->mu);
shared->num_done++;
if (shared->num_done >= shared->total) {
shared->cv.SignalAll();
}
}
}
void Create(std::string name)
{
assert(kv_ == nullptr);
auto start = g_env->NowMicros();
auto size = 512ULL * 1024ULL * 1024ULL * FLAGS_db_size_in_gb;
pmem::kv::config cfg;
auto cfg_s = cfg.put_string("path", FLAGS_db);
if (cfg_s != pmem::kv::status::OK)
throw std::runtime_error("putting 'path' to config failed");
cfg_s = cfg.put_uint64("force_create", 1);
if (cfg_s != pmem::kv::status::OK)
throw std::runtime_error("putting 'force_create' to config failed");
cfg_s = cfg.put_uint64("size", size);
if (cfg_s != pmem::kv::status::OK)
throw std::runtime_error("putting 'size' to config failed");
/* Check if the path is a directory or a file
* (we don't pass filename in case of memkind
* based engines, only dir). If it is a file,
* remove the previous file with the same name. */
struct stat info;
if (stat(FLAGS_db, &info) == 0 && !(info.st_mode & S_IFDIR))
{
auto start = g_env->NowMicros();
/* Remove pool file. This should be
* implemented using libpmempool for backward
* compatibility. */
if (pmempool_rm(FLAGS_db, PMEMPOOL_RM_FORCE) != 0) {
throw std::runtime_error(std::string("Cannot remove pool: ") + FLAGS_db);
}
logger.insert("Remove [millis/op]", ((g_env->NowMicros() - start) * 1e-3));
}
kv_ = new pmem::kv::db;
auto s = kv_->open(engine, std::move(cfg));
if (s != pmem::kv::status::OK) {
fprintf(stderr,
"Cannot start engine (%s) for path (%s) with %i GB capacity\n%s\n\nUSAGE: %s",
engine, FLAGS_db, FLAGS_db_size_in_gb, pmem::kv::errormsg().c_str(),
USAGE.c_str());
exit(-42);
}
logger.insert("Open [millis/op]", ((g_env->NowMicros() - start) * 1e-3));
}
template <typename Inserter = DbInserter>
void DoWrite(ThreadState *thread, bool seq)
{
if (num_ != FLAGS_num) {
char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_);
thread->stats.AddMessage(msg);
}
std::unique_ptr<const char[]> key_guard;
Slice key = AllocateKey(key_guard);
auto num = FLAGS_disjoint ? num_ / FLAGS_threads : num_;
auto start = FLAGS_disjoint ? thread->tid * num : 0;
auto end = FLAGS_disjoint ? (thread->tid + 1) * num : num_;
pmem::kv::status s;
int64_t bytes = 0;
auto batch_size = std::is_same<Inserter, TxInserter>::value ? tx_size_ : 1;
for (int n = start; n < end; n += batch_size) {
Inserter inserter(kv_);
for (int i = n; i < n + batch_size; i++) {
const int k = seq ? i : (thread->rand.Next() % num) + start;
GenerateKeyFromInt(k, FLAGS_num, &key);
std::string value = std::string();
value.append(value_size_, 'X');
s = inserter.put(key.ToString(), value);
bytes += value_size_ + key.size();
if (s != pmem::kv::status::OK) {
fprintf(stdout, "Out of space at key %i\n", i);
exit(1);
}
}
s = inserter.commit();
thread->stats.FinishedSingleOp();
if (s != pmem::kv::status::OK) {
fprintf(stdout, "Commit failed at batch %i\n", n);
exit(1);
}
}
thread->stats.AddBytes(bytes);
}
void WriteSeq(ThreadState *thread)
{
DoWrite<DbInserter>(thread, true);
}
void WriteRandom(ThreadState *thread)
{
DoWrite<DbInserter>(thread, false);
}
void DoRead(ThreadState *thread, bool seq, bool missing)
{
pmem::kv::status s;
int64_t bytes = 0;
int found = 0;
std::unique_ptr<const char[]> key_guard;
Slice key = AllocateKey(key_guard);
auto num = FLAGS_disjoint ? reads_ / FLAGS_threads : reads_;
auto start = FLAGS_disjoint ? thread->tid * num : 0;
auto end = FLAGS_disjoint ? (thread->tid + 1) * num : reads_;
for (int i = start; i < end; i++) {
const int k = seq ? i : (thread->rand.Next() % num) + start;
GenerateKeyFromInt(k, FLAGS_num, &key, missing);
std::string value;
if (kv_->get(key.ToString(), &value) == pmem::kv::status::OK)
found++;
thread->stats.FinishedSingleOp();
bytes += value.length() + key.size();
}
thread->stats.AddBytes(bytes);
char msg[100];
snprintf(msg, sizeof(msg), "(%d of %d found by one thread)", found, reads_);
thread->stats.AddMessage(msg);
}
void ReadSeq(ThreadState *thread)
{
DoRead(thread, true, false);
}
void ReadRandom(ThreadState *thread)
{
DoRead(thread, false, false);
}
void ReadMissing(ThreadState *thread)
{
DoRead(thread, false, true);
}
void DoDelete(ThreadState *thread, bool seq)
{
std::unique_ptr<const char[]> key_guard;
Slice key = AllocateKey(key_guard);
for (int i = 0; i < num_; i++) {
const int k = seq ? i : (thread->rand.Next() % FLAGS_num);
GenerateKeyFromInt(k, FLAGS_num, &key);
kv_->remove(key.ToString());
thread->stats.FinishedSingleOp();
}
}
void DeleteSeq(ThreadState *thread)
{
DoDelete(thread, true);
}
void DeleteRandom(ThreadState *thread)
{
DoDelete(thread, false);
}
void BGWriter(ThreadState *thread, enum OperationType write_merge)
{
// Special thread that keeps writing until other threads are done.
RandomGenerator gen;
int64_t bytes = 0;
// Don't merge stats from this thread with the readers.
thread->stats.SetExcludeFromMerge();
std::unique_ptr<const char[]> key_guard;
Slice key = AllocateKey(key_guard);
uint32_t written = 0;
bool hint_printed = false;
while (true) {
{
MutexLock l(&thread->shared->mu);
if (thread->shared->num_done + 1 >= thread->shared->num_initialized) {
// Finish the write immediately
break;
}
}
GenerateKeyFromInt(thread->rand.Next() % FLAGS_num, FLAGS_num, &key);
pmem::kv::status s;
if (write_merge == kWrite) {
s = kv_->put(key.ToString(), gen.Generate(value_size_).ToString());
} else {
fprintf(stderr, "Merge operation not supported\n");
exit(1);
}
written++;
if (s != pmem::kv::status::OK) {
fprintf(stderr, "Put error\n");
exit(1);
}
bytes += key.size() + value_size_;
}
thread->stats.AddBytes(bytes);
}
void ReadWhileWriting(ThreadState *thread)
{
if (thread->tid > 0) {
ReadRandom(thread);
} else {
BGWriter(thread, kWrite);
}
}
void ReadRandomWriteRandom(ThreadState *thread)
{
RandomGenerator gen;
std::string value;
int64_t found = 0;
int get_weight = 0;
int put_weight = 0;
int64_t reads_done = 0;
int64_t writes_done = 0;
int64_t bytes = 0;
Duration duration(FLAGS_duration, readwrites_);
std::unique_ptr<const char[]> key_guard;
Slice key = AllocateKey(key_guard);
// the number of iterations is the larger of read_ or write_
while (!duration.Done(1)) {
GenerateKeyFromInt(thread->rand.Next() % FLAGS_num, FLAGS_num, &key);
if (get_weight == 0 && put_weight == 0) {
// one batch completed, reinitialize for next batch
get_weight = FLAGS_readwritepercent;
put_weight = 100 - get_weight;
}
if (get_weight > 0) {
value.clear();
pmem::kv::status s = kv_->get(key.ToString(), &value);
if (s == pmem::kv::status::OK) {
found++;
} else if (s != pmem::kv::status::NOT_FOUND) {
fprintf(stderr, "get error\n");
}
bytes += value.length() + key.size();
get_weight--;
reads_done++;
thread->stats.FinishedSingleOp();
} else if (put_weight > 0) {
// then do all the corresponding number of puts
// for all the gets we have done earlier
pmem::kv::status s =
kv_->put(key.ToString(), gen.Generate(value_size_).ToString());
if (s != pmem::kv::status::OK) {
fprintf(stderr, "put error\n");
exit(1);
}
bytes += key.size() + value_size_;
put_weight--;
writes_done++;
thread->stats.FinishedSingleOp();
}
}
thread->stats.AddBytes(bytes);
char msg[100];
snprintf(msg, sizeof(msg),
"(reads:%" PRIu64 " writes:%" PRIu64 " total:%" PRIu64 " found:%" PRIu64 ")",
reads_done, writes_done, readwrites_, found);
thread->stats.AddMessage(msg);
}
void TxFillRandom(ThreadState *thread)
{
DoWrite<TxInserter>(thread, false);
}
};
/////////////////Page fault handling/////////////////
#include <bits/types/sig_atomic_t.h>
#include <bits/types/sigset_t.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <libpmem.h>
#define SIGSTKSZ 8192
#define SA_SIGINFO 4
#define SA_ONSTACK 0x08000000 /* Use signal stack by using `sa_restorer'. */
#define SA_RESTART 0x10000000 /* Restart syscall on signal return. */
#define SA_NODEFER 0x40000000 /* Don't automatically block the signal when*/
stack_t _sigstk;
int updated_page_count = 0;
int all_updates = 0;
void * checkpoint_start;
void * page[50];
void * device;
void cmd_issue( uint32_t opcode,
uint32_t TXID,
uint32_t TID,
uint32_t OID,
uint64_t data_addr,
uint32_t data_size,
void * ptr){
//command with thread id encoded as first 8 bits of each word
uint32_t issue_cmd[7];
issue_cmd[0] = (TID<<24)|(opcode<<16)|(TXID<<8)|TID;
issue_cmd[1] = (TID<<24)|(OID<<16)|(data_addr>>48);
issue_cmd[2] = (TID<<24)|((data_addr & 0x0000FFFFFFFFFFFF)>>24);
issue_cmd[3] = (TID<<24)|(data_addr & 0x0000000000FFFFFF);
issue_cmd[4] = (TID<<24)|(data_size<<8);
issue_cmd[5] = (TID<<24)|(0X00FFFFFF>>16);
issue_cmd[6] = (TID<<24)|((0X00FFFFFF & 0x0000FFFF)<<8);
for(int i=0;i<7;i++){
//printf("%d %08x\n",TID, issue_cmd[i]);
*((u_int32_t *) ptr) = issue_cmd[i];
}
}
static inline uint64_t getCycle(){
uint32_t cycles_high, cycles_low, pid;
asm volatile ("RDTSCP\n\t" // rdtscp into eax and edx
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"mov %%ecx, %2\n\t"
:"=r" (cycles_high), "=r" (cycles_low), "=r" (pid) //store in vars
:// no input
:"%eax", "%edx", "%ecx" // clobbered by rdtscp
);
return((uint64_t)cycles_high << 32) | cycles_low;
}
/// @brief Signal handler to trap SEGVs.
static void segvHandle(int signum, siginfo_t * siginfo, void * context) {
#define CPTIME
#ifdef CPTIME
uint64_t endCycles, startCycles,totalCycles;
startCycles = getCycle();
#endif
void * addr = siginfo->si_addr; // address of access
uint64_t pageNo = ((uint64_t)addr)/4096;
unsigned long * pageStart = (unsigned long *)(pageNo*4096);
// Check if this was a SEGV that we are supposed to trap.
if (siginfo->si_code == SEGV_ACCERR) {
mprotect(pageStart, 4096, PROT_READ|PROT_WRITE);
// printf("test1\n");
if(all_updates > 5 || updated_page_count == 50){
for(int i=0;i<updated_page_count;i++){
//memcpy(checkpoint_start + i*4096, page[i],4096);
//pmem_persist( checkpoint_start + i*4096,4096);
cmd_issue(2,0,0,0, (uint64_t)(checkpoint_start + i*4096),4096,device);
page[updated_page_count] = 0;
}
updated_page_count = 0;
all_updates = 0;
}
all_updates ++;
//printf("te\n");
for(int i=0; i<updated_page_count; i++){
if(page[i] == pageStart){
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
#endif
return;}
}
page[updated_page_count] = pageStart;
//printf("test1 %lx %d %d\n",page[updated_page_count],updated_page_count,all_updates);
updated_page_count++;
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
#endif
//*((int *)checkpoint_start) = 10;
//test++;
//printf("test1 %lx %d\n",updated_page_count);
} else if (siginfo->si_code == SEGV_MAPERR) {
fprintf (stderr, "%d : map error with addr %p!\n", getpid(), addr);
abort();
} else {
fprintf (stderr, "%d : other access error with addr %p.\n", getpid(), addr);
abort();
}
}
static void installSignalHandler(void) {
// Set up an alternate signal stack.
printf("page fault handler initialized!!\n");
_sigstk.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
_sigstk.ss_size = SIGSTKSZ;
_sigstk.ss_flags = 0;
sigaltstack(&_sigstk, (stack_t *) 0);
// Now set up a signal handler for SIGSEGV events.
struct sigaction siga;
sigemptyset(&siga.sa_mask);
// Set the following signals to a set
sigaddset(&siga.sa_mask, SIGSEGV);
sigaddset(&siga.sa_mask, SIGALRM);
sigprocmask(SIG_BLOCK, &siga.sa_mask, NULL);
// Point to the handler function.
siga.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART | SA_NODEFER;
siga.sa_sigaction = segvHandle;
if (sigaction(SIGSEGV, &siga, NULL) == -1) {
perror("sigaction(SIGSEGV)");
exit(-1);
}
sigprocmask(SIG_UNBLOCK, &siga.sa_mask, NULL);
return;
}
//static void setpage(void * addr){
// uint64_t pageNo = ((uint64_t)addr)/4096;
// unsigned long * pageStart = (unsigned long *)(pageNo*4096);
// mprotect(pageStart, 4096, PROT_READ);
// return;
//}
static void resetpage(void * addr){
uint64_t pageNo = ((uint64_t)addr)/4096;
unsigned long * pageStart = (unsigned long *)(pageNo*4096);
mprotect(pageStart, 4096, PROT_READ|PROT_WRITE);
return;
}
void* open_device(const char* pathname)
{
//int fd = os_open("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0",O_RDWR|O_SYNC);
int fd = open(pathname,O_RDWR|O_SYNC);
if(fd == -1)
{
printf("Couldnt opene file!!\n");
exit(0);
}
void * ptr = mmap(0,4096,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);
if(ptr == (void *)-1)
{
printf("Could not map memory!!\n");
exit(0);
}
printf("opened device without error!!\n");
return ptr;
}
///////////////////////////////////////////////////////////////
void installSignalHandler (void) __attribute__ ((constructor));
int main(int argc, char **argv)
{
size_t mapped_len1;
int is_pmem1;
if ((checkpoint_start = pmem_map_file("/mnt/mem/checkpoint", 4096*50,
PMEM_FILE_CREATE, 0666, &mapped_len1, &is_pmem1)) == NULL) {
fprintf(stderr, "pmem_map_file failed\n");
exit(0);
}
device = open_device("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0");
// Default list of comma-separated operations to run
static const char *FLAGS_benchmarks =
"fillseq,fillrandom,overwrite,readseq,readrandom,readmissing,deleteseq,deleterandom,readwhilewriting,readrandomwriterandom";
// Default engine name
static const char *FLAGS_engine = "cmap";
// Print usage statement if necessary
if (argc != 1) {
if ((strcmp(argv[1], "?") == 0) || (strcmp(argv[1], "-?") == 0) ||
(strcmp(argv[1], "h") == 0) || (strcmp(argv[1], "-h") == 0) ||
(strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "--help") == 0)) {
fprintf(stderr, "%s", USAGE.c_str());
exit(1);
}
}
// Parse command-line arguments
for (int i = 1; i < argc; i++) {
int n;
char junk;
if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
} else if (strncmp(argv[i], "--engine=", 9) == 0) {
FLAGS_engine = argv[i] + 9;
} else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 && (n == 0 || n == 1)) {
FLAGS_histogram = n;
} else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
FLAGS_num = n;
} else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
FLAGS_reads = n;
} else if (sscanf(argv[i], "--threads=%d%c", &n, &junk) == 1) {
FLAGS_threads = n;
} else if (sscanf(argv[i], "--key_size=%d%c", &n, &junk) == 1) {
FLAGS_key_size = n;
} else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
FLAGS_value_size = n;
} else if (sscanf(argv[i], "--readwritepercent=%d%c", &n, &junk) == 1) {
FLAGS_readwritepercent = n;
} else if (strncmp(argv[i], "--db=", 5) == 0) {
FLAGS_db = argv[i] + 5;
} else if (sscanf(argv[i], "--db_size_in_gb=%d%c", &n, &junk) == 1) {
FLAGS_db_size_in_gb = n;
} else if (sscanf(argv[i], "--tx_size=%d%c", &n, &junk) == 1) {
FLAGS_tx_size = n;
} else if (sscanf(argv[i], "--disjoint=%d%c", &n, &junk) == 1 && (n == 0 || n == 1)) {
FLAGS_disjoint = n;
} else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1);
}
}
// Run benchmark against default environment
g_env = leveldb::Env::Default();
BenchmarkLogger logger = BenchmarkLogger();
int return_value = 0;
pmem::kv::db *kv = NULL;
const char *benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
const char *sep = strchr(benchmarks, ',');
Slice name;
if (sep == NULL) {
name = benchmarks;
benchmarks = NULL;
} else {
name = Slice(benchmarks, sep - benchmarks);
benchmarks = sep + 1;
}
try {
auto benchmark = Benchmark(name, kv, FLAGS_threads, FLAGS_engine, logger);
benchmark.Run();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return_value = 1;
break;
}
}
if (kv != NULL) {
kv->close();
delete kv;
}
logger.print();
if (FLAGS_histogram) {
logger.print_histogram();
}
return return_value;
}
| 35,996 | 25.984258 | 126 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/csv.h | // SPDX-License-Identifier: Apache-2.0
/* Copyright 2020-2021, Intel Corporation */
#pragma once
#include <iostream>
#include <map>
#include <ostream>
#include <set>
#include <string>
template <typename IdType>
class CSV {
private:
/* Hold data in two-dimensional map of strings: data_matrix[row][column]
*/
std::map<IdType, std::map<std::string, std::string>> data_matrix;
/* List of all columns, which is filled during inserts. Needed for
* printing header and data in the same order.
* */
std::set<std::string> columns;
std::string id_name;
public:
CSV(std::string id_column_name) : id_name(id_column_name){};
void insert(IdType row, std::string column, std::string data)
{
columns.insert(column);
data_matrix[row][column] = data;
}
void insert(IdType row, std::string column, const char *data)
{
insert(row, column, std::string(data));
}
template <typename T>
void insert(IdType row, std::string column, T data)
{
insert(row, column, std::to_string(data));
}
void print()
{
// Print first column name
std::cout << id_name;
for (auto &column : columns) {
std::cout << "," << column;
}
std::cout << "\r\n" << std::flush;
for (auto &row : data_matrix) {
std::cout << row.first;
for (auto &column : columns) {
std::cout << "," << data_matrix[row.first][column];
}
std::cout << "\r\n" << std::flush;
}
}
};
| 1,381 | 21.290323 | 73 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/env.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
#include "leveldb/env.h"
namespace leveldb
{
Env::~Env()
{
}
Status Env::NewAppendableFile(const std::string &fname, WritableFile **result)
{
return Status::NotSupported("NewAppendableFile", fname);
}
SequentialFile::~SequentialFile()
{
}
RandomAccessFile::~RandomAccessFile()
{
}
WritableFile::~WritableFile()
{
}
Logger::~Logger()
{
}
FileLock::~FileLock()
{
}
void Log(Logger *info_log, const char *format, ...)
{
if (info_log != NULL) {
va_list ap;
va_start(ap, format);
info_log->Logv(format, ap);
va_end(ap);
}
}
static Status DoWriteStringToFile(Env *env, const Slice &data, const std::string &fname, bool should_sync)
{
WritableFile *file;
Status s = env->NewWritableFile(fname, &file);
if (!s.ok()) {
return s;
}
s = file->Append(data);
if (s.ok() && should_sync) {
s = file->Sync();
}
if (s.ok()) {
s = file->Close();
}
delete file; // Will auto-close if we did not close above
if (!s.ok()) {
env->DeleteFile(fname);
}
return s;
}
Status WriteStringToFile(Env *env, const Slice &data, const std::string &fname)
{
return DoWriteStringToFile(env, data, fname, false);
}
Status WriteStringToFileSync(Env *env, const Slice &data, const std::string &fname)
{
return DoWriteStringToFile(env, data, fname, true);
}
Status ReadFileToString(Env *env, const std::string &fname, std::string *data)
{
data->clear();
SequentialFile *file;
Status s = env->NewSequentialFile(fname, &file);
if (!s.ok()) {
return s;
}
static const int kBufferSize = 8192;
char *space = new char[kBufferSize];
while (true) {
Slice fragment;
s = file->Read(kBufferSize, &fragment, space);
if (!s.ok()) {
break;
}
data->append(fragment.data(), fragment.size());
if (fragment.empty()) {
break;
}
}
delete[] space;
delete file;
return s;
}
EnvWrapper::~EnvWrapper()
{
}
} // namespace leveldb
| 2,069 | 17.648649 | 106 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/logging.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "util/logging.h"
#include "leveldb/env.h"
#include "leveldb/slice.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
namespace leveldb
{
void AppendNumberTo(std::string *str, uint64_t num)
{
char buf[30];
snprintf(buf, sizeof(buf), "%llu", (unsigned long long)num);
str->append(buf);
}
void AppendEscapedStringTo(std::string *str, const Slice &value)
{
for (size_t i = 0; i < value.size(); i++) {
char c = value[i];
if (c >= ' ' && c <= '~') {
str->push_back(c);
} else {
char buf[10];
snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned int>(c) & 0xff);
str->append(buf);
}
}
}
std::string NumberToString(uint64_t num)
{
std::string r;
AppendNumberTo(&r, num);
return r;
}
std::string EscapeString(const Slice &value)
{
std::string r;
AppendEscapedStringTo(&r, value);
return r;
}
bool ConsumeDecimalNumber(Slice *in, uint64_t *val)
{
uint64_t v = 0;
int digits = 0;
while (!in->empty()) {
char c = (*in)[0];
if (c >= '0' && c <= '9') {
++digits;
// |delta| intentionally unit64_t to avoid Android crash (see log).
const uint64_t delta = (c - '0');
static const uint64_t kMaxUint64 = ~static_cast<uint64_t>(0);
if (v > kMaxUint64 / 10 || (v == kMaxUint64 / 10 && delta > kMaxUint64 % 10)) {
// Overflow
return false;
}
v = (v * 10) + delta;
in->remove_prefix(1);
} else {
break;
}
}
*val = v;
return (digits > 0);
}
} // namespace leveldb
| 1,775 | 20.925926 | 82 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/logging.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// Must not be included from any .h files to avoid polluting the namespace
// with macros.
#ifndef STORAGE_LEVELDB_UTIL_LOGGING_H_
#define STORAGE_LEVELDB_UTIL_LOGGING_H_
#include "port/port_posix.h"
#include <stdint.h>
#include <stdio.h>
#include <string>
namespace leveldb
{
class Slice;
class WritableFile;
// Append a human-readable printout of "num" to *str
extern void AppendNumberTo(std::string *str, uint64_t num);
// Append a human-readable printout of "value" to *str.
// Escapes any non-printable characters found in "value".
extern void AppendEscapedStringTo(std::string *str, const Slice &value);
// Return a human-readable printout of "num"
extern std::string NumberToString(uint64_t num);
// Return a human-readable version of "value".
// Escapes any non-printable characters found in "value".
extern std::string EscapeString(const Slice &value);
// Parse a human-readable number from "*in" into *value. On success,
// advances "*in" past the consumed number and sets "*val" to the
// numeric value. Otherwise, returns false and leaves *in in an
// unspecified state.
extern bool ConsumeDecimalNumber(Slice *in, uint64_t *val);
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_LOGGING_H_
| 1,519 | 30.666667 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/status.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "leveldb/status.h"
#include "port/port_posix.h"
#include <stdio.h>
namespace leveldb
{
const char *Status::CopyState(const char *state)
{
uint32_t size;
memcpy(&size, state, sizeof(size));
char *result = new char[size + 5];
memcpy(result, state, size + 5);
return result;
}
Status::Status(Code code, const Slice &msg, const Slice &msg2)
{
assert(code != kOk);
const uint32_t len1 = msg.size();
const uint32_t len2 = msg2.size();
const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
char *result = new char[size + 5];
memcpy(result, &size, sizeof(size));
result[4] = static_cast<char>(code);
memcpy(result + 5, msg.data(), len1);
if (len2) {
result[5 + len1] = ':';
result[6 + len1] = ' ';
memcpy(result + 7 + len1, msg2.data(), len2);
}
state_ = result;
}
std::string Status::ToString() const
{
if (state_ == NULL) {
return "OK";
} else {
char tmp[30];
const char *type;
switch (code()) {
case kOk:
type = "OK";
break;
case kNotFound:
type = "NotFound: ";
break;
case kCorruption:
type = "Corruption: ";
break;
case kNotSupported:
type = "Not implemented: ";
break;
case kInvalidArgument:
type = "Invalid argument: ";
break;
case kIOError:
type = "IO error: ";
break;
default:
snprintf(tmp, sizeof(tmp), "Unknown code(%d): ", static_cast<int>(code()));
type = tmp;
break;
}
std::string result(type);
uint32_t length;
memcpy(&length, state_, sizeof(length));
result.append(state_ + 5, length);
return result;
}
}
} // namespace leveldb
| 1,877 | 21.902439 | 81 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/testutil.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_TESTUTIL_H_
#define STORAGE_LEVELDB_UTIL_TESTUTIL_H_
#include "leveldb/env.h"
#include "leveldb/slice.h"
#include "util/random.h"
namespace leveldb
{
namespace test
{
// Store in *dst a random string of length "len" and return a Slice that
// references the generated data.
Slice RandomString(Random *rnd, int len, std::string *dst);
// Return a random key with the specified length that may contain interesting
// characters (e.g. \x00, \xff, etc.).
std::string RandomKey(Random *rnd, int len);
// Store in *dst a string of length "len" that will compress to
// "N*compressed_fraction" bytes and return a Slice that references
// the generated data.
Slice CompressibleString(Random *rnd, double compressed_fraction, size_t len, std::string *dst);
// A wrapper that allows injection of errors.
class ErrorEnv : public EnvWrapper {
public:
bool writable_file_error_;
int num_writable_file_errors_;
ErrorEnv() : EnvWrapper(Env::Default()), writable_file_error_(false), num_writable_file_errors_(0)
{
}
virtual Status NewWritableFile(const std::string &fname, WritableFile **result)
{
if (writable_file_error_) {
++num_writable_file_errors_;
*result = nullptr;
return Status::IOError(fname, "fake error");
}
return target()->NewWritableFile(fname, result);
}
virtual Status NewAppendableFile(const std::string &fname, WritableFile **result)
{
if (writable_file_error_) {
++num_writable_file_errors_;
*result = nullptr;
return Status::IOError(fname, "fake error");
}
return target()->NewAppendableFile(fname, result);
}
};
} // namespace test
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_TESTUTIL_H_
| 1,984 | 28.191176 | 99 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/mutexlock.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
#define STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
#include "port/port_posix.h"
#include "port/thread_annotations.h"
namespace leveldb
{
// Helper class that locks a mutex on construction and unlocks the mutex when
// the destructor of the MutexLock object is invoked.
//
// Typical usage:
//
// void MyClass::MyMethod() {
// MutexLock l(&mu_); // mu_ is an instance variable
// ... some complex code, possibly with multiple return paths ...
// }
class SCOPED_LOCKABLE MutexLock {
public:
explicit MutexLock(port::Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu)
{
this->mu_->Lock();
}
~MutexLock() UNLOCK_FUNCTION()
{
this->mu_->Unlock();
}
private:
port::Mutex *const mu_;
// No copying allowed
MutexLock(const MutexLock &);
void operator=(const MutexLock &);
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_
| 1,202 | 24.0625 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/histogram.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017-2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
#define STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
#include <string>
namespace leveldb
{
class Histogram {
public:
Histogram()
{
}
~Histogram()
{
}
void Clear();
void Add(double value);
void Merge(const Histogram &other);
std::string ToString() const;
double Median() const;
double Percentile(double p) const;
double Average() const;
double StandardDeviation() const;
private:
double min_;
double max_;
double num_;
double sum_;
double sum_squares_;
enum { kNumBuckets = 154 };
static const double kBucketLimit[kNumBuckets];
double buckets_[kNumBuckets];
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_HISTOGRAM_H_
| 993 | 18.490196 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/testutil.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
#include "util/testutil.h"
#include "util/random.h"
namespace leveldb
{
namespace test
{
Slice RandomString(Random *rnd, int len, std::string *dst)
{
dst->resize(len);
for (int i = 0; i < len; i++) {
(*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95)); // ' ' .. '~'
}
return Slice(*dst);
}
std::string RandomKey(Random *rnd, int len)
{
// Make sure to generate a wide variety of characters so we
// test the boundary conditions for short-key optimizations.
static const char kTestChars[] = {'\0', '\1', 'a', 'b', 'c', 'd', 'e', '\xfd', '\xfe', '\xff'};
std::string result;
for (int i = 0; i < len; i++) {
result += kTestChars[rnd->Uniform(sizeof(kTestChars))];
}
return result;
}
Slice CompressibleString(Random *rnd, double compressed_fraction, size_t len, std::string *dst)
{
int raw = static_cast<int>(len * compressed_fraction);
if (raw < 1)
raw = 1;
std::string raw_data;
RandomString(rnd, raw, &raw_data);
// Duplicate the random data until we have filled "len" bytes
dst->clear();
while (dst->size() < len) {
dst->append(raw_data);
}
dst->resize(len);
return Slice(*dst);
}
} // namespace test
} // namespace leveldb
| 1,384 | 24.648148 | 96 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/histogram.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "util/histogram.h"
#include "port/port_posix.h"
#include <math.h>
#include <stdio.h>
namespace leveldb
{
// clang-format off
const double Histogram::kBucketLimit[kNumBuckets] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 25, 30, 35, 40, 45,
50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 250, 300, 350, 400, 450,
500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000,
3500, 4000, 4500, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000,
16000, 18000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 60000,
70000, 80000, 90000, 100000, 120000, 140000, 160000, 180000, 200000,
250000, 300000, 350000, 400000, 450000, 500000, 600000, 700000, 800000,
900000, 1000000, 1200000, 1400000, 1600000, 1800000, 2000000, 2500000,
3000000, 3500000, 4000000, 4500000, 5000000, 6000000, 7000000, 8000000,
9000000, 10000000, 12000000, 14000000, 16000000, 18000000, 20000000,
25000000, 30000000, 35000000, 40000000, 45000000, 50000000, 60000000,
70000000, 80000000, 90000000, 100000000, 120000000, 140000000, 160000000,
180000000, 200000000, 250000000, 300000000, 350000000, 400000000,
450000000, 500000000, 600000000, 700000000, 800000000, 900000000,
1000000000, 1200000000, 1400000000, 1600000000, 1800000000, 2000000000,
2500000000.0, 3000000000.0, 3500000000.0, 4000000000.0, 4500000000.0,
5000000000.0, 6000000000.0, 7000000000.0, 8000000000.0, 9000000000.0,
1e200,
};
// clang-format on
void Histogram::Clear()
{
min_ = kBucketLimit[kNumBuckets - 1];
max_ = 0;
num_ = 0;
sum_ = 0;
sum_squares_ = 0;
for (int i = 0; i < kNumBuckets; i++) {
buckets_[i] = 0;
}
}
void Histogram::Add(double value)
{
// Linear search is fast enough for our usage in db_bench
int b = 0;
while (b < kNumBuckets - 1 && kBucketLimit[b] <= value) {
b++;
}
buckets_[b] += 1.0;
if (min_ > value)
min_ = value;
if (max_ < value)
max_ = value;
num_++;
sum_ += value;
sum_squares_ += (value * value);
}
void Histogram::Merge(const Histogram &other)
{
if (other.min_ < min_)
min_ = other.min_;
if (other.max_ > max_)
max_ = other.max_;
num_ += other.num_;
sum_ += other.sum_;
sum_squares_ += other.sum_squares_;
for (int b = 0; b < kNumBuckets; b++) {
buckets_[b] += other.buckets_[b];
}
}
double Histogram::Median() const
{
return Percentile(50.0);
}
double Histogram::Percentile(double p) const
{
double threshold = num_ * (p / 100.0);
double sum = 0;
for (int b = 0; b < kNumBuckets; b++) {
sum += buckets_[b];
if (sum >= threshold) {
// Scale linearly within this bucket
double left_point = (b == 0) ? 0 : kBucketLimit[b - 1];
double right_point = kBucketLimit[b];
double left_sum = sum - buckets_[b];
double right_sum = sum;
double pos = (threshold - left_sum) / (right_sum - left_sum);
double r = left_point + (right_point - left_point) * pos;
if (r < min_)
r = min_;
if (r > max_)
r = max_;
return r;
}
}
return max_;
}
double Histogram::Average() const
{
if (num_ == 0.0)
return 0;
return sum_ / num_;
}
double Histogram::StandardDeviation() const
{
if (num_ == 0.0)
return 0;
double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_);
return sqrt(variance);
}
std::string Histogram::ToString() const
{
std::string r;
char buf[200];
snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, Average(),
StandardDeviation());
r.append(buf);
snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", (num_ == 0.0 ? 0.0 : min_),
Median(), max_);
r.append(buf);
snprintf(buf, sizeof(buf), "Percentiles: P50: %.2f P75: %.2f P99: %.2f P99.9: %.2f P99.99: %.2f\n",
Percentile(50), Percentile(75), Percentile(99), Percentile(99.9), Percentile(99.99));
r.append(buf);
r.append("------------------------------------------------------\n");
const double mult = 100.0 / num_;
double sum = 0;
for (int b = 0; b < kNumBuckets; b++) {
if (buckets_[b] <= 0.0)
continue;
sum += buckets_[b];
snprintf(buf, sizeof(buf), "[ %7.0f, %7.0f ) %7.0f %7.3f%% %7.3f%% ",
((b == 0) ? 0.0 : kBucketLimit[b - 1]), // left
kBucketLimit[b], // right
buckets_[b], // count
mult * buckets_[b], // percentage
mult * sum); // cumulative percentage
r.append(buf);
// Add hash marks based on percentage; 20 marks for 100%.
int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5);
r.append(marks, '#');
r.push_back('\n');
}
return r;
}
} // namespace leveldb
| 4,793 | 28.411043 | 100 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/env_posix.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include <deque>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits>
#include <pthread.h>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "leveldb/env.h"
#include "leveldb/slice.h"
#include "port/port_posix.h"
#include "util/env_posix_test_helper.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/posix_logger.h"
namespace leveldb
{
namespace
{
static int open_read_only_file_limit = -1;
static int mmap_limit = -1;
static const size_t kBufSize = 65536;
static Status PosixError(const std::string &context, int err_number)
{
if (err_number == ENOENT) {
return Status::NotFound(context, strerror(err_number));
} else {
return Status::IOError(context, strerror(err_number));
}
}
// Helper class to limit resource usage to avoid exhaustion.
// Currently used to limit read-only file descriptors and mmap file usage
// so that we do not end up running out of file descriptors, virtual memory,
// or running into kernel performance problems for very large databases.
class Limiter {
public:
// Limit maximum number of resources to |n|.
Limiter(intptr_t n)
{
SetAllowed(n);
}
// If another resource is available, acquire it and return true.
// Else return false.
bool Acquire()
{
if (GetAllowed() <= 0) {
return false;
}
MutexLock l(&mu_);
intptr_t x = GetAllowed();
if (x <= 0) {
return false;
} else {
SetAllowed(x - 1);
return true;
}
}
// Release a resource acquired by a previous call to Acquire() that returned
// true.
void Release()
{
MutexLock l(&mu_);
SetAllowed(GetAllowed() + 1);
}
private:
port::Mutex mu_;
port::AtomicPointer allowed_;
intptr_t GetAllowed() const
{
return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
}
// REQUIRES: mu_ must be held
void SetAllowed(intptr_t v)
{
allowed_.Release_Store(reinterpret_cast<void *>(v));
}
Limiter(const Limiter &);
void operator=(const Limiter &);
};
class PosixSequentialFile : public SequentialFile {
private:
std::string filename_;
int fd_;
public:
PosixSequentialFile(const std::string &fname, int fd) : filename_(fname), fd_(fd)
{
}
virtual ~PosixSequentialFile()
{
close(fd_);
}
virtual Status Read(size_t n, Slice *result, char *scratch)
{
Status s;
while (true) {
ssize_t r = read(fd_, scratch, n);
if (r < 0) {
if (errno == EINTR) {
continue; // Retry
}
s = PosixError(filename_, errno);
break;
}
*result = Slice(scratch, r);
break;
}
return s;
}
virtual Status Skip(uint64_t n)
{
if (lseek(fd_, n, SEEK_CUR) == static_cast<off_t>(-1)) {
return PosixError(filename_, errno);
}
return Status::OK();
}
};
// pread() based random-access
class PosixRandomAccessFile : public RandomAccessFile {
private:
std::string filename_;
bool temporary_fd_; // If true, fd_ is -1 and we open on every read.
int fd_;
Limiter *limiter_;
public:
PosixRandomAccessFile(const std::string &fname, int fd, Limiter *limiter)
: filename_(fname), fd_(fd), limiter_(limiter)
{
temporary_fd_ = !limiter->Acquire();
if (temporary_fd_) {
// Open file on every access.
close(fd_);
fd_ = -1;
}
}
virtual ~PosixRandomAccessFile()
{
if (!temporary_fd_) {
close(fd_);
limiter_->Release();
}
}
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const
{
int fd = fd_;
if (temporary_fd_) {
fd = open(filename_.c_str(), O_RDONLY);
if (fd < 0) {
return PosixError(filename_, errno);
}
}
Status s;
ssize_t r = pread(fd, scratch, n, static_cast<off_t>(offset));
*result = Slice(scratch, (r < 0) ? 0 : r);
if (r < 0) {
// An error: return a non-ok status
s = PosixError(filename_, errno);
}
if (temporary_fd_) {
// Close the temporary file descriptor opened earlier.
close(fd);
}
return s;
}
};
// mmap() based random-access
class PosixMmapReadableFile : public RandomAccessFile {
private:
std::string filename_;
void *mmapped_region_;
size_t length_;
Limiter *limiter_;
public:
// base[0,length-1] contains the mmapped contents of the file.
PosixMmapReadableFile(const std::string &fname, void *base, size_t length, Limiter *limiter)
: filename_(fname), mmapped_region_(base), length_(length), limiter_(limiter)
{
}
virtual ~PosixMmapReadableFile()
{
munmap(mmapped_region_, length_);
limiter_->Release();
}
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const
{
Status s;
if (offset + n > length_) {
*result = Slice();
s = PosixError(filename_, EINVAL);
} else {
*result = Slice(reinterpret_cast<char *>(mmapped_region_) + offset, n);
}
return s;
}
};
class PosixWritableFile : public WritableFile {
private:
// buf_[0, pos_-1] contains data to be written to fd_.
std::string filename_;
int fd_;
char buf_[kBufSize];
size_t pos_;
public:
PosixWritableFile(const std::string &fname, int fd) : filename_(fname), fd_(fd), pos_(0)
{
}
~PosixWritableFile()
{
if (fd_ >= 0) {
// Ignoring any potential errors
Close();
}
}
virtual Status Append(const Slice &data)
{
size_t n = data.size();
const char *p = data.data();
// Fit as much as possible into buffer.
size_t copy = std::min(n, kBufSize - pos_);
memcpy(buf_ + pos_, p, copy);
p += copy;
n -= copy;
pos_ += copy;
if (n == 0) {
return Status::OK();
}
// Can't fit in buffer, so need to do at least one write.
Status s = FlushBuffered();
if (!s.ok()) {
return s;
}
// Small writes go to buffer, large writes are written directly.
if (n < kBufSize) {
memcpy(buf_, p, n);
pos_ = n;
return Status::OK();
}
return WriteRaw(p, n);
}
virtual Status Close()
{
Status result = FlushBuffered();
const int r = close(fd_);
if (r < 0 && result.ok()) {
result = PosixError(filename_, errno);
}
fd_ = -1;
return result;
}
virtual Status Flush()
{
return FlushBuffered();
}
Status SyncDirIfManifest()
{
const char *f = filename_.c_str();
const char *sep = strrchr(f, '/');
Slice basename;
std::string dir;
if (sep == NULL) {
dir = ".";
basename = f;
} else {
dir = std::string(f, sep - f);
basename = sep + 1;
}
Status s;
if (basename.starts_with("MANIFEST")) {
int fd = open(dir.c_str(), O_RDONLY);
if (fd < 0) {
s = PosixError(dir, errno);
} else {
if (fsync(fd) < 0) {
s = PosixError(dir, errno);
}
close(fd);
}
}
return s;
}
virtual Status Sync()
{
// Ensure new files referred to by the manifest are in the filesystem.
Status s = SyncDirIfManifest();
if (!s.ok()) {
return s;
}
s = FlushBuffered();
if (s.ok()) {
if (fdatasync(fd_) != 0) {
s = PosixError(filename_, errno);
}
}
return s;
}
private:
Status FlushBuffered()
{
Status s = WriteRaw(buf_, pos_);
pos_ = 0;
return s;
}
Status WriteRaw(const char *p, size_t n)
{
while (n > 0) {
ssize_t r = write(fd_, p, n);
if (r < 0) {
if (errno == EINTR) {
continue; // Retry
}
return PosixError(filename_, errno);
}
p += r;
n -= r;
}
return Status::OK();
}
};
static int LockOrUnlock(int fd, bool lock)
{
errno = 0;
struct flock f;
memset(&f, 0, sizeof(f));
f.l_type = (lock ? F_WRLCK : F_UNLCK);
f.l_whence = SEEK_SET;
f.l_start = 0;
f.l_len = 0; // Lock/unlock entire file
return fcntl(fd, F_SETLK, &f);
}
class PosixFileLock : public FileLock {
public:
int fd_;
std::string name_;
};
// Set of locked files. We keep a separate set instead of just
// relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
// any protection against multiple uses from the same process.
class PosixLockTable {
private:
port::Mutex mu_;
std::set<std::string> locked_files_;
public:
bool Insert(const std::string &fname)
{
MutexLock l(&mu_);
return locked_files_.insert(fname).second;
}
void Remove(const std::string &fname)
{
MutexLock l(&mu_);
locked_files_.erase(fname);
}
};
class PosixEnv : public Env {
public:
PosixEnv();
virtual ~PosixEnv()
{
char msg[] = "Destroying Env::Default()\n";
fwrite(msg, 1, sizeof(msg), stderr);
abort();
}
virtual Status NewSequentialFile(const std::string &fname, SequentialFile **result)
{
int fd = open(fname.c_str(), O_RDONLY);
if (fd < 0) {
*result = NULL;
return PosixError(fname, errno);
} else {
*result = new PosixSequentialFile(fname, fd);
return Status::OK();
}
}
virtual Status NewRandomAccessFile(const std::string &fname, RandomAccessFile **result)
{
*result = NULL;
Status s;
int fd = open(fname.c_str(), O_RDONLY);
if (fd < 0) {
s = PosixError(fname, errno);
} else if (mmap_limit_.Acquire()) {
uint64_t size;
s = GetFileSize(fname, &size);
if (s.ok()) {
void *base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
if (base != MAP_FAILED) {
*result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
} else {
s = PosixError(fname, errno);
}
}
close(fd);
if (!s.ok()) {
mmap_limit_.Release();
}
} else {
*result = new PosixRandomAccessFile(fname, fd, &fd_limit_);
}
return s;
}
virtual Status NewWritableFile(const std::string &fname, WritableFile **result)
{
Status s;
int fd = open(fname.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
*result = NULL;
s = PosixError(fname, errno);
} else {
*result = new PosixWritableFile(fname, fd);
}
return s;
}
virtual Status NewAppendableFile(const std::string &fname, WritableFile **result)
{
Status s;
int fd = open(fname.c_str(), O_APPEND | O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
*result = NULL;
s = PosixError(fname, errno);
} else {
*result = new PosixWritableFile(fname, fd);
}
return s;
}
virtual bool FileExists(const std::string &fname)
{
return access(fname.c_str(), F_OK) == 0;
}
virtual Status GetChildren(const std::string &dir, std::vector<std::string> *result)
{
result->clear();
DIR *d = opendir(dir.c_str());
if (d == NULL) {
return PosixError(dir, errno);
}
struct dirent *entry;
while ((entry = readdir(d)) != NULL) {
result->push_back(entry->d_name);
}
closedir(d);
return Status::OK();
}
virtual Status DeleteFile(const std::string &fname)
{
Status result;
if (unlink(fname.c_str()) != 0) {
result = PosixError(fname, errno);
}
return result;
}
virtual Status CreateDir(const std::string &name)
{
Status result;
if (mkdir(name.c_str(), 0755) != 0) {
result = PosixError(name, errno);
}
return result;
}
virtual Status DeleteDir(const std::string &name)
{
Status result;
if (rmdir(name.c_str()) != 0) {
result = PosixError(name, errno);
}
return result;
}
virtual Status GetFileSize(const std::string &fname, uint64_t *size)
{
Status s;
struct stat sbuf;
if (stat(fname.c_str(), &sbuf) != 0) {
*size = 0;
s = PosixError(fname, errno);
} else {
*size = sbuf.st_size;
}
return s;
}
virtual Status RenameFile(const std::string &src, const std::string &target)
{
Status result;
if (rename(src.c_str(), target.c_str()) != 0) {
result = PosixError(src, errno);
}
return result;
}
virtual Status LockFile(const std::string &fname, FileLock **lock)
{
*lock = NULL;
Status result;
int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
if (fd < 0) {
result = PosixError(fname, errno);
} else if (!locks_.Insert(fname)) {
close(fd);
result = Status::IOError("lock " + fname, "already held by process");
} else if (LockOrUnlock(fd, true) == -1) {
result = PosixError("lock " + fname, errno);
close(fd);
locks_.Remove(fname);
} else {
PosixFileLock *my_lock = new PosixFileLock;
my_lock->fd_ = fd;
my_lock->name_ = fname;
*lock = my_lock;
}
return result;
}
virtual Status UnlockFile(FileLock *lock)
{
PosixFileLock *my_lock = reinterpret_cast<PosixFileLock *>(lock);
Status result;
if (LockOrUnlock(my_lock->fd_, false) == -1) {
result = PosixError("unlock", errno);
}
locks_.Remove(my_lock->name_);
close(my_lock->fd_);
delete my_lock;
return result;
}
virtual void Schedule(void (*function)(void *), void *arg);
virtual void StartThread(void (*function)(void *arg), void *arg);
virtual Status GetTestDirectory(std::string *result)
{
const char *env = getenv("TEST_TMPDIR");
if (env && env[0] != '\0') {
*result = env;
} else {
char buf[100];
snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
*result = buf;
}
// Directory may already exist
CreateDir(*result);
return Status::OK();
}
static uint64_t gettid()
{
pthread_t tid = pthread_self();
uint64_t thread_id = 0;
memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
return thread_id;
}
virtual Status NewLogger(const std::string &fname, Logger **result)
{
FILE *f = fopen(fname.c_str(), "w");
if (f == NULL) {
*result = NULL;
return PosixError(fname, errno);
} else {
*result = new PosixLogger(f, &PosixEnv::gettid);
return Status::OK();
}
}
virtual uint64_t NowMicros()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
}
virtual void SleepForMicroseconds(int micros)
{
usleep(micros);
}
private:
void PthreadCall(const char *label, int result)
{
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
// BGThread() is the body of the background thread
void BGThread();
static void *BGThreadWrapper(void *arg)
{
reinterpret_cast<PosixEnv *>(arg)->BGThread();
return NULL;
}
pthread_mutex_t mu_;
pthread_cond_t bgsignal_;
pthread_t bgthread_;
bool started_bgthread_;
// Entry per Schedule() call
struct BGItem {
void *arg;
void (*function)(void *);
};
typedef std::deque<BGItem> BGQueue;
BGQueue queue_;
PosixLockTable locks_;
Limiter mmap_limit_;
Limiter fd_limit_;
};
// Return the maximum number of concurrent mmaps.
static int MaxMmaps()
{
if (mmap_limit >= 0) {
return mmap_limit;
}
// Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
mmap_limit = sizeof(void *) >= 8 ? 1000 : 0;
return mmap_limit;
}
// Return the maximum number of read-only files to keep open.
static intptr_t MaxOpenFiles()
{
if (open_read_only_file_limit >= 0) {
return open_read_only_file_limit;
}
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim)) {
// getrlimit failed, fallback to hard-coded default.
open_read_only_file_limit = 50;
} else if (rlim.rlim_cur == RLIM_INFINITY) {
open_read_only_file_limit = std::numeric_limits<int>::max();
} else {
// Allow use of 20% of available file descriptors for read-only files.
open_read_only_file_limit = rlim.rlim_cur / 5;
}
return open_read_only_file_limit;
}
PosixEnv::PosixEnv() : started_bgthread_(false), mmap_limit_(MaxMmaps()), fd_limit_(MaxOpenFiles())
{
PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
}
void PosixEnv::Schedule(void (*function)(void *), void *arg)
{
PthreadCall("lock", pthread_mutex_lock(&mu_));
// Start background thread if necessary
if (!started_bgthread_) {
started_bgthread_ = true;
PthreadCall("create thread",
pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
}
// If the queue is currently empty, the background thread may currently be
// waiting.
if (queue_.empty()) {
PthreadCall("signal", pthread_cond_signal(&bgsignal_));
}
// Add to priority queue
queue_.push_back(BGItem());
queue_.back().function = function;
queue_.back().arg = arg;
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
}
void PosixEnv::BGThread()
{
while (true) {
// Wait until there is an item that is ready to run
PthreadCall("lock", pthread_mutex_lock(&mu_));
while (queue_.empty()) {
PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
}
void (*function)(void *) = queue_.front().function;
void *arg = queue_.front().arg;
queue_.pop_front();
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
(*function)(arg);
}
}
namespace
{
struct StartThreadState {
void (*user_function)(void *);
void *arg;
};
}
static void *StartThreadWrapper(void *arg)
{
StartThreadState *state = reinterpret_cast<StartThreadState *>(arg);
state->user_function(state->arg);
delete state;
return NULL;
}
void PosixEnv::StartThread(void (*function)(void *arg), void *arg)
{
pthread_t t;
StartThreadState *state = new StartThreadState;
state->user_function = function;
state->arg = arg;
PthreadCall("start thread", pthread_create(&t, NULL, &StartThreadWrapper, state));
}
} // namespace
static pthread_once_t once = PTHREAD_ONCE_INIT;
static Env *default_env;
static void InitDefaultEnv()
{
default_env = new PosixEnv;
}
void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit)
{
assert(default_env == NULL);
open_read_only_file_limit = limit;
}
void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit)
{
assert(default_env == NULL);
mmap_limit = limit;
}
Env *Env::Default()
{
pthread_once(&once, InitDefaultEnv);
return default_env;
}
} // namespace leveldb
| 17,689 | 20.812577 | 99 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/random.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_
#define STORAGE_LEVELDB_UTIL_RANDOM_H_
#include <stdint.h>
namespace leveldb
{
// A very simple random number generator. Not especially good at
// generating truly random bits, but good enough for our needs in this
// package.
class Random {
private:
uint32_t seed_;
public:
explicit Random(uint32_t s) : seed_(s & 0x7fffffffu)
{
// Avoid bad seeds.
if (seed_ == 0 || seed_ == 2147483647L) {
seed_ = 1;
}
}
uint32_t Next()
{
static const uint32_t M = 2147483647L; // 2^31-1
static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
// We are computing
// seed_ = (seed_ * A) % M, where M = 2^31-1
//
// seed_ must not be zero or M, or else all subsequent computed values
// will be zero or M respectively. For all other values, seed_ will end
// up cycling through every number in [1,M-1]
uint64_t product = seed_ * A;
// Compute (product % M) using the fact that ((x << 31) % M) == x.
seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
// The first reduction may overflow by 1 bit, so we may need to
// repeat. mod == M is not possible; using > allows the faster
// sign-bit-based test.
if (seed_ > M) {
seed_ -= M;
}
return seed_;
}
// Returns a uniformly distributed value in the range [0..n-1]
// REQUIRES: n > 0
uint32_t Uniform(int n)
{
return Next() % n;
}
// Randomly returns true ~"1/n" of the time, and false otherwise.
// REQUIRES: n > 0
bool OneIn(int n)
{
return (Next() % n) == 0;
}
// Skewed: pick "base" uniformly from range [0,max_log] and then
// return "base" random bits. The effect is to pick a number in the
// range [0,2^max_log-1] with exponential bias towards smaller numbers.
uint32_t Skewed(int max_log)
{
return Uniform(1 << Uniform(max_log + 1));
}
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_RANDOM_H_
| 2,202 | 26.886076 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/posix_logger.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
//
// Logger implementation that can be shared by all environments
// where enough posix functionality is available.
#ifndef STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
#define STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
#include "leveldb/env.h"
#include <algorithm>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
namespace leveldb
{
class PosixLogger : public Logger {
private:
FILE *file_;
uint64_t (*gettid_)(); // Return the thread id for the current thread
public:
PosixLogger(FILE *f, uint64_t (*gettid)()) : file_(f), gettid_(gettid)
{
}
virtual ~PosixLogger()
{
fclose(file_);
}
virtual void Logv(const char *format, va_list ap)
{
const uint64_t thread_id = (*gettid_)();
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char *base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char *p = base;
char *limit = base + bufsize;
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
const time_t seconds = now_tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
p += snprintf(p, limit - p, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min,
t.tm_sec, static_cast<int>(now_tv.tv_usec),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
fwrite(base, 1, p - base, file_);
fflush(file_);
if (base != buffer) {
delete[] base;
}
break;
}
}
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_
| 2,503 | 23.54902 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/util/env_posix_test_helper.h | // Copyright 2017 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
#define STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
namespace leveldb
{
class EnvPosixTest;
// A helper for the POSIX Env to facilitate testing.
class EnvPosixTestHelper {
private:
friend class EnvPosixTest;
// Set the maximum number of read-only files that will be opened.
// Must be called before creating an Env.
static void SetReadOnlyFDLimit(int limit);
// Set the maximum number of read-only files that will be mapped via mmap.
// Must be called before creating an Env.
static void SetReadOnlyMMapLimit(int limit);
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_
| 967 | 28.333333 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/port/port_posix.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// See port_example.h for documentation for the following types/functions.
#ifndef STORAGE_LEVELDB_PORT_PORT_POSIX_H_
#define STORAGE_LEVELDB_PORT_PORT_POSIX_H_
#undef PLATFORM_IS_LITTLE_ENDIAN
#if defined(__APPLE__)
#include <machine/endian.h>
#if defined(__DARWIN_LITTLE_ENDIAN) && defined(__DARWIN_BYTE_ORDER)
#define PLATFORM_IS_LITTLE_ENDIAN (__DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN)
#endif
#elif defined(OS_SOLARIS)
#include <sys/isa_defs.h>
#ifdef _LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN true
#else
#define PLATFORM_IS_LITTLE_ENDIAN false
#endif
#elif defined(OS_FREEBSD) || defined(OS_OPENBSD) || defined(OS_NETBSD) || defined(OS_DRAGONFLYBSD)
#include <sys/endian.h>
#include <sys/types.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#elif defined(OS_HPUX)
#define PLATFORM_IS_LITTLE_ENDIAN false
#elif defined(OS_ANDROID)
// Due to a bug in the NDK x86 <sys/endian.h> definition,
// _BYTE_ORDER must be used instead of __BYTE_ORDER on Android.
// See http://code.google.com/p/android/issues/detail?id=39824
#include <endian.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#else
#include <endian.h>
#endif
#include <pthread.h>
#if defined(HAVE_CRC32C)
#include <crc32c/crc32c.h>
#endif // defined(HAVE_CRC32C)
#ifdef HAVE_SNAPPY
#include <snappy.h>
#endif // defined(HAVE_SNAPPY)
#include "port/atomic_pointer.h"
#include <stdint.h>
#include <string>
#ifndef PLATFORM_IS_LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN)
#endif
#if defined(__APPLE__) || defined(OS_FREEBSD) || defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD)
// Use fsync() on platforms without fdatasync()
#define fdatasync fsync
#endif
#if defined(OS_ANDROID) && __ANDROID_API__ < 9
// fdatasync() was only introduced in API level 9 on Android. Use fsync()
// when targetting older platforms.
#define fdatasync fsync
#endif
namespace leveldb
{
namespace port
{
static const bool kLittleEndian = PLATFORM_IS_LITTLE_ENDIAN;
#undef PLATFORM_IS_LITTLE_ENDIAN
class CondVar;
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
void AssertHeld()
{
}
private:
friend class CondVar;
pthread_mutex_t mu_;
// No copying
Mutex(const Mutex &);
void operator=(const Mutex &);
};
class CondVar {
public:
explicit CondVar(Mutex *mu);
~CondVar();
void Wait();
void Signal();
void SignalAll();
private:
pthread_cond_t cv_;
Mutex *mu_;
};
typedef pthread_once_t OnceType;
#define LEVELDB_ONCE_INIT PTHREAD_ONCE_INIT
extern void InitOnce(OnceType *once, void (*initializer)());
inline bool Snappy_Compress(const char *input, size_t length, ::std::string *output)
{
#ifdef HAVE_SNAPPY
output->resize(snappy::MaxCompressedLength(length));
size_t outlen;
snappy::RawCompress(input, length, &(*output)[0], &outlen);
output->resize(outlen);
return true;
#endif // defined(HAVE_SNAPPY)
return false;
}
inline bool Snappy_GetUncompressedLength(const char *input, size_t length, size_t *result)
{
#ifdef HAVE_SNAPPY
return snappy::GetUncompressedLength(input, length, result);
#else
return false;
#endif // defined(HAVE_SNAPPY)
}
inline bool Snappy_Uncompress(const char *input, size_t length, char *output)
{
#ifdef HAVE_SNAPPY
return snappy::RawUncompress(input, length, output);
#else
return false;
#endif // defined(HAVE_SNAPPY)
}
inline bool GetHeapProfile(void (*func)(void *, const char *, int), void *arg)
{
return false;
}
inline uint32_t AcceleratedCRC32C(uint32_t crc, const char *buf, size_t size)
{
#if defined(HAVE_CRC32C)
return ::crc32c::Extend(crc, reinterpret_cast<const uint8_t *>(buf), size);
#else
return 0;
#endif // defined(HAVE_CRC32C)
}
} // namespace port
} // namespace leveldb
#endif // STORAGE_LEVELDB_PORT_PORT_POSIX_H_
| 4,061 | 23.768293 | 98 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/port/port_posix.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2020, Intel Corporation */
#include "port/port_posix.h"
#include <cstdlib>
#include <stdio.h>
#include <string.h>
namespace leveldb
{
namespace port
{
static void PthreadCall(const char *label, int result)
{
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
Mutex::Mutex()
{
PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL));
}
Mutex::~Mutex()
{
PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_));
}
void Mutex::Lock()
{
PthreadCall("lock", pthread_mutex_lock(&mu_));
}
void Mutex::Unlock()
{
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
}
CondVar::CondVar(Mutex *mu) : mu_(mu)
{
PthreadCall("init cv", pthread_cond_init(&cv_, NULL));
}
CondVar::~CondVar()
{
PthreadCall("destroy cv", pthread_cond_destroy(&cv_));
}
void CondVar::Wait()
{
PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_));
}
void CondVar::Signal()
{
PthreadCall("signal", pthread_cond_signal(&cv_));
}
void CondVar::SignalAll()
{
PthreadCall("broadcast", pthread_cond_broadcast(&cv_));
}
void InitOnce(OnceType *once, void (*initializer)())
{
PthreadCall("once", pthread_once(once, initializer));
}
} // namespace port
} // namespace leveldb
| 1,484 | 17.797468 | 81 | cc |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/port/thread_annotations.h | // Copyright (c) 2012 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
#ifndef STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
#define STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
// Some environments provide custom macros to aid in static thread-safety
// analysis. Provide empty definitions of such macros unless they are already
// defined.
#ifndef EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#endif
#ifndef SHARED_LOCKS_REQUIRED
#define SHARED_LOCKS_REQUIRED(...)
#endif
#ifndef LOCKS_EXCLUDED
#define LOCKS_EXCLUDED(...)
#endif
#ifndef LOCK_RETURNED
#define LOCK_RETURNED(x)
#endif
#ifndef LOCKABLE
#define LOCKABLE
#endif
#ifndef SCOPED_LOCKABLE
#define SCOPED_LOCKABLE
#endif
#ifndef EXCLUSIVE_LOCK_FUNCTION
#define EXCLUSIVE_LOCK_FUNCTION(...)
#endif
#ifndef SHARED_LOCK_FUNCTION
#define SHARED_LOCK_FUNCTION(...)
#endif
#ifndef EXCLUSIVE_TRYLOCK_FUNCTION
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
#endif
#ifndef SHARED_TRYLOCK_FUNCTION
#define SHARED_TRYLOCK_FUNCTION(...)
#endif
#ifndef UNLOCK_FUNCTION
#define UNLOCK_FUNCTION(...)
#endif
#ifndef NO_THREAD_SAFETY_ANALYSIS
#define NO_THREAD_SAFETY_ANALYSIS
#endif
#endif // STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_
| 1,429 | 21.34375 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/port/atomic_pointer.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// AtomicPointer provides storage for a lock-free pointer.
// Platform-dependent implementation of AtomicPointer:
// - If the platform provides a cheap barrier, we use it with raw pointers
// - If <atomic> is present (on newer versions of gcc, it is), we use
// a <atomic>-based AtomicPointer. However we prefer the memory
// barrier based version, because at least on a gcc 4.4 32-bit build
// on linux, we have encountered a buggy <atomic> implementation.
// Also, some <atomic> implementations are much slower than a memory-barrier
// based implementation (~16ns for <atomic> based acquire-load vs. ~1ns for
// a barrier based acquire-load).
// This code is based on atomicops-internals-* in Google's perftools:
// http://code.google.com/p/google-perftools/source/browse/#svn%2Ftrunk%2Fsrc%2Fbase
#ifndef PORT_ATOMIC_POINTER_H_
#define PORT_ATOMIC_POINTER_H_
#include <stdint.h>
#ifdef LEVELDB_ATOMIC_PRESENT
#include <atomic>
#endif
#ifdef OS_WIN
#include <windows.h>
#endif
#ifdef __APPLE__
#include <libkern/OSAtomic.h>
#endif
#if defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
#define ARCH_CPU_X86_FAMILY 1
#elif defined(__ARMEL__)
#define ARCH_CPU_ARM_FAMILY 1
#elif defined(__aarch64__)
#define ARCH_CPU_ARM64_FAMILY 1
#elif defined(__ppc__) || defined(__powerpc__) || defined(__powerpc64__)
#define ARCH_CPU_PPC_FAMILY 1
#elif defined(__mips__)
#define ARCH_CPU_MIPS_FAMILY 1
#endif
namespace leveldb
{
namespace port
{
// Define MemoryBarrier() if available
// Windows on x86
#if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY)
// windows.h already provides a MemoryBarrier(void) macro
// http://msdn.microsoft.com/en-us/library/ms684208(v=vs.85).aspx
#define LEVELDB_HAVE_MEMORY_BARRIER
// Mac OS
#elif defined(__APPLE__)
inline void MemoryBarrier()
{
OSMemoryBarrier();
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// Gcc on x86
#elif defined(ARCH_CPU_X86_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
// See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on
// this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering.
__asm__ __volatile__("" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// Sun Studio
#elif defined(ARCH_CPU_X86_FAMILY) && defined(__SUNPRO_CC)
inline void MemoryBarrier()
{
// See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on
// this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering.
asm volatile("" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// ARM Linux
#elif defined(ARCH_CPU_ARM_FAMILY) && defined(__linux__)
typedef void (*LinuxKernelMemoryBarrierFunc)(void);
// The Linux ARM kernel provides a highly optimized device-specific memory
// barrier function at a fixed memory address that is mapped in every
// user-level process.
//
// This beats using CPU-specific instructions which are, on single-core
// devices, un-necessary and very costly (e.g. ARMv7-A "dmb" takes more
// than 180ns on a Cortex-A8 like the one on a Nexus One). Benchmarking
// shows that the extra function call cost is completely negligible on
// multi-core devices.
//
inline void MemoryBarrier()
{
(*(LinuxKernelMemoryBarrierFunc)0xffff0fa0)();
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// ARM64
#elif defined(ARCH_CPU_ARM64_FAMILY)
inline void MemoryBarrier()
{
asm volatile("dmb sy" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// PPC
#elif defined(ARCH_CPU_PPC_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
// TODO for some powerpc expert: is there a cheaper suitable variant?
// Perhaps by having separate barriers for acquire and release ops.
asm volatile("sync" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
// MIPS
#elif defined(ARCH_CPU_MIPS_FAMILY) && defined(__GNUC__)
inline void MemoryBarrier()
{
__asm__ __volatile__("sync" : : : "memory");
}
#define LEVELDB_HAVE_MEMORY_BARRIER
#endif
// AtomicPointer built using platform-specific MemoryBarrier()
#if defined(LEVELDB_HAVE_MEMORY_BARRIER)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *p) : rep_(p)
{
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
inline void *Acquire_Load() const
{
void *result = rep_;
MemoryBarrier();
return result;
}
inline void Release_Store(void *v)
{
MemoryBarrier();
rep_ = v;
}
};
// AtomicPointer based on <cstdatomic>
#elif defined(LEVELDB_ATOMIC_PRESENT)
class AtomicPointer {
private:
std::atomic<void *> rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
return rep_.load(std::memory_order_acquire);
}
inline void Release_Store(void *v)
{
rep_.store(v, std::memory_order_release);
}
inline void *NoBarrier_Load() const
{
return rep_.load(std::memory_order_relaxed);
}
inline void NoBarrier_Store(void *v)
{
rep_.store(v, std::memory_order_relaxed);
}
};
// Atomic pointer based on sparc memory barriers
#elif defined(__sparcv9) && defined(__GNUC__)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
void *val;
__asm__ __volatile__("ldx [%[rep_]], %[val] \n\t"
"membar #LoadLoad|#LoadStore \n\t"
: [val] "=r"(val)
: [rep_] "r"(&rep_)
: "memory");
return val;
}
inline void Release_Store(void *v)
{
__asm__ __volatile__("membar #LoadStore|#StoreStore \n\t"
"stx %[v], [%[rep_]] \n\t"
:
: [rep_] "r"(&rep_), [v] "r"(v)
: "memory");
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
};
// Atomic pointer based on ia64 acq/rel
#elif defined(__ia64) && defined(__GNUC__)
class AtomicPointer {
private:
void *rep_;
public:
AtomicPointer()
{
}
explicit AtomicPointer(void *v) : rep_(v)
{
}
inline void *Acquire_Load() const
{
void *val;
__asm__ __volatile__("ld8.acq %[val] = [%[rep_]] \n\t"
: [val] "=r"(val)
: [rep_] "r"(&rep_)
: "memory");
return val;
}
inline void Release_Store(void *v)
{
__asm__ __volatile__("st8.rel [%[rep_]] = %[v] \n\t"
:
: [rep_] "r"(&rep_), [v] "r"(v)
: "memory");
}
inline void *NoBarrier_Load() const
{
return rep_;
}
inline void NoBarrier_Store(void *v)
{
rep_ = v;
}
};
// We have neither MemoryBarrier(), nor <atomic>
#else
#error Please implement AtomicPointer for this platform.
#endif
#undef LEVELDB_HAVE_MEMORY_BARRIER
#undef ARCH_CPU_X86_FAMILY
#undef ARCH_CPU_ARM_FAMILY
#undef ARCH_CPU_ARM64_FAMILY
#undef ARCH_CPU_PPC_FAMILY
} // namespace port
} // namespace leveldb
#endif // PORT_ATOMIC_POINTER_H_
| 7,207 | 23.26936 | 84 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/include/leveldb/status.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// A Status encapsulates the result of an operation. It may indicate success,
// or it may indicate an error with an associated error message.
//
// Multiple threads can invoke const methods on a Status without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Status must use
// external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_STATUS_H_
#define STORAGE_LEVELDB_INCLUDE_STATUS_H_
#include "leveldb/slice.h"
#include <string>
namespace leveldb
{
class Status {
public:
// Create a success status.
Status() : state_(NULL)
{
}
~Status()
{
delete[] state_;
}
// Copy the specified status.
Status(const Status &s);
void operator=(const Status &s);
// Return a success status.
static Status OK()
{
return Status();
}
// Return error status of an appropriate type.
static Status NotFound(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kNotFound, msg, msg2);
}
static Status Corruption(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kCorruption, msg, msg2);
}
static Status NotSupported(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kNotSupported, msg, msg2);
}
static Status InvalidArgument(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kInvalidArgument, msg, msg2);
}
static Status IOError(const Slice &msg, const Slice &msg2 = Slice())
{
return Status(kIOError, msg, msg2);
}
// Returns true iff the status indicates success.
bool ok() const
{
return (state_ == NULL);
}
// Returns true iff the status indicates a NotFound error.
bool IsNotFound() const
{
return code() == kNotFound;
}
// Returns true iff the status indicates a Corruption error.
bool IsCorruption() const
{
return code() == kCorruption;
}
// Returns true iff the status indicates an IOError.
bool IsIOError() const
{
return code() == kIOError;
}
// Returns true iff the status indicates a NotSupportedError.
bool IsNotSupportedError() const
{
return code() == kNotSupported;
}
// Returns true iff the status indicates an InvalidArgument.
bool IsInvalidArgument() const
{
return code() == kInvalidArgument;
}
// Return a string representation of this status suitable for printing.
// Returns the string "OK" for success.
std::string ToString() const;
private:
// OK status has a NULL state_. Otherwise, state_ is a new[] array
// of the following form:
// state_[0..3] == length of message
// state_[4] == code
// state_[5..] == message
const char *state_;
enum Code {
kOk = 0,
kNotFound = 1,
kCorruption = 2,
kNotSupported = 3,
kInvalidArgument = 4,
kIOError = 5
};
Code code() const
{
return (state_ == NULL) ? kOk : static_cast<Code>(state_[4]);
}
Status(Code code, const Slice &msg, const Slice &msg2);
static const char *CopyState(const char *s);
};
inline Status::Status(const Status &s)
{
state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_);
}
inline void Status::operator=(const Status &s)
{
// The following condition catches both aliasing (when this == &s),
// and the common case where both s and *this are ok.
if (state_ != s.state_) {
delete[] state_;
state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_);
}
}
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_STATUS_H_
| 3,658 | 23.231788 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/include/leveldb/slice.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// Slice is a simple structure containing a pointer into some external
// storage and a size. The user of a Slice must ensure that the slice
// is not used after the corresponding external storage has been
// deallocated.
//
// Multiple threads can invoke const methods on a Slice without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Slice must use
// external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_SLICE_H_
#define STORAGE_LEVELDB_INCLUDE_SLICE_H_
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <string>
namespace leveldb
{
class Slice {
public:
// Create an empty slice.
Slice() : data_(""), size_(0)
{
}
// Create a slice that refers to d[0,n-1].
Slice(const char *d, size_t n) : data_(d), size_(n)
{
}
// Create a slice that refers to the contents of "s"
Slice(const std::string &s) : data_(s.data()), size_(s.size())
{
}
// Create a slice that refers to s[0,strlen(s)-1]
Slice(const char *s) : data_(s), size_(strlen(s))
{
}
// Return a pointer to the beginning of the referenced data
const char *data() const
{
return data_;
}
// Return the length (in bytes) of the referenced data
size_t size() const
{
return size_;
}
// Return true iff the length of the referenced data is zero
bool empty() const
{
return size_ == 0;
}
// Return the ith byte in the referenced data.
// REQUIRES: n < size()
char operator[](size_t n) const
{
assert(n < size());
return data_[n];
}
// Change this slice to refer to an empty array
void clear()
{
data_ = "";
size_ = 0;
}
// Drop the first "n" bytes from this slice.
void remove_prefix(size_t n)
{
assert(n <= size());
data_ += n;
size_ -= n;
}
// Return a string that contains the copy of the referenced data.
std::string ToString() const
{
return std::string(data_, size_);
}
// Three-way comparison. Returns value:
// < 0 iff "*this" < "b",
// == 0 iff "*this" == "b",
// > 0 iff "*this" > "b"
int compare(const Slice &b) const;
// Return true iff "x" is a prefix of "*this"
bool starts_with(const Slice &x) const
{
return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}
private:
const char *data_;
size_t size_;
// Intentionally copyable
};
inline bool operator==(const Slice &x, const Slice &y)
{
return ((x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0));
}
inline bool operator!=(const Slice &x, const Slice &y)
{
return !(x == y);
}
inline int Slice::compare(const Slice &b) const
{
const size_t min_len = (size_ < b.size_) ? size_ : b.size_;
int r = memcmp(data_, b.data_, min_len);
if (r == 0) {
if (size_ < b.size_)
r = -1;
else if (size_ > b.size_)
r = +1;
}
return r;
}
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_SLICE_H_
| 3,163 | 21.125874 | 81 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/bench/include/leveldb/env.h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file. See the AUTHORS file for names of contributors.
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020, Intel Corporation
// An Env is an interface used by the leveldb implementation to access
// operating system functionality like the filesystem etc. Callers
// may wish to provide a custom Env object when opening a database to
// get fine gain control; e.g., to rate limit file system operations.
//
// All Env implementations are safe for concurrent access from
// multiple threads without any external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_ENV_H_
#define STORAGE_LEVELDB_INCLUDE_ENV_H_
#include "leveldb/status.h"
#include <stdarg.h>
#include <stdint.h>
#include <string>
#include <vector>
namespace leveldb
{
class FileLock;
class Logger;
class RandomAccessFile;
class SequentialFile;
class Slice;
class WritableFile;
class Env {
public:
Env()
{
}
virtual ~Env();
// Return a default environment suitable for the current operating
// system. Sophisticated users may wish to provide their own Env
// implementation instead of relying on this default environment.
//
// The result of Default() belongs to leveldb and must never be deleted.
static Env *Default();
// Create a brand new sequentially-readable file with the specified name.
// On success, stores a pointer to the new file in *result and returns OK.
// On failure stores NULL in *result and returns non-OK. If the file does
// not exist, returns a non-OK status. Implementations should return a
// NotFound status when the file does not exist.
//
// The returned file will only be accessed by one thread at a time.
virtual Status NewSequentialFile(const std::string &fname, SequentialFile **result) = 0;
// Create a brand new random access read-only file with the
// specified name. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK. If the file does not exist, returns a non-OK
// status. Implementations should return a NotFound status when the file does
// not exist.
//
// The returned file may be concurrently accessed by multiple threads.
virtual Status NewRandomAccessFile(const std::string &fname, RandomAccessFile **result) = 0;
// Create an object that writes to a new file with the specified
// name. Deletes any existing file with the same name and creates a
// new file. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK.
//
// The returned file will only be accessed by one thread at a time.
virtual Status NewWritableFile(const std::string &fname, WritableFile **result) = 0;
// Create an object that either appends to an existing file, or
// writes to a new file (if the file does not exist to begin with).
// On success, stores a pointer to the new file in *result and
// returns OK. On failure stores NULL in *result and returns
// non-OK.
//
// The returned file will only be accessed by one thread at a time.
//
// May return an IsNotSupportedError error if this Env does
// not allow appending to an existing file. Users of Env (including
// the leveldb implementation) must be prepared to deal with
// an Env that does not support appending.
virtual Status NewAppendableFile(const std::string &fname, WritableFile **result);
// Returns true iff the named file exists.
virtual bool FileExists(const std::string &fname) = 0;
// Store in *result the names of the children of the specified directory.
// The names are relative to "dir".
// Original contents of *results are dropped.
virtual Status GetChildren(const std::string &dir, std::vector<std::string> *result) = 0;
// Delete the named file.
virtual Status DeleteFile(const std::string &fname) = 0;
// Create the specified directory.
virtual Status CreateDir(const std::string &dirname) = 0;
// Delete the specified directory.
virtual Status DeleteDir(const std::string &dirname) = 0;
// Store the size of fname in *file_size.
virtual Status GetFileSize(const std::string &fname, uint64_t *file_size) = 0;
// Rename file src to target.
virtual Status RenameFile(const std::string &src, const std::string &target) = 0;
// Lock the specified file. Used to prevent concurrent access to
// the same db by multiple processes. On failure, stores NULL in
// *lock and returns non-OK.
//
// On success, stores a pointer to the object that represents the
// acquired lock in *lock and returns OK. The caller should call
// UnlockFile(*lock) to release the lock. If the process exits,
// the lock will be automatically released.
//
// If somebody else already holds the lock, finishes immediately
// with a failure. I.e., this call does not wait for existing locks
// to go away.
//
// May create the named file if it does not already exist.
virtual Status LockFile(const std::string &fname, FileLock **lock) = 0;
// Release the lock acquired by a previous successful call to LockFile.
// REQUIRES: lock was returned by a successful LockFile() call
// REQUIRES: lock has not already been unlocked.
virtual Status UnlockFile(FileLock *lock) = 0;
// Arrange to run "(*function)(arg)" once in a background thread.
//
// "function" may run in an unspecified thread. Multiple functions
// added to the same Env may run concurrently in different threads.
// I.e., the caller may not assume that background work items are
// serialized.
virtual void Schedule(void (*function)(void *arg), void *arg) = 0;
// Start a new thread, invoking "function(arg)" within the new thread.
// When "function(arg)" returns, the thread will be destroyed.
virtual void StartThread(void (*function)(void *arg), void *arg) = 0;
// *path is set to a temporary directory that can be used for testing. It may
// or many not have just been created. The directory may or may not differ
// between runs of the same process, but subsequent calls will return the
// same directory.
virtual Status GetTestDirectory(std::string *path) = 0;
// Create and return a log file for storing informational messages.
virtual Status NewLogger(const std::string &fname, Logger **result) = 0;
// Returns the number of micro-seconds since some fixed point in time. Only
// useful for computing deltas of time.
virtual uint64_t NowMicros() = 0;
// Sleep/delay the thread for the prescribed number of micro-seconds.
virtual void SleepForMicroseconds(int micros) = 0;
private:
// No copying allowed
Env(const Env &);
void operator=(const Env &);
};
// A file abstraction for reading sequentially through a file
class SequentialFile {
public:
SequentialFile()
{
}
virtual ~SequentialFile();
// Read up to "n" bytes from the file. "scratch[0..n-1]" may be
// written by this routine. Sets "*result" to the data that was
// read (including if fewer than "n" bytes were successfully read).
// May set "*result" to point at data in "scratch[0..n-1]", so
// "scratch[0..n-1]" must be live when "*result" is used.
// If an error was encountered, returns a non-OK status.
//
// REQUIRES: External synchronization
virtual Status Read(size_t n, Slice *result, char *scratch) = 0;
// Skip "n" bytes from the file. This is guaranteed to be no
// slower that reading the same data, but may be faster.
//
// If end of file is reached, skipping will stop at the end of the
// file, and Skip will return OK.
//
// REQUIRES: External synchronization
virtual Status Skip(uint64_t n) = 0;
private:
// No copying allowed
SequentialFile(const SequentialFile &);
void operator=(const SequentialFile &);
};
// A file abstraction for randomly reading the contents of a file.
class RandomAccessFile {
public:
RandomAccessFile()
{
}
virtual ~RandomAccessFile();
// Read up to "n" bytes from the file starting at "offset".
// "scratch[0..n-1]" may be written by this routine. Sets "*result"
// to the data that was read (including if fewer than "n" bytes were
// successfully read). May set "*result" to point at data in
// "scratch[0..n-1]", so "scratch[0..n-1]" must be live when
// "*result" is used. If an error was encountered, returns a non-OK
// status.
//
// Safe for concurrent use by multiple threads.
virtual Status Read(uint64_t offset, size_t n, Slice *result, char *scratch) const = 0;
private:
// No copying allowed
RandomAccessFile(const RandomAccessFile &);
void operator=(const RandomAccessFile &);
};
// A file abstraction for sequential writing. The implementation
// must provide buffering since callers may append small fragments
// at a time to the file.
class WritableFile {
public:
WritableFile()
{
}
virtual ~WritableFile();
virtual Status Append(const Slice &data) = 0;
virtual Status Close() = 0;
virtual Status Flush() = 0;
virtual Status Sync() = 0;
private:
// No copying allowed
WritableFile(const WritableFile &);
void operator=(const WritableFile &);
};
// An interface for writing log messages.
class Logger {
public:
Logger()
{
}
virtual ~Logger();
// Write an entry to the log file with the specified format.
virtual void Logv(const char *format, va_list ap) = 0;
private:
// No copying allowed
Logger(const Logger &);
void operator=(const Logger &);
};
// Identifies a locked file.
class FileLock {
public:
FileLock()
{
}
virtual ~FileLock();
private:
// No copying allowed
FileLock(const FileLock &);
void operator=(const FileLock &);
};
// Log the specified data to *info_log if info_log is non-NULL.
extern void Log(Logger *info_log, const char *format, ...)
#if defined(__GNUC__) || defined(__clang__)
__attribute__((__format__(__printf__, 2, 3)))
#endif
;
// A utility routine: write "data" to the named file.
Status WriteStringToFile(Env *env, const Slice &data, const std::string &fname);
// A utility routine: read contents of named file into *data
Status ReadFileToString(Env *env, const std::string &fname, std::string *data);
// An implementation of Env that forwards all calls to another Env.
// May be useful to clients who wish to override just part of the
// functionality of another Env.
class EnvWrapper : public Env {
public:
// Initialize an EnvWrapper that delegates all calls to *t
explicit EnvWrapper(Env *t) : target_(t)
{
}
virtual ~EnvWrapper();
// Return the target to which this Env forwards all calls
Env *target() const
{
return target_;
}
// The following text is boilerplate that forwards all methods to target()
Status NewSequentialFile(const std::string &f, SequentialFile **r)
{
return target_->NewSequentialFile(f, r);
}
Status NewRandomAccessFile(const std::string &f, RandomAccessFile **r)
{
return target_->NewRandomAccessFile(f, r);
}
Status NewWritableFile(const std::string &f, WritableFile **r)
{
return target_->NewWritableFile(f, r);
}
Status NewAppendableFile(const std::string &f, WritableFile **r)
{
return target_->NewAppendableFile(f, r);
}
bool FileExists(const std::string &f)
{
return target_->FileExists(f);
}
Status GetChildren(const std::string &dir, std::vector<std::string> *r)
{
return target_->GetChildren(dir, r);
}
Status DeleteFile(const std::string &f)
{
return target_->DeleteFile(f);
}
Status CreateDir(const std::string &d)
{
return target_->CreateDir(d);
}
Status DeleteDir(const std::string &d)
{
return target_->DeleteDir(d);
}
Status GetFileSize(const std::string &f, uint64_t *s)
{
return target_->GetFileSize(f, s);
}
Status RenameFile(const std::string &s, const std::string &t)
{
return target_->RenameFile(s, t);
}
Status LockFile(const std::string &f, FileLock **l)
{
return target_->LockFile(f, l);
}
Status UnlockFile(FileLock *l)
{
return target_->UnlockFile(l);
}
void Schedule(void (*f)(void *), void *a)
{
return target_->Schedule(f, a);
}
void StartThread(void (*f)(void *), void *a)
{
return target_->StartThread(f, a);
}
virtual Status GetTestDirectory(std::string *path)
{
return target_->GetTestDirectory(path);
}
virtual Status NewLogger(const std::string &fname, Logger **result)
{
return target_->NewLogger(fname, result);
}
uint64_t NowMicros()
{
return target_->NowMicros();
}
void SleepForMicroseconds(int micros)
{
target_->SleepForMicroseconds(micros);
}
private:
Env *target_;
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_ENV_H_
| 12,539 | 30.827411 | 93 | h |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/utils/jenkins/scripts/createNamespace.sh | #!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# createNamespace.sh - Remove old namespaces and create new
set -e
# region used for dax namespaces.
DEV_DAX_R=0x0000
# region used for fsdax namespaces.
FS_DAX_R=0x0001
CREATE_DAX=false
CREATE_PMEM=false
MOUNT_POINT="/mnt/pmem0"
SIZE=100G
function usage()
{
echo ""
echo "Script for creating namespaces, mountpoint, and configuring file permissions."
echo "Usage: $(basename $1) [-h|--help] [-d|--dax] [-p|--pmem] [--size]"
echo "-h, --help Print help and exit"
echo "-d, --dax Create dax device."
echo "-p, --pmem Create fsdax device and create mountpoint."
echo "--size Set size for namespaces [default: $SIZE]"
}
function clear_namespaces() {
scriptdir=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
$scriptdir/removeNamespaces.sh
}
function create_devdax() {
local align=$1
local size=$2
local cmd="sudo ndctl create-namespace --mode devdax -a ${align} -s ${size} -r ${DEV_DAX_R} -f"
result=$(${cmd})
if [ $? -ne 0 ]; then
exit 1;
fi
jq -r '.daxregion.devices[].chardev' <<< $result
}
function create_fsdax() {
local size=$1
local cmd="sudo ndctl create-namespace --mode fsdax -s ${size} -r ${FS_DAX_R} -f"
result=$(${cmd})
if [ $? -ne 0 ]; then
exit 1;
fi
jq -r '.blockdev' <<< $result
}
while getopts ":dhp-:" optchar; do
case "${optchar}" in
-)
case "$OPTARG" in
help) usage $0 && exit 0 ;;
dax) CREATE_DAX=true ;;
pmem) CREATE_PMEM=true ;;
size=*) SIZE="${OPTARG#*=}" ;;
*) echo "Invalid argument '$OPTARG'"; usage $0 && exit 1 ;;
esac
;;
p) CREATE_PMEM=true ;;
d) CREATE_DAX=true ;;
h) usage $0 && exit 0 ;;
*) echo "Invalid argument '$OPTARG'"; usage $0 && exit 1 ;;
esac
done
# There is no default test cofiguration in this script. Configurations has to be specified.
if ! $CREATE_DAX && ! $CREATE_PMEM; then
echo ""
echo "ERROR: No config type selected. Please select one or more config types."
exit 1
fi
# Remove existing namespaces.
clear_namespaces
# Creating namespaces.
trap 'echo "ERROR: Failed to create namespaces"; clear_namespaces; exit 1' ERR SIGTERM SIGABRT
if $CREATE_DAX; then
create_devdax 4k $SIZE
fi
if $CREATE_PMEM; then
pmem_name=$(create_fsdax $SIZE)
fi
# Creating mountpoint.
trap 'echo "ERROR: Failed to create mountpoint"; clear_namespaces; exit 1' ERR SIGTERM SIGABRT
if $CREATE_PMEM; then
if [ ! -d "$MOUNT_POINT" ]; then
sudo mkdir $MOUNT_POINT
fi
if ! grep -qs "$MOUNT_POINT " /proc/mounts; then
sudo mkfs.ext4 -F /dev/$pmem_name
sudo mount -o dax /dev/$pmem_name $MOUNT_POINT
fi
fi
# Changing file permissions.
sudo chmod 777 $MOUNT_POINT || true
sudo chmod 777 /dev/dax* || true
sudo chmod a+rw /sys/bus/nd/devices/region*/deep_flush
sudo chmod +r /sys/bus/nd/devices/ndbus*/region*/resource
sudo chmod +r /sys/bus/nd/devices/ndbus*/region*/dax*/resource
# Print created namespaces.
ndctl list -X | jq -r '.[] | select(.mode=="devdax") | [.daxregion.devices[].chardev, "align: "+(.daxregion.align/1024|tostring+"k"), "size: "+(.size/1024/1024/1024|tostring+"G") ]'
ndctl list | jq -r '.[] | select(.mode=="fsdax") | [.blockdev, "size: "+(.size/1024/1024/1024|tostring+"G") ]'
| 3,239 | 26.457627 | 181 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/utils/jenkins/scripts/removeNamespaces.sh | #!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# removeNamespaces.sh - clear all existing namespaces.
set -e
MOUNT_POINT="/mnt/pmem*"
sudo umount $MOUNT_POINT || true
namespace_names=$(ndctl list -X | jq -r '.[].dev')
for n in $namespace_names
do
sudo ndctl clear-errors $n -v
done
sudo ndctl disable-namespace all || true
sudo ndctl destroy-namespace all || true
| 424 | 20.25 | 54 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmemkv-bench-chekpointing/utils/jenkins/scripts/common.sh | #!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019-2020, Intel Corporation
# common.sh - contains bash functions used in all jenkins pipelines.
set -o pipefail
scriptdir=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
function system_info {
echo "********** system-info **********"
cat /etc/os-release | grep -oP "PRETTY_NAME=\K.*"
uname -r
echo "libndctl: $(pkg-config --modversion libndctl || echo 'libndctl not found')"
echo "libfabric: $(pkg-config --modversion libfabric || echo 'libfabric not found')"
echo "libpmem: $(pkg-config --modversion libpmem || echo 'libpmem not found')"
echo "libpmemobj: $(pkg-config --modversion libpmemobj || echo 'libpmemobj not found')"
echo "libpmemobj++: $(pkg-config --modversion libpmemobj++ || echo 'libpmemobj++ not found')"
echo "memkind: $(pkg-config --modversion memkind || echo 'memkind not found')"
echo "TBB : $(pkg-config --modversion TBB || echo 'TBB not found')"
echo "valgrind: $(pkg-config --modversion valgrind || echo 'valgrind not found')"
echo "**********memory-info**********"
sudo ipmctl show -dimm || true
sudo ipmctl show -topology || true
echo "**********list-existing-namespaces**********"
sudo ndctl list -M -N
echo "**********installed-packages**********"
zypper se --installed-only 2>/dev/null || true
apt list --installed 2>/dev/null || true
yum list installed 2>/dev/null || true
echo "**********/proc/cmdline**********"
cat /proc/cmdline
echo "**********/proc/modules**********"
cat /proc/modules
echo "**********/proc/cpuinfo**********"
cat /proc/cpuinfo
echo "**********/proc/meminfo**********"
cat /proc/meminfo
eco "**********/proc/swaps**********"
cat /proc/swaps
echo "**********/proc/version**********"
cat /proc/version
echo "**********check-updates**********"
sudo zypper list-updates 2>/dev/null || true
sudo apt-get update 2>/dev/null || true ; apt upgrade --dry-run 2>/dev/null || true
sudo dnf check-update 2>/dev/null || true
echo "**********list-enviroment**********"
env
}
function set_warning_message {
local info_addr=$1
sudo bash -c "cat > /etc/motd <<EOL
___ ___
/ \ / \ HELLO!
\_ \ / __/ THIS NODE IS CONNECTED TO PMEMKV JENKINS
_\ \ / /__ THERE ARE TESTS CURRENTLY RUNNING ON THIS MACHINE
\___ \____/ __/ PLEASE GO AWAY :)
\_ _/
| @ @ \_
| FOR MORE INFORMATION GO: ${info_addr}
_/ /\
/o) (o/\ \_
\_____/ /
\____/
EOL"
}
function disable_warning_message {
sudo rm /etc/motd || true
}
# Check host linux distribution and return distro name
function check_distro {
distro=$(cat /etc/os-release | grep -e ^NAME= | cut -c6-) && echo "${distro//\"}"
}
| 2,808 | 34.556962 | 94 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/builddatastoreall.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
cat builddatastoreall.sh
| 236 | 46.4 | 99 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/buildclobber.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=1
cat buildclobber.sh
| 171 | 33.4 | 70 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/buildredo.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=1
cat buildredo.sh
| 166 | 32.4 | 69 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/builddatastoreclobber.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
cat builddatastoreclobber.sh
| 182 | 35.6 | 70 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/run.sh | make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=100000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DRUN_COUNT=100000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DGET_NDP_BREAKDOWN
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DGET_NDP_BREAKDOWN
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000 EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER
EXTRA_CFLAGS="-Wno-error"
| 481 | 67.857143 | 112 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/build.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000
cat run.sh
| 180 | 35.2 | 79 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/builddatastore.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1
make EXTRA_CFLAGS+=-DRUN_COUNT=1
cat builddatastore.sh
| 111 | 21.4 | 38 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/builddatastoreredo.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO
make EXTRA_CFLAGS+=-DRUN_COUNT=1 EXTRA_CFLAGS+=-DUSE_NDP_REDO
cat builddatastoreredo.sh
| 173 | 33.8 | 67 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/buildall.sh | make clobber
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=10000
make EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DUSE_NDP_REDO EXTRA_CFLAGS+=-DUSE_NDP_CLOBBER EXTRA_CFLAGS+=-DRUN_COUNT=10000
cat run.sh
| 300 | 59.2 | 139 | sh |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_config.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_config.h -- internal definitions for rpmemd config
*/
#include <stdint.h>
#include <stdbool.h>
#ifndef RPMEMD_DEFAULT_LOG_FILE
#define RPMEMD_DEFAULT_LOG_FILE ("/var/log/" DAEMON_NAME ".log")
#endif
#ifndef RPMEMD_GLOBAL_CONFIG_FILE
#define RPMEMD_GLOBAL_CONFIG_FILE ("/etc/" DAEMON_NAME "/" DAEMON_NAME\
".conf")
#endif
#define RPMEMD_USER_CONFIG_FILE ("." DAEMON_NAME ".conf")
#define RPMEM_DEFAULT_MAX_LANES 1024
#define RPMEM_DEFAULT_NTHREADS 0
#define HOME_ENV "HOME"
#define HOME_STR_PLACEHOLDER ("$" HOME_ENV)
struct rpmemd_config {
char *log_file;
char *poolset_dir;
const char *rm_poolset;
bool force;
bool pool_set;
bool persist_apm;
bool persist_general;
bool use_syslog;
uint64_t max_lanes;
enum rpmemd_log_level log_level;
size_t nthreads;
};
int rpmemd_config_read(struct rpmemd_config *config, int argc, char *argv[]);
void rpmemd_config_free(struct rpmemd_config *config);
| 1,012 | 21.021739 | 77 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_log.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_log.h -- rpmemd logging functions declarations
*/
#include <string.h>
#include "util.h"
#define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b))))
/*
* The tab character is not allowed in rpmemd log,
* because it is not well handled by syslog.
* Please use RPMEMD_LOG_INDENT instead.
*/
#define RPMEMD_LOG_INDENT " "
#ifdef DEBUG
#define RPMEMD_LOG(level, fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(RPD_LOG_##level, __FILE__, __LINE__, fmt, ## arg);\
} while (0)
#else
#define RPMEMD_LOG(level, fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(RPD_LOG_##level, NULL, 0, fmt, ## arg);\
} while (0)
#endif
#ifdef DEBUG
#define RPMEMD_DBG(fmt, arg...) do {\
COMPILE_ERROR_ON(strchr(fmt, '\t') != 0);\
rpmemd_log(_RPD_LOG_DBG, __FILE__, __LINE__, fmt, ## arg);\
} while (0)
#else
#define RPMEMD_DBG(fmt, arg...) do {} while (0)
#endif
#define RPMEMD_ERR(fmt, arg...) do {\
RPMEMD_LOG(ERR, fmt, ## arg);\
} while (0)
#define RPMEMD_FATAL(fmt, arg...) do {\
RPMEMD_LOG(ERR, fmt, ## arg);\
abort();\
} while (0)
#define RPMEMD_ASSERT(cond) do {\
if (!(cond)) {\
rpmemd_log(RPD_LOG_ERR, __FILE__, __LINE__,\
"assertion fault: %s", #cond);\
abort();\
}\
} while (0)
enum rpmemd_log_level {
RPD_LOG_ERR,
RPD_LOG_WARN,
RPD_LOG_NOTICE,
RPD_LOG_INFO,
_RPD_LOG_DBG, /* disallow to use this with LOG macro */
MAX_RPD_LOG,
};
enum rpmemd_log_level rpmemd_log_level_from_str(const char *str);
const char *rpmemd_log_level_to_str(enum rpmemd_log_level level);
extern enum rpmemd_log_level rpmemd_log_level;
int rpmemd_log_init(const char *ident, const char *fname, int use_syslog);
void rpmemd_log_close(void);
int rpmemd_prefix(const char *fmt, ...) FORMAT_PRINTF(1, 2);
void rpmemd_log(enum rpmemd_log_level level, const char *fname,
int lineno, const char *fmt, ...) FORMAT_PRINTF(4, 5);
| 1,991 | 25.210526 | 77 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_db.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_db.h -- internal definitions for rpmemd database of pool set files
*/
struct rpmemd_db;
struct rpmem_pool_attr;
/*
* struct rpmemd_db_pool -- remote pool context
*/
struct rpmemd_db_pool {
void *pool_addr;
size_t pool_size;
struct pool_set *set;
};
struct rpmemd_db *rpmemd_db_init(const char *root_dir, mode_t mode);
struct rpmemd_db_pool *rpmemd_db_pool_create(struct rpmemd_db *db,
const char *pool_desc, size_t pool_size,
const struct rpmem_pool_attr *rattr);
struct rpmemd_db_pool *rpmemd_db_pool_open(struct rpmemd_db *db,
const char *pool_desc, size_t pool_size, struct rpmem_pool_attr *rattr);
int rpmemd_db_pool_remove(struct rpmemd_db *db, const char *pool_desc,
int force, int pool_set);
int rpmemd_db_pool_set_attr(struct rpmemd_db_pool *prp,
const struct rpmem_pool_attr *rattr);
void rpmemd_db_pool_close(struct rpmemd_db *db, struct rpmemd_db_pool *prp);
void rpmemd_db_fini(struct rpmemd_db *db);
int rpmemd_db_check_dir(struct rpmemd_db *db);
int rpmemd_db_pool_is_pmem(struct rpmemd_db_pool *pool);
| 1,132 | 32.323529 | 76 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_util.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2018, Intel Corporation */
/*
* rpmemd_util.h -- rpmemd utility functions declarations
*/
int rpmemd_pmem_persist(const void *addr, size_t len);
int rpmemd_flush_fatal(const void *addr, size_t len);
int rpmemd_apply_pm_policy(enum rpmem_persist_method *persist_method,
int (**persist)(const void *addr, size_t len),
void *(**memcpy_persist)(void *pmemdest, const void *src, size_t len),
const int is_pmem);
| 473 | 32.857143 | 71 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_fip.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_fip.h -- rpmemd libfabric provider module header file
*/
#include <stddef.h>
struct rpmemd_fip;
struct rpmemd_fip_attr {
void *addr;
size_t size;
unsigned nlanes;
size_t nthreads;
size_t buff_size;
enum rpmem_provider provider;
enum rpmem_persist_method persist_method;
int (*persist)(const void *addr, size_t len);
void *(*memcpy_persist)(void *pmemdest, const void *src, size_t len);
int (*deep_persist)(const void *addr, size_t len, void *ctx);
void *ctx;
};
struct rpmemd_fip *rpmemd_fip_init(const char *node,
const char *service,
struct rpmemd_fip_attr *attr,
struct rpmem_resp_attr *resp,
enum rpmem_err *err);
void rpmemd_fip_fini(struct rpmemd_fip *fip);
int rpmemd_fip_accept(struct rpmemd_fip *fip, int timeout);
int rpmemd_fip_process_start(struct rpmemd_fip *fip);
int rpmemd_fip_process_stop(struct rpmemd_fip *fip);
int rpmemd_fip_wait_close(struct rpmemd_fip *fip, int timeout);
int rpmemd_fip_close(struct rpmemd_fip *fip);
| 1,066 | 27.078947 | 70 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016, Intel Corporation */
/*
* rpmemd.h -- rpmemd main header file
*/
#define DAEMON_NAME "rpmemd"
| 158 | 16.666667 | 40 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/rpmemd/rpmemd_obc.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* rpmemd_obc.h -- rpmemd out-of-band connection declarations
*/
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
struct rpmemd_obc;
struct rpmemd_obc_requests {
int (*create)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req,
const struct rpmem_pool_attr *pool_attr);
int (*open)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req);
int (*close)(struct rpmemd_obc *obc, void *arg, int flags);
int (*set_attr)(struct rpmemd_obc *obc, void *arg,
const struct rpmem_pool_attr *pool_attr);
};
struct rpmemd_obc *rpmemd_obc_init(int fd_in, int fd_out);
void rpmemd_obc_fini(struct rpmemd_obc *obc);
int rpmemd_obc_status(struct rpmemd_obc *obc, uint32_t status);
int rpmemd_obc_process(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg);
int rpmemd_obc_create_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res);
int rpmemd_obc_open_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res,
const struct rpmem_pool_attr *pool_attr);
int rpmemd_obc_set_attr_resp(struct rpmemd_obc *obc, int status);
int rpmemd_obc_close_resp(struct rpmemd_obc *obc,
int status);
| 1,296 | 31.425 | 65 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/check.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* check.h -- pmempool check command header file
*/
int pmempool_check_func(const char *appname, int argc, char *argv[]);
void pmempool_check_help(const char *appname);
| 261 | 25.2 | 69 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/create.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* create.h -- pmempool create command header file
*/
int pmempool_create_func(const char *appname, int argc, char *argv[]);
void pmempool_create_help(const char *appname);
| 265 | 25.6 | 70 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/dump.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* dump.h -- pmempool dump command header file
*/
int pmempool_dump_func(const char *appname, int argc, char *argv[]);
void pmempool_dump_help(const char *appname);
| 257 | 24.8 | 68 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/rm.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* rm.h -- pmempool rm command header file
*/
void pmempool_rm_help(const char *appname);
int pmempool_rm_func(const char *appname, int argc, char *argv[]);
| 249 | 24 | 66 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/feature.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018, Intel Corporation */
/*
* feature.h -- pmempool feature command header file
*/
int pmempool_feature_func(const char *appname, int argc, char *argv[]);
void pmempool_feature_help(const char *appname);
| 264 | 25.5 | 71 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/convert.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* convert.h -- pmempool convert command header file
*/
#include <sys/types.h>
int pmempool_convert_func(const char *appname, int argc, char *argv[]);
void pmempool_convert_help(const char *appname);
| 293 | 23.5 | 71 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/synchronize.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* synchronize.h -- pmempool sync command header file
*/
int pmempool_sync_func(const char *appname, int argc, char *argv[]);
void pmempool_sync_help(const char *appname);
| 264 | 25.5 | 68 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/common.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* common.h -- declarations of common functions
*/
#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include "queue.h"
#include "log.h"
#include "blk.h"
#include "libpmemobj.h"
#include "lane.h"
#include "ulog.h"
#include "memops.h"
#include "pmalloc.h"
#include "list.h"
#include "obj.h"
#include "memblock.h"
#include "heap_layout.h"
#include "tx.h"
#include "heap.h"
#include "btt_layout.h"
#include "page_size.h"
/* XXX - modify Linux makefiles to generate srcversion.h and remove #ifdef */
#ifdef _WIN32
#include "srcversion.h"
#endif
#define COUNT_OF(x) (sizeof(x) / sizeof(0[x]))
#define OPT_SHIFT 12
#define OPT_MASK (~((1 << OPT_SHIFT) - 1))
#define OPT_LOG (1 << (PMEM_POOL_TYPE_LOG + OPT_SHIFT))
#define OPT_BLK (1 << (PMEM_POOL_TYPE_BLK + OPT_SHIFT))
#define OPT_OBJ (1 << (PMEM_POOL_TYPE_OBJ + OPT_SHIFT))
#define OPT_BTT (1 << (PMEM_POOL_TYPE_BTT + OPT_SHIFT))
#define OPT_ALL (OPT_LOG | OPT_BLK | OPT_OBJ | OPT_BTT)
#define OPT_REQ_SHIFT 8
#define OPT_REQ_MASK ((1 << OPT_REQ_SHIFT) - 1)
#define _OPT_REQ(c, n) ((c) << (OPT_REQ_SHIFT * (n)))
#define OPT_REQ0(c) _OPT_REQ(c, 0)
#define OPT_REQ1(c) _OPT_REQ(c, 1)
#define OPT_REQ2(c) _OPT_REQ(c, 2)
#define OPT_REQ3(c) _OPT_REQ(c, 3)
#define OPT_REQ4(c) _OPT_REQ(c, 4)
#define OPT_REQ5(c) _OPT_REQ(c, 5)
#define OPT_REQ6(c) _OPT_REQ(c, 6)
#define OPT_REQ7(c) _OPT_REQ(c, 7)
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#define FOREACH_RANGE(range, ranges)\
PMDK_LIST_FOREACH(range, &(ranges)->head, next)
#define PLIST_OFF_TO_PTR(pop, off)\
((off) == 0 ? NULL : (void *)((uintptr_t)(pop) + (off) - OBJ_OOB_SIZE))
#define ENTRY_TO_ALLOC_HDR(entry)\
((void *)((uintptr_t)(entry) - sizeof(struct allocation_header)))
#define OBJH_FROM_PTR(ptr)\
((void *)((uintptr_t)(ptr) - sizeof(struct legacy_object_header)))
#define DEFAULT_HDR_SIZE PMEM_PAGESIZE
#define DEFAULT_DESC_SIZE PMEM_PAGESIZE
#define POOL_HDR_DESC_SIZE (DEFAULT_HDR_SIZE + DEFAULT_DESC_SIZE)
#define PTR_TO_ALLOC_HDR(ptr)\
((void *)((uintptr_t)(ptr) -\
sizeof(struct legacy_object_header)))
#define OBJH_TO_PTR(objh)\
((void *)((uintptr_t)(objh) + sizeof(struct legacy_object_header)))
/* invalid answer for ask_* functions */
#define INV_ANS '\0'
#define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b))))
/*
* pmem_pool_type_t -- pool types
*/
typedef enum {
PMEM_POOL_TYPE_LOG = 0x01,
PMEM_POOL_TYPE_BLK = 0x02,
PMEM_POOL_TYPE_OBJ = 0x04,
PMEM_POOL_TYPE_BTT = 0x08,
PMEM_POOL_TYPE_ALL = 0x0f,
PMEM_POOL_TYPE_UNKNOWN = 0x80,
} pmem_pool_type_t;
struct option_requirement {
int opt;
pmem_pool_type_t type;
uint64_t req;
};
struct options {
const struct option *opts;
size_t noptions;
char *bitmap;
const struct option_requirement *req;
};
struct pmem_pool_params {
pmem_pool_type_t type;
char signature[POOL_HDR_SIG_LEN];
uint64_t size;
mode_t mode;
int is_poolset;
int is_part;
int is_checksum_ok;
union {
struct {
uint64_t bsize;
} blk;
struct {
char layout[PMEMOBJ_MAX_LAYOUT];
} obj;
};
};
struct pool_set_file {
int fd;
char *fname;
void *addr;
size_t size;
struct pool_set *poolset;
size_t replica;
time_t mtime;
mode_t mode;
bool fileio;
};
struct pool_set_file *pool_set_file_open(const char *fname,
int rdonly, int check);
void pool_set_file_close(struct pool_set_file *file);
int pool_set_file_read(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off);
int pool_set_file_write(struct pool_set_file *file, void *buff,
size_t nbytes, uint64_t off);
int pool_set_file_set_replica(struct pool_set_file *file, size_t replica);
size_t pool_set_file_nreplicas(struct pool_set_file *file);
void *pool_set_file_map(struct pool_set_file *file, uint64_t offset);
void pool_set_file_persist(struct pool_set_file *file,
const void *addr, size_t len);
struct range {
PMDK_LIST_ENTRY(range) next;
uint64_t first;
uint64_t last;
};
struct ranges {
PMDK_LIST_HEAD(rangeshead, range) head;
};
pmem_pool_type_t pmem_pool_type_parse_hdr(const struct pool_hdr *hdrp);
pmem_pool_type_t pmem_pool_type(const void *base_pool_addr);
int pmem_pool_checksum(const void *base_pool_addr);
pmem_pool_type_t pmem_pool_type_parse_str(const char *str);
uint64_t pmem_pool_get_min_size(pmem_pool_type_t type);
int pmem_pool_parse_params(const char *fname, struct pmem_pool_params *paramsp,
int check);
int util_poolset_map(const char *fname, struct pool_set **poolset, int rdonly);
struct options *util_options_alloc(const struct option *options,
size_t nopts, const struct option_requirement *req);
void util_options_free(struct options *opts);
int util_options_verify(const struct options *opts, pmem_pool_type_t type);
int util_options_getopt(int argc, char *argv[], const char *optstr,
const struct options *opts);
pmem_pool_type_t util_get_pool_type_second_page(const void *pool_base_addr);
int util_parse_mode(const char *str, mode_t *mode);
int util_parse_ranges(const char *str, struct ranges *rangesp,
struct range entire);
int util_ranges_add(struct ranges *rangesp, struct range range);
void util_ranges_clear(struct ranges *rangesp);
int util_ranges_contain(const struct ranges *rangesp, uint64_t n);
int util_ranges_empty(const struct ranges *rangesp);
int util_check_memory(const uint8_t *buff, size_t len, uint8_t val);
int util_parse_chunk_types(const char *str, uint64_t *types);
int util_parse_lane_sections(const char *str, uint64_t *types);
char ask(char op, char *answers, char def_ans, const char *fmt, va_list ap);
char ask_Yn(char op, const char *fmt, ...) FORMAT_PRINTF(2, 3);
char ask_yN(char op, const char *fmt, ...) FORMAT_PRINTF(2, 3);
unsigned util_heap_max_zone(size_t size);
int util_pool_clear_badblocks(const char *path, int create);
static const struct range ENTIRE_UINT64 = {
{ NULL, NULL }, /* range */
0, /* first */
UINT64_MAX /* last */
};
| 5,957 | 28.205882 | 79 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/transform.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* transform.h -- pmempool transform command header file
*/
int pmempool_transform_func(const char *appname, int argc, char *argv[]);
void pmempool_transform_help(const char *appname);
| 277 | 26.8 | 73 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/info.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info.h -- pmempool info command header file
*/
#include "vec.h"
/*
* Verbose levels used in application:
*
* VERBOSE_DEFAULT:
* Default value for application's verbosity level.
* This is also set for data structures which should be
* printed without any command line argument.
*
* VERBOSE_MAX:
* Maximum value for application's verbosity level.
* This value is used when -v command line argument passed.
*
* VERBOSE_SILENT:
* This value is higher than VERBOSE_MAX and it is used only
* for verbosity levels of data structures which should _not_ be
* printed without specified command line arguments.
*/
#define VERBOSE_SILENT 0
#define VERBOSE_DEFAULT 1
#define VERBOSE_MAX 2
/*
* print_bb_e -- printing bad blocks options
*/
enum print_bb_e {
PRINT_BAD_BLOCKS_NOT_SET,
PRINT_BAD_BLOCKS_NO,
PRINT_BAD_BLOCKS_YES,
PRINT_BAD_BLOCKS_MAX
};
/*
* pmempool_info_args -- structure for storing command line arguments
*/
struct pmempool_info_args {
char *file; /* input file */
unsigned col_width; /* column width for printing fields */
bool human; /* sizes in human-readable formats */
bool force; /* force parsing pool */
enum print_bb_e badblocks; /* print bad blocks */
pmem_pool_type_t type; /* forced pool type */
bool use_range; /* use range for blocks */
struct ranges ranges; /* range of block/chunks to dump */
int vlevel; /* verbosity level */
int vdata; /* verbosity level for data dump */
int vhdrdump; /* verbosity level for headers hexdump */
int vstats; /* verbosity level for statistics */
struct {
size_t walk; /* data chunk size */
} log;
struct {
int vmap; /* verbosity level for BTT Map */
int vflog; /* verbosity level for BTT FLOG */
int vbackup; /* verbosity level for BTT Info backup */
bool skip_zeros; /* skip blocks marked with zero flag */
bool skip_error; /* skip blocks marked with error flag */
bool skip_no_flag; /* skip blocks not marked with any flag */
} blk;
struct {
int vlanes; /* verbosity level for lanes */
int vroot;
int vobjects;
int valloc;
int voobhdr;
int vheap;
int vzonehdr;
int vchunkhdr;
int vbitmap;
bool lanes_recovery;
bool ignore_empty_obj;
uint64_t chunk_types;
size_t replica;
struct ranges lane_ranges;
struct ranges type_ranges;
struct ranges zone_ranges;
struct ranges chunk_ranges;
} obj;
};
/*
* pmem_blk_stats -- structure with statistics for pmemblk
*/
struct pmem_blk_stats {
uint32_t total; /* number of processed blocks */
uint32_t zeros; /* number of blocks marked by zero flag */
uint32_t errors; /* number of blocks marked by error flag */
uint32_t noflag; /* number of blocks not marked with any flag */
};
struct pmem_obj_class_stats {
uint64_t n_units;
uint64_t n_used;
uint64_t unit_size;
uint64_t alignment;
uint32_t nallocs;
uint16_t flags;
};
struct pmem_obj_zone_stats {
uint64_t n_chunks;
uint64_t n_chunks_type[MAX_CHUNK_TYPE];
uint64_t size_chunks;
uint64_t size_chunks_type[MAX_CHUNK_TYPE];
VEC(, struct pmem_obj_class_stats) class_stats;
};
struct pmem_obj_type_stats {
PMDK_TAILQ_ENTRY(pmem_obj_type_stats) next;
uint64_t type_num;
uint64_t n_objects;
uint64_t n_bytes;
};
struct pmem_obj_stats {
uint64_t n_total_objects;
uint64_t n_total_bytes;
uint64_t n_zones;
uint64_t n_zones_used;
struct pmem_obj_zone_stats *zone_stats;
PMDK_TAILQ_HEAD(obj_type_stats_head, pmem_obj_type_stats) type_stats;
};
/*
* pmem_info -- context for pmeminfo application
*/
struct pmem_info {
const char *file_name; /* current file name */
struct pool_set_file *pfile;
struct pmempool_info_args args; /* arguments parsed from command line */
struct options *opts;
struct pool_set *poolset;
pmem_pool_type_t type;
struct pmem_pool_params params;
struct {
struct pmem_blk_stats stats;
} blk;
struct {
struct pmemobjpool *pop;
struct palloc_heap *heap;
struct alloc_class_collection *alloc_classes;
size_t size;
struct pmem_obj_stats stats;
uint64_t uuid_lo;
uint64_t objid;
} obj;
};
int pmempool_info_func(const char *appname, int argc, char *argv[]);
void pmempool_info_help(const char *appname);
int pmempool_info_read(struct pmem_info *pip, void *buff,
size_t nbytes, uint64_t off);
int pmempool_info_blk(struct pmem_info *pip);
int pmempool_info_log(struct pmem_info *pip);
int pmempool_info_obj(struct pmem_info *pip);
int pmempool_info_btt(struct pmem_info *pip);
| 4,492 | 25.904192 | 73 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/tools/pmempool/output.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* output.h -- declarations of output printing related functions
*/
#include <time.h>
#include <stdint.h>
#include <stdio.h>
void out_set_vlevel(int vlevel);
void out_set_stream(FILE *stream);
void out_set_prefix(const char *prefix);
void out_set_col_width(unsigned col_width);
void outv_err(const char *fmt, ...) FORMAT_PRINTF(1, 2);
void out_err(const char *file, int line, const char *func,
const char *fmt, ...) FORMAT_PRINTF(4, 5);
void outv_err_vargs(const char *fmt, va_list ap);
void outv_indent(int vlevel, int i);
void outv(int vlevel, const char *fmt, ...) FORMAT_PRINTF(2, 3);
void outv_nl(int vlevel);
int outv_check(int vlevel);
void outv_title(int vlevel, const char *fmt, ...) FORMAT_PRINTF(2, 3);
void outv_field(int vlevel, const char *field, const char *fmt,
...) FORMAT_PRINTF(3, 4);
void outv_hexdump(int vlevel, const void *addr, size_t len, size_t offset,
int sep);
const char *out_get_uuid_str(uuid_t uuid);
const char *out_get_time_str(time_t time);
const char *out_get_size_str(uint64_t size, int human);
const char *out_get_percentage(double percentage);
const char *out_get_checksum(void *addr, size_t len, uint64_t *csump,
uint64_t skip_off);
const char *out_get_btt_map_entry(uint32_t map);
const char *out_get_pool_type_str(pmem_pool_type_t type);
const char *out_get_pool_signature(pmem_pool_type_t type);
const char *out_get_tx_state_str(uint64_t state);
const char *out_get_chunk_type_str(enum chunk_type type);
const char *out_get_chunk_flags(uint16_t flags);
const char *out_get_zone_magic_str(uint32_t magic);
const char *out_get_pmemoid_str(PMEMoid oid, uint64_t uuid_lo);
const char *out_get_arch_machine_class_str(uint8_t machine_class);
const char *out_get_arch_data_str(uint8_t data);
const char *out_get_arch_machine_str(uint16_t machine);
const char *out_get_last_shutdown_str(uint8_t dirty);
const char *out_get_alignment_desc_str(uint64_t ad, uint64_t cur_ad);
const char *out_get_incompat_features_str(uint32_t incompat);
| 2,070 | 41.265306 | 74 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/libpmemlog/log.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* log.h -- internal definitions for libpmem log module
*/
#ifndef LOG_H
#define LOG_H 1
#include <stdint.h>
#include <stddef.h>
#include <endian.h>
#include "ctl.h"
#include "util.h"
#include "os_thread.h"
#include "pool_hdr.h"
#include "page_size.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "alloc.h"
#include "fault_injection.h"
#define PMEMLOG_LOG_PREFIX "libpmemlog"
#define PMEMLOG_LOG_LEVEL_VAR "PMEMLOG_LOG_LEVEL"
#define PMEMLOG_LOG_FILE_VAR "PMEMLOG_LOG_FILE"
/* attributes of the log memory pool format for the pool header */
#define LOG_HDR_SIG "PMEMLOG" /* must be 8 bytes including '\0' */
#define LOG_FORMAT_MAJOR 1
#define LOG_FORMAT_FEAT_DEFAULT \
{POOL_FEAT_COMPAT_DEFAULT, POOL_FEAT_INCOMPAT_DEFAULT, 0x0000}
#define LOG_FORMAT_FEAT_CHECK \
{POOL_FEAT_COMPAT_VALID, POOL_FEAT_INCOMPAT_VALID, 0x0000}
static const features_t log_format_feat_default = LOG_FORMAT_FEAT_DEFAULT;
struct pmemlog {
struct pool_hdr hdr; /* memory pool header */
/* root info for on-media format... */
uint64_t start_offset; /* start offset of the usable log space */
uint64_t end_offset; /* maximum offset of the usable log space */
uint64_t write_offset; /* current write point for the log */
/* some run-time state, allocated out of memory pool... */
void *addr; /* mapped region */
size_t size; /* size of mapped region */
int is_pmem; /* true if pool is PMEM */
int rdonly; /* true if pool is opened read-only */
os_rwlock_t *rwlockp; /* pointer to RW lock */
int is_dev_dax; /* true if mapped on device dax */
struct ctl *ctl; /* top level node of the ctl tree structure */
struct pool_set *set; /* pool set info */
};
/* data area starts at this alignment after the struct pmemlog above */
#define LOG_FORMAT_DATA_ALIGN ((uintptr_t)PMEM_PAGESIZE)
/*
* log_convert2h -- convert pmemlog structure to host byte order
*/
static inline void
log_convert2h(struct pmemlog *plp)
{
plp->start_offset = le64toh(plp->start_offset);
plp->end_offset = le64toh(plp->end_offset);
plp->write_offset = le64toh(plp->write_offset);
}
/*
* log_convert2le -- convert pmemlog structure to LE byte order
*/
static inline void
log_convert2le(struct pmemlog *plp)
{
plp->start_offset = htole64(plp->start_offset);
plp->end_offset = htole64(plp->end_offset);
plp->write_offset = htole64(plp->write_offset);
}
#if FAULT_INJECTION
void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at);
int
pmemlog_fault_injection_enabled(void);
#else
static inline void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at)
{
abort();
}
static inline int
pmemlog_fault_injection_enabled(void)
{
return 0;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
| 2,832 | 23.422414 | 74 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/freebsd/include/endian.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* endian.h -- redirect for FreeBSD <sys/endian.h>
*/
#include <sys/endian.h>
| 165 | 17.444444 | 50 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/freebsd/include/features.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* features.h -- Empty file redirect
*/
| 126 | 17.142857 | 40 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/freebsd/include/sys/sysmacros.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* sys/sysmacros.h -- Empty file redirect
*/
| 131 | 17.857143 | 41 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/freebsd/include/linux/kdev_t.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* linux/kdev_t.h -- Empty file redirect
*/
| 130 | 17.714286 | 40 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/freebsd/include/linux/limits.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017, Intel Corporation */
/*
* linux/limits.h -- Empty file redirect
*/
| 130 | 17.714286 | 40 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/pmemcore.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020, Intel Corporation */
/*
* pmemcore.h -- definitions for "core" module
*/
#ifndef PMEMCORE_H
#define PMEMCORE_H 1
#include "util.h"
#include "out.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* core_init -- core module initialization
*/
static inline void
core_init(const char *log_prefix, const char *log_level_var,
const char *log_file_var, int major_version,
int minor_version)
{
util_init();
out_init(log_prefix, log_level_var, log_file_var, major_version,
minor_version);
}
/*
* core_fini -- core module cleanup
*/
static inline void
core_fini(void)
{
out_fini();
}
#ifdef __cplusplus
}
#endif
#endif
| 687 | 14.288889 | 65 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/fault_injection.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
#ifndef CORE_FAULT_INJECTION
#define CORE_FAULT_INJECTION
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
enum pmem_allocation_type { PMEM_MALLOC, PMEM_REALLOC };
#if FAULT_INJECTION
void core_inject_fault_at(enum pmem_allocation_type type,
int nth, const char *at);
int core_fault_injection_enabled(void);
#else
static inline void
core_inject_fault_at(enum pmem_allocation_type type, int nth, const char *at)
{
abort();
}
static inline int
core_fault_injection_enabled(void)
{
return 0;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
| 642 | 15.075 | 77 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/os.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* os.h -- os abstraction layer
*/
#ifndef PMDK_OS_H
#define PMDK_OS_H 1
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include "errno_freebsd.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _WIN32
#define OS_DIR_SEPARATOR '/'
#define OS_DIR_SEP_STR "/"
#else
#define OS_DIR_SEPARATOR '\\'
#define OS_DIR_SEP_STR "\\"
#endif
#ifndef _WIN32
/* madvise() */
#ifdef __FreeBSD__
#define os_madvise minherit
#define MADV_DONTFORK INHERIT_NONE
#else
#define os_madvise madvise
#endif
/* dlopen() */
#ifdef __FreeBSD__
#define RTLD_DEEPBIND 0 /* XXX */
#endif
/* major(), minor() */
#ifdef __FreeBSD__
#define os_major (unsigned)major
#define os_minor (unsigned)minor
#else
#define os_major major
#define os_minor minor
#endif
#endif /* #ifndef _WIN32 */
struct iovec;
/* os_flock */
#define OS_LOCK_SH 1
#define OS_LOCK_EX 2
#define OS_LOCK_NB 4
#define OS_LOCK_UN 8
#ifndef _WIN32
typedef struct stat os_stat_t;
#define os_fstat fstat
#define os_lseek lseek
#else
typedef struct _stat64 os_stat_t;
#define os_fstat _fstat64
#define os_lseek _lseeki64
#endif
#define os_close close
#define os_fclose fclose
#ifndef _WIN32
typedef off_t os_off_t;
#else
/* XXX: os_off_t defined in platform.h */
#endif
int os_open(const char *pathname, int flags, ...);
int os_fsync(int fd);
int os_fsync_dir(const char *dir_name);
int os_stat(const char *pathname, os_stat_t *buf);
int os_unlink(const char *pathname);
int os_access(const char *pathname, int mode);
FILE *os_fopen(const char *pathname, const char *mode);
FILE *os_fdopen(int fd, const char *mode);
int os_chmod(const char *pathname, mode_t mode);
int os_mkstemp(char *temp);
int os_posix_fallocate(int fd, os_off_t offset, os_off_t len);
int os_ftruncate(int fd, os_off_t length);
int os_flock(int fd, int operation);
ssize_t os_writev(int fd, const struct iovec *iov, int iovcnt);
int os_clock_gettime(int id, struct timespec *ts);
unsigned os_rand_r(unsigned *seedp);
int os_unsetenv(const char *name);
int os_setenv(const char *name, const char *value, int overwrite);
char *os_getenv(const char *name);
const char *os_strsignal(int sig);
int os_execv(const char *path, char *const argv[]);
/*
* XXX: missing APis (used in ut_file.c)
*
* rename
* read
* write
*/
#ifdef __cplusplus
}
#endif
#endif /* os.h */
| 2,388 | 19.594828 | 66 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/util.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* Copyright (c) 2016-2020, Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* util.h -- internal definitions for util module
*/
#ifndef PMDK_UTIL_H
#define PMDK_UTIL_H 1
#include <string.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <ctype.h>
#ifdef _MSC_VER
#include <intrin.h> /* popcnt, bitscan */
#endif
#include <sys/param.h>
#ifdef __cplusplus
extern "C" {
#endif
extern unsigned long long Pagesize;
extern unsigned long long Mmap_align;
#if defined(__x86_64) || defined(_M_X64) || defined(__aarch64__)
#define CACHELINE_SIZE 64ULL
#elif defined(__PPC64__)
#define CACHELINE_SIZE 128ULL
#else
#error unable to recognize architecture at compile time
#endif
#define PAGE_ALIGNED_DOWN_SIZE(size) ((size) & ~(Pagesize - 1))
#define PAGE_ALIGNED_UP_SIZE(size)\
PAGE_ALIGNED_DOWN_SIZE((size) + (Pagesize - 1))
#define IS_PAGE_ALIGNED(size) (((size) & (Pagesize - 1)) == 0)
#define IS_MMAP_ALIGNED(size) (((size) & (Mmap_align - 1)) == 0)
#define PAGE_ALIGN_UP(addr) ((void *)PAGE_ALIGNED_UP_SIZE((uintptr_t)(addr)))
#define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1))
#define ALIGN_DOWN(size, align) ((size) & ~((align) - 1))
#define ADDR_SUM(vp, lp) ((void *)((char *)(vp) + (lp)))
#define util_alignof(t) offsetof(struct {char _util_c; t _util_m; }, _util_m)
#define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b))))
void util_init(void);
int util_is_zeroed(const void *addr, size_t len);
uint64_t util_checksum_compute(void *addr, size_t len, uint64_t *csump,
size_t skip_off);
int util_checksum(void *addr, size_t len, uint64_t *csump,
int insert, size_t skip_off);
uint64_t util_checksum_seq(const void *addr, size_t len, uint64_t csum);
int util_parse_size(const char *str, size_t *sizep);
char *util_fgets(char *buffer, int max, FILE *stream);
char *util_getexecname(char *path, size_t pathlen);
char *util_part_realpath(const char *path);
int util_compare_file_inodes(const char *path1, const char *path2);
void *util_aligned_malloc(size_t alignment, size_t size);
void util_aligned_free(void *ptr);
struct tm *util_localtime(const time_t *timep);
int util_safe_strcpy(char *dst, const char *src, size_t max_length);
void util_emit_log(const char *lib, const char *func, int order);
char *util_readline(FILE *fh);
int util_snprintf(char *str, size_t size,
const char *format, ...) FORMAT_PRINTF(3, 4);
#ifdef _WIN32
char *util_toUTF8(const wchar_t *wstr);
wchar_t *util_toUTF16(const char *wstr);
void util_free_UTF8(char *str);
void util_free_UTF16(wchar_t *str);
int util_toUTF16_buff(const char *in, wchar_t *out, size_t out_size);
int util_toUTF8_buff(const wchar_t *in, char *out, size_t out_size);
void util_suppress_errmsg(void);
int util_lasterror_to_errno(unsigned long err);
#endif
#define UTIL_MAX_ERR_MSG 128
void util_strerror(int errnum, char *buff, size_t bufflen);
void util_strwinerror(unsigned long err, char *buff, size_t bufflen);
void util_set_alloc_funcs(
void *(*malloc_func)(size_t size),
void (*free_func)(void *ptr),
void *(*realloc_func)(void *ptr, size_t size),
char *(*strdup_func)(const char *s));
/*
* Macro calculates number of elements in given table
*/
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
#ifdef _MSC_VER
#define force_inline inline __forceinline
#define NORETURN __declspec(noreturn)
#define barrier() _ReadWriteBarrier()
#else
#define force_inline __attribute__((always_inline)) inline
#define NORETURN __attribute__((noreturn))
#define barrier() asm volatile("" ::: "memory")
#endif
#ifdef _MSC_VER
typedef UNALIGNED uint64_t ua_uint64_t;
typedef UNALIGNED uint32_t ua_uint32_t;
typedef UNALIGNED uint16_t ua_uint16_t;
#else
typedef uint64_t ua_uint64_t __attribute__((aligned(1)));
typedef uint32_t ua_uint32_t __attribute__((aligned(1)));
typedef uint16_t ua_uint16_t __attribute__((aligned(1)));
#endif
#define util_get_not_masked_bits(x, mask) ((x) & ~(mask))
/*
* util_setbit -- setbit macro substitution which properly deals with types
*/
static inline void
util_setbit(uint8_t *b, uint32_t i)
{
b[i / 8] = (uint8_t)(b[i / 8] | (uint8_t)(1 << (i % 8)));
}
/*
* util_clrbit -- clrbit macro substitution which properly deals with types
*/
static inline void
util_clrbit(uint8_t *b, uint32_t i)
{
b[i / 8] = (uint8_t)(b[i / 8] & (uint8_t)(~(1 << (i % 8))));
}
#define util_isset(a, i) isset(a, i)
#define util_isclr(a, i) isclr(a, i)
#define util_flag_isset(a, f) ((a) & (f))
#define util_flag_isclr(a, f) (((a) & (f)) == 0)
/*
* util_is_pow2 -- returns !0 when there's only 1 bit set in v, 0 otherwise
*/
static force_inline int
util_is_pow2(uint64_t v)
{
return v && !(v & (v - 1));
}
/*
* util_div_ceil -- divides a by b and rounds up the result
*/
static force_inline unsigned
util_div_ceil(unsigned a, unsigned b)
{
return (unsigned)(((unsigned long)a + b - 1) / b);
}
/*
* util_bool_compare_and_swap -- perform an atomic compare and swap
* util_fetch_and_* -- perform an operation atomically, return old value
* util_synchronize -- issue a full memory barrier
* util_popcount -- count number of set bits
* util_lssb_index -- return index of least significant set bit,
* undefined on zero
* util_mssb_index -- return index of most significant set bit
* undefined on zero
*
* XXX assertions needed on (value != 0) in both versions of bitscans
*
*/
#ifndef _MSC_VER
/*
* ISO C11 -- 7.17.1.4
* memory_order - an enumerated type whose enumerators identify memory ordering
* constraints.
*/
typedef enum {
memory_order_relaxed = __ATOMIC_RELAXED,
memory_order_consume = __ATOMIC_CONSUME,
memory_order_acquire = __ATOMIC_ACQUIRE,
memory_order_release = __ATOMIC_RELEASE,
memory_order_acq_rel = __ATOMIC_ACQ_REL,
memory_order_seq_cst = __ATOMIC_SEQ_CST
} memory_order;
/*
* ISO C11 -- 7.17.7.2 The atomic_load generic functions
* Integer width specific versions as supplement for:
*
*
* #include <stdatomic.h>
* C atomic_load(volatile A *object);
* C atomic_load_explicit(volatile A *object, memory_order order);
*
* The atomic_load interface doesn't return the loaded value, but instead
* copies it to a specified address -- see comments at the MSVC version.
*
* Also, instead of generic functions, two versions are available:
* for 32 bit fundamental integers, and for 64 bit ones.
*/
#define util_atomic_load_explicit32 __atomic_load
#define util_atomic_load_explicit64 __atomic_load
/*
* ISO C11 -- 7.17.7.1 The atomic_store generic functions
* Integer width specific versions as supplement for:
*
* #include <stdatomic.h>
* void atomic_store(volatile A *object, C desired);
* void atomic_store_explicit(volatile A *object, C desired,
* memory_order order);
*/
#define util_atomic_store_explicit32 __atomic_store_n
#define util_atomic_store_explicit64 __atomic_store_n
/*
* https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html
* https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
* https://clang.llvm.org/docs/LanguageExtensions.html#builtin-functions
*/
#define util_bool_compare_and_swap32 __sync_bool_compare_and_swap
#define util_bool_compare_and_swap64 __sync_bool_compare_and_swap
#define util_fetch_and_add32 __sync_fetch_and_add
#define util_fetch_and_add64 __sync_fetch_and_add
#define util_fetch_and_sub32 __sync_fetch_and_sub
#define util_fetch_and_sub64 __sync_fetch_and_sub
#define util_fetch_and_and32 __sync_fetch_and_and
#define util_fetch_and_and64 __sync_fetch_and_and
#define util_fetch_and_or32 __sync_fetch_and_or
#define util_fetch_and_or64 __sync_fetch_and_or
#define util_synchronize __sync_synchronize
#define util_popcount(value) ((unsigned char)__builtin_popcount(value))
#define util_popcount64(value) ((unsigned char)__builtin_popcountll(value))
#define util_lssb_index(value) ((unsigned char)__builtin_ctz(value))
#define util_lssb_index64(value) ((unsigned char)__builtin_ctzll(value))
#define util_mssb_index(value) ((unsigned char)(31 - __builtin_clz(value)))
#define util_mssb_index64(value) ((unsigned char)(63 - __builtin_clzll(value)))
#else
/* ISO C11 -- 7.17.1.4 */
typedef enum {
memory_order_relaxed,
memory_order_consume,
memory_order_acquire,
memory_order_release,
memory_order_acq_rel,
memory_order_seq_cst
} memory_order;
/*
* ISO C11 -- 7.17.7.2 The atomic_load generic functions
* Integer width specific versions as supplement for:
*
*
* #include <stdatomic.h>
* C atomic_load(volatile A *object);
* C atomic_load_explicit(volatile A *object, memory_order order);
*
* The atomic_load interface doesn't return the loaded value, but instead
* copies it to a specified address.
* The MSVC specific implementation needs to trigger a barrier (at least
* compiler barrier) after the load from the volatile value. The actual load
* from the volatile value itself is expected to be atomic.
*
* The actual isnterface here:
* #include "util.h"
* void util_atomic_load32(volatile A *object, A *destination);
* void util_atomic_load64(volatile A *object, A *destination);
* void util_atomic_load_explicit32(volatile A *object, A *destination,
* memory_order order);
* void util_atomic_load_explicit64(volatile A *object, A *destination,
* memory_order order);
*/
#ifndef _M_X64
#error MSVC ports of util_atomic_ only work on X86_64
#endif
#if _MSC_VER >= 2000
#error util_atomic_ utility functions not tested with this version of VC++
#error These utility functions are not future proof, as they are not
#error based on publicly available documentation.
#endif
#define util_atomic_load_explicit(object, dest, order)\
do {\
COMPILE_ERROR_ON(order != memory_order_seq_cst &&\
order != memory_order_consume &&\
order != memory_order_acquire &&\
order != memory_order_relaxed);\
*dest = *object;\
if (order == memory_order_seq_cst ||\
order == memory_order_consume ||\
order == memory_order_acquire)\
_ReadWriteBarrier();\
} while (0)
#define util_atomic_load_explicit32 util_atomic_load_explicit
#define util_atomic_load_explicit64 util_atomic_load_explicit
/* ISO C11 -- 7.17.7.1 The atomic_store generic functions */
#define util_atomic_store_explicit64(object, desired, order)\
do {\
COMPILE_ERROR_ON(order != memory_order_seq_cst &&\
order != memory_order_release &&\
order != memory_order_relaxed);\
if (order == memory_order_seq_cst) {\
_InterlockedExchange64(\
(volatile long long *)object, desired);\
} else {\
if (order == memory_order_release)\
_ReadWriteBarrier();\
*object = desired;\
}\
} while (0)
#define util_atomic_store_explicit32(object, desired, order)\
do {\
COMPILE_ERROR_ON(order != memory_order_seq_cst &&\
order != memory_order_release &&\
order != memory_order_relaxed);\
if (order == memory_order_seq_cst) {\
_InterlockedExchange(\
(volatile long *)object, desired);\
} else {\
if (order == memory_order_release)\
_ReadWriteBarrier();\
*object = desired;\
}\
} while (0)
/*
* https://msdn.microsoft.com/en-us/library/hh977022.aspx
*/
static __inline int
bool_compare_and_swap32_VC(volatile LONG *ptr,
LONG oldval, LONG newval)
{
LONG old = InterlockedCompareExchange(ptr, newval, oldval);
return (old == oldval);
}
static __inline int
bool_compare_and_swap64_VC(volatile LONG64 *ptr,
LONG64 oldval, LONG64 newval)
{
LONG64 old = InterlockedCompareExchange64(ptr, newval, oldval);
return (old == oldval);
}
#define util_bool_compare_and_swap32(p, o, n)\
bool_compare_and_swap32_VC((LONG *)(p), (LONG)(o), (LONG)(n))
#define util_bool_compare_and_swap64(p, o, n)\
bool_compare_and_swap64_VC((LONG64 *)(p), (LONG64)(o), (LONG64)(n))
#define util_fetch_and_add32(ptr, value)\
InterlockedExchangeAdd((LONG *)(ptr), value)
#define util_fetch_and_add64(ptr, value)\
InterlockedExchangeAdd64((LONG64 *)(ptr), value)
#define util_fetch_and_sub32(ptr, value)\
InterlockedExchangeSubtract((LONG *)(ptr), value)
#define util_fetch_and_sub64(ptr, value)\
InterlockedExchangeAdd64((LONG64 *)(ptr), -((LONG64)(value)))
#define util_fetch_and_and32(ptr, value)\
InterlockedAnd((LONG *)(ptr), value)
#define util_fetch_and_and64(ptr, value)\
InterlockedAnd64((LONG64 *)(ptr), value)
#define util_fetch_and_or32(ptr, value)\
InterlockedOr((LONG *)(ptr), value)
#define util_fetch_and_or64(ptr, value)\
InterlockedOr64((LONG64 *)(ptr), value)
static __inline void
util_synchronize(void)
{
MemoryBarrier();
}
#define util_popcount(value) (unsigned char)__popcnt(value)
#define util_popcount64(value) (unsigned char)__popcnt64(value)
static __inline unsigned char
util_lssb_index(int value)
{
unsigned long ret;
_BitScanForward(&ret, value);
return (unsigned char)ret;
}
static __inline unsigned char
util_lssb_index64(long long value)
{
unsigned long ret;
_BitScanForward64(&ret, value);
return (unsigned char)ret;
}
static __inline unsigned char
util_mssb_index(int value)
{
unsigned long ret;
_BitScanReverse(&ret, value);
return (unsigned char)ret;
}
static __inline unsigned char
util_mssb_index64(long long value)
{
unsigned long ret;
_BitScanReverse64(&ret, value);
return (unsigned char)ret;
}
#endif
/* ISO C11 -- 7.17.7 Operations on atomic types */
#define util_atomic_load32(object, dest)\
util_atomic_load_explicit32(object, dest, memory_order_seq_cst)
#define util_atomic_load64(object, dest)\
util_atomic_load_explicit64(object, dest, memory_order_seq_cst)
#define util_atomic_store32(object, desired)\
util_atomic_store_explicit32(object, desired, memory_order_seq_cst)
#define util_atomic_store64(object, desired)\
util_atomic_store_explicit64(object, desired, memory_order_seq_cst)
/*
* util_get_printable_ascii -- convert non-printable ascii to dot '.'
*/
static inline char
util_get_printable_ascii(char c)
{
return isprint((unsigned char)c) ? c : '.';
}
char *util_concat_str(const char *s1, const char *s2);
#if !defined(likely)
#if defined(__GNUC__)
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else
#define likely(x) (!!(x))
#define unlikely(x) (!!(x))
#endif
#endif
#if defined(__CHECKER__)
#define COMPILE_ERROR_ON(cond)
#define ASSERT_COMPILE_ERROR_ON(cond)
#elif defined(_MSC_VER)
#define COMPILE_ERROR_ON(cond) C_ASSERT(!(cond))
/* XXX - can't be done with C_ASSERT() unless we have __builtin_constant_p() */
#define ASSERT_COMPILE_ERROR_ON(cond) do {} while (0)
#else
#define COMPILE_ERROR_ON(cond) ((void)sizeof(char[(cond) ? -1 : 1]))
#define ASSERT_COMPILE_ERROR_ON(cond) COMPILE_ERROR_ON(cond)
#endif
#ifndef _MSC_VER
#define ATTR_CONSTRUCTOR __attribute__((constructor)) static
#define ATTR_DESTRUCTOR __attribute__((destructor)) static
#else
#define ATTR_CONSTRUCTOR
#define ATTR_DESTRUCTOR
#endif
#ifndef _MSC_VER
#define CONSTRUCTOR(fun) ATTR_CONSTRUCTOR
#else
#ifdef __cplusplus
#define CONSTRUCTOR(fun) \
void fun(); \
struct _##fun { \
_##fun() { \
fun(); \
} \
}; static _##fun foo; \
static
#else
#define CONSTRUCTOR(fun) \
MSVC_CONSTR(fun) \
static
#endif
#endif
#ifdef __GNUC__
#define CHECK_FUNC_COMPATIBLE(func1, func2)\
COMPILE_ERROR_ON(!__builtin_types_compatible_p(typeof(func1),\
typeof(func2)))
#else
#define CHECK_FUNC_COMPATIBLE(func1, func2) do {} while (0)
#endif /* __GNUC__ */
#ifdef __cplusplus
}
#endif
#endif /* util.h */
| 17,058 | 30.47417 | 79 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/valgrind_internal.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* valgrind_internal.h -- internal definitions for valgrind macros
*/
#ifndef PMDK_VALGRIND_INTERNAL_H
#define PMDK_VALGRIND_INTERNAL_H 1
#if !defined(_WIN32) && !defined(__FreeBSD__)
#ifndef VALGRIND_ENABLED
#define VALGRIND_ENABLED 1
#endif
#endif
#if VALGRIND_ENABLED
#define VG_PMEMCHECK_ENABLED 1
#define VG_HELGRIND_ENABLED 1
#define VG_MEMCHECK_ENABLED 1
#define VG_DRD_ENABLED 1
#endif
#if VG_PMEMCHECK_ENABLED || VG_HELGRIND_ENABLED || VG_MEMCHECK_ENABLED || \
VG_DRD_ENABLED
#define ANY_VG_TOOL_ENABLED 1
#else
#define ANY_VG_TOOL_ENABLED 0
#endif
#if ANY_VG_TOOL_ENABLED
extern unsigned _On_valgrind;
#define On_valgrind __builtin_expect(_On_valgrind, 0)
#include "valgrind/valgrind.h"
#else
#define On_valgrind (0)
#endif
#if VG_HELGRIND_ENABLED
extern unsigned _On_helgrind;
#define On_helgrind __builtin_expect(_On_helgrind, 0)
#include "valgrind/helgrind.h"
#else
#define On_helgrind (0)
#endif
#if VG_DRD_ENABLED
extern unsigned _On_drd;
#define On_drd __builtin_expect(_On_drd, 0)
#include "valgrind/drd.h"
#else
#define On_drd (0)
#endif
#if VG_HELGRIND_ENABLED || VG_DRD_ENABLED
extern unsigned _On_drd_or_hg;
#define On_drd_or_hg __builtin_expect(_On_drd_or_hg, 0)
#define VALGRIND_ANNOTATE_HAPPENS_BEFORE(obj) do {\
if (On_drd_or_hg) \
ANNOTATE_HAPPENS_BEFORE((obj));\
} while (0)
#define VALGRIND_ANNOTATE_HAPPENS_AFTER(obj) do {\
if (On_drd_or_hg) \
ANNOTATE_HAPPENS_AFTER((obj));\
} while (0)
#define VALGRIND_ANNOTATE_NEW_MEMORY(addr, size) do {\
if (On_drd_or_hg) \
ANNOTATE_NEW_MEMORY((addr), (size));\
} while (0)
#define VALGRIND_ANNOTATE_IGNORE_READS_BEGIN() do {\
if (On_drd_or_hg) \
ANNOTATE_IGNORE_READS_BEGIN();\
} while (0)
#define VALGRIND_ANNOTATE_IGNORE_READS_END() do {\
if (On_drd_or_hg) \
ANNOTATE_IGNORE_READS_END();\
} while (0)
#define VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN() do {\
if (On_drd_or_hg) \
ANNOTATE_IGNORE_WRITES_BEGIN();\
} while (0)
#define VALGRIND_ANNOTATE_IGNORE_WRITES_END() do {\
if (On_drd_or_hg) \
ANNOTATE_IGNORE_WRITES_END();\
} while (0)
/* Supported by both helgrind and drd. */
#define VALGRIND_HG_DRD_DISABLE_CHECKING(addr, size) do {\
if (On_drd_or_hg) \
VALGRIND_HG_DISABLE_CHECKING((addr), (size));\
} while (0)
#else
#define On_drd_or_hg (0)
#define VALGRIND_ANNOTATE_HAPPENS_BEFORE(obj) do { (void)(obj); } while (0)
#define VALGRIND_ANNOTATE_HAPPENS_AFTER(obj) do { (void)(obj); } while (0)
#define VALGRIND_ANNOTATE_NEW_MEMORY(addr, size) do {\
(void) (addr);\
(void) (size);\
} while (0)
#define VALGRIND_ANNOTATE_IGNORE_READS_BEGIN() do {} while (0)
#define VALGRIND_ANNOTATE_IGNORE_READS_END() do {} while (0)
#define VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN() do {} while (0)
#define VALGRIND_ANNOTATE_IGNORE_WRITES_END() do {} while (0)
#define VALGRIND_HG_DRD_DISABLE_CHECKING(addr, size) do {\
(void) (addr);\
(void) (size);\
} while (0)
#endif
#if VG_PMEMCHECK_ENABLED
extern unsigned _On_pmemcheck;
#define On_pmemcheck __builtin_expect(_On_pmemcheck, 0)
#include "valgrind/pmemcheck.h"
void pobj_emit_log(const char *func, int order);
void pmem_emit_log(const char *func, int order);
void pmem2_emit_log(const char *func, int order);
extern int _Pmreorder_emit;
#define Pmreorder_emit __builtin_expect(_Pmreorder_emit, 0)
#define VALGRIND_REGISTER_PMEM_MAPPING(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_REGISTER_PMEM_MAPPING((addr), (len));\
} while (0)
#define VALGRIND_REGISTER_PMEM_FILE(desc, base_addr, size, offset) do {\
if (On_pmemcheck)\
VALGRIND_PMC_REGISTER_PMEM_FILE((desc), (base_addr), (size), \
(offset));\
} while (0)
#define VALGRIND_REMOVE_PMEM_MAPPING(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_REMOVE_PMEM_MAPPING((addr), (len));\
} while (0)
#define VALGRIND_CHECK_IS_PMEM_MAPPING(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_CHECK_IS_PMEM_MAPPING((addr), (len));\
} while (0)
#define VALGRIND_PRINT_PMEM_MAPPINGS do {\
if (On_pmemcheck)\
VALGRIND_PMC_PRINT_PMEM_MAPPINGS;\
} while (0)
#define VALGRIND_DO_FLUSH(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_DO_FLUSH((addr), (len));\
} while (0)
#define VALGRIND_DO_FENCE do {\
if (On_pmemcheck)\
VALGRIND_PMC_DO_FENCE;\
} while (0)
#define VALGRIND_DO_PERSIST(addr, len) do {\
if (On_pmemcheck) {\
VALGRIND_PMC_DO_FLUSH((addr), (len));\
VALGRIND_PMC_DO_FENCE;\
}\
} while (0)
#define VALGRIND_SET_CLEAN(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_SET_CLEAN(addr, len);\
} while (0)
#define VALGRIND_WRITE_STATS do {\
if (On_pmemcheck)\
VALGRIND_PMC_WRITE_STATS;\
} while (0)
#define VALGRIND_EMIT_LOG(emit_log) do {\
if (On_pmemcheck)\
VALGRIND_PMC_EMIT_LOG((emit_log));\
} while (0)
#define VALGRIND_START_TX do {\
if (On_pmemcheck)\
VALGRIND_PMC_START_TX;\
} while (0)
#define VALGRIND_START_TX_N(txn) do {\
if (On_pmemcheck)\
VALGRIND_PMC_START_TX_N(txn);\
} while (0)
#define VALGRIND_END_TX do {\
if (On_pmemcheck)\
VALGRIND_PMC_END_TX;\
} while (0)
#define VALGRIND_END_TX_N(txn) do {\
if (On_pmemcheck)\
VALGRIND_PMC_END_TX_N(txn);\
} while (0)
#define VALGRIND_ADD_TO_TX(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_ADD_TO_TX(addr, len);\
} while (0)
#define VALGRIND_ADD_TO_TX_N(txn, addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_ADD_TO_TX_N(txn, addr, len);\
} while (0)
#define VALGRIND_REMOVE_FROM_TX(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_REMOVE_FROM_TX(addr, len);\
} while (0)
#define VALGRIND_REMOVE_FROM_TX_N(txn, addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_REMOVE_FROM_TX_N(txn, addr, len);\
} while (0)
#define VALGRIND_ADD_TO_GLOBAL_TX_IGNORE(addr, len) do {\
if (On_pmemcheck)\
VALGRIND_PMC_ADD_TO_GLOBAL_TX_IGNORE(addr, len);\
} while (0)
/*
* Logs library and function name with proper suffix
* to pmemcheck store log file.
*/
#define PMEMOBJ_API_START()\
if (Pmreorder_emit)\
pobj_emit_log(__func__, 0);
#define PMEMOBJ_API_END()\
if (Pmreorder_emit)\
pobj_emit_log(__func__, 1);
#define PMEM_API_START()\
if (Pmreorder_emit)\
pmem_emit_log(__func__, 0);
#define PMEM_API_END()\
if (Pmreorder_emit)\
pmem_emit_log(__func__, 1);
#define PMEM2_API_START(func_name)\
if (Pmreorder_emit)\
pmem2_emit_log(func_name, 0);
#define PMEM2_API_END(func_name)\
if (Pmreorder_emit)\
pmem2_emit_log(func_name, 1);
#else
#define On_pmemcheck (0)
#define Pmreorder_emit (0)
#define VALGRIND_REGISTER_PMEM_MAPPING(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_REGISTER_PMEM_FILE(desc, base_addr, size, offset) do {\
(void) (desc);\
(void) (base_addr);\
(void) (size);\
(void) (offset);\
} while (0)
#define VALGRIND_REMOVE_PMEM_MAPPING(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_CHECK_IS_PMEM_MAPPING(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_PRINT_PMEM_MAPPINGS do {} while (0)
#define VALGRIND_DO_FLUSH(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_DO_FENCE do {} while (0)
#define VALGRIND_DO_PERSIST(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_SET_CLEAN(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_WRITE_STATS do {} while (0)
#define VALGRIND_EMIT_LOG(emit_log) do {\
(void) (emit_log);\
} while (0)
#define VALGRIND_START_TX do {} while (0)
#define VALGRIND_START_TX_N(txn) do { (void) (txn); } while (0)
#define VALGRIND_END_TX do {} while (0)
#define VALGRIND_END_TX_N(txn) do {\
(void) (txn);\
} while (0)
#define VALGRIND_ADD_TO_TX(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_ADD_TO_TX_N(txn, addr, len) do {\
(void) (txn);\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_REMOVE_FROM_TX(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_REMOVE_FROM_TX_N(txn, addr, len) do {\
(void) (txn);\
(void) (addr);\
(void) (len);\
} while (0)
#define VALGRIND_ADD_TO_GLOBAL_TX_IGNORE(addr, len) do {\
(void) (addr);\
(void) (len);\
} while (0)
#define PMEMOBJ_API_START() do {} while (0)
#define PMEMOBJ_API_END() do {} while (0)
#define PMEM_API_START() do {} while (0)
#define PMEM_API_END() do {} while (0)
#define PMEM2_API_START(func_name) do {\
(void) (func_name);\
} while (0)
#define PMEM2_API_END(func_name) do {\
(void) (func_name);\
} while (0)
#endif
#if VG_MEMCHECK_ENABLED
extern unsigned _On_memcheck;
#define On_memcheck __builtin_expect(_On_memcheck, 0)
#include "valgrind/memcheck.h"
#define VALGRIND_DO_DISABLE_ERROR_REPORTING do {\
if (On_valgrind)\
VALGRIND_DISABLE_ERROR_REPORTING;\
} while (0)
#define VALGRIND_DO_ENABLE_ERROR_REPORTING do {\
if (On_valgrind)\
VALGRIND_ENABLE_ERROR_REPORTING;\
} while (0)
#define VALGRIND_DO_CREATE_MEMPOOL(heap, rzB, is_zeroed) do {\
if (On_memcheck)\
VALGRIND_CREATE_MEMPOOL(heap, rzB, is_zeroed);\
} while (0)
#define VALGRIND_DO_DESTROY_MEMPOOL(heap) do {\
if (On_memcheck)\
VALGRIND_DESTROY_MEMPOOL(heap);\
} while (0)
#define VALGRIND_DO_MEMPOOL_ALLOC(heap, addr, size) do {\
if (On_memcheck)\
VALGRIND_MEMPOOL_ALLOC(heap, addr, size);\
} while (0)
#define VALGRIND_DO_MEMPOOL_FREE(heap, addr) do {\
if (On_memcheck)\
VALGRIND_MEMPOOL_FREE(heap, addr);\
} while (0)
#define VALGRIND_DO_MEMPOOL_CHANGE(heap, addrA, addrB, size) do {\
if (On_memcheck)\
VALGRIND_MEMPOOL_CHANGE(heap, addrA, addrB, size);\
} while (0)
#define VALGRIND_DO_MAKE_MEM_DEFINED(addr, len) do {\
if (On_memcheck)\
VALGRIND_MAKE_MEM_DEFINED(addr, len);\
} while (0)
#define VALGRIND_DO_MAKE_MEM_UNDEFINED(addr, len) do {\
if (On_memcheck)\
VALGRIND_MAKE_MEM_UNDEFINED(addr, len);\
} while (0)
#define VALGRIND_DO_MAKE_MEM_NOACCESS(addr, len) do {\
if (On_memcheck)\
VALGRIND_MAKE_MEM_NOACCESS(addr, len);\
} while (0)
#define VALGRIND_DO_CHECK_MEM_IS_ADDRESSABLE(addr, len) do {\
if (On_memcheck)\
VALGRIND_CHECK_MEM_IS_ADDRESSABLE(addr, len);\
} while (0)
#else
#define On_memcheck (0)
#define VALGRIND_DO_DISABLE_ERROR_REPORTING do {} while (0)
#define VALGRIND_DO_ENABLE_ERROR_REPORTING do {} while (0)
#define VALGRIND_DO_CREATE_MEMPOOL(heap, rzB, is_zeroed)\
do { (void) (heap); (void) (rzB); (void) (is_zeroed); } while (0)
#define VALGRIND_DO_DESTROY_MEMPOOL(heap)\
do { (void) (heap); } while (0)
#define VALGRIND_DO_MEMPOOL_ALLOC(heap, addr, size)\
do { (void) (heap); (void) (addr); (void) (size); } while (0)
#define VALGRIND_DO_MEMPOOL_FREE(heap, addr)\
do { (void) (heap); (void) (addr); } while (0)
#define VALGRIND_DO_MEMPOOL_CHANGE(heap, addrA, addrB, size)\
do {\
(void) (heap); (void) (addrA); (void) (addrB); (void) (size);\
} while (0)
#define VALGRIND_DO_MAKE_MEM_DEFINED(addr, len)\
do { (void) (addr); (void) (len); } while (0)
#define VALGRIND_DO_MAKE_MEM_UNDEFINED(addr, len)\
do { (void) (addr); (void) (len); } while (0)
#define VALGRIND_DO_MAKE_MEM_NOACCESS(addr, len)\
do { (void) (addr); (void) (len); } while (0)
#define VALGRIND_DO_CHECK_MEM_IS_ADDRESSABLE(addr, len)\
do { (void) (addr); (void) (len); } while (0)
#endif
#endif
| 11,169 | 22.319415 | 75 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/fs.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* fs.h -- file system traversal abstraction layer
*/
#ifndef PMDK_FS_H
#define PMDK_FS_H 1
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
struct fs;
enum fs_entry_type {
FS_ENTRY_FILE,
FS_ENTRY_DIRECTORY,
FS_ENTRY_SYMLINK,
FS_ENTRY_OTHER,
MAX_FS_ENTRY_TYPES
};
struct fs_entry {
enum fs_entry_type type;
const char *name;
size_t namelen;
const char *path;
size_t pathlen;
/* the depth of the traversal */
/* XXX long on FreeBSD. Linux uses short. No harm in it being bigger */
long level;
};
struct fs *fs_new(const char *path);
void fs_delete(struct fs *f);
/* this call invalidates the previous entry */
struct fs_entry *fs_read(struct fs *f);
#ifdef __cplusplus
}
#endif
#endif /* PMDK_FS_H */
| 827 | 14.923077 | 72 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/alloc.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
#ifndef COMMON_ALLOC_H
#define COMMON_ALLOC_H
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*Malloc_func)(size_t size);
typedef void *(*Realloc_func)(void *ptr, size_t size);
extern Malloc_func fn_malloc;
extern Realloc_func fn_realloc;
#if FAULT_INJECTION
void *_flt_Malloc(size_t, const char *);
void *_flt_Realloc(void *, size_t, const char *);
#define Malloc(size) _flt_Malloc(size, __func__)
#define Realloc(ptr, size) _flt_Realloc(ptr, size, __func__)
#else
void *_Malloc(size_t);
void *_Realloc(void *, size_t);
#define Malloc(size) _Malloc(size)
#define Realloc(ptr, size) _Realloc(ptr, size)
#endif
void set_func_malloc(void *(*malloc_func)(size_t size));
void set_func_realloc(void *(*realloc_func)(void *ptr, size_t size));
/*
* overridable names for malloc & friends used by this library
*/
typedef void (*Free_func)(void *ptr);
typedef char *(*Strdup_func)(const char *s);
extern Free_func Free;
extern Strdup_func Strdup;
extern void *Zalloc(size_t sz);
#ifdef __cplusplus
}
#endif
#endif
| 1,131 | 21.64 | 69 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/errno_freebsd.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* errno_freebsd.h -- map Linux errno's to something close on FreeBSD
*/
#ifndef PMDK_ERRNO_FREEBSD_H
#define PMDK_ERRNO_FREEBSD_H 1
#ifdef __FreeBSD__
#define EBADFD EBADF
#define ELIBACC EINVAL
#define EMEDIUMTYPE EOPNOTSUPP
#define ENOMEDIUM ENODEV
#define EREMOTEIO EIO
#endif
#endif /* PMDK_ERRNO_FREEBSD_H */
| 409 | 19.5 | 69 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/os_thread.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* Copyright (c) 2016, Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* os_thread.h -- os thread abstraction layer
*/
#ifndef OS_THREAD_H
#define OS_THREAD_H 1
#include <stdint.h>
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef union {
long long align;
char padding[44]; /* linux: 40 windows: 44 */
} os_mutex_t;
typedef union {
long long align;
char padding[56]; /* linux: 56 windows: 13 */
} os_rwlock_t;
typedef union {
long long align;
char padding[48]; /* linux: 48 windows: 12 */
} os_cond_t;
typedef union {
long long align;
char padding[32]; /* linux: 8 windows: 32 */
} os_thread_t;
typedef union {
long long align; /* linux: long windows: 8 FreeBSD: 12 */
char padding[16]; /* 16 to be safe */
} os_once_t;
#define OS_ONCE_INIT { .padding = {0} }
typedef unsigned os_tls_key_t;
typedef union {
long long align;
char padding[56]; /* linux: 56 windows: 8 */
} os_semaphore_t;
typedef union {
long long align;
char padding[56]; /* linux: 56 windows: 8 */
} os_thread_attr_t;
typedef union {
long long align;
char padding[512];
} os_cpu_set_t;
#ifdef __FreeBSD__
#define cpu_set_t cpuset_t
typedef uintptr_t os_spinlock_t;
#else
typedef volatile int os_spinlock_t; /* XXX: not implemented on windows */
#endif
void os_cpu_zero(os_cpu_set_t *set);
void os_cpu_set(size_t cpu, os_cpu_set_t *set);
#ifndef _WIN32
#define _When_(...)
#endif
int os_once(os_once_t *o, void (*func)(void));
int os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *));
int os_tls_key_delete(os_tls_key_t key);
int os_tls_set(os_tls_key_t key, const void *value);
void *os_tls_get(os_tls_key_t key);
int os_mutex_init(os_mutex_t *__restrict mutex);
int os_mutex_destroy(os_mutex_t *__restrict mutex);
_When_(return == 0, _Acquires_lock_(mutex->lock))
int os_mutex_lock(os_mutex_t *__restrict mutex);
_When_(return == 0, _Acquires_lock_(mutex->lock))
int os_mutex_trylock(os_mutex_t *__restrict mutex);
int os_mutex_unlock(os_mutex_t *__restrict mutex);
/* XXX - non POSIX */
int os_mutex_timedlock(os_mutex_t *__restrict mutex,
const struct timespec *abstime);
int os_rwlock_init(os_rwlock_t *__restrict rwlock);
int os_rwlock_destroy(os_rwlock_t *__restrict rwlock);
int os_rwlock_rdlock(os_rwlock_t *__restrict rwlock);
int os_rwlock_wrlock(os_rwlock_t *__restrict rwlock);
int os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock);
_When_(return == 0, _Acquires_exclusive_lock_(rwlock->lock))
int os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock);
_When_(rwlock->is_write != 0, _Requires_exclusive_lock_held_(rwlock->lock))
_When_(rwlock->is_write == 0, _Requires_shared_lock_held_(rwlock->lock))
int os_rwlock_unlock(os_rwlock_t *__restrict rwlock);
int os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime);
int os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime);
int os_spin_init(os_spinlock_t *lock, int pshared);
int os_spin_destroy(os_spinlock_t *lock);
int os_spin_lock(os_spinlock_t *lock);
int os_spin_unlock(os_spinlock_t *lock);
int os_spin_trylock(os_spinlock_t *lock);
int os_cond_init(os_cond_t *__restrict cond);
int os_cond_destroy(os_cond_t *__restrict cond);
int os_cond_broadcast(os_cond_t *__restrict cond);
int os_cond_signal(os_cond_t *__restrict cond);
int os_cond_timedwait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex, const struct timespec *abstime);
int os_cond_wait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex);
/* threading */
int os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
int os_thread_join(os_thread_t *thread, void **result);
void os_thread_self(os_thread_t *thread);
/* thread affinity */
int os_thread_setaffinity_np(os_thread_t *thread, size_t set_size,
const os_cpu_set_t *set);
int os_thread_atfork(void (*prepare)(void), void (*parent)(void),
void (*child)(void));
int os_semaphore_init(os_semaphore_t *sem, unsigned value);
int os_semaphore_destroy(os_semaphore_t *sem);
int os_semaphore_wait(os_semaphore_t *sem);
int os_semaphore_trywait(os_semaphore_t *sem);
int os_semaphore_post(os_semaphore_t *sem);
#ifdef __cplusplus
}
#endif
#endif /* OS_THREAD_H */
| 5,876 | 31.291209 | 75 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/out.h | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* out.h -- definitions for "out" module
*/
#ifndef PMDK_OUT_H
#define PMDK_OUT_H 1
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include "util.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Suppress errors which are after appropriate ASSERT* macro for nondebug
* builds.
*/
#if !defined(DEBUG) && (defined(__clang_analyzer__) || defined(__COVERITY__) ||\
defined(__KLOCWORK__))
#define OUT_FATAL_DISCARD_NORETURN __attribute__((noreturn))
#else
#define OUT_FATAL_DISCARD_NORETURN
#endif
#ifndef EVALUATE_DBG_EXPRESSIONS
#if defined(DEBUG) || defined(__clang_analyzer__) || defined(__COVERITY__) ||\
defined(__KLOCWORK__)
#define EVALUATE_DBG_EXPRESSIONS 1
#else
#define EVALUATE_DBG_EXPRESSIONS 0
#endif
#endif
#ifdef DEBUG
#define OUT_LOG out_log
#define OUT_NONL out_nonl
#define OUT_FATAL out_fatal
#define OUT_FATAL_ABORT out_fatal
#else
static __attribute__((always_inline)) inline void
out_log_discard(const char *file, int line, const char *func, int level,
const char *fmt, ...)
{
(void) file;
(void) line;
(void) func;
(void) level;
(void) fmt;
}
static __attribute__((always_inline)) inline void
out_nonl_discard(int level, const char *fmt, ...)
{
(void) level;
(void) fmt;
}
static __attribute__((always_inline)) OUT_FATAL_DISCARD_NORETURN inline void
out_fatal_discard(const char *file, int line, const char *func,
const char *fmt, ...)
{
(void) file;
(void) line;
(void) func;
(void) fmt;
}
static __attribute__((always_inline)) NORETURN inline void
out_fatal_abort(const char *file, int line, const char *func,
const char *fmt, ...)
{
(void) file;
(void) line;
(void) func;
(void) fmt;
abort();
}
#define OUT_LOG out_log_discard
#define OUT_NONL out_nonl_discard
#define OUT_FATAL out_fatal_discard
#define OUT_FATAL_ABORT out_fatal_abort
#endif
#if defined(__KLOCWORK__)
#define TEST_ALWAYS_TRUE_EXPR(cnd)
#define TEST_ALWAYS_EQ_EXPR(cnd)
#define TEST_ALWAYS_NE_EXPR(cnd)
#else
#define TEST_ALWAYS_TRUE_EXPR(cnd)\
if (__builtin_constant_p(cnd))\
ASSERT_COMPILE_ERROR_ON(cnd);
#define TEST_ALWAYS_EQ_EXPR(lhs, rhs)\
if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\
ASSERT_COMPILE_ERROR_ON((lhs) == (rhs));
#define TEST_ALWAYS_NE_EXPR(lhs, rhs)\
if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\
ASSERT_COMPILE_ERROR_ON((lhs) != (rhs));
#endif
/* produce debug/trace output */
#define LOG(level, ...) do { \
if (!EVALUATE_DBG_EXPRESSIONS) break;\
OUT_LOG(__FILE__, __LINE__, __func__, level, __VA_ARGS__);\
} while (0)
/* produce debug/trace output without prefix and new line */
#define LOG_NONL(level, ...) do { \
if (!EVALUATE_DBG_EXPRESSIONS) break; \
OUT_NONL(level, __VA_ARGS__); \
} while (0)
/* produce output and exit */
#define FATAL(...)\
OUT_FATAL_ABORT(__FILE__, __LINE__, __func__, __VA_ARGS__)
/* assert a condition is true at runtime */
#define ASSERT_rt(cnd) do { \
if (!EVALUATE_DBG_EXPRESSIONS || (cnd)) break; \
OUT_FATAL(__FILE__, __LINE__, __func__, "assertion failure: %s", #cnd);\
} while (0)
/* assertion with extra info printed if assertion fails at runtime */
#define ASSERTinfo_rt(cnd, info) do { \
if (!EVALUATE_DBG_EXPRESSIONS || (cnd)) break; \
OUT_FATAL(__FILE__, __LINE__, __func__, \
"assertion failure: %s (%s = %s)", #cnd, #info, info);\
} while (0)
/* assert two integer values are equal at runtime */
#define ASSERTeq_rt(lhs, rhs) do { \
if (!EVALUATE_DBG_EXPRESSIONS || ((lhs) == (rhs))) break; \
OUT_FATAL(__FILE__, __LINE__, __func__,\
"assertion failure: %s (0x%llx) == %s (0x%llx)", #lhs,\
(unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)); \
} while (0)
/* assert two integer values are not equal at runtime */
#define ASSERTne_rt(lhs, rhs) do { \
if (!EVALUATE_DBG_EXPRESSIONS || ((lhs) != (rhs))) break; \
OUT_FATAL(__FILE__, __LINE__, __func__,\
"assertion failure: %s (0x%llx) != %s (0x%llx)", #lhs,\
(unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)); \
} while (0)
/* assert a condition is true */
#define ASSERT(cnd)\
do {\
/*\
* Detect useless asserts on always true expression. Please use\
* COMPILE_ERROR_ON(!cnd) or ASSERT_rt(cnd) in such cases.\
*/\
TEST_ALWAYS_TRUE_EXPR(cnd);\
ASSERT_rt(cnd);\
} while (0)
/* assertion with extra info printed if assertion fails */
#define ASSERTinfo(cnd, info)\
do {\
/* See comment in ASSERT. */\
TEST_ALWAYS_TRUE_EXPR(cnd);\
ASSERTinfo_rt(cnd, info);\
} while (0)
/* assert two integer values are equal */
#define ASSERTeq(lhs, rhs)\
do {\
/* See comment in ASSERT. */\
TEST_ALWAYS_EQ_EXPR(lhs, rhs);\
ASSERTeq_rt(lhs, rhs);\
} while (0)
/* assert two integer values are not equal */
#define ASSERTne(lhs, rhs)\
do {\
/* See comment in ASSERT. */\
TEST_ALWAYS_NE_EXPR(lhs, rhs);\
ASSERTne_rt(lhs, rhs);\
} while (0)
#define ERR(...)\
out_err(__FILE__, __LINE__, __func__, __VA_ARGS__)
void out_init(const char *log_prefix, const char *log_level_var,
const char *log_file_var, int major_version,
int minor_version);
void out_fini(void);
void out(const char *fmt, ...) FORMAT_PRINTF(1, 2);
void out_nonl(int level, const char *fmt, ...) FORMAT_PRINTF(2, 3);
void out_log(const char *file, int line, const char *func, int level,
const char *fmt, ...) FORMAT_PRINTF(5, 6);
void out_err(const char *file, int line, const char *func,
const char *fmt, ...) FORMAT_PRINTF(4, 5);
void NORETURN out_fatal(const char *file, int line, const char *func,
const char *fmt, ...) FORMAT_PRINTF(4, 5);
void out_set_print_func(void (*print_func)(const char *s));
void out_set_vsnprintf_func(int (*vsnprintf_func)(char *str, size_t size,
const char *format, va_list ap));
#ifdef _WIN32
#ifndef PMDK_UTF8_API
#define out_get_errormsg out_get_errormsgW
#else
#define out_get_errormsg out_get_errormsgU
#endif
#endif
#ifndef _WIN32
const char *out_get_errormsg(void);
#else
const char *out_get_errormsgU(void);
const wchar_t *out_get_errormsgW(void);
#endif
#ifdef __cplusplus
}
#endif
#endif
| 6,066 | 25.150862 | 80 | h |
null | NearPMSW-main/nearpm/checkpointing/pmdk-checkpoint1/src/core/valgrind/memcheck.h |
/*
----------------------------------------------------------------
Notice that the following BSD-style license applies to this one
file (memcheck.h) only. The rest of Valgrind is licensed under the
terms of the GNU General Public License, version 2, unless
otherwise indicated. See the COPYING file in the source
distribution for details.
----------------------------------------------------------------
This file is part of MemCheck, a heavyweight Valgrind tool for
detecting memory errors.
Copyright (C) 2000-2017 Julian Seward. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------
Notice that the above BSD-style license applies to this one file
(memcheck.h) only. The entire rest of Valgrind is licensed under
the terms of the GNU General Public License, version 2. See the
COPYING file in the source distribution for details.
----------------------------------------------------------------
*/
#ifndef __MEMCHECK_H
#define __MEMCHECK_H
/* This file is for inclusion into client (your!) code.
You can use these macros to manipulate and query memory permissions
inside your own programs.
See comment near the top of valgrind.h on how to use them.
*/
#include "valgrind.h"
/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !!
This enum comprises an ABI exported by Valgrind to programs
which use client requests. DO NOT CHANGE THE ORDER OF THESE
ENTRIES, NOR DELETE ANY -- add new ones at the end. */
typedef
enum {
VG_USERREQ__MAKE_MEM_NOACCESS = VG_USERREQ_TOOL_BASE('M','C'),
VG_USERREQ__MAKE_MEM_UNDEFINED,
VG_USERREQ__MAKE_MEM_DEFINED,
VG_USERREQ__DISCARD,
VG_USERREQ__CHECK_MEM_IS_ADDRESSABLE,
VG_USERREQ__CHECK_MEM_IS_DEFINED,
VG_USERREQ__DO_LEAK_CHECK,
VG_USERREQ__COUNT_LEAKS,
VG_USERREQ__GET_VBITS,
VG_USERREQ__SET_VBITS,
VG_USERREQ__CREATE_BLOCK,
VG_USERREQ__MAKE_MEM_DEFINED_IF_ADDRESSABLE,
/* Not next to VG_USERREQ__COUNT_LEAKS because it was added later. */
VG_USERREQ__COUNT_LEAK_BLOCKS,
VG_USERREQ__ENABLE_ADDR_ERROR_REPORTING_IN_RANGE,
VG_USERREQ__DISABLE_ADDR_ERROR_REPORTING_IN_RANGE,
VG_USERREQ__CHECK_MEM_IS_UNADDRESSABLE,
VG_USERREQ__CHECK_MEM_IS_UNDEFINED,
/* This is just for memcheck's internal use - don't use it */
_VG_USERREQ__MEMCHECK_RECORD_OVERLAP_ERROR
= VG_USERREQ_TOOL_BASE('M','C') + 256
} Vg_MemCheckClientRequest;
/* Client-code macros to manipulate the state of memory. */
/* Mark memory at _qzz_addr as unaddressable for _qzz_len bytes. */
#define VALGRIND_MAKE_MEM_NOACCESS(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__MAKE_MEM_NOACCESS, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Similarly, mark memory at _qzz_addr as addressable but undefined
for _qzz_len bytes. */
#define VALGRIND_MAKE_MEM_UNDEFINED(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__MAKE_MEM_UNDEFINED, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Similarly, mark memory at _qzz_addr as addressable and defined
for _qzz_len bytes. */
#define VALGRIND_MAKE_MEM_DEFINED(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__MAKE_MEM_DEFINED, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Similar to VALGRIND_MAKE_MEM_DEFINED except that addressability is
not altered: bytes which are addressable are marked as defined,
but those which are not addressable are left unchanged. */
#define VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__MAKE_MEM_DEFINED_IF_ADDRESSABLE, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Create a block-description handle. The description is an ascii
string which is included in any messages pertaining to addresses
within the specified memory range. Has no other effect on the
properties of the memory range. */
#define VALGRIND_CREATE_BLOCK(_qzz_addr,_qzz_len, _qzz_desc) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__CREATE_BLOCK, \
(_qzz_addr), (_qzz_len), (_qzz_desc), \
0, 0)
/* Discard a block-description-handle. Returns 1 for an
invalid handle, 0 for a valid handle. */
#define VALGRIND_DISCARD(_qzz_blkindex) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__DISCARD, \
0, (_qzz_blkindex), 0, 0, 0)
/* Client-code macros to check the state of memory. */
/* Check that memory at _qzz_addr is addressable for _qzz_len bytes.
If suitable addressability is not established, Valgrind prints an
error message and returns the address of the first offending byte.
Otherwise it returns zero. */
#define VALGRIND_CHECK_MEM_IS_ADDRESSABLE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__CHECK_MEM_IS_ADDRESSABLE, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Check that memory at _qzz_addr is addressable and defined for
_qzz_len bytes. If suitable addressability and definedness are not
established, Valgrind prints an error message and returns the
address of the first offending byte. Otherwise it returns zero. */
#define VALGRIND_CHECK_MEM_IS_DEFINED(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__CHECK_MEM_IS_DEFINED, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Use this macro to force the definedness and addressability of an
lvalue to be checked. If suitable addressability and definedness
are not established, Valgrind prints an error message and returns
the address of the first offending byte. Otherwise it returns
zero. */
#define VALGRIND_CHECK_VALUE_IS_DEFINED(__lvalue) \
VALGRIND_CHECK_MEM_IS_DEFINED( \
(volatile unsigned char *)&(__lvalue), \
(unsigned long)(sizeof (__lvalue)))
/* Check that memory at _qzz_addr is unaddressable for _qzz_len bytes.
If any byte in this range is addressable, Valgrind returns the
address of the first offending byte. Otherwise it returns zero. */
#define VALGRIND_CHECK_MEM_IS_UNADDRESSABLE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__CHECK_MEM_IS_UNADDRESSABLE,\
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Check that memory at _qzz_addr is undefined for _qzz_len bytes. If any
byte in this range is defined or unaddressable, Valgrind returns the
address of the first offending byte. Otherwise it returns zero. */
#define VALGRIND_CHECK_MEM_IS_UNDEFINED(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__CHECK_MEM_IS_UNDEFINED, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/* Do a full memory leak check (like --leak-check=full) mid-execution. */
#define VALGRIND_DO_LEAK_CHECK \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \
0, 0, 0, 0, 0)
/* Same as VALGRIND_DO_LEAK_CHECK but only showing the entries for
which there was an increase in leaked bytes or leaked nr of blocks
since the previous leak search. */
#define VALGRIND_DO_ADDED_LEAK_CHECK \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \
0, 1, 0, 0, 0)
/* Same as VALGRIND_DO_ADDED_LEAK_CHECK but showing entries with
increased or decreased leaked bytes/blocks since previous leak
search. */
#define VALGRIND_DO_CHANGED_LEAK_CHECK \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \
0, 2, 0, 0, 0)
/* Do a summary memory leak check (like --leak-check=summary) mid-execution. */
#define VALGRIND_DO_QUICK_LEAK_CHECK \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \
1, 0, 0, 0, 0)
/* Return number of leaked, dubious, reachable and suppressed bytes found by
all previous leak checks. They must be lvalues. */
#define VALGRIND_COUNT_LEAKS(leaked, dubious, reachable, suppressed) \
/* For safety on 64-bit platforms we assign the results to private
unsigned long variables, then assign these to the lvalues the user
specified, which works no matter what type 'leaked', 'dubious', etc
are. We also initialise '_qzz_leaked', etc because
VG_USERREQ__COUNT_LEAKS doesn't mark the values returned as
defined. */ \
{ \
unsigned long _qzz_leaked = 0, _qzz_dubious = 0; \
unsigned long _qzz_reachable = 0, _qzz_suppressed = 0; \
VALGRIND_DO_CLIENT_REQUEST_STMT( \
VG_USERREQ__COUNT_LEAKS, \
&_qzz_leaked, &_qzz_dubious, \
&_qzz_reachable, &_qzz_suppressed, 0); \
leaked = _qzz_leaked; \
dubious = _qzz_dubious; \
reachable = _qzz_reachable; \
suppressed = _qzz_suppressed; \
}
/* Return number of leaked, dubious, reachable and suppressed bytes found by
all previous leak checks. They must be lvalues. */
#define VALGRIND_COUNT_LEAK_BLOCKS(leaked, dubious, reachable, suppressed) \
/* For safety on 64-bit platforms we assign the results to private
unsigned long variables, then assign these to the lvalues the user
specified, which works no matter what type 'leaked', 'dubious', etc
are. We also initialise '_qzz_leaked', etc because
VG_USERREQ__COUNT_LEAKS doesn't mark the values returned as
defined. */ \
{ \
unsigned long _qzz_leaked = 0, _qzz_dubious = 0; \
unsigned long _qzz_reachable = 0, _qzz_suppressed = 0; \
VALGRIND_DO_CLIENT_REQUEST_STMT( \
VG_USERREQ__COUNT_LEAK_BLOCKS, \
&_qzz_leaked, &_qzz_dubious, \
&_qzz_reachable, &_qzz_suppressed, 0); \
leaked = _qzz_leaked; \
dubious = _qzz_dubious; \
reachable = _qzz_reachable; \
suppressed = _qzz_suppressed; \
}
/* Get the validity data for addresses [zza..zza+zznbytes-1] and copy it
into the provided zzvbits array. Return values:
0 if not running on valgrind
1 success
2 [previously indicated unaligned arrays; these are now allowed]
3 if any parts of zzsrc/zzvbits are not addressable.
The metadata is not copied in cases 0, 2 or 3 so it should be
impossible to segfault your system by using this call.
*/
#define VALGRIND_GET_VBITS(zza,zzvbits,zznbytes) \
(unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__GET_VBITS, \
(const char*)(zza), \
(char*)(zzvbits), \
(zznbytes), 0, 0)
/* Set the validity data for addresses [zza..zza+zznbytes-1], copying it
from the provided zzvbits array. Return values:
0 if not running on valgrind
1 success
2 [previously indicated unaligned arrays; these are now allowed]
3 if any parts of zza/zzvbits are not addressable.
The metadata is not copied in cases 0, 2 or 3 so it should be
impossible to segfault your system by using this call.
*/
#define VALGRIND_SET_VBITS(zza,zzvbits,zznbytes) \
(unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \
VG_USERREQ__SET_VBITS, \
(const char*)(zza), \
(const char*)(zzvbits), \
(zznbytes), 0, 0 )
/* Disable and re-enable reporting of addressing errors in the
specified address range. */
#define VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__DISABLE_ADDR_ERROR_REPORTING_IN_RANGE, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
#define VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__ENABLE_ADDR_ERROR_REPORTING_IN_RANGE, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
#endif
| 15,621 | 47.666667 | 79 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.