repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_nt_sse2.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_sse2.h"
#include "out.h"
#include "valgrind_internal.h"
static force_inline void
mm_stream_si128(char *dest, unsigned idx, __m128i src)
{
_mm_stream_si128((__m128i *)dest + idx, src);
barrier();
}
static force_inline void
memset_movnt4x64b(char *dest, __m128i xmm)
{
mm_stream_si128(dest, 0, xmm);
mm_stream_si128(dest, 1, xmm);
mm_stream_si128(dest, 2, xmm);
mm_stream_si128(dest, 3, xmm);
mm_stream_si128(dest, 4, xmm);
mm_stream_si128(dest, 5, xmm);
mm_stream_si128(dest, 6, xmm);
mm_stream_si128(dest, 7, xmm);
mm_stream_si128(dest, 8, xmm);
mm_stream_si128(dest, 9, xmm);
mm_stream_si128(dest, 10, xmm);
mm_stream_si128(dest, 11, xmm);
mm_stream_si128(dest, 12, xmm);
mm_stream_si128(dest, 13, xmm);
mm_stream_si128(dest, 14, xmm);
mm_stream_si128(dest, 15, xmm);
}
static force_inline void
memset_movnt2x64b(char *dest, __m128i xmm)
{
mm_stream_si128(dest, 0, xmm);
mm_stream_si128(dest, 1, xmm);
mm_stream_si128(dest, 2, xmm);
mm_stream_si128(dest, 3, xmm);
mm_stream_si128(dest, 4, xmm);
mm_stream_si128(dest, 5, xmm);
mm_stream_si128(dest, 6, xmm);
mm_stream_si128(dest, 7, xmm);
}
static force_inline void
memset_movnt1x64b(char *dest, __m128i xmm)
{
mm_stream_si128(dest, 0, xmm);
mm_stream_si128(dest, 1, xmm);
mm_stream_si128(dest, 2, xmm);
mm_stream_si128(dest, 3, xmm);
}
static force_inline void
memset_movnt1x32b(char *dest, __m128i xmm)
{
mm_stream_si128(dest, 0, xmm);
mm_stream_si128(dest, 1, xmm);
}
static force_inline void
memset_movnt1x16b(char *dest, __m128i xmm)
{
_mm_stream_si128((__m128i *)dest, xmm);
}
static force_inline void
memset_movnt1x8b(char *dest, __m128i xmm)
{
uint64_t x = (uint64_t)_mm_cvtsi128_si64(xmm);
_mm_stream_si64((long long *)dest, (long long)x);
}
static force_inline void
memset_movnt1x4b(char *dest, __m128i xmm)
{
uint32_t x = (uint32_t)_mm_cvtsi128_si32(xmm);
_mm_stream_si32((int *)dest, (int)x);
}
static force_inline void
memset_movnt_sse2(char *dest, int c, size_t len, flush_fn flush,
barrier_fn barrier, perf_barrier_fn perf_barrier)
{
char *orig_dest = dest;
size_t orig_len = len;
__m128i xmm = _mm_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_sse2(dest, xmm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= PERF_BARRIER_SIZE) {
memset_movnt4x64b(dest, xmm);
dest += 4 * 64;
len -= 4 * 64;
memset_movnt4x64b(dest, xmm);
dest += 4 * 64;
len -= 4 * 64;
memset_movnt4x64b(dest, xmm);
dest += 4 * 64;
len -= 4 * 64;
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (4 + 4 + 4) * 64);
if (len)
perf_barrier();
}
while (len >= 4 * 64) {
memset_movnt4x64b(dest, xmm);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_movnt2x64b(dest, xmm);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_movnt1x64b(dest, xmm);
dest += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memset_movnt1x32b(dest, xmm);
else if (len == 16)
memset_movnt1x16b(dest, xmm);
else if (len == 8)
memset_movnt1x8b(dest, xmm);
else if (len == 4)
memset_movnt1x4b(dest, xmm);
else
goto nonnt;
goto end;
}
nonnt:
memset_small_sse2(dest, xmm, len, flush);
end:
barrier();
VALGRIND_DO_FLUSH(orig_dest, orig_len);
}
/* variants without perf_barrier */
void
memset_movnt_sse2_noflush_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, noflush, barrier_after_ntstores,
no_barrier);
}
void
memset_movnt_sse2_empty_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_empty_nolog,
barrier_after_ntstores, no_barrier);
}
void
memset_movnt_sse2_clflush_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clflush_nolog,
barrier_after_ntstores, no_barrier);
}
void
memset_movnt_sse2_clflushopt_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, no_barrier);
}
void
memset_movnt_sse2_clwb_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clwb_nolog,
no_barrier_after_ntstores, no_barrier);
}
/* variants with perf_barrier */
void
memset_movnt_sse2_noflush_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, noflush, barrier_after_ntstores,
wc_barrier);
}
void
memset_movnt_sse2_empty_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_empty_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_sse2_clflush_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clflush_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_sse2_clflushopt_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_sse2_clwb_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_sse2(dest, c, len, flush_clwb_nolog,
no_barrier_after_ntstores, wc_barrier);
}
| 5,912 | 20.580292 | 71 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_nt_avx.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_avx.h"
#include "out.h"
#include "valgrind_internal.h"
static force_inline void
mm256_stream_si256(char *dest, unsigned idx, __m256i src)
{
_mm256_stream_si256((__m256i *)dest + idx, src);
barrier();
}
static force_inline void
memset_movnt8x64b(char *dest, __m256i ymm)
{
mm256_stream_si256(dest, 0, ymm);
mm256_stream_si256(dest, 1, ymm);
mm256_stream_si256(dest, 2, ymm);
mm256_stream_si256(dest, 3, ymm);
mm256_stream_si256(dest, 4, ymm);
mm256_stream_si256(dest, 5, ymm);
mm256_stream_si256(dest, 6, ymm);
mm256_stream_si256(dest, 7, ymm);
mm256_stream_si256(dest, 8, ymm);
mm256_stream_si256(dest, 9, ymm);
mm256_stream_si256(dest, 10, ymm);
mm256_stream_si256(dest, 11, ymm);
mm256_stream_si256(dest, 12, ymm);
mm256_stream_si256(dest, 13, ymm);
mm256_stream_si256(dest, 14, ymm);
mm256_stream_si256(dest, 15, ymm);
}
static force_inline void
memset_movnt4x64b(char *dest, __m256i ymm)
{
mm256_stream_si256(dest, 0, ymm);
mm256_stream_si256(dest, 1, ymm);
mm256_stream_si256(dest, 2, ymm);
mm256_stream_si256(dest, 3, ymm);
mm256_stream_si256(dest, 4, ymm);
mm256_stream_si256(dest, 5, ymm);
mm256_stream_si256(dest, 6, ymm);
mm256_stream_si256(dest, 7, ymm);
}
static force_inline void
memset_movnt2x64b(char *dest, __m256i ymm)
{
mm256_stream_si256(dest, 0, ymm);
mm256_stream_si256(dest, 1, ymm);
mm256_stream_si256(dest, 2, ymm);
mm256_stream_si256(dest, 3, ymm);
}
static force_inline void
memset_movnt1x64b(char *dest, __m256i ymm)
{
mm256_stream_si256(dest, 0, ymm);
mm256_stream_si256(dest, 1, ymm);
}
static force_inline void
memset_movnt1x32b(char *dest, __m256i ymm)
{
mm256_stream_si256(dest, 0, ymm);
}
static force_inline void
memset_movnt1x16b(char *dest, __m256i ymm)
{
__m128i xmm0 = m256_get16b(ymm);
_mm_stream_si128((__m128i *)dest, xmm0);
}
static force_inline void
memset_movnt1x8b(char *dest, __m256i ymm)
{
uint64_t x = m256_get8b(ymm);
_mm_stream_si64((long long *)dest, (long long)x);
}
static force_inline void
memset_movnt1x4b(char *dest, __m256i ymm)
{
uint32_t x = m256_get4b(ymm);
_mm_stream_si32((int *)dest, (int)x);
}
static force_inline void
memset_movnt_avx(char *dest, int c, size_t len, flush_fn flush,
barrier_fn barrier, perf_barrier_fn perf_barrier)
{
char *orig_dest = dest;
size_t orig_len = len;
__m256i ymm = _mm256_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_avx(dest, ymm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= PERF_BARRIER_SIZE) {
memset_movnt8x64b(dest, ymm);
dest += 8 * 64;
len -= 8 * 64;
memset_movnt4x64b(dest, ymm);
dest += 4 * 64;
len -= 4 * 64;
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (8 + 4) * 64);
if (len)
perf_barrier();
}
if (len >= 8 * 64) {
memset_movnt8x64b(dest, ymm);
dest += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memset_movnt4x64b(dest, ymm);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_movnt2x64b(dest, ymm);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_movnt1x64b(dest, ymm);
dest += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memset_movnt1x32b(dest, ymm);
else if (len == 16)
memset_movnt1x16b(dest, ymm);
else if (len == 8)
memset_movnt1x8b(dest, ymm);
else if (len == 4)
memset_movnt1x4b(dest, ymm);
else
goto nonnt;
goto end;
}
nonnt:
memset_small_avx(dest, ymm, len, flush);
end:
avx_zeroupper();
barrier();
VALGRIND_DO_FLUSH(orig_dest, orig_len);
}
/* variants without perf_barrier */
void
memset_movnt_avx_noflush_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, noflush, barrier_after_ntstores,
no_barrier);
}
void
memset_movnt_avx_empty_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_empty_nolog,
barrier_after_ntstores, no_barrier);
}
void
memset_movnt_avx_clflush_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clflush_nolog,
barrier_after_ntstores, no_barrier);
}
void
memset_movnt_avx_clflushopt_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, no_barrier);
}
void
memset_movnt_avx_clwb_nobarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clwb_nolog,
no_barrier_after_ntstores, no_barrier);
}
/* variants with perf_barrier */
void
memset_movnt_avx_noflush_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, noflush, barrier_after_ntstores,
wc_barrier);
}
void
memset_movnt_avx_empty_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_empty_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_avx_clflush_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clflush_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_avx_clflushopt_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, wc_barrier);
}
void
memset_movnt_avx_clwb_wcbarrier(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx(dest, c, len, flush_clwb_nolog,
no_barrier_after_ntstores, wc_barrier);
}
| 6,151 | 20.43554 | 71 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_t_avx512f.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_avx512f.h"
static force_inline void
mm512_store_si512(char *dest, unsigned idx, __m512i src)
{
_mm512_store_si512((__m512i *)dest + idx, src);
}
static force_inline void
memset_mov32x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
mm512_store_si512(dest, 1, zmm);
mm512_store_si512(dest, 2, zmm);
mm512_store_si512(dest, 3, zmm);
mm512_store_si512(dest, 4, zmm);
mm512_store_si512(dest, 5, zmm);
mm512_store_si512(dest, 6, zmm);
mm512_store_si512(dest, 7, zmm);
mm512_store_si512(dest, 8, zmm);
mm512_store_si512(dest, 9, zmm);
mm512_store_si512(dest, 10, zmm);
mm512_store_si512(dest, 11, zmm);
mm512_store_si512(dest, 12, zmm);
mm512_store_si512(dest, 13, zmm);
mm512_store_si512(dest, 14, zmm);
mm512_store_si512(dest, 15, zmm);
mm512_store_si512(dest, 16, zmm);
mm512_store_si512(dest, 17, zmm);
mm512_store_si512(dest, 18, zmm);
mm512_store_si512(dest, 19, zmm);
mm512_store_si512(dest, 20, zmm);
mm512_store_si512(dest, 21, zmm);
mm512_store_si512(dest, 22, zmm);
mm512_store_si512(dest, 23, zmm);
mm512_store_si512(dest, 24, zmm);
mm512_store_si512(dest, 25, zmm);
mm512_store_si512(dest, 26, zmm);
mm512_store_si512(dest, 27, zmm);
mm512_store_si512(dest, 28, zmm);
mm512_store_si512(dest, 29, zmm);
mm512_store_si512(dest, 30, zmm);
mm512_store_si512(dest, 31, zmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
flush64b(dest + 8 * 64);
flush64b(dest + 9 * 64);
flush64b(dest + 10 * 64);
flush64b(dest + 11 * 64);
flush64b(dest + 12 * 64);
flush64b(dest + 13 * 64);
flush64b(dest + 14 * 64);
flush64b(dest + 15 * 64);
flush64b(dest + 16 * 64);
flush64b(dest + 17 * 64);
flush64b(dest + 18 * 64);
flush64b(dest + 19 * 64);
flush64b(dest + 20 * 64);
flush64b(dest + 21 * 64);
flush64b(dest + 22 * 64);
flush64b(dest + 23 * 64);
flush64b(dest + 24 * 64);
flush64b(dest + 25 * 64);
flush64b(dest + 26 * 64);
flush64b(dest + 27 * 64);
flush64b(dest + 28 * 64);
flush64b(dest + 29 * 64);
flush64b(dest + 30 * 64);
flush64b(dest + 31 * 64);
}
static force_inline void
memset_mov16x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
mm512_store_si512(dest, 1, zmm);
mm512_store_si512(dest, 2, zmm);
mm512_store_si512(dest, 3, zmm);
mm512_store_si512(dest, 4, zmm);
mm512_store_si512(dest, 5, zmm);
mm512_store_si512(dest, 6, zmm);
mm512_store_si512(dest, 7, zmm);
mm512_store_si512(dest, 8, zmm);
mm512_store_si512(dest, 9, zmm);
mm512_store_si512(dest, 10, zmm);
mm512_store_si512(dest, 11, zmm);
mm512_store_si512(dest, 12, zmm);
mm512_store_si512(dest, 13, zmm);
mm512_store_si512(dest, 14, zmm);
mm512_store_si512(dest, 15, zmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
flush64b(dest + 8 * 64);
flush64b(dest + 9 * 64);
flush64b(dest + 10 * 64);
flush64b(dest + 11 * 64);
flush64b(dest + 12 * 64);
flush64b(dest + 13 * 64);
flush64b(dest + 14 * 64);
flush64b(dest + 15 * 64);
}
static force_inline void
memset_mov8x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
mm512_store_si512(dest, 1, zmm);
mm512_store_si512(dest, 2, zmm);
mm512_store_si512(dest, 3, zmm);
mm512_store_si512(dest, 4, zmm);
mm512_store_si512(dest, 5, zmm);
mm512_store_si512(dest, 6, zmm);
mm512_store_si512(dest, 7, zmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
}
static force_inline void
memset_mov4x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
mm512_store_si512(dest, 1, zmm);
mm512_store_si512(dest, 2, zmm);
mm512_store_si512(dest, 3, zmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memset_mov2x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
mm512_store_si512(dest, 1, zmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memset_mov1x64b(char *dest, __m512i zmm, flush64b_fn flush64b)
{
mm512_store_si512(dest, 0, zmm);
flush64b(dest + 0 * 64);
}
static force_inline void
memset_mov_avx512f(char *dest, int c, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
__m512i zmm = _mm512_set1_epi8((char)c);
/* See comment in memset_movnt_avx512f */
__m256i ymm = _mm256_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_avx512f(dest, ymm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= 32 * 64) {
memset_mov32x64b(dest, zmm, flush64b);
dest += 32 * 64;
len -= 32 * 64;
}
if (len >= 16 * 64) {
memset_mov16x64b(dest, zmm, flush64b);
dest += 16 * 64;
len -= 16 * 64;
}
if (len >= 8 * 64) {
memset_mov8x64b(dest, zmm, flush64b);
dest += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memset_mov4x64b(dest, zmm, flush64b);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_mov2x64b(dest, zmm, flush64b);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_mov1x64b(dest, zmm, flush64b);
dest += 1 * 64;
len -= 1 * 64;
}
if (len)
memset_small_avx512f(dest, ymm, len, flush);
avx_zeroupper();
}
void
memset_mov_avx512f_noflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx512f(dest, c, len, noflush, noflush64b);
}
void
memset_mov_avx512f_empty(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx512f(dest, c, len, flush_empty_nolog, flush64b_empty);
}
void
memset_mov_avx512f_clflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx512f(dest, c, len, flush_clflush_nolog, pmem_clflush);
}
void
memset_mov_avx512f_clflushopt(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx512f(dest, c, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memset_mov_avx512f_clwb(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx512f(dest, c, len, flush_clwb_nolog, pmem_clwb);
}
| 6,851 | 22.958042 | 69 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_nt_avx512f.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_avx512f.h"
#include "out.h"
#include "util.h"
#include "valgrind_internal.h"
static force_inline void
mm512_stream_si512(char *dest, unsigned idx, __m512i src)
{
_mm512_stream_si512((__m512i *)dest + idx, src);
barrier();
}
static force_inline void
memset_movnt32x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
mm512_stream_si512(dest, 1, zmm);
mm512_stream_si512(dest, 2, zmm);
mm512_stream_si512(dest, 3, zmm);
mm512_stream_si512(dest, 4, zmm);
mm512_stream_si512(dest, 5, zmm);
mm512_stream_si512(dest, 6, zmm);
mm512_stream_si512(dest, 7, zmm);
mm512_stream_si512(dest, 8, zmm);
mm512_stream_si512(dest, 9, zmm);
mm512_stream_si512(dest, 10, zmm);
mm512_stream_si512(dest, 11, zmm);
mm512_stream_si512(dest, 12, zmm);
mm512_stream_si512(dest, 13, zmm);
mm512_stream_si512(dest, 14, zmm);
mm512_stream_si512(dest, 15, zmm);
mm512_stream_si512(dest, 16, zmm);
mm512_stream_si512(dest, 17, zmm);
mm512_stream_si512(dest, 18, zmm);
mm512_stream_si512(dest, 19, zmm);
mm512_stream_si512(dest, 20, zmm);
mm512_stream_si512(dest, 21, zmm);
mm512_stream_si512(dest, 22, zmm);
mm512_stream_si512(dest, 23, zmm);
mm512_stream_si512(dest, 24, zmm);
mm512_stream_si512(dest, 25, zmm);
mm512_stream_si512(dest, 26, zmm);
mm512_stream_si512(dest, 27, zmm);
mm512_stream_si512(dest, 28, zmm);
mm512_stream_si512(dest, 29, zmm);
mm512_stream_si512(dest, 30, zmm);
mm512_stream_si512(dest, 31, zmm);
}
static force_inline void
memset_movnt16x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
mm512_stream_si512(dest, 1, zmm);
mm512_stream_si512(dest, 2, zmm);
mm512_stream_si512(dest, 3, zmm);
mm512_stream_si512(dest, 4, zmm);
mm512_stream_si512(dest, 5, zmm);
mm512_stream_si512(dest, 6, zmm);
mm512_stream_si512(dest, 7, zmm);
mm512_stream_si512(dest, 8, zmm);
mm512_stream_si512(dest, 9, zmm);
mm512_stream_si512(dest, 10, zmm);
mm512_stream_si512(dest, 11, zmm);
mm512_stream_si512(dest, 12, zmm);
mm512_stream_si512(dest, 13, zmm);
mm512_stream_si512(dest, 14, zmm);
mm512_stream_si512(dest, 15, zmm);
}
static force_inline void
memset_movnt8x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
mm512_stream_si512(dest, 1, zmm);
mm512_stream_si512(dest, 2, zmm);
mm512_stream_si512(dest, 3, zmm);
mm512_stream_si512(dest, 4, zmm);
mm512_stream_si512(dest, 5, zmm);
mm512_stream_si512(dest, 6, zmm);
mm512_stream_si512(dest, 7, zmm);
}
static force_inline void
memset_movnt4x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
mm512_stream_si512(dest, 1, zmm);
mm512_stream_si512(dest, 2, zmm);
mm512_stream_si512(dest, 3, zmm);
}
static force_inline void
memset_movnt2x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
mm512_stream_si512(dest, 1, zmm);
}
static force_inline void
memset_movnt1x64b(char *dest, __m512i zmm)
{
mm512_stream_si512(dest, 0, zmm);
}
static force_inline void
memset_movnt1x32b(char *dest, __m256i ymm)
{
_mm256_stream_si256((__m256i *)dest, ymm);
}
static force_inline void
memset_movnt1x16b(char *dest, __m256i ymm)
{
__m128i xmm = _mm256_extracti128_si256(ymm, 0);
_mm_stream_si128((__m128i *)dest, xmm);
}
static force_inline void
memset_movnt1x8b(char *dest, __m256i ymm)
{
uint64_t x = m256_get8b(ymm);
_mm_stream_si64((long long *)dest, (long long)x);
}
static force_inline void
memset_movnt1x4b(char *dest, __m256i ymm)
{
uint32_t x = m256_get4b(ymm);
_mm_stream_si32((int *)dest, (int)x);
}
static force_inline void
memset_movnt_avx512f(char *dest, int c, size_t len, flush_fn flush,
barrier_fn barrier)
{
char *orig_dest = dest;
size_t orig_len = len;
__m512i zmm = _mm512_set1_epi8((char)c);
/*
* Can't use _mm512_extracti64x4_epi64, because some versions of gcc
* crash. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82887
*/
__m256i ymm = _mm256_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_avx512f(dest, ymm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= 32 * 64) {
memset_movnt32x64b(dest, zmm);
dest += 32 * 64;
len -= 32 * 64;
}
if (len >= 16 * 64) {
memset_movnt16x64b(dest, zmm);
dest += 16 * 64;
len -= 16 * 64;
}
if (len >= 8 * 64) {
memset_movnt8x64b(dest, zmm);
dest += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memset_movnt4x64b(dest, zmm);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_movnt2x64b(dest, zmm);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_movnt1x64b(dest, zmm);
dest += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memset_movnt1x32b(dest, ymm);
else if (len == 16)
memset_movnt1x16b(dest, ymm);
else if (len == 8)
memset_movnt1x8b(dest, ymm);
else if (len == 4)
memset_movnt1x4b(dest, ymm);
else
goto nonnt;
goto end;
}
nonnt:
memset_small_avx512f(dest, ymm, len, flush);
end:
avx_zeroupper();
barrier();
VALGRIND_DO_FLUSH(orig_dest, orig_len);
}
void
memset_movnt_avx512f_noflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx512f(dest, c, len, noflush, barrier_after_ntstores);
}
void
memset_movnt_avx512f_empty(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx512f(dest, c, len, flush_empty_nolog,
barrier_after_ntstores);
}
void
memset_movnt_avx512f_clflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx512f(dest, c, len, flush_clflush_nolog,
barrier_after_ntstores);
}
void
memset_movnt_avx512f_clflushopt(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx512f(dest, c, len, flush_clflushopt_nolog,
no_barrier_after_ntstores);
}
void
memset_movnt_avx512f_clwb(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_movnt_avx512f(dest, c, len, flush_clwb_nolog,
no_barrier_after_ntstores);
}
| 6,397 | 21.607774 | 71 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_t_sse2.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_sse2.h"
static force_inline void
mm_store_si128(char *dest, unsigned idx, __m128i src)
{
_mm_store_si128((__m128i *)dest + idx, src);
}
static force_inline void
memset_mov4x64b(char *dest, __m128i xmm, flush64b_fn flush64b)
{
mm_store_si128(dest, 0, xmm);
mm_store_si128(dest, 1, xmm);
mm_store_si128(dest, 2, xmm);
mm_store_si128(dest, 3, xmm);
mm_store_si128(dest, 4, xmm);
mm_store_si128(dest, 5, xmm);
mm_store_si128(dest, 6, xmm);
mm_store_si128(dest, 7, xmm);
mm_store_si128(dest, 8, xmm);
mm_store_si128(dest, 9, xmm);
mm_store_si128(dest, 10, xmm);
mm_store_si128(dest, 11, xmm);
mm_store_si128(dest, 12, xmm);
mm_store_si128(dest, 13, xmm);
mm_store_si128(dest, 14, xmm);
mm_store_si128(dest, 15, xmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memset_mov2x64b(char *dest, __m128i xmm, flush64b_fn flush64b)
{
mm_store_si128(dest, 0, xmm);
mm_store_si128(dest, 1, xmm);
mm_store_si128(dest, 2, xmm);
mm_store_si128(dest, 3, xmm);
mm_store_si128(dest, 4, xmm);
mm_store_si128(dest, 5, xmm);
mm_store_si128(dest, 6, xmm);
mm_store_si128(dest, 7, xmm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memset_mov1x64b(char *dest, __m128i xmm, flush64b_fn flush64b)
{
mm_store_si128(dest, 0, xmm);
mm_store_si128(dest, 1, xmm);
mm_store_si128(dest, 2, xmm);
mm_store_si128(dest, 3, xmm);
flush64b(dest + 0 * 64);
}
static force_inline void
memset_mov_sse2(char *dest, int c, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
__m128i xmm = _mm_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_sse2(dest, xmm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= 4 * 64) {
memset_mov4x64b(dest, xmm, flush64b);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_mov2x64b(dest, xmm, flush64b);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_mov1x64b(dest, xmm, flush64b);
dest += 1 * 64;
len -= 1 * 64;
}
if (len)
memset_small_sse2(dest, xmm, len, flush);
}
void
memset_mov_sse2_noflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_sse2(dest, c, len, noflush, noflush64b);
}
void
memset_mov_sse2_empty(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_sse2(dest, c, len, flush_empty_nolog, flush64b_empty);
}
void
memset_mov_sse2_clflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_sse2(dest, c, len, flush_clflush_nolog, pmem_clflush);
}
void
memset_mov_sse2_clflushopt(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_sse2(dest, c, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memset_mov_sse2_clwb(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_sse2(dest, c, len, flush_clwb_nolog, pmem_clwb);
}
| 3,304 | 20.461039 | 66 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_sse2.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#ifndef PMEM2_MEMSET_SSE2_H
#define PMEM2_MEMSET_SSE2_H
#include <xmmintrin.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "out.h"
static force_inline void
memset_small_sse2_noflush(char *dest, __m128i xmm, size_t len)
{
ASSERT(len <= 64);
if (len <= 8)
goto le8;
if (len <= 32)
goto le32;
if (len > 48) {
/* 49..64 */
_mm_storeu_si128((__m128i *)(dest + 0), xmm);
_mm_storeu_si128((__m128i *)(dest + 16), xmm);
_mm_storeu_si128((__m128i *)(dest + 32), xmm);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm);
return;
}
/* 33..48 */
_mm_storeu_si128((__m128i *)(dest + 0), xmm);
_mm_storeu_si128((__m128i *)(dest + 16), xmm);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm);
return;
le32:
if (len > 16) {
/* 17..32 */
_mm_storeu_si128((__m128i *)(dest + 0), xmm);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm);
return;
}
/* 9..16 */
uint64_t d8 = (uint64_t)_mm_cvtsi128_si64(xmm);
*(ua_uint64_t *)dest = d8;
*(ua_uint64_t *)(dest + len - 8) = d8;
return;
le8:
if (len <= 2)
goto le2;
if (len > 4) {
/* 5..8 */
uint32_t d4 = (uint32_t)_mm_cvtsi128_si32(xmm);
*(ua_uint32_t *)dest = d4;
*(ua_uint32_t *)(dest + len - 4) = d4;
return;
}
/* 3..4 */
uint16_t d2 = (uint16_t)(uint32_t)_mm_cvtsi128_si32(xmm);
*(ua_uint16_t *)dest = d2;
*(ua_uint16_t *)(dest + len - 2) = d2;
return;
le2:
if (len == 2) {
uint16_t d2 = (uint16_t)(uint32_t)_mm_cvtsi128_si32(xmm);
*(ua_uint16_t *)dest = d2;
return;
}
*(uint8_t *)dest = (uint8_t)_mm_cvtsi128_si32(xmm);
}
static force_inline void
memset_small_sse2(char *dest, __m128i xmm, size_t len, flush_fn flush)
{
/*
* pmemcheck complains about "overwritten stores before they were made
* persistent" for overlapping stores (last instruction in each code
* path) in the optimized version.
* libc's memset also does that, so we can't use it here.
*/
if (On_pmemcheck) {
memset_nodrain_generic(dest, (uint8_t)_mm_cvtsi128_si32(xmm),
len, PMEM2_F_MEM_NOFLUSH, NULL);
} else {
memset_small_sse2_noflush(dest, xmm, len);
}
flush(dest, len);
}
#endif
| 2,213 | 20.085714 | 71 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memset/memset_t_avx.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memset_avx.h"
static force_inline void
mm256_store_si256(char *dest, unsigned idx, __m256i src)
{
_mm256_store_si256((__m256i *)dest + idx, src);
}
static force_inline void
memset_mov8x64b(char *dest, __m256i ymm, flush64b_fn flush64b)
{
mm256_store_si256(dest, 0, ymm);
mm256_store_si256(dest, 1, ymm);
mm256_store_si256(dest, 2, ymm);
mm256_store_si256(dest, 3, ymm);
mm256_store_si256(dest, 4, ymm);
mm256_store_si256(dest, 5, ymm);
mm256_store_si256(dest, 6, ymm);
mm256_store_si256(dest, 7, ymm);
mm256_store_si256(dest, 8, ymm);
mm256_store_si256(dest, 9, ymm);
mm256_store_si256(dest, 10, ymm);
mm256_store_si256(dest, 11, ymm);
mm256_store_si256(dest, 12, ymm);
mm256_store_si256(dest, 13, ymm);
mm256_store_si256(dest, 14, ymm);
mm256_store_si256(dest, 15, ymm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
}
static force_inline void
memset_mov4x64b(char *dest, __m256i ymm, flush64b_fn flush64b)
{
mm256_store_si256(dest, 0, ymm);
mm256_store_si256(dest, 1, ymm);
mm256_store_si256(dest, 2, ymm);
mm256_store_si256(dest, 3, ymm);
mm256_store_si256(dest, 4, ymm);
mm256_store_si256(dest, 5, ymm);
mm256_store_si256(dest, 6, ymm);
mm256_store_si256(dest, 7, ymm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memset_mov2x64b(char *dest, __m256i ymm, flush64b_fn flush64b)
{
mm256_store_si256(dest, 0, ymm);
mm256_store_si256(dest, 1, ymm);
mm256_store_si256(dest, 2, ymm);
mm256_store_si256(dest, 3, ymm);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memset_mov1x64b(char *dest, __m256i ymm, flush64b_fn flush64b)
{
mm256_store_si256(dest, 0, ymm);
mm256_store_si256(dest, 1, ymm);
flush64b(dest + 0 * 64);
}
static force_inline void
memset_mov_avx(char *dest, int c, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
__m256i ymm = _mm256_set1_epi8((char)c);
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memset_small_avx(dest, ymm, cnt, flush);
dest += cnt;
len -= cnt;
}
while (len >= 8 * 64) {
memset_mov8x64b(dest, ymm, flush64b);
dest += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memset_mov4x64b(dest, ymm, flush64b);
dest += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memset_mov2x64b(dest, ymm, flush64b);
dest += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memset_mov1x64b(dest, ymm, flush64b);
dest += 1 * 64;
len -= 1 * 64;
}
if (len)
memset_small_avx(dest, ymm, len, flush);
avx_zeroupper();
}
void
memset_mov_avx_noflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx(dest, c, len, noflush, noflush64b);
}
void
memset_mov_avx_empty(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx(dest, c, len, flush_empty_nolog, flush64b_empty);
}
void
memset_mov_avx_clflush(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx(dest, c, len, flush_clflush_nolog, pmem_clflush);
}
void
memset_mov_avx_clflushopt(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx(dest, c, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memset_mov_avx_clwb(char *dest, int c, size_t len)
{
LOG(15, "dest %p c %d len %zu", dest, c, len);
memset_mov_avx(dest, c, len, flush_clwb_nolog, pmem_clwb);
}
| 3,890 | 20.73743 | 65 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_t_sse2.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_sse2.h"
#include "out.h"
static force_inline __m128i
mm_loadu_si128(const char *src, unsigned idx)
{
return _mm_loadu_si128((const __m128i *)src + idx);
}
static force_inline void
mm_store_si128(char *dest, unsigned idx, __m128i src)
{
_mm_store_si128((__m128i *)dest + idx, src);
}
static force_inline void
memmove_mov4x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
__m128i xmm4 = mm_loadu_si128(src, 4);
__m128i xmm5 = mm_loadu_si128(src, 5);
__m128i xmm6 = mm_loadu_si128(src, 6);
__m128i xmm7 = mm_loadu_si128(src, 7);
__m128i xmm8 = mm_loadu_si128(src, 8);
__m128i xmm9 = mm_loadu_si128(src, 9);
__m128i xmm10 = mm_loadu_si128(src, 10);
__m128i xmm11 = mm_loadu_si128(src, 11);
__m128i xmm12 = mm_loadu_si128(src, 12);
__m128i xmm13 = mm_loadu_si128(src, 13);
__m128i xmm14 = mm_loadu_si128(src, 14);
__m128i xmm15 = mm_loadu_si128(src, 15);
mm_store_si128(dest, 0, xmm0);
mm_store_si128(dest, 1, xmm1);
mm_store_si128(dest, 2, xmm2);
mm_store_si128(dest, 3, xmm3);
mm_store_si128(dest, 4, xmm4);
mm_store_si128(dest, 5, xmm5);
mm_store_si128(dest, 6, xmm6);
mm_store_si128(dest, 7, xmm7);
mm_store_si128(dest, 8, xmm8);
mm_store_si128(dest, 9, xmm9);
mm_store_si128(dest, 10, xmm10);
mm_store_si128(dest, 11, xmm11);
mm_store_si128(dest, 12, xmm12);
mm_store_si128(dest, 13, xmm13);
mm_store_si128(dest, 14, xmm14);
mm_store_si128(dest, 15, xmm15);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memmove_mov2x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
__m128i xmm4 = mm_loadu_si128(src, 4);
__m128i xmm5 = mm_loadu_si128(src, 5);
__m128i xmm6 = mm_loadu_si128(src, 6);
__m128i xmm7 = mm_loadu_si128(src, 7);
mm_store_si128(dest, 0, xmm0);
mm_store_si128(dest, 1, xmm1);
mm_store_si128(dest, 2, xmm2);
mm_store_si128(dest, 3, xmm3);
mm_store_si128(dest, 4, xmm4);
mm_store_si128(dest, 5, xmm5);
mm_store_si128(dest, 6, xmm6);
mm_store_si128(dest, 7, xmm7);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memmove_mov1x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
mm_store_si128(dest, 0, xmm0);
mm_store_si128(dest, 1, xmm1);
mm_store_si128(dest, 2, xmm2);
mm_store_si128(dest, 3, xmm3);
flush64b(dest + 0 * 64);
}
static force_inline void
memmove_mov_sse_fw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_sse2(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
while (len >= 4 * 64) {
memmove_mov4x64b(dest, src, flush64b);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_mov2x64b(dest, src, flush64b);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_mov1x64b(dest, src, flush64b);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len)
memmove_small_sse2(dest, src, len, flush);
}
static force_inline void
memmove_mov_sse_bw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_sse2(dest, src, cnt, flush);
}
while (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_mov4x64b(dest, src, flush64b);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_mov2x64b(dest, src, flush64b);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_mov1x64b(dest, src, flush64b);
}
if (len)
memmove_small_sse2(dest - len, src - len, len, flush);
}
static force_inline void
memmove_mov_sse2(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_mov_sse_fw(dest, src, len, flush, flush64b);
else
memmove_mov_sse_bw(dest, src, len, flush, flush64b);
}
void
memmove_mov_sse2_noflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_sse2(dest, src, len, noflush, noflush64b);
}
void
memmove_mov_sse2_empty(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_sse2(dest, src, len, flush_empty_nolog, flush64b_empty);
}
void
memmove_mov_sse2_clflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_sse2(dest, src, len, flush_clflush_nolog, pmem_clflush);
}
void
memmove_mov_sse2_clflushopt(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_sse2(dest, src, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memmove_mov_sse2_clwb(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_sse2(dest, src, len, flush_clwb_nolog, pmem_clwb);
}
| 5,820 | 22.566802 | 69 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_avx.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#ifndef PMEM2_MEMCPY_AVX_H
#define PMEM2_MEMCPY_AVX_H
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "out.h"
static force_inline void
memmove_small_avx_noflush(char *dest, const char *src, size_t len)
{
ASSERT(len <= 64);
if (len <= 8)
goto le8;
if (len <= 32)
goto le32;
/* 33..64 */
__m256i ymm0 = _mm256_loadu_si256((__m256i *)src);
__m256i ymm1 = _mm256_loadu_si256((__m256i *)(src + len - 32));
_mm256_storeu_si256((__m256i *)dest, ymm0);
_mm256_storeu_si256((__m256i *)(dest + len - 32), ymm1);
return;
le32:
if (len > 16) {
/* 17..32 */
__m128i xmm0 = _mm_loadu_si128((__m128i *)src);
__m128i xmm1 = _mm_loadu_si128((__m128i *)(src + len - 16));
_mm_storeu_si128((__m128i *)dest, xmm0);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm1);
return;
}
/* 9..16 */
ua_uint64_t d80 = *(ua_uint64_t *)src;
ua_uint64_t d81 = *(ua_uint64_t *)(src + len - 8);
*(ua_uint64_t *)dest = d80;
*(ua_uint64_t *)(dest + len - 8) = d81;
return;
le8:
if (len <= 2)
goto le2;
if (len > 4) {
/* 5..8 */
ua_uint32_t d40 = *(ua_uint32_t *)src;
ua_uint32_t d41 = *(ua_uint32_t *)(src + len - 4);
*(ua_uint32_t *)dest = d40;
*(ua_uint32_t *)(dest + len - 4) = d41;
return;
}
/* 3..4 */
ua_uint16_t d20 = *(ua_uint16_t *)src;
ua_uint16_t d21 = *(ua_uint16_t *)(src + len - 2);
*(ua_uint16_t *)dest = d20;
*(ua_uint16_t *)(dest + len - 2) = d21;
return;
le2:
if (len == 2) {
*(ua_uint16_t *)dest = *(ua_uint16_t *)src;
return;
}
*(uint8_t *)dest = *(uint8_t *)src;
}
static force_inline void
memmove_small_avx(char *dest, const char *src, size_t len, flush_fn flush)
{
/*
* pmemcheck complains about "overwritten stores before they were made
* persistent" for overlapping stores (last instruction in each code
* path) in the optimized version.
* libc's memcpy also does that, so we can't use it here.
*/
if (On_pmemcheck) {
memmove_nodrain_generic(dest, src, len, PMEM2_F_MEM_NOFLUSH,
NULL);
} else {
memmove_small_avx_noflush(dest, src, len);
}
flush(dest, len);
}
#endif
| 2,173 | 20.524752 | 74 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_t_avx.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_avx.h"
static force_inline __m256i
mm256_loadu_si256(const char *src, unsigned idx)
{
return _mm256_loadu_si256((const __m256i *)src + idx);
}
static force_inline void
mm256_store_si256(char *dest, unsigned idx, __m256i src)
{
_mm256_store_si256((__m256i *)dest + idx, src);
}
static force_inline void
memmove_mov8x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
__m256i ymm4 = mm256_loadu_si256(src, 4);
__m256i ymm5 = mm256_loadu_si256(src, 5);
__m256i ymm6 = mm256_loadu_si256(src, 6);
__m256i ymm7 = mm256_loadu_si256(src, 7);
__m256i ymm8 = mm256_loadu_si256(src, 8);
__m256i ymm9 = mm256_loadu_si256(src, 9);
__m256i ymm10 = mm256_loadu_si256(src, 10);
__m256i ymm11 = mm256_loadu_si256(src, 11);
__m256i ymm12 = mm256_loadu_si256(src, 12);
__m256i ymm13 = mm256_loadu_si256(src, 13);
__m256i ymm14 = mm256_loadu_si256(src, 14);
__m256i ymm15 = mm256_loadu_si256(src, 15);
mm256_store_si256(dest, 0, ymm0);
mm256_store_si256(dest, 1, ymm1);
mm256_store_si256(dest, 2, ymm2);
mm256_store_si256(dest, 3, ymm3);
mm256_store_si256(dest, 4, ymm4);
mm256_store_si256(dest, 5, ymm5);
mm256_store_si256(dest, 6, ymm6);
mm256_store_si256(dest, 7, ymm7);
mm256_store_si256(dest, 8, ymm8);
mm256_store_si256(dest, 9, ymm9);
mm256_store_si256(dest, 10, ymm10);
mm256_store_si256(dest, 11, ymm11);
mm256_store_si256(dest, 12, ymm12);
mm256_store_si256(dest, 13, ymm13);
mm256_store_si256(dest, 14, ymm14);
mm256_store_si256(dest, 15, ymm15);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
}
static force_inline void
memmove_mov4x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
__m256i ymm4 = mm256_loadu_si256(src, 4);
__m256i ymm5 = mm256_loadu_si256(src, 5);
__m256i ymm6 = mm256_loadu_si256(src, 6);
__m256i ymm7 = mm256_loadu_si256(src, 7);
mm256_store_si256(dest, 0, ymm0);
mm256_store_si256(dest, 1, ymm1);
mm256_store_si256(dest, 2, ymm2);
mm256_store_si256(dest, 3, ymm3);
mm256_store_si256(dest, 4, ymm4);
mm256_store_si256(dest, 5, ymm5);
mm256_store_si256(dest, 6, ymm6);
mm256_store_si256(dest, 7, ymm7);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memmove_mov2x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
mm256_store_si256(dest, 0, ymm0);
mm256_store_si256(dest, 1, ymm1);
mm256_store_si256(dest, 2, ymm2);
mm256_store_si256(dest, 3, ymm3);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memmove_mov1x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
mm256_store_si256(dest, 0, ymm0);
mm256_store_si256(dest, 1, ymm1);
flush64b(dest + 0 * 64);
}
static force_inline void
memmove_mov_avx_fw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_avx(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
while (len >= 8 * 64) {
memmove_mov8x64b(dest, src, flush64b);
dest += 8 * 64;
src += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memmove_mov4x64b(dest, src, flush64b);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_mov2x64b(dest, src, flush64b);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_mov1x64b(dest, src, flush64b);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len)
memmove_small_avx(dest, src, len, flush);
}
static force_inline void
memmove_mov_avx_bw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_avx(dest, src, cnt, flush);
}
while (len >= 8 * 64) {
dest -= 8 * 64;
src -= 8 * 64;
len -= 8 * 64;
memmove_mov8x64b(dest, src, flush64b);
}
if (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_mov4x64b(dest, src, flush64b);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_mov2x64b(dest, src, flush64b);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_mov1x64b(dest, src, flush64b);
}
if (len)
memmove_small_avx(dest - len, src - len, len, flush);
}
static force_inline void
memmove_mov_avx(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_mov_avx_fw(dest, src, len, flush, flush64b);
else
memmove_mov_avx_bw(dest, src, len, flush, flush64b);
avx_zeroupper();
}
void
memmove_mov_avx_noflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx(dest, src, len, noflush, noflush64b);
}
void
memmove_mov_avx_empty(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx(dest, src, len, flush_empty_nolog, flush64b_empty);
}
void
memmove_mov_avx_clflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx(dest, src, len, flush_clflush_nolog, pmem_clflush);
}
void
memmove_mov_avx_clflushopt(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx(dest, src, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memmove_mov_avx_clwb(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx(dest, src, len, flush_clwb_nolog, pmem_clwb);
}
| 6,705 | 22.780142 | 68 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_t_avx512f.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_avx512f.h"
static force_inline __m512i
mm512_loadu_si512(const char *src, unsigned idx)
{
return _mm512_loadu_si512((const __m512i *)src + idx);
}
static force_inline void
mm512_store_si512(char *dest, unsigned idx, __m512i src)
{
_mm512_store_si512((__m512i *)dest + idx, src);
}
static force_inline void
memmove_mov32x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
__m512i zmm8 = mm512_loadu_si512(src, 8);
__m512i zmm9 = mm512_loadu_si512(src, 9);
__m512i zmm10 = mm512_loadu_si512(src, 10);
__m512i zmm11 = mm512_loadu_si512(src, 11);
__m512i zmm12 = mm512_loadu_si512(src, 12);
__m512i zmm13 = mm512_loadu_si512(src, 13);
__m512i zmm14 = mm512_loadu_si512(src, 14);
__m512i zmm15 = mm512_loadu_si512(src, 15);
__m512i zmm16 = mm512_loadu_si512(src, 16);
__m512i zmm17 = mm512_loadu_si512(src, 17);
__m512i zmm18 = mm512_loadu_si512(src, 18);
__m512i zmm19 = mm512_loadu_si512(src, 19);
__m512i zmm20 = mm512_loadu_si512(src, 20);
__m512i zmm21 = mm512_loadu_si512(src, 21);
__m512i zmm22 = mm512_loadu_si512(src, 22);
__m512i zmm23 = mm512_loadu_si512(src, 23);
__m512i zmm24 = mm512_loadu_si512(src, 24);
__m512i zmm25 = mm512_loadu_si512(src, 25);
__m512i zmm26 = mm512_loadu_si512(src, 26);
__m512i zmm27 = mm512_loadu_si512(src, 27);
__m512i zmm28 = mm512_loadu_si512(src, 28);
__m512i zmm29 = mm512_loadu_si512(src, 29);
__m512i zmm30 = mm512_loadu_si512(src, 30);
__m512i zmm31 = mm512_loadu_si512(src, 31);
mm512_store_si512(dest, 0, zmm0);
mm512_store_si512(dest, 1, zmm1);
mm512_store_si512(dest, 2, zmm2);
mm512_store_si512(dest, 3, zmm3);
mm512_store_si512(dest, 4, zmm4);
mm512_store_si512(dest, 5, zmm5);
mm512_store_si512(dest, 6, zmm6);
mm512_store_si512(dest, 7, zmm7);
mm512_store_si512(dest, 8, zmm8);
mm512_store_si512(dest, 9, zmm9);
mm512_store_si512(dest, 10, zmm10);
mm512_store_si512(dest, 11, zmm11);
mm512_store_si512(dest, 12, zmm12);
mm512_store_si512(dest, 13, zmm13);
mm512_store_si512(dest, 14, zmm14);
mm512_store_si512(dest, 15, zmm15);
mm512_store_si512(dest, 16, zmm16);
mm512_store_si512(dest, 17, zmm17);
mm512_store_si512(dest, 18, zmm18);
mm512_store_si512(dest, 19, zmm19);
mm512_store_si512(dest, 20, zmm20);
mm512_store_si512(dest, 21, zmm21);
mm512_store_si512(dest, 22, zmm22);
mm512_store_si512(dest, 23, zmm23);
mm512_store_si512(dest, 24, zmm24);
mm512_store_si512(dest, 25, zmm25);
mm512_store_si512(dest, 26, zmm26);
mm512_store_si512(dest, 27, zmm27);
mm512_store_si512(dest, 28, zmm28);
mm512_store_si512(dest, 29, zmm29);
mm512_store_si512(dest, 30, zmm30);
mm512_store_si512(dest, 31, zmm31);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
flush64b(dest + 8 * 64);
flush64b(dest + 9 * 64);
flush64b(dest + 10 * 64);
flush64b(dest + 11 * 64);
flush64b(dest + 12 * 64);
flush64b(dest + 13 * 64);
flush64b(dest + 14 * 64);
flush64b(dest + 15 * 64);
flush64b(dest + 16 * 64);
flush64b(dest + 17 * 64);
flush64b(dest + 18 * 64);
flush64b(dest + 19 * 64);
flush64b(dest + 20 * 64);
flush64b(dest + 21 * 64);
flush64b(dest + 22 * 64);
flush64b(dest + 23 * 64);
flush64b(dest + 24 * 64);
flush64b(dest + 25 * 64);
flush64b(dest + 26 * 64);
flush64b(dest + 27 * 64);
flush64b(dest + 28 * 64);
flush64b(dest + 29 * 64);
flush64b(dest + 30 * 64);
flush64b(dest + 31 * 64);
}
static force_inline void
memmove_mov16x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
__m512i zmm8 = mm512_loadu_si512(src, 8);
__m512i zmm9 = mm512_loadu_si512(src, 9);
__m512i zmm10 = mm512_loadu_si512(src, 10);
__m512i zmm11 = mm512_loadu_si512(src, 11);
__m512i zmm12 = mm512_loadu_si512(src, 12);
__m512i zmm13 = mm512_loadu_si512(src, 13);
__m512i zmm14 = mm512_loadu_si512(src, 14);
__m512i zmm15 = mm512_loadu_si512(src, 15);
mm512_store_si512(dest, 0, zmm0);
mm512_store_si512(dest, 1, zmm1);
mm512_store_si512(dest, 2, zmm2);
mm512_store_si512(dest, 3, zmm3);
mm512_store_si512(dest, 4, zmm4);
mm512_store_si512(dest, 5, zmm5);
mm512_store_si512(dest, 6, zmm6);
mm512_store_si512(dest, 7, zmm7);
mm512_store_si512(dest, 8, zmm8);
mm512_store_si512(dest, 9, zmm9);
mm512_store_si512(dest, 10, zmm10);
mm512_store_si512(dest, 11, zmm11);
mm512_store_si512(dest, 12, zmm12);
mm512_store_si512(dest, 13, zmm13);
mm512_store_si512(dest, 14, zmm14);
mm512_store_si512(dest, 15, zmm15);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
flush64b(dest + 8 * 64);
flush64b(dest + 9 * 64);
flush64b(dest + 10 * 64);
flush64b(dest + 11 * 64);
flush64b(dest + 12 * 64);
flush64b(dest + 13 * 64);
flush64b(dest + 14 * 64);
flush64b(dest + 15 * 64);
}
static force_inline void
memmove_mov8x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
mm512_store_si512(dest, 0, zmm0);
mm512_store_si512(dest, 1, zmm1);
mm512_store_si512(dest, 2, zmm2);
mm512_store_si512(dest, 3, zmm3);
mm512_store_si512(dest, 4, zmm4);
mm512_store_si512(dest, 5, zmm5);
mm512_store_si512(dest, 6, zmm6);
mm512_store_si512(dest, 7, zmm7);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
flush64b(dest + 4 * 64);
flush64b(dest + 5 * 64);
flush64b(dest + 6 * 64);
flush64b(dest + 7 * 64);
}
static force_inline void
memmove_mov4x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
mm512_store_si512(dest, 0, zmm0);
mm512_store_si512(dest, 1, zmm1);
mm512_store_si512(dest, 2, zmm2);
mm512_store_si512(dest, 3, zmm3);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
flush64b(dest + 2 * 64);
flush64b(dest + 3 * 64);
}
static force_inline void
memmove_mov2x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
mm512_store_si512(dest, 0, zmm0);
mm512_store_si512(dest, 1, zmm1);
flush64b(dest + 0 * 64);
flush64b(dest + 1 * 64);
}
static force_inline void
memmove_mov1x64b(char *dest, const char *src, flush64b_fn flush64b)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
mm512_store_si512(dest, 0, zmm0);
flush64b(dest + 0 * 64);
}
static force_inline void
memmove_mov_avx512f_fw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_avx512f(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
while (len >= 32 * 64) {
memmove_mov32x64b(dest, src, flush64b);
dest += 32 * 64;
src += 32 * 64;
len -= 32 * 64;
}
if (len >= 16 * 64) {
memmove_mov16x64b(dest, src, flush64b);
dest += 16 * 64;
src += 16 * 64;
len -= 16 * 64;
}
if (len >= 8 * 64) {
memmove_mov8x64b(dest, src, flush64b);
dest += 8 * 64;
src += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memmove_mov4x64b(dest, src, flush64b);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_mov2x64b(dest, src, flush64b);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_mov1x64b(dest, src, flush64b);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len)
memmove_small_avx512f(dest, src, len, flush);
}
static force_inline void
memmove_mov_avx512f_bw(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_avx512f(dest, src, cnt, flush);
}
while (len >= 32 * 64) {
dest -= 32 * 64;
src -= 32 * 64;
len -= 32 * 64;
memmove_mov32x64b(dest, src, flush64b);
}
if (len >= 16 * 64) {
dest -= 16 * 64;
src -= 16 * 64;
len -= 16 * 64;
memmove_mov16x64b(dest, src, flush64b);
}
if (len >= 8 * 64) {
dest -= 8 * 64;
src -= 8 * 64;
len -= 8 * 64;
memmove_mov8x64b(dest, src, flush64b);
}
if (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_mov4x64b(dest, src, flush64b);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_mov2x64b(dest, src, flush64b);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_mov1x64b(dest, src, flush64b);
}
if (len)
memmove_small_avx512f(dest - len, src - len, len, flush);
}
static force_inline void
memmove_mov_avx512f(char *dest, const char *src, size_t len,
flush_fn flush, flush64b_fn flush64b)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_mov_avx512f_fw(dest, src, len, flush, flush64b);
else
memmove_mov_avx512f_bw(dest, src, len, flush, flush64b);
avx_zeroupper();
}
void
memmove_mov_avx512f_noflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx512f(dest, src, len, noflush, noflush64b);
}
void
memmove_mov_avx512f_empty(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx512f(dest, src, len, flush_empty_nolog, flush64b_empty);
}
void
memmove_mov_avx512f_clflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx512f(dest, src, len, flush_clflush_nolog, pmem_clflush);
}
void
memmove_mov_avx512f_clflushopt(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx512f(dest, src, len, flush_clflushopt_nolog,
pmem_clflushopt);
}
void
memmove_mov_avx512f_clwb(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_mov_avx512f(dest, src, len, flush_clwb_nolog, pmem_clwb);
}
| 11,422 | 25.020501 | 72 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_sse2.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#ifndef PMEM2_MEMCPY_SSE2_H
#define PMEM2_MEMCPY_SSE2_H
#include <xmmintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "out.h"
static force_inline void
memmove_small_sse2_noflush(char *dest, const char *src, size_t len)
{
ASSERT(len <= 64);
if (len <= 8)
goto le8;
if (len <= 32)
goto le32;
if (len > 48) {
/* 49..64 */
__m128i xmm0 = _mm_loadu_si128((__m128i *)src);
__m128i xmm1 = _mm_loadu_si128((__m128i *)(src + 16));
__m128i xmm2 = _mm_loadu_si128((__m128i *)(src + 32));
__m128i xmm3 = _mm_loadu_si128((__m128i *)(src + len - 16));
_mm_storeu_si128((__m128i *)dest, xmm0);
_mm_storeu_si128((__m128i *)(dest + 16), xmm1);
_mm_storeu_si128((__m128i *)(dest + 32), xmm2);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm3);
return;
}
/* 33..48 */
__m128i xmm0 = _mm_loadu_si128((__m128i *)src);
__m128i xmm1 = _mm_loadu_si128((__m128i *)(src + 16));
__m128i xmm2 = _mm_loadu_si128((__m128i *)(src + len - 16));
_mm_storeu_si128((__m128i *)dest, xmm0);
_mm_storeu_si128((__m128i *)(dest + 16), xmm1);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm2);
return;
le32:
if (len > 16) {
/* 17..32 */
__m128i xmm0 = _mm_loadu_si128((__m128i *)src);
__m128i xmm1 = _mm_loadu_si128((__m128i *)(src + len - 16));
_mm_storeu_si128((__m128i *)dest, xmm0);
_mm_storeu_si128((__m128i *)(dest + len - 16), xmm1);
return;
}
/* 9..16 */
uint64_t d80 = *(ua_uint64_t *)src;
uint64_t d81 = *(ua_uint64_t *)(src + len - 8);
*(ua_uint64_t *)dest = d80;
*(ua_uint64_t *)(dest + len - 8) = d81;
return;
le8:
if (len <= 2)
goto le2;
if (len > 4) {
/* 5..8 */
uint32_t d40 = *(ua_uint32_t *)src;
uint32_t d41 = *(ua_uint32_t *)(src + len - 4);
*(ua_uint32_t *)dest = d40;
*(ua_uint32_t *)(dest + len - 4) = d41;
return;
}
/* 3..4 */
uint16_t d20 = *(ua_uint16_t *)src;
uint16_t d21 = *(ua_uint16_t *)(src + len - 2);
*(ua_uint16_t *)dest = d20;
*(ua_uint16_t *)(dest + len - 2) = d21;
return;
le2:
if (len == 2) {
*(ua_uint16_t *)dest = *(ua_uint16_t *)src;
return;
}
*(uint8_t *)dest = *(uint8_t *)src;
}
static force_inline void
memmove_small_sse2(char *dest, const char *src, size_t len, flush_fn flush)
{
/*
* pmemcheck complains about "overwritten stores before they were made
* persistent" for overlapping stores (last instruction in each code
* path) in the optimized version.
* libc's memcpy also does that, so we can't use it here.
*/
if (On_pmemcheck) {
memmove_nodrain_generic(dest, src, len, PMEM2_F_MEM_NOFLUSH,
NULL);
} else {
memmove_small_sse2_noflush(dest, src, len);
}
flush(dest, len);
}
#endif
| 2,726 | 22.307692 | 75 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_nt_avx.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_avx.h"
#include "valgrind_internal.h"
static force_inline __m256i
mm256_loadu_si256(const char *src, unsigned idx)
{
return _mm256_loadu_si256((const __m256i *)src + idx);
}
static force_inline void
mm256_stream_si256(char *dest, unsigned idx, __m256i src)
{
_mm256_stream_si256((__m256i *)dest + idx, src);
barrier();
}
static force_inline void
memmove_movnt8x64b(char *dest, const char *src)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
__m256i ymm4 = mm256_loadu_si256(src, 4);
__m256i ymm5 = mm256_loadu_si256(src, 5);
__m256i ymm6 = mm256_loadu_si256(src, 6);
__m256i ymm7 = mm256_loadu_si256(src, 7);
__m256i ymm8 = mm256_loadu_si256(src, 8);
__m256i ymm9 = mm256_loadu_si256(src, 9);
__m256i ymm10 = mm256_loadu_si256(src, 10);
__m256i ymm11 = mm256_loadu_si256(src, 11);
__m256i ymm12 = mm256_loadu_si256(src, 12);
__m256i ymm13 = mm256_loadu_si256(src, 13);
__m256i ymm14 = mm256_loadu_si256(src, 14);
__m256i ymm15 = mm256_loadu_si256(src, 15);
mm256_stream_si256(dest, 0, ymm0);
mm256_stream_si256(dest, 1, ymm1);
mm256_stream_si256(dest, 2, ymm2);
mm256_stream_si256(dest, 3, ymm3);
mm256_stream_si256(dest, 4, ymm4);
mm256_stream_si256(dest, 5, ymm5);
mm256_stream_si256(dest, 6, ymm6);
mm256_stream_si256(dest, 7, ymm7);
mm256_stream_si256(dest, 8, ymm8);
mm256_stream_si256(dest, 9, ymm9);
mm256_stream_si256(dest, 10, ymm10);
mm256_stream_si256(dest, 11, ymm11);
mm256_stream_si256(dest, 12, ymm12);
mm256_stream_si256(dest, 13, ymm13);
mm256_stream_si256(dest, 14, ymm14);
mm256_stream_si256(dest, 15, ymm15);
}
static force_inline void
memmove_movnt4x64b(char *dest, const char *src)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
__m256i ymm4 = mm256_loadu_si256(src, 4);
__m256i ymm5 = mm256_loadu_si256(src, 5);
__m256i ymm6 = mm256_loadu_si256(src, 6);
__m256i ymm7 = mm256_loadu_si256(src, 7);
mm256_stream_si256(dest, 0, ymm0);
mm256_stream_si256(dest, 1, ymm1);
mm256_stream_si256(dest, 2, ymm2);
mm256_stream_si256(dest, 3, ymm3);
mm256_stream_si256(dest, 4, ymm4);
mm256_stream_si256(dest, 5, ymm5);
mm256_stream_si256(dest, 6, ymm6);
mm256_stream_si256(dest, 7, ymm7);
}
static force_inline void
memmove_movnt2x64b(char *dest, const char *src)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
__m256i ymm2 = mm256_loadu_si256(src, 2);
__m256i ymm3 = mm256_loadu_si256(src, 3);
mm256_stream_si256(dest, 0, ymm0);
mm256_stream_si256(dest, 1, ymm1);
mm256_stream_si256(dest, 2, ymm2);
mm256_stream_si256(dest, 3, ymm3);
}
static force_inline void
memmove_movnt1x64b(char *dest, const char *src)
{
__m256i ymm0 = mm256_loadu_si256(src, 0);
__m256i ymm1 = mm256_loadu_si256(src, 1);
mm256_stream_si256(dest, 0, ymm0);
mm256_stream_si256(dest, 1, ymm1);
}
static force_inline void
memmove_movnt1x32b(char *dest, const char *src)
{
__m256i ymm0 = _mm256_loadu_si256((__m256i *)src);
mm256_stream_si256(dest, 0, ymm0);
}
static force_inline void
memmove_movnt1x16b(char *dest, const char *src)
{
__m128i xmm0 = _mm_loadu_si128((__m128i *)src);
_mm_stream_si128((__m128i *)dest, xmm0);
}
static force_inline void
memmove_movnt1x8b(char *dest, const char *src)
{
_mm_stream_si64((long long *)dest, *(long long *)src);
}
static force_inline void
memmove_movnt1x4b(char *dest, const char *src)
{
_mm_stream_si32((int *)dest, *(int *)src);
}
static force_inline void
memmove_movnt_avx_fw(char *dest, const char *src, size_t len, flush_fn flush,
perf_barrier_fn perf_barrier)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_avx(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
const char *srcend = src + len;
prefetch_ini_fw(src, len);
while (len >= PERF_BARRIER_SIZE) {
prefetch_next_fw(src, srcend);
memmove_movnt8x64b(dest, src);
dest += 8 * 64;
src += 8 * 64;
len -= 8 * 64;
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (8 + 4) * 64);
if (len)
perf_barrier();
}
if (len >= 8 * 64) {
memmove_movnt8x64b(dest, src);
dest += 8 * 64;
src += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_movnt2x64b(dest, src);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_movnt1x64b(dest, src);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memmove_movnt1x32b(dest, src);
else if (len == 16)
memmove_movnt1x16b(dest, src);
else if (len == 8)
memmove_movnt1x8b(dest, src);
else if (len == 4)
memmove_movnt1x4b(dest, src);
else
goto nonnt;
goto end;
}
nonnt:
memmove_small_avx(dest, src, len, flush);
end:
avx_zeroupper();
}
static force_inline void
memmove_movnt_avx_bw(char *dest, const char *src, size_t len, flush_fn flush,
perf_barrier_fn perf_barrier)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_avx(dest, src, cnt, flush);
}
const char *srcbegin = src - len;
prefetch_ini_bw(src, len);
while (len >= PERF_BARRIER_SIZE) {
prefetch_next_bw(src, srcbegin);
dest -= 8 * 64;
src -= 8 * 64;
len -= 8 * 64;
memmove_movnt8x64b(dest, src);
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (8 + 4) * 64);
if (len)
perf_barrier();
}
if (len >= 8 * 64) {
dest -= 8 * 64;
src -= 8 * 64;
len -= 8 * 64;
memmove_movnt8x64b(dest, src);
}
if (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_movnt2x64b(dest, src);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_movnt1x64b(dest, src);
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32) {
dest -= 32;
src -= 32;
memmove_movnt1x32b(dest, src);
} else if (len == 16) {
dest -= 16;
src -= 16;
memmove_movnt1x16b(dest, src);
} else if (len == 8) {
dest -= 8;
src -= 8;
memmove_movnt1x8b(dest, src);
} else if (len == 4) {
dest -= 4;
src -= 4;
memmove_movnt1x4b(dest, src);
} else {
goto nonnt;
}
goto end;
}
nonnt:
dest -= len;
src -= len;
memmove_small_avx(dest, src, len, flush);
end:
avx_zeroupper();
}
static force_inline void
memmove_movnt_avx(char *dest, const char *src, size_t len, flush_fn flush,
barrier_fn barrier, perf_barrier_fn perf_barrier)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_movnt_avx_fw(dest, src, len, flush, perf_barrier);
else
memmove_movnt_avx_bw(dest, src, len, flush, perf_barrier);
barrier();
VALGRIND_DO_FLUSH(dest, len);
}
/* variants without perf_barrier */
void
memmove_movnt_avx_noflush_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, noflush, barrier_after_ntstores,
no_barrier);
}
void
memmove_movnt_avx_empty_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_empty_nolog,
barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_avx_clflush_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clflush_nolog,
barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_avx_clflushopt_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_avx_clwb_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clwb_nolog,
no_barrier_after_ntstores, no_barrier);
}
/* variants with perf_barrier */
void
memmove_movnt_avx_noflush_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, noflush, barrier_after_ntstores,
wc_barrier);
}
void
memmove_movnt_avx_empty_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_empty_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_avx_clflush_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clflush_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_avx_clflushopt_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_avx_clwb_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx(dest, src, len, flush_clwb_nolog,
no_barrier_after_ntstores, wc_barrier);
}
| 10,092 | 21.731982 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_nt_sse2.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_sse2.h"
#include "valgrind_internal.h"
static force_inline __m128i
mm_loadu_si128(const char *src, unsigned idx)
{
return _mm_loadu_si128((const __m128i *)src + idx);
}
static force_inline void
mm_stream_si128(char *dest, unsigned idx, __m128i src)
{
_mm_stream_si128((__m128i *)dest + idx, src);
barrier();
}
static force_inline void
memmove_movnt4x64b(char *dest, const char *src)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
__m128i xmm4 = mm_loadu_si128(src, 4);
__m128i xmm5 = mm_loadu_si128(src, 5);
__m128i xmm6 = mm_loadu_si128(src, 6);
__m128i xmm7 = mm_loadu_si128(src, 7);
__m128i xmm8 = mm_loadu_si128(src, 8);
__m128i xmm9 = mm_loadu_si128(src, 9);
__m128i xmm10 = mm_loadu_si128(src, 10);
__m128i xmm11 = mm_loadu_si128(src, 11);
__m128i xmm12 = mm_loadu_si128(src, 12);
__m128i xmm13 = mm_loadu_si128(src, 13);
__m128i xmm14 = mm_loadu_si128(src, 14);
__m128i xmm15 = mm_loadu_si128(src, 15);
mm_stream_si128(dest, 0, xmm0);
mm_stream_si128(dest, 1, xmm1);
mm_stream_si128(dest, 2, xmm2);
mm_stream_si128(dest, 3, xmm3);
mm_stream_si128(dest, 4, xmm4);
mm_stream_si128(dest, 5, xmm5);
mm_stream_si128(dest, 6, xmm6);
mm_stream_si128(dest, 7, xmm7);
mm_stream_si128(dest, 8, xmm8);
mm_stream_si128(dest, 9, xmm9);
mm_stream_si128(dest, 10, xmm10);
mm_stream_si128(dest, 11, xmm11);
mm_stream_si128(dest, 12, xmm12);
mm_stream_si128(dest, 13, xmm13);
mm_stream_si128(dest, 14, xmm14);
mm_stream_si128(dest, 15, xmm15);
}
static force_inline void
memmove_movnt2x64b(char *dest, const char *src)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
__m128i xmm4 = mm_loadu_si128(src, 4);
__m128i xmm5 = mm_loadu_si128(src, 5);
__m128i xmm6 = mm_loadu_si128(src, 6);
__m128i xmm7 = mm_loadu_si128(src, 7);
mm_stream_si128(dest, 0, xmm0);
mm_stream_si128(dest, 1, xmm1);
mm_stream_si128(dest, 2, xmm2);
mm_stream_si128(dest, 3, xmm3);
mm_stream_si128(dest, 4, xmm4);
mm_stream_si128(dest, 5, xmm5);
mm_stream_si128(dest, 6, xmm6);
mm_stream_si128(dest, 7, xmm7);
}
static force_inline void
memmove_movnt1x64b(char *dest, const char *src)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
__m128i xmm2 = mm_loadu_si128(src, 2);
__m128i xmm3 = mm_loadu_si128(src, 3);
mm_stream_si128(dest, 0, xmm0);
mm_stream_si128(dest, 1, xmm1);
mm_stream_si128(dest, 2, xmm2);
mm_stream_si128(dest, 3, xmm3);
}
static force_inline void
memmove_movnt1x32b(char *dest, const char *src)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
__m128i xmm1 = mm_loadu_si128(src, 1);
mm_stream_si128(dest, 0, xmm0);
mm_stream_si128(dest, 1, xmm1);
}
static force_inline void
memmove_movnt1x16b(char *dest, const char *src)
{
__m128i xmm0 = mm_loadu_si128(src, 0);
mm_stream_si128(dest, 0, xmm0);
}
static force_inline void
memmove_movnt1x8b(char *dest, const char *src)
{
_mm_stream_si64((long long *)dest, *(long long *)src);
}
static force_inline void
memmove_movnt1x4b(char *dest, const char *src)
{
_mm_stream_si32((int *)dest, *(int *)src);
}
static force_inline void
memmove_movnt_sse_fw(char *dest, const char *src, size_t len, flush_fn flush,
perf_barrier_fn perf_barrier)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_sse2(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
const char *srcend = src + len;
prefetch_ini_fw(src, len);
while (len >= PERF_BARRIER_SIZE) {
prefetch_next_fw(src, srcend);
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (4 + 4 + 4) * 64);
if (len)
perf_barrier();
}
while (len >= 4 * 64) {
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_movnt2x64b(dest, src);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_movnt1x64b(dest, src);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
return;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memmove_movnt1x32b(dest, src);
else if (len == 16)
memmove_movnt1x16b(dest, src);
else if (len == 8)
memmove_movnt1x8b(dest, src);
else if (len == 4)
memmove_movnt1x4b(dest, src);
else
goto nonnt;
return;
}
nonnt:
memmove_small_sse2(dest, src, len, flush);
}
static force_inline void
memmove_movnt_sse_bw(char *dest, const char *src, size_t len, flush_fn flush,
perf_barrier_fn perf_barrier)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_sse2(dest, src, cnt, flush);
}
const char *srcbegin = src - len;
prefetch_ini_bw(src, len);
while (len >= PERF_BARRIER_SIZE) {
prefetch_next_bw(src, srcbegin);
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
COMPILE_ERROR_ON(PERF_BARRIER_SIZE != (4 + 4 + 4) * 64);
if (len)
perf_barrier();
}
while (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_movnt2x64b(dest, src);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_movnt1x64b(dest, src);
}
if (len == 0)
return;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32) {
dest -= 32;
src -= 32;
memmove_movnt1x32b(dest, src);
} else if (len == 16) {
dest -= 16;
src -= 16;
memmove_movnt1x16b(dest, src);
} else if (len == 8) {
dest -= 8;
src -= 8;
memmove_movnt1x8b(dest, src);
} else if (len == 4) {
dest -= 4;
src -= 4;
memmove_movnt1x4b(dest, src);
} else {
goto nonnt;
}
return;
}
nonnt:
dest -= len;
src -= len;
memmove_small_sse2(dest, src, len, flush);
}
static force_inline void
memmove_movnt_sse2(char *dest, const char *src, size_t len, flush_fn flush,
barrier_fn barrier, perf_barrier_fn perf_barrier)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_movnt_sse_fw(dest, src, len, flush, perf_barrier);
else
memmove_movnt_sse_bw(dest, src, len, flush, perf_barrier);
barrier();
VALGRIND_DO_FLUSH(dest, len);
}
/* variants without perf_barrier */
void
memmove_movnt_sse2_noflush_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, noflush, barrier_after_ntstores,
no_barrier);
}
void
memmove_movnt_sse2_empty_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_empty_nolog,
barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_sse2_clflush_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clflush_nolog,
barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_sse2_clflushopt_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, no_barrier);
}
void
memmove_movnt_sse2_clwb_nobarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clwb_nolog,
no_barrier_after_ntstores, no_barrier);
}
/* variants with perf_barrier */
void
memmove_movnt_sse2_noflush_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, noflush, barrier_after_ntstores,
wc_barrier);
}
void
memmove_movnt_sse2_empty_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_empty_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_sse2_clflush_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clflush_nolog,
barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_sse2_clflushopt_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clflushopt_nolog,
no_barrier_after_ntstores, wc_barrier);
}
void
memmove_movnt_sse2_clwb_wcbarrier(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_sse2(dest, src, len, flush_clwb_nolog,
no_barrier_after_ntstores, wc_barrier);
}
| 9,636 | 21.463869 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/x86_64/memcpy/memcpy_nt_avx512f.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include "pmem2_arch.h"
#include "avx.h"
#include "flush.h"
#include "memcpy_memset.h"
#include "memcpy_avx512f.h"
#include "valgrind_internal.h"
static force_inline __m512i
mm512_loadu_si512(const char *src, unsigned idx)
{
return _mm512_loadu_si512((const __m512i *)src + idx);
}
static force_inline void
mm512_stream_si512(char *dest, unsigned idx, __m512i src)
{
_mm512_stream_si512((__m512i *)dest + idx, src);
barrier();
}
static force_inline void
memmove_movnt32x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
__m512i zmm8 = mm512_loadu_si512(src, 8);
__m512i zmm9 = mm512_loadu_si512(src, 9);
__m512i zmm10 = mm512_loadu_si512(src, 10);
__m512i zmm11 = mm512_loadu_si512(src, 11);
__m512i zmm12 = mm512_loadu_si512(src, 12);
__m512i zmm13 = mm512_loadu_si512(src, 13);
__m512i zmm14 = mm512_loadu_si512(src, 14);
__m512i zmm15 = mm512_loadu_si512(src, 15);
__m512i zmm16 = mm512_loadu_si512(src, 16);
__m512i zmm17 = mm512_loadu_si512(src, 17);
__m512i zmm18 = mm512_loadu_si512(src, 18);
__m512i zmm19 = mm512_loadu_si512(src, 19);
__m512i zmm20 = mm512_loadu_si512(src, 20);
__m512i zmm21 = mm512_loadu_si512(src, 21);
__m512i zmm22 = mm512_loadu_si512(src, 22);
__m512i zmm23 = mm512_loadu_si512(src, 23);
__m512i zmm24 = mm512_loadu_si512(src, 24);
__m512i zmm25 = mm512_loadu_si512(src, 25);
__m512i zmm26 = mm512_loadu_si512(src, 26);
__m512i zmm27 = mm512_loadu_si512(src, 27);
__m512i zmm28 = mm512_loadu_si512(src, 28);
__m512i zmm29 = mm512_loadu_si512(src, 29);
__m512i zmm30 = mm512_loadu_si512(src, 30);
__m512i zmm31 = mm512_loadu_si512(src, 31);
mm512_stream_si512(dest, 0, zmm0);
mm512_stream_si512(dest, 1, zmm1);
mm512_stream_si512(dest, 2, zmm2);
mm512_stream_si512(dest, 3, zmm3);
mm512_stream_si512(dest, 4, zmm4);
mm512_stream_si512(dest, 5, zmm5);
mm512_stream_si512(dest, 6, zmm6);
mm512_stream_si512(dest, 7, zmm7);
mm512_stream_si512(dest, 8, zmm8);
mm512_stream_si512(dest, 9, zmm9);
mm512_stream_si512(dest, 10, zmm10);
mm512_stream_si512(dest, 11, zmm11);
mm512_stream_si512(dest, 12, zmm12);
mm512_stream_si512(dest, 13, zmm13);
mm512_stream_si512(dest, 14, zmm14);
mm512_stream_si512(dest, 15, zmm15);
mm512_stream_si512(dest, 16, zmm16);
mm512_stream_si512(dest, 17, zmm17);
mm512_stream_si512(dest, 18, zmm18);
mm512_stream_si512(dest, 19, zmm19);
mm512_stream_si512(dest, 20, zmm20);
mm512_stream_si512(dest, 21, zmm21);
mm512_stream_si512(dest, 22, zmm22);
mm512_stream_si512(dest, 23, zmm23);
mm512_stream_si512(dest, 24, zmm24);
mm512_stream_si512(dest, 25, zmm25);
mm512_stream_si512(dest, 26, zmm26);
mm512_stream_si512(dest, 27, zmm27);
mm512_stream_si512(dest, 28, zmm28);
mm512_stream_si512(dest, 29, zmm29);
mm512_stream_si512(dest, 30, zmm30);
mm512_stream_si512(dest, 31, zmm31);
}
static force_inline void
memmove_movnt16x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
__m512i zmm8 = mm512_loadu_si512(src, 8);
__m512i zmm9 = mm512_loadu_si512(src, 9);
__m512i zmm10 = mm512_loadu_si512(src, 10);
__m512i zmm11 = mm512_loadu_si512(src, 11);
__m512i zmm12 = mm512_loadu_si512(src, 12);
__m512i zmm13 = mm512_loadu_si512(src, 13);
__m512i zmm14 = mm512_loadu_si512(src, 14);
__m512i zmm15 = mm512_loadu_si512(src, 15);
mm512_stream_si512(dest, 0, zmm0);
mm512_stream_si512(dest, 1, zmm1);
mm512_stream_si512(dest, 2, zmm2);
mm512_stream_si512(dest, 3, zmm3);
mm512_stream_si512(dest, 4, zmm4);
mm512_stream_si512(dest, 5, zmm5);
mm512_stream_si512(dest, 6, zmm6);
mm512_stream_si512(dest, 7, zmm7);
mm512_stream_si512(dest, 8, zmm8);
mm512_stream_si512(dest, 9, zmm9);
mm512_stream_si512(dest, 10, zmm10);
mm512_stream_si512(dest, 11, zmm11);
mm512_stream_si512(dest, 12, zmm12);
mm512_stream_si512(dest, 13, zmm13);
mm512_stream_si512(dest, 14, zmm14);
mm512_stream_si512(dest, 15, zmm15);
}
static force_inline void
memmove_movnt8x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
__m512i zmm4 = mm512_loadu_si512(src, 4);
__m512i zmm5 = mm512_loadu_si512(src, 5);
__m512i zmm6 = mm512_loadu_si512(src, 6);
__m512i zmm7 = mm512_loadu_si512(src, 7);
mm512_stream_si512(dest, 0, zmm0);
mm512_stream_si512(dest, 1, zmm1);
mm512_stream_si512(dest, 2, zmm2);
mm512_stream_si512(dest, 3, zmm3);
mm512_stream_si512(dest, 4, zmm4);
mm512_stream_si512(dest, 5, zmm5);
mm512_stream_si512(dest, 6, zmm6);
mm512_stream_si512(dest, 7, zmm7);
}
static force_inline void
memmove_movnt4x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
__m512i zmm2 = mm512_loadu_si512(src, 2);
__m512i zmm3 = mm512_loadu_si512(src, 3);
mm512_stream_si512(dest, 0, zmm0);
mm512_stream_si512(dest, 1, zmm1);
mm512_stream_si512(dest, 2, zmm2);
mm512_stream_si512(dest, 3, zmm3);
}
static force_inline void
memmove_movnt2x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
__m512i zmm1 = mm512_loadu_si512(src, 1);
mm512_stream_si512(dest, 0, zmm0);
mm512_stream_si512(dest, 1, zmm1);
}
static force_inline void
memmove_movnt1x64b(char *dest, const char *src)
{
__m512i zmm0 = mm512_loadu_si512(src, 0);
mm512_stream_si512(dest, 0, zmm0);
}
static force_inline void
memmove_movnt1x32b(char *dest, const char *src)
{
__m256i zmm0 = _mm256_loadu_si256((__m256i *)src);
_mm256_stream_si256((__m256i *)dest, zmm0);
}
static force_inline void
memmove_movnt1x16b(char *dest, const char *src)
{
__m128i ymm0 = _mm_loadu_si128((__m128i *)src);
_mm_stream_si128((__m128i *)dest, ymm0);
}
static force_inline void
memmove_movnt1x8b(char *dest, const char *src)
{
_mm_stream_si64((long long *)dest, *(long long *)src);
}
static force_inline void
memmove_movnt1x4b(char *dest, const char *src)
{
_mm_stream_si32((int *)dest, *(int *)src);
}
static force_inline void
memmove_movnt_avx512f_fw(char *dest, const char *src, size_t len,
flush_fn flush)
{
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
cnt = 64 - cnt;
if (cnt > len)
cnt = len;
memmove_small_avx512f(dest, src, cnt, flush);
dest += cnt;
src += cnt;
len -= cnt;
}
while (len >= 32 * 64) {
memmove_movnt32x64b(dest, src);
dest += 32 * 64;
src += 32 * 64;
len -= 32 * 64;
}
if (len >= 16 * 64) {
memmove_movnt16x64b(dest, src);
dest += 16 * 64;
src += 16 * 64;
len -= 16 * 64;
}
if (len >= 8 * 64) {
memmove_movnt8x64b(dest, src);
dest += 8 * 64;
src += 8 * 64;
len -= 8 * 64;
}
if (len >= 4 * 64) {
memmove_movnt4x64b(dest, src);
dest += 4 * 64;
src += 4 * 64;
len -= 4 * 64;
}
if (len >= 2 * 64) {
memmove_movnt2x64b(dest, src);
dest += 2 * 64;
src += 2 * 64;
len -= 2 * 64;
}
if (len >= 1 * 64) {
memmove_movnt1x64b(dest, src);
dest += 1 * 64;
src += 1 * 64;
len -= 1 * 64;
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32)
memmove_movnt1x32b(dest, src);
else if (len == 16)
memmove_movnt1x16b(dest, src);
else if (len == 8)
memmove_movnt1x8b(dest, src);
else if (len == 4)
memmove_movnt1x4b(dest, src);
else
goto nonnt;
goto end;
}
nonnt:
memmove_small_avx512f(dest, src, len, flush);
end:
avx_zeroupper();
}
static force_inline void
memmove_movnt_avx512f_bw(char *dest, const char *src, size_t len,
flush_fn flush)
{
dest += len;
src += len;
size_t cnt = (uint64_t)dest & 63;
if (cnt > 0) {
if (cnt > len)
cnt = len;
dest -= cnt;
src -= cnt;
len -= cnt;
memmove_small_avx512f(dest, src, cnt, flush);
}
while (len >= 32 * 64) {
dest -= 32 * 64;
src -= 32 * 64;
len -= 32 * 64;
memmove_movnt32x64b(dest, src);
}
if (len >= 16 * 64) {
dest -= 16 * 64;
src -= 16 * 64;
len -= 16 * 64;
memmove_movnt16x64b(dest, src);
}
if (len >= 8 * 64) {
dest -= 8 * 64;
src -= 8 * 64;
len -= 8 * 64;
memmove_movnt8x64b(dest, src);
}
if (len >= 4 * 64) {
dest -= 4 * 64;
src -= 4 * 64;
len -= 4 * 64;
memmove_movnt4x64b(dest, src);
}
if (len >= 2 * 64) {
dest -= 2 * 64;
src -= 2 * 64;
len -= 2 * 64;
memmove_movnt2x64b(dest, src);
}
if (len >= 1 * 64) {
dest -= 1 * 64;
src -= 1 * 64;
len -= 1 * 64;
memmove_movnt1x64b(dest, src);
}
if (len == 0)
goto end;
/* There's no point in using more than 1 nt store for 1 cache line. */
if (util_is_pow2(len)) {
if (len == 32) {
dest -= 32;
src -= 32;
memmove_movnt1x32b(dest, src);
} else if (len == 16) {
dest -= 16;
src -= 16;
memmove_movnt1x16b(dest, src);
} else if (len == 8) {
dest -= 8;
src -= 8;
memmove_movnt1x8b(dest, src);
} else if (len == 4) {
dest -= 4;
src -= 4;
memmove_movnt1x4b(dest, src);
} else {
goto nonnt;
}
goto end;
}
nonnt:
dest -= len;
src -= len;
memmove_small_avx512f(dest, src, len, flush);
end:
avx_zeroupper();
}
static force_inline void
memmove_movnt_avx512f(char *dest, const char *src, size_t len, flush_fn flush,
barrier_fn barrier)
{
if ((uintptr_t)dest - (uintptr_t)src >= len)
memmove_movnt_avx512f_fw(dest, src, len, flush);
else
memmove_movnt_avx512f_bw(dest, src, len, flush);
barrier();
VALGRIND_DO_FLUSH(dest, len);
}
void
memmove_movnt_avx512f_noflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx512f(dest, src, len, noflush, barrier_after_ntstores);
}
void
memmove_movnt_avx512f_empty(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx512f(dest, src, len, flush_empty_nolog,
barrier_after_ntstores);
}
void
memmove_movnt_avx512f_clflush(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx512f(dest, src, len, flush_clflush_nolog,
barrier_after_ntstores);
}
void
memmove_movnt_avx512f_clflushopt(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx512f(dest, src, len, flush_clflushopt_nolog,
no_barrier_after_ntstores);
}
void
memmove_movnt_avx512f_clwb(char *dest, const char *src, size_t len)
{
LOG(15, "dest %p src %p len %zu", dest, src, len);
memmove_movnt_avx512f(dest, src, len, flush_clwb_nolog,
no_barrier_after_ntstores);
}
| 11,246 | 23.45 | 78 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/aarch64/arm_cacheops.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* ARM inline assembly to flush and invalidate caches
* clwb => dc cvac
* clflushopt => dc civac
* fence => dmb ish
* sfence => dmb ishst
*/
/*
* Cache instructions on ARM:
* ARMv8.0-a DC CVAC - cache clean to Point of Coherency
* Meant for thread synchronization, usually implies
* real memory flush but may mean less.
* ARMv8.2-a DC CVAP - cache clean to Point of Persistency
* Meant exactly for our use.
* ARMv8.5-a DC CVADP - cache clean to Point of Deep Persistency
* As of mid-2019 not on any commercially available CPU.
* Any of the above may be disabled for EL0, but it's probably safe to consider
* that a system configuration error.
* Other flags include I (like "DC CIVAC") that invalidates the cache line, but
* we don't want that.
*
* Memory fences:
* * DMB [ISH] MFENCE
* * DMB [ISH]ST SFENCE
* * DMB [ISH]LD LFENCE
*
* Memory domains (cache coherency):
* * non-shareable - local to a single core
* * inner shareable (ISH) - a group of CPU clusters/sockets/other hardware
* Linux requires that anything within one operating system/hypervisor
* is within the same Inner Shareable domain.
* * outer shareable (OSH) - one or more separate ISH domains
* * full system (SY) - anything that can possibly access memory
* Docs: ARM DDI 0487E.a page B2-144.
*
* Exception (privilege) levels:
* * EL0 - userspace (ring 3)
* * EL1 - kernel (ring 0)
* * EL2 - hypervisor (ring -1)
* * EL3 - "secure world" (ring -3)
*/
#ifndef AARCH64_CACHEOPS_H
#define AARCH64_CACHEOPS_H
#include <stdlib.h>
static inline void
arm_clean_va_to_poc(void const *p __attribute__((unused)))
{
asm volatile("dc cvac, %0" : : "r" (p) : "memory");
}
static inline void
arm_store_memory_barrier(void)
{
asm volatile("dmb ishst" : : : "memory");
}
#endif
| 1,988 | 30.571429 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/libpmem2/ppc64/init.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019, IBM Corporation */
/* Copyright 2019-2020, Intel Corporation */
#include <errno.h>
#include <sys/mman.h>
#include "out.h"
#include "pmem2_arch.h"
#include "util.h"
/*
* Older assemblers versions do not support the latest versions of L, e.g.
* Binutils 2.34.
* Workaround this by using longs.
*/
#define __SYNC(l) ".long (0x7c0004AC | ((" #l ") << 21))"
#define __DCBF(ra, rb, l) ".long (0x7c0000AC | ((" #l ") << 21)" \
" | ((" #ra ") << 16) | ((" #rb ") << 11))"
static void
ppc_fence(void)
{
LOG(15, NULL);
/*
* Force a memory barrier to flush out all cache lines.
* Uses a heavyweight sync in order to guarantee the memory ordering
* even with a data cache flush.
* According to the POWER ISA 3.1, phwsync (aka. sync (L=4)) is treated
* as a hwsync by processors compatible with previous versions of the
* POWER ISA.
*/
asm volatile(__SYNC(4) : : : "memory");
}
static void
ppc_flush(const void *addr, size_t size)
{
LOG(15, "addr %p size %zu", addr, size);
uintptr_t uptr = (uintptr_t)addr;
uintptr_t end = uptr + size;
/* round down the address */
uptr &= ~(CACHELINE_SIZE - 1);
while (uptr < end) {
/*
* Flush the data cache block.
* According to the POWER ISA 3.1, dcbstps (aka. dcbf (L=6))
* behaves as dcbf (L=0) on previous processors.
*/
asm volatile(__DCBF(0, %0, 6) : :"r"(uptr) : "memory");
uptr += CACHELINE_SIZE;
}
}
void
pmem2_arch_init(struct pmem2_arch_info *info)
{
LOG(3, "libpmem*: PPC64 support");
info->fence = ppc_fence;
info->flush = ppc_flush;
}
| 1,594 | 22.80597 | 74 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/getopt/getopt.c
|
/*
* *Copyright (c) 2012, Kim Gräsman
* 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 Kim Gräsman nor the
* names of 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 KIM GRÄSMAN 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.
*/
#include "getopt.h"
#include <stddef.h>
#include <string.h>
#include <stdio.h>
char* optarg;
int optopt;
/* The variable optind [...] shall be initialized to 1 by the system. */
int optind = 1;
int opterr;
static char* optcursor = NULL;
static char *first = NULL;
/* rotates argv array */
static void rotate(char **argv, int argc) {
if (argc <= 1)
return;
char *tmp = argv[0];
memmove(argv, argv + 1, (argc - 1) * sizeof(char *));
argv[argc - 1] = tmp;
}
/* Implemented based on [1] and [2] for optional arguments.
optopt is handled FreeBSD-style, per [3].
Other GNU and FreeBSD extensions are purely accidental.
[1] https://pubs.opengroup.org/onlinepubs/000095399/functions/getopt.html
[2] https://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html
[3] https://www.freebsd.org/cgi/man.cgi?query=getopt&sektion=3&manpath=FreeBSD+9.0-RELEASE
*/
int getopt(int argc, char* const argv[], const char* optstring) {
int optchar = -1;
const char* optdecl = NULL;
optarg = NULL;
opterr = 0;
optopt = 0;
/* Unspecified, but we need it to avoid overrunning the argv bounds. */
if (optind >= argc)
goto no_more_optchars;
/* If, when getopt() is called argv[optind] is a null pointer, getopt()
shall return -1 without changing optind. */
if (argv[optind] == NULL)
goto no_more_optchars;
/* If, when getopt() is called *argv[optind] is not the character '-',
permute argv to move non options to the end */
if (*argv[optind] != '-') {
if (argc - optind <= 1)
goto no_more_optchars;
if (!first)
first = argv[optind];
do {
rotate((char **)(argv + optind), argc - optind);
} while (*argv[optind] != '-' && argv[optind] != first);
if (argv[optind] == first)
goto no_more_optchars;
}
/* If, when getopt() is called argv[optind] points to the string "-",
getopt() shall return -1 without changing optind. */
if (strcmp(argv[optind], "-") == 0)
goto no_more_optchars;
/* If, when getopt() is called argv[optind] points to the string "--",
getopt() shall return -1 after incrementing optind. */
if (strcmp(argv[optind], "--") == 0) {
++optind;
if (first) {
do {
rotate((char **)(argv + optind), argc - optind);
} while (argv[optind] != first);
}
goto no_more_optchars;
}
if (optcursor == NULL || *optcursor == '\0')
optcursor = argv[optind] + 1;
optchar = *optcursor;
/* FreeBSD: The variable optopt saves the last known option character
returned by getopt(). */
optopt = optchar;
/* The getopt() function shall return the next option character (if one is
found) from argv that matches a character in optstring, if there is
one that matches. */
optdecl = strchr(optstring, optchar);
if (optdecl) {
/* [I]f a character is followed by a colon, the option takes an
argument. */
if (optdecl[1] == ':') {
optarg = ++optcursor;
if (*optarg == '\0') {
/* GNU extension: Two colons mean an option takes an
optional arg; if there is text in the current argv-element
(i.e., in the same word as the option name itself, for example,
"-oarg"), then it is returned in optarg, otherwise optarg is set
to zero. */
if (optdecl[2] != ':') {
/* If the option was the last character in the string pointed to by
an element of argv, then optarg shall contain the next element
of argv, and optind shall be incremented by 2. If the resulting
value of optind is greater than argc, this indicates a missing
option-argument, and getopt() shall return an error indication.
Otherwise, optarg shall point to the string following the
option character in that element of argv, and optind shall be
incremented by 1.
*/
if (++optind < argc) {
optarg = argv[optind];
} else {
/* If it detects a missing option-argument, it shall return the
colon character ( ':' ) if the first character of optstring
was a colon, or a question-mark character ( '?' ) otherwise.
*/
optarg = NULL;
fprintf(stderr, "%s: option requires an argument -- '%c'\n", argv[0], optchar);
optchar = (optstring[0] == ':') ? ':' : '?';
}
} else {
optarg = NULL;
}
}
optcursor = NULL;
}
} else {
fprintf(stderr,"%s: invalid option -- '%c'\n", argv[0], optchar);
/* If getopt() encounters an option character that is not contained in
optstring, it shall return the question-mark ( '?' ) character. */
optchar = '?';
}
if (optcursor == NULL || *++optcursor == '\0')
++optind;
return optchar;
no_more_optchars:
optcursor = NULL;
first = NULL;
return -1;
}
/* Implementation based on [1].
[1] https://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html
*/
int getopt_long(int argc, char* const argv[], const char* optstring,
const struct option* longopts, int* longindex) {
const struct option* o = longopts;
const struct option* match = NULL;
int num_matches = 0;
size_t argument_name_length = 0;
const char* current_argument = NULL;
int retval = -1;
optarg = NULL;
optopt = 0;
if (optind >= argc)
return -1;
/* If, when getopt() is called argv[optind] is a null pointer, getopt_long()
shall return -1 without changing optind. */
if (argv[optind] == NULL)
goto no_more_optchars;
/* If, when getopt_long() is called *argv[optind] is not the character '-',
permute argv to move non options to the end */
if (*argv[optind] != '-') {
if (argc - optind <= 1)
goto no_more_optchars;
if (!first)
first = argv[optind];
do {
rotate((char **)(argv + optind), argc - optind);
} while (*argv[optind] != '-' && argv[optind] != first);
if (argv[optind] == first)
goto no_more_optchars;
}
if (strlen(argv[optind]) < 3 || strncmp(argv[optind], "--", 2) != 0)
return getopt(argc, argv, optstring);
/* It's an option; starts with -- and is longer than two chars. */
current_argument = argv[optind] + 2;
argument_name_length = strcspn(current_argument, "=");
for (; o->name; ++o) {
if (strncmp(o->name, current_argument, argument_name_length) == 0) {
match = o;
++num_matches;
if (strlen(o->name) == argument_name_length) {
/* found match is exactly the one which we are looking for */
num_matches = 1;
break;
}
}
}
if (num_matches == 1) {
/* If longindex is not NULL, it points to a variable which is set to the
index of the long option relative to longopts. */
if (longindex)
*longindex = (int)(match - longopts);
/* If flag is NULL, then getopt_long() shall return val.
Otherwise, getopt_long() returns 0, and flag shall point to a variable
which shall be set to val if the option is found, but left unchanged if
the option is not found. */
if (match->flag)
*(match->flag) = match->val;
retval = match->flag ? 0 : match->val;
if (match->has_arg != no_argument) {
optarg = strchr(argv[optind], '=');
if (optarg != NULL)
++optarg;
if (match->has_arg == required_argument) {
/* Only scan the next argv for required arguments. Behavior is not
specified, but has been observed with Ubuntu and Mac OSX. */
if (optarg == NULL && ++optind < argc) {
optarg = argv[optind];
}
if (optarg == NULL)
retval = ':';
}
} else if (strchr(argv[optind], '=')) {
/* An argument was provided to a non-argument option.
I haven't seen this specified explicitly, but both GNU and BSD-based
implementations show this behavior.
*/
retval = '?';
}
} else {
/* Unknown option or ambiguous match. */
retval = '?';
if (num_matches == 0) {
fprintf(stderr, "%s: unrecognized option -- '%s'\n", argv[0], argv[optind]);
} else {
fprintf(stderr, "%s: option '%s' is ambiguous\n", argv[0], argv[optind]);
}
}
++optind;
return retval;
no_more_optchars:
first = NULL;
return -1;
}
| 9,866 | 32.561224 | 91 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/getopt/getopt.h
|
/*
* *Copyright (c) 2012, Kim Gräsman
* 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 Kim Gräsman nor the
* names of 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 KIM GRÄSMAN 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 INCLUDED_GETOPT_PORT_H
#define INCLUDED_GETOPT_PORT_H
#if defined(__cplusplus)
extern "C" {
#endif
#define no_argument 0
#define required_argument 1
#define optional_argument 2
extern char* optarg;
extern int optind, opterr, optopt;
struct option {
const char* name;
int has_arg;
int* flag;
int val;
};
int getopt(int argc, char* const argv[], const char* optstring);
int getopt_long(int argc, char* const argv[],
const char* optstring, const struct option* longopts, int* longindex);
#if defined(__cplusplus)
}
#endif
#endif // INCLUDED_GETOPT_PORT_H
| 2,137 | 35.237288 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/include/win_mmap.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2019, 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.
*/
/*
* win_mmap.h -- (internal) tracks the regions mapped by mmap
*/
#ifndef WIN_MMAP_H
#define WIN_MMAP_H 1
#include "queue.h"
#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
#define rounddown(x, y) (((x) / (y)) * (y))
void win_mmap_init(void);
void win_mmap_fini(void);
/* allocation/mmap granularity */
extern unsigned long long Mmap_align;
typedef enum FILE_MAPPING_TRACKER_FLAGS {
FILE_MAPPING_TRACKER_FLAG_DIRECT_MAPPED = 0x0001,
/*
* This should hold the value of all flags ORed for debug purpose.
*/
FILE_MAPPING_TRACKER_FLAGS_MASK =
FILE_MAPPING_TRACKER_FLAG_DIRECT_MAPPED
} FILE_MAPPING_TRACKER_FLAGS;
/*
* this structure tracks the file mappings outstanding per file handle
*/
typedef struct FILE_MAPPING_TRACKER {
PMDK_SORTEDQ_ENTRY(FILE_MAPPING_TRACKER) ListEntry;
HANDLE FileHandle;
HANDLE FileMappingHandle;
void *BaseAddress;
void *EndAddress;
DWORD Access;
os_off_t Offset;
size_t FileLen;
FILE_MAPPING_TRACKER_FLAGS Flags;
} FILE_MAPPING_TRACKER, *PFILE_MAPPING_TRACKER;
extern SRWLOCK FileMappingQLock;
extern PMDK_SORTEDQ_HEAD(FMLHead, FILE_MAPPING_TRACKER) FileMappingQHead;
#endif /* WIN_MMAP_H */
| 2,871 | 34.02439 | 74 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/include/platform.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.
*/
/*
* platform.h -- dirty hacks to compile Linux code on Windows using VC++
*
* This is included to each source file using "/FI" (forced include) option.
*
* XXX - it is a subject for refactoring
*/
#ifndef PLATFORM_H
#define PLATFORM_H 1
#pragma warning(disable : 4996)
#pragma warning(disable : 4200) /* allow flexible array member */
#pragma warning(disable : 4819) /* non unicode characters */
#ifdef __cplusplus
extern "C" {
#endif
/* Prevent PMDK compilation for 32-bit platforms */
#if defined(_WIN32) && !defined(_WIN64)
#error "32-bit builds of PMDK are not supported!"
#endif
#define _CRT_RAND_S /* rand_s() */
#include <windows.h>
#include <stdint.h>
#include <time.h>
#include <io.h>
#include <process.h>
#include <fcntl.h>
#include <sys/types.h>
#include <malloc.h>
#include <signal.h>
#include <intrin.h>
#include <direct.h>
/* use uuid_t definition from util.h */
#ifdef uuid_t
#undef uuid_t
#endif
/* a few trivial substitutions */
#define PATH_MAX MAX_PATH
#define __thread __declspec(thread)
#define __func__ __FUNCTION__
#ifdef _DEBUG
#define DEBUG
#endif
/*
* The inline keyword is available only in VC++.
* https://msdn.microsoft.com/en-us/library/bw1hbe6y.aspx
*/
#ifndef __cplusplus
#define inline __inline
#endif
/* XXX - no equivalents in VC++ */
#define __attribute__(a)
#define __builtin_constant_p(cnd) 0
/*
* missing definitions
*/
/* errno.h */
#define ELIBACC 79 /* cannot access a needed shared library */
/* sys/stat.h */
#define S_IRUSR S_IREAD
#define S_IWUSR S_IWRITE
#define S_IRGRP S_IRUSR
#define S_IWGRP S_IWUSR
#define O_SYNC 0
typedef int mode_t;
#define fchmod(fd, mode) 0 /* XXX - dummy */
#define setlinebuf(fp) setvbuf(fp, NULL, _IOLBF, BUFSIZ);
/* unistd.h */
typedef long long os_off_t;
typedef long long ssize_t;
int setenv(const char *name, const char *value, int overwrite);
int unsetenv(const char *name);
/* fcntl.h */
int posix_fallocate(int fd, os_off_t offset, os_off_t len);
/* string.h */
#define strtok_r strtok_s
/* time.h */
#define CLOCK_MONOTONIC 1
#define CLOCK_REALTIME 2
int clock_gettime(int id, struct timespec *ts);
/* signal.h */
typedef unsigned long long sigset_t; /* one bit for each signal */
C_ASSERT(NSIG <= sizeof(sigset_t) * 8);
struct sigaction {
void (*sa_handler) (int signum);
/* void (*sa_sigaction)(int, siginfo_t *, void *); */
sigset_t sa_mask;
int sa_flags;
void (*sa_restorer) (void);
};
__inline int
sigemptyset(sigset_t *set)
{
*set = 0;
return 0;
}
__inline int
sigfillset(sigset_t *set)
{
*set = ~0;
return 0;
}
__inline int
sigaddset(sigset_t *set, int signum)
{
if (signum <= 0 || signum >= NSIG) {
errno = EINVAL;
return -1;
}
*set |= (1ULL << (signum - 1));
return 0;
}
__inline int
sigdelset(sigset_t *set, int signum)
{
if (signum <= 0 || signum >= NSIG) {
errno = EINVAL;
return -1;
}
*set &= ~(1ULL << (signum - 1));
return 0;
}
__inline int
sigismember(const sigset_t *set, int signum)
{
if (signum <= 0 || signum >= NSIG) {
errno = EINVAL;
return -1;
}
return ((*set & (1ULL << (signum - 1))) ? 1 : 0);
}
/* sched.h */
/*
* sched_yield -- yield the processor
*/
__inline int
sched_yield(void)
{
SwitchToThread();
return 0; /* always succeeds */
}
/*
* helper macros for library ctor/dtor function declarations
*/
#define MSVC_CONSTR(func) \
void func(void); \
__pragma(comment(linker, "/include:_" #func)) \
__pragma(section(".CRT$XCU", read)) \
__declspec(allocate(".CRT$XCU")) \
const void (WINAPI *_##func)(void) = (const void (WINAPI *)(void))func;
#define MSVC_DESTR(func) \
void func(void); \
static void _##func##_reg(void) { atexit(func); }; \
MSVC_CONSTR(_##func##_reg)
#ifdef __cplusplus
}
#endif
#endif /* PLATFORM_H */
| 5,431 | 22.929515 | 76 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/include/endian.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2017, Intel Corporation */
/*
* endian.h -- convert values between host and big-/little-endian byte order
*/
#ifndef ENDIAN_H
#define ENDIAN_H 1
/*
* XXX: On Windows we can assume little-endian architecture
*/
#include <intrin.h>
#define htole16(a) (a)
#define htole32(a) (a)
#define htole64(a) (a)
#define le16toh(a) (a)
#define le32toh(a) (a)
#define le64toh(a) (a)
#define htobe16(x) _byteswap_ushort(x)
#define htobe32(x) _byteswap_ulong(x)
#define htobe64(x) _byteswap_uint64(x)
#define be16toh(x) _byteswap_ushort(x)
#define be32toh(x) _byteswap_ulong(x)
#define be64toh(x) _byteswap_uint64(x)
#endif /* ENDIAN_H */
| 696 | 20.121212 | 76 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/include/sys/file.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2018, 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.
*/
/*
* sys/file.h -- file locking
*/
| 1,750 | 45.078947 | 74 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/windows/include/sys/param.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2018, Intel Corporation */
/*
* sys/param.h -- a few useful macros
*/
#ifndef SYS_PARAM_H
#define SYS_PARAM_H 1
#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
#define howmany(x, y) (((x) + ((y) - 1)) / (y))
#define BPB 8 /* bits per byte */
#define setbit(b, i) ((b)[(i) / BPB] |= 1 << ((i) % BPB))
#define isset(b, i) ((b)[(i) / BPB] & (1 << ((i) % BPB)))
#define isclr(b, i) (((b)[(i) / BPB] & (1 << ((i) % BPB))) == 0)
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif /* SYS_PARAM_H */
| 612 | 24.541667 | 64 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemblk.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemblk.h -- definitions of libpmemblk entry points
*
* This library provides support for programming with persistent memory (pmem).
*
* libpmemblk provides support for arrays of atomically-writable blocks.
*
* See libpmemblk(7) for details.
*/
#ifndef LIBPMEMBLK_H
#define LIBPMEMBLK_H 1
#include <sys/types.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmemblk_open pmemblk_openW
#define pmemblk_create pmemblk_createW
#define pmemblk_check pmemblk_checkW
#define pmemblk_check_version pmemblk_check_versionW
#define pmemblk_errormsg pmemblk_errormsgW
#define pmemblk_ctl_get pmemblk_ctl_getW
#define pmemblk_ctl_set pmemblk_ctl_setW
#define pmemblk_ctl_exec pmemblk_ctl_execW
#else
#define pmemblk_open pmemblk_openU
#define pmemblk_create pmemblk_createU
#define pmemblk_check pmemblk_checkU
#define pmemblk_check_version pmemblk_check_versionU
#define pmemblk_errormsg pmemblk_errormsgU
#define pmemblk_ctl_get pmemblk_ctl_getU
#define pmemblk_ctl_set pmemblk_ctl_setU
#define pmemblk_ctl_exec pmemblk_ctl_execU
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* opaque type, internal to libpmemblk
*/
typedef struct pmemblk PMEMblkpool;
/*
* PMEMBLK_MAJOR_VERSION and PMEMBLK_MINOR_VERSION provide the current version
* of the libpmemblk API as provided by this header file. Applications can
* verify that the version available at run-time is compatible with the version
* used at compile-time by passing these defines to pmemblk_check_version().
*/
#define PMEMBLK_MAJOR_VERSION 1
#define PMEMBLK_MINOR_VERSION 1
#ifndef _WIN32
const char *pmemblk_check_version(unsigned major_required,
unsigned minor_required);
#else
const char *pmemblk_check_versionU(unsigned major_required,
unsigned minor_required);
const wchar_t *pmemblk_check_versionW(unsigned major_required,
unsigned minor_required);
#endif
/* XXX - unify minimum pool size for both OS-es */
#ifndef _WIN32
#if defined(__x86_64__) || defined(__M_X64__) || defined(__aarch64__)
/* minimum pool size: 16MiB + 4KiB (minimum BTT size + mmap alignment) */
#define PMEMBLK_MIN_POOL ((size_t)((1u << 20) * 16 + (1u << 10) * 8))
#elif defined(__PPC64__)
/* minimum pool size: 16MiB + 128KiB (minimum BTT size + mmap alignment) */
#define PMEMBLK_MIN_POOL ((size_t)((1u << 20) * 16 + (1u << 10) * 128))
#else
#error unable to recognize ISA at compile time
#endif
#else
/* minimum pool size: 16MiB + 64KiB (minimum BTT size + mmap alignment) */
#define PMEMBLK_MIN_POOL ((size_t)((1u << 20) * 16 + (1u << 10) * 64))
#endif
/*
* This limit is set arbitrary to incorporate a pool header and required
* alignment plus supply.
*/
#define PMEMBLK_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */
#define PMEMBLK_MIN_BLK ((size_t)512)
#ifndef _WIN32
PMEMblkpool *pmemblk_open(const char *path, size_t bsize);
#else
PMEMblkpool *pmemblk_openU(const char *path, size_t bsize);
PMEMblkpool *pmemblk_openW(const wchar_t *path, size_t bsize);
#endif
#ifndef _WIN32
PMEMblkpool *pmemblk_create(const char *path, size_t bsize,
size_t poolsize, mode_t mode);
#else
PMEMblkpool *pmemblk_createU(const char *path, size_t bsize,
size_t poolsize, mode_t mode);
PMEMblkpool *pmemblk_createW(const wchar_t *path, size_t bsize,
size_t poolsize, mode_t mode);
#endif
#ifndef _WIN32
int pmemblk_check(const char *path, size_t bsize);
#else
int pmemblk_checkU(const char *path, size_t bsize);
int pmemblk_checkW(const wchar_t *path, size_t bsize);
#endif
void pmemblk_close(PMEMblkpool *pbp);
size_t pmemblk_bsize(PMEMblkpool *pbp);
size_t pmemblk_nblock(PMEMblkpool *pbp);
int pmemblk_read(PMEMblkpool *pbp, void *buf, long long blockno);
int pmemblk_write(PMEMblkpool *pbp, const void *buf, long long blockno);
int pmemblk_set_zero(PMEMblkpool *pbp, long long blockno);
int pmemblk_set_error(PMEMblkpool *pbp, long long blockno);
/*
* Passing NULL to pmemblk_set_funcs() tells libpmemblk to continue to use the
* default for that function. The replacement functions must not make calls
* back into libpmemblk.
*/
void pmemblk_set_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));
#ifndef _WIN32
const char *pmemblk_errormsg(void);
#else
const char *pmemblk_errormsgU(void);
const wchar_t *pmemblk_errormsgW(void);
#endif
#ifndef _WIN32
/* EXPERIMENTAL */
int pmemblk_ctl_get(PMEMblkpool *pbp, const char *name, void *arg);
int pmemblk_ctl_set(PMEMblkpool *pbp, const char *name, void *arg);
int pmemblk_ctl_exec(PMEMblkpool *pbp, const char *name, void *arg);
#else
int pmemblk_ctl_getU(PMEMblkpool *pbp, const char *name, void *arg);
int pmemblk_ctl_getW(PMEMblkpool *pbp, const wchar_t *name, void *arg);
int pmemblk_ctl_setU(PMEMblkpool *pbp, const char *name, void *arg);
int pmemblk_ctl_setW(PMEMblkpool *pbp, const wchar_t *name, void *arg);
int pmemblk_ctl_execU(PMEMblkpool *pbp, const char *name, void *arg);
int pmemblk_ctl_execW(PMEMblkpool *pbp, const wchar_t *name, void *arg);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmemblk.h */
| 5,183 | 30.418182 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmempool.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* libpmempool.h -- definitions of libpmempool entry points
*
* See libpmempool(7) for details.
*/
#ifndef LIBPMEMPOOL_H
#define LIBPMEMPOOL_H 1
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmempool_check_status pmempool_check_statusW
#define pmempool_check_args pmempool_check_argsW
#define pmempool_check_init pmempool_check_initW
#define pmempool_check pmempool_checkW
#define pmempool_sync pmempool_syncW
#define pmempool_transform pmempool_transformW
#define pmempool_rm pmempool_rmW
#define pmempool_check_version pmempool_check_versionW
#define pmempool_errormsg pmempool_errormsgW
#define pmempool_feature_enable pmempool_feature_enableW
#define pmempool_feature_disable pmempool_feature_disableW
#define pmempool_feature_query pmempool_feature_queryW
#else
#define pmempool_check_status pmempool_check_statusU
#define pmempool_check_args pmempool_check_argsU
#define pmempool_check_init pmempool_check_initU
#define pmempool_check pmempool_checkU
#define pmempool_sync pmempool_syncU
#define pmempool_transform pmempool_transformU
#define pmempool_rm pmempool_rmU
#define pmempool_check_version pmempool_check_versionU
#define pmempool_errormsg pmempool_errormsgU
#define pmempool_feature_enable pmempool_feature_enableU
#define pmempool_feature_disable pmempool_feature_disableU
#define pmempool_feature_query pmempool_feature_queryU
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* PMEMPOOL CHECK */
/*
* pool types
*/
enum pmempool_pool_type {
PMEMPOOL_POOL_TYPE_DETECT,
PMEMPOOL_POOL_TYPE_LOG,
PMEMPOOL_POOL_TYPE_BLK,
PMEMPOOL_POOL_TYPE_OBJ,
PMEMPOOL_POOL_TYPE_BTT,
PMEMPOOL_POOL_TYPE_RESERVED1, /* used to be cto */
};
/*
* perform repairs
*/
#define PMEMPOOL_CHECK_REPAIR (1U << 0)
/*
* emulate repairs
*/
#define PMEMPOOL_CHECK_DRY_RUN (1U << 1)
/*
* perform hazardous repairs
*/
#define PMEMPOOL_CHECK_ADVANCED (1U << 2)
/*
* do not ask before repairs
*/
#define PMEMPOOL_CHECK_ALWAYS_YES (1U << 3)
/*
* generate info statuses
*/
#define PMEMPOOL_CHECK_VERBOSE (1U << 4)
/*
* generate string format statuses
*/
#define PMEMPOOL_CHECK_FORMAT_STR (1U << 5)
/*
* types of check statuses
*/
enum pmempool_check_msg_type {
PMEMPOOL_CHECK_MSG_TYPE_INFO,
PMEMPOOL_CHECK_MSG_TYPE_ERROR,
PMEMPOOL_CHECK_MSG_TYPE_QUESTION,
};
/*
* check result types
*/
enum pmempool_check_result {
PMEMPOOL_CHECK_RESULT_CONSISTENT,
PMEMPOOL_CHECK_RESULT_NOT_CONSISTENT,
PMEMPOOL_CHECK_RESULT_REPAIRED,
PMEMPOOL_CHECK_RESULT_CANNOT_REPAIR,
PMEMPOOL_CHECK_RESULT_ERROR,
PMEMPOOL_CHECK_RESULT_SYNC_REQ,
};
/*
* check context
*/
typedef struct pmempool_check_ctx PMEMpoolcheck;
/*
* finalize the check and get the result
*/
enum pmempool_check_result pmempool_check_end(PMEMpoolcheck *ppc);
/* PMEMPOOL RM */
#define PMEMPOOL_RM_FORCE (1U << 0) /* ignore any errors */
#define PMEMPOOL_RM_POOLSET_LOCAL (1U << 1) /* remove local poolsets */
#define PMEMPOOL_RM_POOLSET_REMOTE (1U << 2) /* remove remote poolsets */
/*
* LIBPMEMPOOL SYNC
*/
/*
* fix bad blocks - it requires creating or reading special recovery files
*/
#define PMEMPOOL_SYNC_FIX_BAD_BLOCKS (1U << 0)
/*
* do not apply changes, only check if operation is viable
*/
#define PMEMPOOL_SYNC_DRY_RUN (1U << 1)
/*
* LIBPMEMPOOL TRANSFORM
*/
/*
* do not apply changes, only check if operation is viable
*/
#define PMEMPOOL_TRANSFORM_DRY_RUN (1U << 1)
/*
* PMEMPOOL_MAJOR_VERSION and PMEMPOOL_MINOR_VERSION provide the current version
* of the libpmempool API as provided by this header file. Applications can
* verify that the version available at run-time is compatible with the version
* used at compile-time by passing these defines to pmempool_check_version().
*/
#define PMEMPOOL_MAJOR_VERSION 1
#define PMEMPOOL_MINOR_VERSION 3
/*
* check status
*/
struct pmempool_check_statusU {
enum pmempool_check_msg_type type;
struct {
const char *msg;
const char *answer;
} str;
};
#ifndef _WIN32
#define pmempool_check_status pmempool_check_statusU
#else
struct pmempool_check_statusW {
enum pmempool_check_msg_type type;
struct {
const wchar_t *msg;
const wchar_t *answer;
} str;
};
#endif
/*
* check context arguments
*/
struct pmempool_check_argsU {
const char *path;
const char *backup_path;
enum pmempool_pool_type pool_type;
unsigned flags;
};
#ifndef _WIN32
#define pmempool_check_args pmempool_check_argsU
#else
struct pmempool_check_argsW {
const wchar_t *path;
const wchar_t *backup_path;
enum pmempool_pool_type pool_type;
unsigned flags;
};
#endif
/*
* initialize a check context
*/
#ifndef _WIN32
PMEMpoolcheck *
pmempool_check_init(struct pmempool_check_args *args, size_t args_size);
#else
PMEMpoolcheck *
pmempool_check_initU(struct pmempool_check_argsU *args, size_t args_size);
PMEMpoolcheck *
pmempool_check_initW(struct pmempool_check_argsW *args, size_t args_size);
#endif
/*
* start / resume the check
*/
#ifndef _WIN32
struct pmempool_check_status *pmempool_check(PMEMpoolcheck *ppc);
#else
struct pmempool_check_statusU *pmempool_checkU(PMEMpoolcheck *ppc);
struct pmempool_check_statusW *pmempool_checkW(PMEMpoolcheck *ppc);
#endif
/*
* LIBPMEMPOOL SYNC & TRANSFORM
*/
/*
* Synchronize data between replicas within a poolset.
*
* EXPERIMENTAL
*/
#ifndef _WIN32
int pmempool_sync(const char *poolset_file, unsigned flags);
#else
int pmempool_syncU(const char *poolset_file, unsigned flags);
int pmempool_syncW(const wchar_t *poolset_file, unsigned flags);
#endif
/*
* Modify internal structure of a poolset.
*
* EXPERIMENTAL
*/
#ifndef _WIN32
int pmempool_transform(const char *poolset_file_src,
const char *poolset_file_dst, unsigned flags);
#else
int pmempool_transformU(const char *poolset_file_src,
const char *poolset_file_dst, unsigned flags);
int pmempool_transformW(const wchar_t *poolset_file_src,
const wchar_t *poolset_file_dst, unsigned flags);
#endif
/* PMEMPOOL feature enable, disable, query */
/*
* feature types
*/
enum pmempool_feature {
PMEMPOOL_FEAT_SINGLEHDR,
PMEMPOOL_FEAT_CKSUM_2K,
PMEMPOOL_FEAT_SHUTDOWN_STATE,
PMEMPOOL_FEAT_CHECK_BAD_BLOCKS,
};
/* PMEMPOOL FEATURE ENABLE */
#ifndef _WIN32
int pmempool_feature_enable(const char *path, enum pmempool_feature feature,
unsigned flags);
#else
int pmempool_feature_enableU(const char *path, enum pmempool_feature feature,
unsigned flags);
int pmempool_feature_enableW(const wchar_t *path,
enum pmempool_feature feature, unsigned flags);
#endif
/* PMEMPOOL FEATURE DISABLE */
#ifndef _WIN32
int pmempool_feature_disable(const char *path, enum pmempool_feature feature,
unsigned flags);
#else
int pmempool_feature_disableU(const char *path, enum pmempool_feature feature,
unsigned flags);
int pmempool_feature_disableW(const wchar_t *path,
enum pmempool_feature feature, unsigned flags);
#endif
/* PMEMPOOL FEATURE QUERY */
#ifndef _WIN32
int pmempool_feature_query(const char *path, enum pmempool_feature feature,
unsigned flags);
#else
int pmempool_feature_queryU(const char *path, enum pmempool_feature feature,
unsigned flags);
int pmempool_feature_queryW(const wchar_t *path,
enum pmempool_feature feature, unsigned flags);
#endif
/* PMEMPOOL RM */
#ifndef _WIN32
int pmempool_rm(const char *path, unsigned flags);
#else
int pmempool_rmU(const char *path, unsigned flags);
int pmempool_rmW(const wchar_t *path, unsigned flags);
#endif
#ifndef _WIN32
const char *pmempool_check_version(unsigned major_required,
unsigned minor_required);
#else
const char *pmempool_check_versionU(unsigned major_required,
unsigned minor_required);
const wchar_t *pmempool_check_versionW(unsigned major_required,
unsigned minor_required);
#endif
#ifndef _WIN32
const char *pmempool_errormsg(void);
#else
const char *pmempool_errormsgU(void);
const wchar_t *pmempool_errormsgW(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmempool.h */
| 8,009 | 22.910448 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/librpmem.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* librpmem.h -- definitions of librpmem entry points (EXPERIMENTAL)
*
* This library provides low-level support for remote access to persistent
* memory utilizing RDMA-capable RNICs.
*
* See librpmem(7) for details.
*/
#ifndef LIBRPMEM_H
#define LIBRPMEM_H 1
#include <sys/types.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct rpmem_pool RPMEMpool;
#define RPMEM_POOL_HDR_SIG_LEN 8
#define RPMEM_POOL_HDR_UUID_LEN 16 /* uuid byte length */
#define RPMEM_POOL_USER_FLAGS_LEN 16
struct rpmem_pool_attr {
char signature[RPMEM_POOL_HDR_SIG_LEN]; /* pool signature */
uint32_t major; /* format major version number */
uint32_t compat_features; /* mask: compatible "may" features */
uint32_t incompat_features; /* mask: "must support" features */
uint32_t ro_compat_features; /* mask: force RO if unsupported */
unsigned char poolset_uuid[RPMEM_POOL_HDR_UUID_LEN]; /* pool uuid */
unsigned char uuid[RPMEM_POOL_HDR_UUID_LEN]; /* first part uuid */
unsigned char next_uuid[RPMEM_POOL_HDR_UUID_LEN]; /* next pool uuid */
unsigned char prev_uuid[RPMEM_POOL_HDR_UUID_LEN]; /* prev pool uuid */
unsigned char user_flags[RPMEM_POOL_USER_FLAGS_LEN]; /* user flags */
};
RPMEMpool *rpmem_create(const char *target, const char *pool_set_name,
void *pool_addr, size_t pool_size, unsigned *nlanes,
const struct rpmem_pool_attr *create_attr);
RPMEMpool *rpmem_open(const char *target, const char *pool_set_name,
void *pool_addr, size_t pool_size, unsigned *nlanes,
struct rpmem_pool_attr *open_attr);
int rpmem_set_attr(RPMEMpool *rpp, const struct rpmem_pool_attr *attr);
int rpmem_close(RPMEMpool *rpp);
#define RPMEM_PERSIST_RELAXED (1U << 0)
#define RPMEM_FLUSH_RELAXED (1U << 0)
int rpmem_flush(RPMEMpool *rpp, size_t offset, size_t length, unsigned lane,
unsigned flags);
int rpmem_drain(RPMEMpool *rpp, unsigned lane, unsigned flags);
int rpmem_persist(RPMEMpool *rpp, size_t offset, size_t length,
unsigned lane, unsigned flags);
int rpmem_read(RPMEMpool *rpp, void *buff, size_t offset, size_t length,
unsigned lane);
int rpmem_deep_persist(RPMEMpool *rpp, size_t offset, size_t length,
unsigned lane);
#define RPMEM_REMOVE_FORCE 0x1
#define RPMEM_REMOVE_POOL_SET 0x2
int rpmem_remove(const char *target, const char *pool_set, int flags);
/*
* RPMEM_MAJOR_VERSION and RPMEM_MINOR_VERSION provide the current version of
* the librpmem API as provided by this header file. Applications can verify
* that the version available at run-time is compatible with the version used
* at compile-time by passing these defines to rpmem_check_version().
*/
#define RPMEM_MAJOR_VERSION 1
#define RPMEM_MINOR_VERSION 3
const char *rpmem_check_version(unsigned major_required,
unsigned minor_required);
const char *rpmem_errormsg(void);
/* minimum size of a pool */
#define RPMEM_MIN_POOL ((size_t)(1024 * 8)) /* 8 KB */
/*
* This limit is set arbitrary to incorporate a pool header and required
* alignment plus supply.
*/
#define RPMEM_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */
#ifdef __cplusplus
}
#endif
#endif /* librpmem.h */
| 3,197 | 31.30303 | 77 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj.h -- definitions of libpmemobj entry points
*
* This library provides support for programming with persistent memory (pmem).
*
* libpmemobj provides a pmem-resident transactional object store.
*
* See libpmemobj(7) for details.
*/
#ifndef LIBPMEMOBJ_H
#define LIBPMEMOBJ_H 1
#include <libpmemobj/action.h>
#include <libpmemobj/atomic.h>
#include <libpmemobj/ctl.h>
#include <libpmemobj/iterator.h>
#include <libpmemobj/lists_atomic.h>
#include <libpmemobj/pool.h>
#include <libpmemobj/thread.h>
#include <libpmemobj/tx.h>
#endif /* libpmemobj.h */
| 662 | 23.555556 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemlog.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemlog.h -- definitions of libpmemlog entry points
*
* This library provides support for programming with persistent memory (pmem).
*
* libpmemlog provides support for pmem-resident log files.
*
* See libpmemlog(7) for details.
*/
#ifndef LIBPMEMLOG_H
#define LIBPMEMLOG_H 1
#include <sys/types.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmemlog_open pmemlog_openW
#define pmemlog_create pmemlog_createW
#define pmemlog_check pmemlog_checkW
#define pmemlog_check_version pmemlog_check_versionW
#define pmemlog_errormsg pmemlog_errormsgW
#define pmemlog_ctl_get pmemlog_ctl_getW
#define pmemlog_ctl_set pmemlog_ctl_setW
#define pmemlog_ctl_exec pmemlog_ctl_execW
#else
#define pmemlog_open pmemlog_openU
#define pmemlog_create pmemlog_createU
#define pmemlog_check pmemlog_checkU
#define pmemlog_check_version pmemlog_check_versionU
#define pmemlog_errormsg pmemlog_errormsgU
#define pmemlog_ctl_get pmemlog_ctl_getU
#define pmemlog_ctl_set pmemlog_ctl_setU
#define pmemlog_ctl_exec pmemlog_ctl_execU
#endif
#else
#include <sys/uio.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* opaque type, internal to libpmemlog
*/
typedef struct pmemlog PMEMlogpool;
/*
* PMEMLOG_MAJOR_VERSION and PMEMLOG_MINOR_VERSION provide the current
* version of the libpmemlog API as provided by this header file.
* Applications can verify that the version available at run-time
* is compatible with the version used at compile-time by passing
* these defines to pmemlog_check_version().
*/
#define PMEMLOG_MAJOR_VERSION 1
#define PMEMLOG_MINOR_VERSION 1
#ifndef _WIN32
const char *pmemlog_check_version(unsigned major_required,
unsigned minor_required);
#else
const char *pmemlog_check_versionU(unsigned major_required,
unsigned minor_required);
const wchar_t *pmemlog_check_versionW(unsigned major_required,
unsigned minor_required);
#endif
/*
* support for PMEM-resident log files...
*/
#define PMEMLOG_MIN_POOL ((size_t)(1024 * 1024 * 2)) /* min pool size: 2MiB */
/*
* This limit is set arbitrary to incorporate a pool header and required
* alignment plus supply.
*/
#define PMEMLOG_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */
#ifndef _WIN32
PMEMlogpool *pmemlog_open(const char *path);
#else
PMEMlogpool *pmemlog_openU(const char *path);
PMEMlogpool *pmemlog_openW(const wchar_t *path);
#endif
#ifndef _WIN32
PMEMlogpool *pmemlog_create(const char *path, size_t poolsize, mode_t mode);
#else
PMEMlogpool *pmemlog_createU(const char *path, size_t poolsize, mode_t mode);
PMEMlogpool *pmemlog_createW(const wchar_t *path, size_t poolsize, mode_t mode);
#endif
#ifndef _WIN32
int pmemlog_check(const char *path);
#else
int pmemlog_checkU(const char *path);
int pmemlog_checkW(const wchar_t *path);
#endif
void pmemlog_close(PMEMlogpool *plp);
size_t pmemlog_nbyte(PMEMlogpool *plp);
int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count);
int pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt);
long long pmemlog_tell(PMEMlogpool *plp);
void pmemlog_rewind(PMEMlogpool *plp);
void pmemlog_walk(PMEMlogpool *plp, size_t chunksize,
int (*process_chunk)(const void *buf, size_t len, void *arg),
void *arg);
/*
* Passing NULL to pmemlog_set_funcs() tells libpmemlog to continue to use the
* default for that function. The replacement functions must not make calls
* back into libpmemlog.
*/
void pmemlog_set_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));
#ifndef _WIN32
const char *pmemlog_errormsg(void);
#else
const char *pmemlog_errormsgU(void);
const wchar_t *pmemlog_errormsgW(void);
#endif
#ifndef _WIN32
/* EXPERIMENTAL */
int pmemlog_ctl_get(PMEMlogpool *plp, const char *name, void *arg);
int pmemlog_ctl_set(PMEMlogpool *plp, const char *name, void *arg);
int pmemlog_ctl_exec(PMEMlogpool *plp, const char *name, void *arg);
#else
int pmemlog_ctl_getU(PMEMlogpool *plp, const char *name, void *arg);
int pmemlog_ctl_getW(PMEMlogpool *plp, const wchar_t *name, void *arg);
int pmemlog_ctl_setU(PMEMlogpool *plp, const char *name, void *arg);
int pmemlog_ctl_setW(PMEMlogpool *plp, const wchar_t *name, void *arg);
int pmemlog_ctl_execU(PMEMlogpool *plp, const char *name, void *arg);
int pmemlog_ctl_execW(PMEMlogpool *plp, const wchar_t *name, void *arg);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmemlog.h */
| 4,540 | 28.679739 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmem.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmem.h -- definitions of libpmem entry points
*
* This library provides support for programming with persistent memory (pmem).
*
* libpmem provides support for using raw pmem directly.
*
* See libpmem(7) for details.
*/
#ifndef LIBPMEM_H
#define LIBPMEM_H 1
#include <sys/types.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmem_map_file pmem_map_fileW
#define pmem_check_version pmem_check_versionW
#define pmem_errormsg pmem_errormsgW
#else
#define pmem_map_file pmem_map_fileU
#define pmem_check_version pmem_check_versionU
#define pmem_errormsg pmem_errormsgU
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* This limit is set arbitrary to incorporate a pool header and required
* alignment plus supply.
*/
#define PMEM_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */
/*
* flags supported by pmem_map_file()
*/
#define PMEM_FILE_CREATE (1 << 0)
#define PMEM_FILE_EXCL (1 << 1)
#define PMEM_FILE_SPARSE (1 << 2)
#define PMEM_FILE_TMPFILE (1 << 3)
#ifndef _WIN32
void *pmem_map_file(const char *path, size_t len, int flags, mode_t mode,
size_t *mapped_lenp, int *is_pmemp);
#else
void *pmem_map_fileU(const char *path, size_t len, int flags, mode_t mode,
size_t *mapped_lenp, int *is_pmemp);
void *pmem_map_fileW(const wchar_t *path, size_t len, int flags, mode_t mode,
size_t *mapped_lenp, int *is_pmemp);
#endif
int pmem_unmap(void *addr, size_t len);
int pmem_is_pmem(const void *addr, size_t len);
void pmem_persist(const void *addr, size_t len);
int pmem_msync(const void *addr, size_t len);
int pmem_has_auto_flush(void);
void pmem_flush(const void *addr, size_t len);
void pmem_deep_flush(const void *addr, size_t len);
int pmem_deep_drain(const void *addr, size_t len);
int pmem_deep_persist(const void *addr, size_t len);
void pmem_drain(void);
int pmem_has_hw_drain(void);
void *pmem_memmove_persist(void *pmemdest, const void *src, size_t len);
void *pmem_memcpy_persist(void *pmemdest, const void *src, size_t len);
void *pmem_memset_persist(void *pmemdest, int c, size_t len);
void *pmem_memmove_nodrain(void *pmemdest, const void *src, size_t len);
void *pmem_memcpy_nodrain(void *pmemdest, const void *src, size_t len);
void *pmem_memset_nodrain(void *pmemdest, int c, size_t len);
#define PMEM_F_MEM_NODRAIN (1U << 0)
#define PMEM_F_MEM_NONTEMPORAL (1U << 1)
#define PMEM_F_MEM_TEMPORAL (1U << 2)
#define PMEM_F_MEM_WC (1U << 3)
#define PMEM_F_MEM_WB (1U << 4)
#define PMEM_F_MEM_NOFLUSH (1U << 5)
#define PMEM_F_MEM_VALID_FLAGS (PMEM_F_MEM_NODRAIN | \
PMEM_F_MEM_NONTEMPORAL | \
PMEM_F_MEM_TEMPORAL | \
PMEM_F_MEM_WC | \
PMEM_F_MEM_WB | \
PMEM_F_MEM_NOFLUSH)
void *pmem_memmove(void *pmemdest, const void *src, size_t len, unsigned flags);
void *pmem_memcpy(void *pmemdest, const void *src, size_t len, unsigned flags);
void *pmem_memset(void *pmemdest, int c, size_t len, unsigned flags);
/*
* PMEM_MAJOR_VERSION and PMEM_MINOR_VERSION provide the current version of the
* libpmem API as provided by this header file. Applications can verify that
* the version available at run-time is compatible with the version used at
* compile-time by passing these defines to pmem_check_version().
*/
#define PMEM_MAJOR_VERSION 1
#define PMEM_MINOR_VERSION 1
#ifndef _WIN32
const char *pmem_check_version(unsigned major_required,
unsigned minor_required);
#else
const char *pmem_check_versionU(unsigned major_required,
unsigned minor_required);
const wchar_t *pmem_check_versionW(unsigned major_required,
unsigned minor_required);
#endif
#ifndef _WIN32
const char *pmem_errormsg(void);
#else
const char *pmem_errormsgU(void);
const wchar_t *pmem_errormsgW(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmem.h */
| 3,829 | 28.015152 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmem2.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2019-2020, Intel Corporation */
/*
* libpmem2.h -- definitions of libpmem2 entry points (EXPERIMENTAL)
*
* This library provides support for programming with persistent memory (pmem).
*
* libpmem2 provides support for using raw pmem directly.
*
* See libpmem2(7) for details.
*/
#ifndef LIBPMEM2_H
#define LIBPMEM2_H 1
#include <stddef.h>
#include <stdint.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmem2_source_device_id pmem2_source_device_idW
#define pmem2_errormsg pmem2_errormsgW
#define pmem2_perror pmem2_perrorW
#else
#define pmem2_source_device_id pmem2_source_device_idU
#define pmem2_errormsg pmem2_errormsgU
#define pmem2_perror pmem2_perrorU
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define PMEM2_E_UNKNOWN (-100000)
#define PMEM2_E_NOSUPP (-100001)
#define PMEM2_E_FILE_HANDLE_NOT_SET (-100003)
#define PMEM2_E_INVALID_FILE_HANDLE (-100004)
#define PMEM2_E_INVALID_FILE_TYPE (-100005)
#define PMEM2_E_MAP_RANGE (-100006)
#define PMEM2_E_MAPPING_EXISTS (-100007)
#define PMEM2_E_GRANULARITY_NOT_SET (-100008)
#define PMEM2_E_GRANULARITY_NOT_SUPPORTED (-100009)
#define PMEM2_E_OFFSET_OUT_OF_RANGE (-100010)
#define PMEM2_E_OFFSET_UNALIGNED (-100011)
#define PMEM2_E_INVALID_ALIGNMENT_FORMAT (-100012)
#define PMEM2_E_INVALID_ALIGNMENT_VALUE (-100013)
#define PMEM2_E_INVALID_SIZE_FORMAT (-100014)
#define PMEM2_E_LENGTH_UNALIGNED (-100015)
#define PMEM2_E_MAPPING_NOT_FOUND (-100016)
#define PMEM2_E_BUFFER_TOO_SMALL (-100017)
#define PMEM2_E_SOURCE_EMPTY (-100018)
#define PMEM2_E_INVALID_SHARING_VALUE (-100019)
#define PMEM2_E_SRC_DEVDAX_PRIVATE (-100020)
#define PMEM2_E_INVALID_ADDRESS_REQUEST_TYPE (-100021)
#define PMEM2_E_ADDRESS_UNALIGNED (-100022)
#define PMEM2_E_ADDRESS_NULL (-100023)
#define PMEM2_E_DEEP_FLUSH_RANGE (-100024)
#define PMEM2_E_INVALID_REGION_FORMAT (-100025)
#define PMEM2_E_DAX_REGION_NOT_FOUND (-100026)
#define PMEM2_E_INVALID_DEV_FORMAT (-100027)
#define PMEM2_E_CANNOT_READ_BOUNDS (-100028)
#define PMEM2_E_NO_BAD_BLOCK_FOUND (-100029)
#define PMEM2_E_LENGTH_OUT_OF_RANGE (-100030)
#define PMEM2_E_INVALID_PROT_FLAG (-100031)
#define PMEM2_E_NO_ACCESS (-100032)
/* source setup */
struct pmem2_source;
int pmem2_source_from_fd(struct pmem2_source **src, int fd);
int pmem2_source_from_anon(struct pmem2_source **src, size_t size);
#ifdef _WIN32
int pmem2_source_from_handle(struct pmem2_source **src, HANDLE handle);
#endif
int pmem2_source_size(const struct pmem2_source *src, size_t *size);
int pmem2_source_alignment(const struct pmem2_source *src,
size_t *alignment);
int pmem2_source_delete(struct pmem2_source **src);
/* vm reservation setup */
struct pmem2_vm_reservation;
int pmem2_vm_reservation_new(struct pmem2_vm_reservation **rsv,
size_t size, void *address);
int pmem2_vm_reservation_delete(struct pmem2_vm_reservation **rsv);
/* config setup */
struct pmem2_config;
int pmem2_config_new(struct pmem2_config **cfg);
int pmem2_config_delete(struct pmem2_config **cfg);
enum pmem2_granularity {
PMEM2_GRANULARITY_BYTE,
PMEM2_GRANULARITY_CACHE_LINE,
PMEM2_GRANULARITY_PAGE,
};
int pmem2_config_set_required_store_granularity(struct pmem2_config *cfg,
enum pmem2_granularity g);
int pmem2_config_set_offset(struct pmem2_config *cfg, size_t offset);
int pmem2_config_set_length(struct pmem2_config *cfg, size_t length);
enum pmem2_sharing_type {
PMEM2_SHARED,
PMEM2_PRIVATE,
};
int pmem2_config_set_sharing(struct pmem2_config *cfg,
enum pmem2_sharing_type type);
#define PMEM2_PROT_EXEC (1U << 29)
#define PMEM2_PROT_READ (1U << 30)
#define PMEM2_PROT_WRITE (1U << 31)
#define PMEM2_PROT_NONE 0
int pmem2_config_set_protection(struct pmem2_config *cfg,
unsigned prot);
enum pmem2_address_request_type {
PMEM2_ADDRESS_FIXED_REPLACE = 1,
PMEM2_ADDRESS_FIXED_NOREPLACE = 2,
};
int pmem2_config_set_address(struct pmem2_config *cfg, void *addr,
enum pmem2_address_request_type request_type);
int pmem2_config_set_vm_reservation(struct pmem2_config *cfg,
struct pmem2_vm_reservation *rsv, size_t offset);
void pmem2_config_clear_address(struct pmem2_config *cfg);
/* mapping */
struct pmem2_map;
int pmem2_map(const struct pmem2_config *cfg, const struct pmem2_source *src,
struct pmem2_map **map_ptr);
int pmem2_unmap(struct pmem2_map **map_ptr);
void *pmem2_map_get_address(struct pmem2_map *map);
size_t pmem2_map_get_size(struct pmem2_map *map);
enum pmem2_granularity pmem2_map_get_store_granularity(struct pmem2_map *map);
/* flushing */
typedef void (*pmem2_persist_fn)(const void *ptr, size_t size);
typedef void (*pmem2_flush_fn)(const void *ptr, size_t size);
typedef void (*pmem2_drain_fn)(void);
pmem2_persist_fn pmem2_get_persist_fn(struct pmem2_map *map);
pmem2_flush_fn pmem2_get_flush_fn(struct pmem2_map *map);
pmem2_drain_fn pmem2_get_drain_fn(struct pmem2_map *map);
#define PMEM2_F_MEM_NODRAIN (1U << 0)
#define PMEM2_F_MEM_NONTEMPORAL (1U << 1)
#define PMEM2_F_MEM_TEMPORAL (1U << 2)
#define PMEM2_F_MEM_WC (1U << 3)
#define PMEM2_F_MEM_WB (1U << 4)
#define PMEM2_F_MEM_NOFLUSH (1U << 5)
#define PMEM2_F_MEM_VALID_FLAGS (PMEM2_F_MEM_NODRAIN | \
PMEM2_F_MEM_NONTEMPORAL | \
PMEM2_F_MEM_TEMPORAL | \
PMEM2_F_MEM_WC | \
PMEM2_F_MEM_WB | \
PMEM2_F_MEM_NOFLUSH)
typedef void *(*pmem2_memmove_fn)(void *pmemdest, const void *src, size_t len,
unsigned flags);
typedef void *(*pmem2_memcpy_fn)(void *pmemdest, const void *src, size_t len,
unsigned flags);
typedef void *(*pmem2_memset_fn)(void *pmemdest, int c, size_t len,
unsigned flags);
pmem2_memmove_fn pmem2_get_memmove_fn(struct pmem2_map *map);
pmem2_memcpy_fn pmem2_get_memcpy_fn(struct pmem2_map *map);
pmem2_memset_fn pmem2_get_memset_fn(struct pmem2_map *map);
/* RAS */
int pmem2_deep_flush(struct pmem2_map *map, void *ptr, size_t size);
#ifndef _WIN32
int pmem2_source_device_id(const struct pmem2_source *src,
char *id, size_t *len);
#else
int pmem2_source_device_idW(const struct pmem2_source *src,
wchar_t *id, size_t *len);
int pmem2_source_device_idU(const struct pmem2_source *src,
char *id, size_t *len);
#endif
int pmem2_source_device_usc(const struct pmem2_source *src, uint64_t *usc);
struct pmem2_badblock_context;
struct pmem2_badblock {
size_t offset;
size_t length;
};
int pmem2_badblock_context_new(const struct pmem2_source *src,
struct pmem2_badblock_context **bbctx);
int pmem2_badblock_next(struct pmem2_badblock_context *bbctx,
struct pmem2_badblock *bb);
void pmem2_badblock_context_delete(
struct pmem2_badblock_context **bbctx);
int pmem2_badblock_clear(struct pmem2_badblock_context *bbctx,
const struct pmem2_badblock *bb);
/* error handling */
#ifndef _WIN32
const char *pmem2_errormsg(void);
#else
const char *pmem2_errormsgU(void);
const wchar_t *pmem2_errormsgW(void);
#endif
int pmem2_err_to_errno(int);
#ifndef _WIN32
void pmem2_perror(const char *format,
...) __attribute__((__format__(__printf__, 1, 2)));
#else
void pmem2_perrorU(const char *format, ...);
void pmem2_perrorW(const wchar_t *format, ...);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmem2.h */
| 7,202 | 25.677778 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/ctl.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2019, Intel Corporation */
/*
* libpmemobj/ctl.h -- definitions of pmemobj_ctl related entry points
*/
#ifndef LIBPMEMOBJ_CTL_H
#define LIBPMEMOBJ_CTL_H 1
#include <stddef.h>
#include <sys/types.h>
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Allocation class interface
*
* When requesting an object from the allocator, the first step is to determine
* which allocation class best approximates the size of the object.
* Once found, the appropriate free list, called bucket, for that
* class is selected in a fashion that minimizes contention between threads.
* Depending on the requested size and the allocation class, it might happen
* that the object size (including required metadata) would be bigger than the
* allocation class size - called unit size. In those situations, the object is
* constructed from two or more units (up to 64).
*
* If the requested number of units cannot be retrieved from the selected
* bucket, the thread reaches out to the global, shared, heap which manages
* memory in 256 kilobyte chunks and gives it out in a best-fit fashion. This
* operation must be performed under an exclusive lock.
* Once the thread is in the possession of a chunk, the lock is dropped, and the
* memory is split into units that repopulate the bucket.
*
* These are the CTL entry points that control allocation classes:
* - heap.alloc_class.[class_id].desc
* Creates/retrieves allocation class information
*
* It's VERY important to remember that the allocation classes are a RUNTIME
* property of the allocator - they are NOT stored persistently in the pool.
* It's recommended to always create custom allocation classes immediately after
* creating or opening the pool, before any use.
* If there are existing objects created using a class that is no longer stored
* in the runtime state of the allocator, they can be normally freed, but
* allocating equivalent objects will be done using the allocation class that
* is currently defined for that size.
*
* Please see the libpmemobj man page for more information about entry points.
*/
/*
* Persistent allocation header
*/
enum pobj_header_type {
/*
* 64-byte header used up until the version 1.3 of the library,
* functionally equivalent to the compact header.
* It's not recommended to create any new classes with this header.
*/
POBJ_HEADER_LEGACY,
/*
* 16-byte header used by the default allocation classes. All library
* metadata is by default allocated using this header.
* Supports type numbers and variably sized allocations.
*/
POBJ_HEADER_COMPACT,
/*
* 0-byte header with metadata stored exclusively in a bitmap. This
* ensures that objects are allocated in memory contiguously and
* without attached headers.
* This can be used to create very small allocation classes, but it
* does not support type numbers.
* Additionally, allocations with this header can only span a single
* unit.
* Objects allocated with this header do show up when iterating through
* the heap using pmemobj_first/pmemobj_next functions, but have a
* type_num equal 0.
*/
POBJ_HEADER_NONE,
MAX_POBJ_HEADER_TYPES
};
/*
* Description of allocation classes
*/
struct pobj_alloc_class_desc {
/*
* The number of bytes in a single unit of allocation. A single
* allocation can span up to 64 units (or 1 in the case of no header).
* If one creates an allocation class with a certain unit size and
* forces it to handle bigger sizes, more than one unit
* will be used.
* For example, an allocation class with a compact header and 128 bytes
* unit size, for a request of 200 bytes will create a memory block
* containing 256 bytes that spans two units. The usable size of that
* allocation will be 240 bytes: 2 * 128 - 16 (header).
*/
size_t unit_size;
/*
* Desired alignment of objects from the allocation class.
* If non zero, must be a power of two and an even divisor of unit size.
*
* All allocation classes have default alignment
* of 64. User data alignment is affected by the size of a header. For
* compact one this means that the alignment is 48 bytes.
*
*/
size_t alignment;
/*
* The minimum number of units that must be present in a
* single, contiguous, memory block.
* Those blocks (internally called runs), are fetched on demand from the
* heap. Accessing that global state is a serialization point for the
* allocator and thus it is imperative for performance and scalability
* that a reasonable amount of memory is fetched in a single call.
* Threads generally do not share memory blocks from which they
* allocate, but blocks do go back to the global heap if they are no
* longer actively used for allocation.
*/
unsigned units_per_block;
/*
* The header of allocations that originate from this allocation class.
*/
enum pobj_header_type header_type;
/*
* The identifier of this allocation class.
*/
unsigned class_id;
};
enum pobj_stats_enabled {
POBJ_STATS_ENABLED_TRANSIENT,
POBJ_STATS_ENABLED_BOTH,
POBJ_STATS_ENABLED_PERSISTENT,
POBJ_STATS_DISABLED,
};
#ifndef _WIN32
/* EXPERIMENTAL */
int pmemobj_ctl_get(PMEMobjpool *pop, const char *name, void *arg);
int pmemobj_ctl_set(PMEMobjpool *pop, const char *name, void *arg);
int pmemobj_ctl_exec(PMEMobjpool *pop, const char *name, void *arg);
#else
int pmemobj_ctl_getU(PMEMobjpool *pop, const char *name, void *arg);
int pmemobj_ctl_getW(PMEMobjpool *pop, const wchar_t *name, void *arg);
int pmemobj_ctl_setU(PMEMobjpool *pop, const char *name, void *arg);
int pmemobj_ctl_setW(PMEMobjpool *pop, const wchar_t *name, void *arg);
int pmemobj_ctl_execU(PMEMobjpool *pop, const char *name, void *arg);
int pmemobj_ctl_execW(PMEMobjpool *pop, const wchar_t *name, void *arg);
#ifndef PMDK_UTF8_API
#define pmemobj_ctl_get pmemobj_ctl_getW
#define pmemobj_ctl_set pmemobj_ctl_setW
#define pmemobj_ctl_exec pmemobj_ctl_execW
#else
#define pmemobj_ctl_get pmemobj_ctl_getU
#define pmemobj_ctl_set pmemobj_ctl_setU
#define pmemobj_ctl_exec pmemobj_ctl_execU
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/ctl.h */
| 6,198 | 34.221591 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/lists_atomic.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* libpmemobj/lists_atomic.h -- definitions of libpmemobj atomic lists macros
*/
#ifndef LIBPMEMOBJ_LISTS_ATOMIC_H
#define LIBPMEMOBJ_LISTS_ATOMIC_H 1
#include <libpmemobj/lists_atomic_base.h>
#include <libpmemobj/thread.h>
#include <libpmemobj/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Non-transactional persistent atomic circular doubly-linked list
*/
#define POBJ_LIST_ENTRY(type)\
struct {\
TOID(type) pe_next;\
TOID(type) pe_prev;\
}
#define POBJ_LIST_HEAD(name, type)\
struct name {\
TOID(type) pe_first;\
PMEMmutex lock;\
}
#define POBJ_LIST_FIRST(head) ((head)->pe_first)
#define POBJ_LIST_LAST(head, field) (\
TOID_IS_NULL((head)->pe_first) ?\
(head)->pe_first :\
D_RO((head)->pe_first)->field.pe_prev)
#define POBJ_LIST_EMPTY(head) (TOID_IS_NULL((head)->pe_first))
#define POBJ_LIST_NEXT(elm, field) (D_RO(elm)->field.pe_next)
#define POBJ_LIST_PREV(elm, field) (D_RO(elm)->field.pe_prev)
#define POBJ_LIST_DEST_HEAD 1
#define POBJ_LIST_DEST_TAIL 0
#define POBJ_LIST_DEST_BEFORE 1
#define POBJ_LIST_DEST_AFTER 0
#define POBJ_LIST_FOREACH(var, head, field)\
for (_pobj_debug_notice("POBJ_LIST_FOREACH", __FILE__, __LINE__),\
(var) = POBJ_LIST_FIRST((head));\
TOID_IS_NULL((var)) == 0;\
TOID_EQUALS(POBJ_LIST_NEXT((var), field),\
POBJ_LIST_FIRST((head))) ?\
TOID_ASSIGN((var), OID_NULL) :\
((var) = POBJ_LIST_NEXT((var), field)))
#define POBJ_LIST_FOREACH_REVERSE(var, head, field)\
for (_pobj_debug_notice("POBJ_LIST_FOREACH_REVERSE", __FILE__, __LINE__),\
(var) = POBJ_LIST_LAST((head), field);\
TOID_IS_NULL((var)) == 0;\
TOID_EQUALS(POBJ_LIST_PREV((var), field),\
POBJ_LIST_LAST((head), field)) ?\
TOID_ASSIGN((var), OID_NULL) :\
((var) = POBJ_LIST_PREV((var), field)))
#define POBJ_LIST_INSERT_HEAD(pop, head, elm, field)\
pmemobj_list_insert((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), OID_NULL,\
POBJ_LIST_DEST_HEAD, (elm).oid)
#define POBJ_LIST_INSERT_TAIL(pop, head, elm, field)\
pmemobj_list_insert((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), OID_NULL,\
POBJ_LIST_DEST_TAIL, (elm).oid)
#define POBJ_LIST_INSERT_AFTER(pop, head, listelm, elm, field)\
pmemobj_list_insert((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), (listelm).oid,\
0 /* after */, (elm).oid)
#define POBJ_LIST_INSERT_BEFORE(pop, head, listelm, elm, field)\
pmemobj_list_insert((pop), \
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), (listelm).oid,\
1 /* before */, (elm).oid)
#define POBJ_LIST_INSERT_NEW_HEAD(pop, head, field, size, constr, arg)\
pmemobj_list_insert_new((pop),\
TOID_OFFSETOF((head)->pe_first, field),\
(head), OID_NULL, POBJ_LIST_DEST_HEAD, (size),\
TOID_TYPE_NUM_OF((head)->pe_first), (constr), (arg))
#define POBJ_LIST_INSERT_NEW_TAIL(pop, head, field, size, constr, arg)\
pmemobj_list_insert_new((pop),\
TOID_OFFSETOF((head)->pe_first, field),\
(head), OID_NULL, POBJ_LIST_DEST_TAIL, (size),\
TOID_TYPE_NUM_OF((head)->pe_first), (constr), (arg))
#define POBJ_LIST_INSERT_NEW_AFTER(pop, head, listelm, field, size,\
constr, arg)\
pmemobj_list_insert_new((pop),\
TOID_OFFSETOF((head)->pe_first, field),\
(head), (listelm).oid, 0 /* after */, (size),\
TOID_TYPE_NUM_OF((head)->pe_first), (constr), (arg))
#define POBJ_LIST_INSERT_NEW_BEFORE(pop, head, listelm, field, size,\
constr, arg)\
pmemobj_list_insert_new((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), (listelm).oid, 1 /* before */, (size),\
TOID_TYPE_NUM_OF((head)->pe_first), (constr), (arg))
#define POBJ_LIST_REMOVE(pop, head, elm, field)\
pmemobj_list_remove((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), (elm).oid, 0 /* no free */)
#define POBJ_LIST_REMOVE_FREE(pop, head, elm, field)\
pmemobj_list_remove((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head), (elm).oid, 1 /* free */)
#define POBJ_LIST_MOVE_ELEMENT_HEAD(pop, head, head_new, elm, field, field_new)\
pmemobj_list_move((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head_new), field_new),\
(head_new), OID_NULL, POBJ_LIST_DEST_HEAD, (elm).oid)
#define POBJ_LIST_MOVE_ELEMENT_TAIL(pop, head, head_new, elm, field, field_new)\
pmemobj_list_move((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head_new), field_new),\
(head_new), OID_NULL, POBJ_LIST_DEST_TAIL, (elm).oid)
#define POBJ_LIST_MOVE_ELEMENT_AFTER(pop,\
head, head_new, listelm, elm, field, field_new)\
pmemobj_list_move((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head_new), field_new),\
(head_new),\
(listelm).oid,\
0 /* after */, (elm).oid)
#define POBJ_LIST_MOVE_ELEMENT_BEFORE(pop,\
head, head_new, listelm, elm, field, field_new)\
pmemobj_list_move((pop),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head), field),\
(head),\
TOID_OFFSETOF(POBJ_LIST_FIRST(head_new), field_new),\
(head_new),\
(listelm).oid,\
1 /* before */, (elm).oid)
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/lists_atomic.h */
| 5,121 | 30.042424 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/iterator.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj/iterator.h -- definitions of libpmemobj iterator macros
*/
#ifndef LIBPMEMOBJ_ITERATOR_H
#define LIBPMEMOBJ_ITERATOR_H 1
#include <libpmemobj/iterator_base.h>
#include <libpmemobj/types.h>
#ifdef __cplusplus
extern "C" {
#endif
static inline PMEMoid
POBJ_FIRST_TYPE_NUM(PMEMobjpool *pop, uint64_t type_num)
{
PMEMoid _pobj_ret = pmemobj_first(pop);
while (!OID_IS_NULL(_pobj_ret) &&
pmemobj_type_num(_pobj_ret) != type_num) {
_pobj_ret = pmemobj_next(_pobj_ret);
}
return _pobj_ret;
}
static inline PMEMoid
POBJ_NEXT_TYPE_NUM(PMEMoid o)
{
PMEMoid _pobj_ret = o;
do {
_pobj_ret = pmemobj_next(_pobj_ret);\
} while (!OID_IS_NULL(_pobj_ret) &&
pmemobj_type_num(_pobj_ret) != pmemobj_type_num(o));
return _pobj_ret;
}
#define POBJ_FIRST(pop, t) ((TOID(t))POBJ_FIRST_TYPE_NUM(pop, TOID_TYPE_NUM(t)))
#define POBJ_NEXT(o) ((__typeof__(o))POBJ_NEXT_TYPE_NUM((o).oid))
/*
* Iterates through every existing allocated object.
*/
#define POBJ_FOREACH(pop, varoid)\
for (_pobj_debug_notice("POBJ_FOREACH", __FILE__, __LINE__),\
varoid = pmemobj_first(pop);\
(varoid).off != 0; varoid = pmemobj_next(varoid))
/*
* Safe variant of POBJ_FOREACH in which pmemobj_free on varoid is allowed
*/
#define POBJ_FOREACH_SAFE(pop, varoid, nvaroid)\
for (_pobj_debug_notice("POBJ_FOREACH_SAFE", __FILE__, __LINE__),\
varoid = pmemobj_first(pop);\
(varoid).off != 0 && (nvaroid = pmemobj_next(varoid), 1);\
varoid = nvaroid)
/*
* Iterates through every object of the specified type.
*/
#define POBJ_FOREACH_TYPE(pop, var)\
POBJ_FOREACH(pop, (var).oid)\
if (pmemobj_type_num((var).oid) == TOID_TYPE_NUM_OF(var))
/*
* Safe variant of POBJ_FOREACH_TYPE in which pmemobj_free on var
* is allowed.
*/
#define POBJ_FOREACH_SAFE_TYPE(pop, var, nvar)\
POBJ_FOREACH_SAFE(pop, (var).oid, (nvar).oid)\
if (pmemobj_type_num((var).oid) == TOID_TYPE_NUM_OF(var))
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/iterator.h */
| 2,041 | 23.60241 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/lists_atomic_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* libpmemobj/lists_atomic_base.h -- definitions of libpmemobj atomic lists
*/
#ifndef LIBPMEMOBJ_LISTS_ATOMIC_BASE_H
#define LIBPMEMOBJ_LISTS_ATOMIC_BASE_H 1
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Non-transactional persistent atomic circular doubly-linked list
*/
int pmemobj_list_insert(PMEMobjpool *pop, size_t pe_offset, void *head,
PMEMoid dest, int before, PMEMoid oid);
PMEMoid pmemobj_list_insert_new(PMEMobjpool *pop, size_t pe_offset, void *head,
PMEMoid dest, int before, size_t size, uint64_t type_num,
pmemobj_constr constructor, void *arg);
int pmemobj_list_remove(PMEMobjpool *pop, size_t pe_offset, void *head,
PMEMoid oid, int free);
int pmemobj_list_move(PMEMobjpool *pop, size_t pe_old_offset,
void *head_old, size_t pe_new_offset, void *head_new,
PMEMoid dest, int before, PMEMoid oid);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/lists_atomic_base.h */
| 1,022 | 24.575 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/tx_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* libpmemobj/tx_base.h -- definitions of libpmemobj transactional entry points
*/
#ifndef LIBPMEMOBJ_TX_BASE_H
#define LIBPMEMOBJ_TX_BASE_H 1
#include <setjmp.h>
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Transactions
*
* Stages are changed only by the pmemobj_tx_* functions, each transition
* to the TX_STAGE_ONABORT is followed by a longjmp to the jmp_buf provided in
* the pmemobj_tx_begin function.
*/
enum pobj_tx_stage {
TX_STAGE_NONE, /* no transaction in this thread */
TX_STAGE_WORK, /* transaction in progress */
TX_STAGE_ONCOMMIT, /* successfully committed */
TX_STAGE_ONABORT, /* tx_begin failed or transaction aborted */
TX_STAGE_FINALLY, /* always called */
MAX_TX_STAGE
};
/*
* Always returns the current transaction stage for a thread.
*/
enum pobj_tx_stage pmemobj_tx_stage(void);
enum pobj_tx_param {
TX_PARAM_NONE,
TX_PARAM_MUTEX, /* PMEMmutex */
TX_PARAM_RWLOCK, /* PMEMrwlock */
TX_PARAM_CB, /* pmemobj_tx_callback cb, void *arg */
};
enum pobj_log_type {
TX_LOG_TYPE_SNAPSHOT,
TX_LOG_TYPE_INTENT,
};
enum pobj_tx_failure_behavior {
POBJ_TX_FAILURE_ABORT,
POBJ_TX_FAILURE_RETURN,
};
#if !defined(pmdk_use_attr_deprec_with_msg) && defined(__COVERITY__)
#define pmdk_use_attr_deprec_with_msg 0
#endif
#if !defined(pmdk_use_attr_deprec_with_msg) && defined(__clang__)
#if __has_extension(attribute_deprecated_with_message)
#define pmdk_use_attr_deprec_with_msg 1
#else
#define pmdk_use_attr_deprec_with_msg 0
#endif
#endif
#if !defined(pmdk_use_attr_deprec_with_msg) && \
defined(__GNUC__) && !defined(__INTEL_COMPILER)
#if __GNUC__ * 100 + __GNUC_MINOR__ >= 601 /* 6.1 */
#define pmdk_use_attr_deprec_with_msg 1
#else
#define pmdk_use_attr_deprec_with_msg 0
#endif
#endif
#if !defined(pmdk_use_attr_deprec_with_msg)
#define pmdk_use_attr_deprec_with_msg 0
#endif
#if pmdk_use_attr_deprec_with_msg
#define tx_lock_deprecated __attribute__((deprecated(\
"enum pobj_tx_lock is deprecated, use enum pobj_tx_param")))
#else
#define tx_lock_deprecated
#endif
/* deprecated, do not use */
enum tx_lock_deprecated pobj_tx_lock {
TX_LOCK_NONE tx_lock_deprecated = TX_PARAM_NONE,
TX_LOCK_MUTEX tx_lock_deprecated = TX_PARAM_MUTEX,
TX_LOCK_RWLOCK tx_lock_deprecated = TX_PARAM_RWLOCK,
};
typedef void (*pmemobj_tx_callback)(PMEMobjpool *pop, enum pobj_tx_stage stage,
void *);
#define POBJ_TX_XALLOC_VALID_FLAGS (POBJ_XALLOC_ZERO |\
POBJ_XALLOC_NO_FLUSH |\
POBJ_XALLOC_ARENA_MASK |\
POBJ_XALLOC_CLASS_MASK |\
POBJ_XALLOC_NO_ABORT)
#define POBJ_XADD_NO_FLUSH POBJ_FLAG_NO_FLUSH
#define POBJ_XADD_NO_SNAPSHOT POBJ_FLAG_NO_SNAPSHOT
#define POBJ_XADD_ASSUME_INITIALIZED POBJ_FLAG_ASSUME_INITIALIZED
#define POBJ_XADD_NO_ABORT POBJ_FLAG_TX_NO_ABORT
#define POBJ_XADD_VALID_FLAGS (POBJ_XADD_NO_FLUSH |\
POBJ_XADD_NO_SNAPSHOT |\
POBJ_XADD_ASSUME_INITIALIZED |\
POBJ_XADD_NO_ABORT)
#define POBJ_XLOCK_NO_ABORT POBJ_FLAG_TX_NO_ABORT
#define POBJ_XLOCK_VALID_FLAGS (POBJ_XLOCK_NO_ABORT)
#define POBJ_XFREE_NO_ABORT POBJ_FLAG_TX_NO_ABORT
#define POBJ_XFREE_VALID_FLAGS (POBJ_XFREE_NO_ABORT)
#define POBJ_XPUBLISH_NO_ABORT POBJ_FLAG_TX_NO_ABORT
#define POBJ_XPUBLISH_VALID_FLAGS (POBJ_XPUBLISH_NO_ABORT)
#define POBJ_XLOG_APPEND_BUFFER_NO_ABORT POBJ_FLAG_TX_NO_ABORT
#define POBJ_XLOG_APPEND_BUFFER_VALID_FLAGS (POBJ_XLOG_APPEND_BUFFER_NO_ABORT)
/*
* Starts a new transaction in the current thread.
* If called within an open transaction, starts a nested transaction.
*
* If successful, transaction stage changes to TX_STAGE_WORK and function
* returns zero. Otherwise, stage changes to TX_STAGE_ONABORT and an error
* number is returned.
*/
int pmemobj_tx_begin(PMEMobjpool *pop, jmp_buf env, ...);
/*
* Adds lock of given type to current transaction.
* 'Flags' is a bitmask of the following values:
* - POBJ_XLOCK_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*/
int pmemobj_tx_xlock(enum pobj_tx_param type, void *lockp, uint64_t flags);
/*
* Adds lock of given type to current transaction.
*/
int pmemobj_tx_lock(enum pobj_tx_param type, void *lockp);
/*
* Aborts current transaction
*
* Causes transition to TX_STAGE_ONABORT.
*
* This function must be called during TX_STAGE_WORK.
*/
void pmemobj_tx_abort(int errnum);
/*
* Commits current transaction
*
* This function must be called during TX_STAGE_WORK.
*/
void pmemobj_tx_commit(void);
/*
* Cleanups current transaction. Must always be called after pmemobj_tx_begin,
* even if starting the transaction failed.
*
* If called during TX_STAGE_NONE, has no effect.
*
* Always causes transition to TX_STAGE_NONE.
*
* If transaction was successful, returns 0. Otherwise returns error code set
* by pmemobj_tx_abort.
*
* This function must *not* be called during TX_STAGE_WORK.
*/
int pmemobj_tx_end(void);
/*
* Performs the actions associated with current stage of the transaction,
* and makes the transition to the next stage. Current stage must always
* be obtained by calling pmemobj_tx_stage.
*
* This function must be called in transaction.
*/
void pmemobj_tx_process(void);
/*
* Returns last transaction error code.
*/
int pmemobj_tx_errno(void);
/*
* Takes a "snapshot" of the memory block of given size and located at given
* offset 'off' in the object 'oid' and saves it in the undo log.
* The application is then free to directly modify the object in that memory
* range. In case of failure or abort, all the changes within this range will
* be rolled-back automatically.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_add_range(PMEMoid oid, uint64_t off, size_t size);
/*
* Takes a "snapshot" of the given memory region and saves it in the undo log.
* The application is then free to directly modify the object in that memory
* range. In case of failure or abort, all the changes within this range will
* be rolled-back automatically. The supplied block of memory has to be within
* the given pool.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_add_range_direct(const void *ptr, size_t size);
/*
* Behaves exactly the same as pmemobj_tx_add_range when 'flags' equals 0.
* 'Flags' is a bitmask of the following values:
* - POBJ_XADD_NO_FLUSH - skips flush on commit
* - POBJ_XADD_NO_SNAPSHOT - added range will not be snapshotted
* - POBJ_XADD_ASSUME_INITIALIZED - added range is assumed to be initialized
* - POBJ_XADD_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*/
int pmemobj_tx_xadd_range(PMEMoid oid, uint64_t off, size_t size,
uint64_t flags);
/*
* Behaves exactly the same as pmemobj_tx_add_range_direct when 'flags' equals
* 0. 'Flags' is a bitmask of the following values:
* - POBJ_XADD_NO_FLUSH - skips flush on commit
* - POBJ_XADD_NO_SNAPSHOT - added range will not be snapshotted
* - POBJ_XADD_ASSUME_INITIALIZED - added range is assumed to be initialized
* - POBJ_XADD_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*/
int pmemobj_tx_xadd_range_direct(const void *ptr, size_t size, uint64_t flags);
/*
* Transactionally allocates a new object.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_alloc(size_t size, uint64_t type_num);
/*
* Transactionally allocates a new object.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
* 'Flags' is a bitmask of the following values:
* - POBJ_XALLOC_ZERO - zero the allocated object
* - POBJ_XALLOC_NO_FLUSH - skip flush on commit
* - POBJ_XALLOC_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_xalloc(size_t size, uint64_t type_num, uint64_t flags);
/*
* Transactionally allocates new zeroed object.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_zalloc(size_t size, uint64_t type_num);
/*
* Transactionally resizes an existing object.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_realloc(PMEMoid oid, size_t size, uint64_t type_num);
/*
* Transactionally resizes an existing object, if extended new space is zeroed.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_zrealloc(PMEMoid oid, size_t size, uint64_t type_num);
/*
* Transactionally allocates a new object with duplicate of the string s.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_strdup(const char *s, uint64_t type_num);
/*
* Transactionally allocates a new object with duplicate of the string s.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
* 'Flags' is a bitmask of the following values:
* - POBJ_XALLOC_ZERO - zero the allocated object
* - POBJ_XALLOC_NO_FLUSH - skip flush on commit
* - POBJ_XALLOC_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_xstrdup(const char *s, uint64_t type_num, uint64_t flags);
/*
* Transactionally allocates a new object with duplicate of the wide character
* string s.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_wcsdup(const wchar_t *s, uint64_t type_num);
/*
* Transactionally allocates a new object with duplicate of the wide character
* string s.
*
* If successful, returns PMEMoid.
* Otherwise, stage changes to TX_STAGE_ONABORT and an OID_NULL is returned.
* 'Flags' is a bitmask of the following values:
* - POBJ_XALLOC_ZERO - zero the allocated object
* - POBJ_XALLOC_NO_FLUSH - skip flush on commit
* - POBJ_XALLOC_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*
* This function must be called during TX_STAGE_WORK.
*/
PMEMoid pmemobj_tx_xwcsdup(const wchar_t *s, uint64_t type_num, uint64_t flags);
/*
* Transactionally frees an existing object.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_free(PMEMoid oid);
/*
* Transactionally frees an existing object.
*
* If successful, returns zero.
* Otherwise, the stage changes to TX_STAGE_ONABORT and the error number is
* returned.
* 'Flags' is a bitmask of the following values:
* - POBJ_XFREE_NO_ABORT - if the function does not end successfully,
* do not abort the transaction and return the error number.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_xfree(PMEMoid oid, uint64_t flags);
/*
* Append user allocated buffer to the ulog.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_log_append_buffer(enum pobj_log_type type,
void *addr, size_t size);
/*
* Append user allocated buffer to the ulog.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
* 'Flags' is a bitmask of the following values:
* - POBJ_XLOG_APPEND_BUFFER_NO_ABORT - if the function does not end
* successfully, do not abort the transaction and return the error number.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_xlog_append_buffer(enum pobj_log_type type,
void *addr, size_t size, uint64_t flags);
/*
* Enables or disables automatic ulog allocations.
*
* If successful, returns zero.
* Otherwise, stage changes to TX_STAGE_ONABORT and an error number is returned.
*
* This function must be called during TX_STAGE_WORK.
*/
int pmemobj_tx_log_auto_alloc(enum pobj_log_type type, int on_off);
/*
* Calculates and returns size for user buffers for snapshots.
*/
size_t pmemobj_tx_log_snapshots_max_size(size_t *sizes, size_t nsizes);
/*
* Calculates and returns size for user buffers for intents.
*/
size_t pmemobj_tx_log_intents_max_size(size_t nintents);
/*
* Sets volatile pointer to the user data for the current transaction.
*/
void pmemobj_tx_set_user_data(void *data);
/*
* Gets volatile pointer to the user data associated with the current
* transaction.
*/
void *pmemobj_tx_get_user_data(void);
/*
* Sets the failure behavior of transactional functions.
*
* This function must be called during TX_STAGE_WORK.
*/
void pmemobj_tx_set_failure_behavior(enum pobj_tx_failure_behavior behavior);
/*
* Returns failure behavior for the current transaction.
*
* This function must be called during TX_STAGE_WORK.
*/
enum pobj_tx_failure_behavior pmemobj_tx_get_failure_behavior(void);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/tx_base.h */
| 14,087 | 30.237251 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/pool_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* libpmemobj/pool_base.h -- definitions of libpmemobj pool entry points
*/
#ifndef LIBPMEMOBJ_POOL_BASE_H
#define LIBPMEMOBJ_POOL_BASE_H 1
#include <stddef.h>
#include <sys/types.h>
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
//NEW
//#define _GNU_SOURCE
//#include <sys/types.h>
//#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
//int __real_open(const char *__path, int __oflag);
//int __wrap_open(const char *__path, int __oflag);
void* open_device(const char* pathname);
//END NEW
#define PMEMOBJ_MIN_POOL ((size_t)(1024 * 1024 * 256)) /* 8 MiB */
/*
* This limit is set arbitrary to incorporate a pool header and required
* alignment plus supply.
*/
#define PMEMOBJ_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */
/*
* Pool management.
*/
#ifdef _WIN32
#ifndef PMDK_UTF8_API
#define pmemobj_open pmemobj_openW
#define pmemobj_create pmemobj_createW
#define pmemobj_check pmemobj_checkW
#else
#define pmemobj_open pmemobj_openU
#define pmemobj_create pmemobj_createU
#define pmemobj_check pmemobj_checkU
#endif
#endif
#ifndef _WIN32
PMEMobjpool *pmemobj_open(const char *path, const char *layout);
#else
PMEMobjpool *pmemobj_openU(const char *path, const char *layout);
PMEMobjpool *pmemobj_openW(const wchar_t *path, const wchar_t *layout);
#endif
#ifndef _WIN32
PMEMobjpool *pmemobj_create(const char *path, const char *layout,
size_t poolsize, mode_t mode);
#else
PMEMobjpool *pmemobj_createU(const char *path, const char *layout,
size_t poolsize, mode_t mode);
PMEMobjpool *pmemobj_createW(const wchar_t *path, const wchar_t *layout,
size_t poolsize, mode_t mode);
#endif
#ifndef _WIN32
int pmemobj_check(const char *path, const char *layout);
#else
int pmemobj_checkU(const char *path, const char *layout);
int pmemobj_checkW(const wchar_t *path, const wchar_t *layout);
#endif
void pmemobj_close(PMEMobjpool *pop);
/*
* If called for the first time on a newly created pool, the root object
* of given size is allocated. Otherwise, it returns the existing root object.
* In such case, the size must be not less than the actual root object size
* stored in the pool. If it's larger, the root object is automatically
* resized.
*
* This function is thread-safe.
*/
PMEMoid pmemobj_root(PMEMobjpool *pop, size_t size);
/*
* Same as above, but calls the constructor function when the object is first
* created and on all subsequent reallocations.
*/
PMEMoid pmemobj_root_construct(PMEMobjpool *pop, size_t size,
pmemobj_constr constructor, void *arg);
/*
* Returns the size in bytes of the root object. Always equal to the requested
* size.
*/
size_t pmemobj_root_size(PMEMobjpool *pop);
/*
* Sets volatile pointer to the user data for specified pool.
*/
void pmemobj_set_user_data(PMEMobjpool *pop, void *data);
/*
* Gets volatile pointer to the user data associated with the specified pool.
*/
void *pmemobj_get_user_data(PMEMobjpool *pop);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/pool_base.h */
| 3,095 | 24.377049 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/action_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* libpmemobj/action_base.h -- definitions of libpmemobj action interface
*/
#ifndef LIBPMEMOBJ_ACTION_BASE_H
#define LIBPMEMOBJ_ACTION_BASE_H 1
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
enum pobj_action_type {
/* a heap action (e.g., alloc) */
POBJ_ACTION_TYPE_HEAP,
/* a single memory operation (e.g., value set) */
POBJ_ACTION_TYPE_MEM,
POBJ_MAX_ACTION_TYPE
};
struct pobj_action_heap {
/* offset to the element being freed/allocated */
uint64_t offset;
/* usable size of the element being allocated */
uint64_t usable_size;
};
struct pobj_action {
/*
* These fields are internal for the implementation and are not
* guaranteed to be stable across different versions of the API.
* Use with caution.
*
* This structure should NEVER be stored on persistent memory!
*/
enum pobj_action_type type;
uint32_t data[3];
union {
struct pobj_action_heap heap;
uint64_t data2[14];
};
};
#define POBJ_ACTION_XRESERVE_VALID_FLAGS\
(POBJ_XALLOC_CLASS_MASK |\
POBJ_XALLOC_ARENA_MASK |\
POBJ_XALLOC_ZERO)
PMEMoid pmemobj_reserve(PMEMobjpool *pop, struct pobj_action *act,
size_t size, uint64_t type_num);
PMEMoid pmemobj_xreserve(PMEMobjpool *pop, struct pobj_action *act,
size_t size, uint64_t type_num, uint64_t flags);
void pmemobj_set_value(PMEMobjpool *pop, struct pobj_action *act,
uint64_t *ptr, uint64_t value);
void pmemobj_defer_free(PMEMobjpool *pop, PMEMoid oid, struct pobj_action *act);
int pmemobj_publish(PMEMobjpool *pop, struct pobj_action *actv,
size_t actvcnt);
int pmemobj_tx_publish(struct pobj_action *actv, size_t actvcnt);
int pmemobj_tx_xpublish(struct pobj_action *actv, size_t actvcnt,
uint64_t flags);
void pmemobj_cancel(PMEMobjpool *pop, struct pobj_action *actv, size_t actvcnt);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/action_base.h */
| 1,935 | 24.813333 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/types.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* libpmemobj/types.h -- definitions of libpmemobj type-safe macros
*/
#ifndef LIBPMEMOBJ_TYPES_H
#define LIBPMEMOBJ_TYPES_H 1
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
#define TOID_NULL(t) ((TOID(t))OID_NULL)
#define PMEMOBJ_MAX_LAYOUT ((size_t)1024)
/*
* Type safety macros
*/
#if !(defined _MSC_VER || defined __clang__)
#define TOID_ASSIGN(o, value)(\
{\
(o).oid = value;\
(o); /* to avoid "error: statement with no effect" */\
})
#else /* _MSC_VER or __clang__ */
#define TOID_ASSIGN(o, value) ((o).oid = value, (o))
#endif
#if (defined _MSC_VER && _MSC_VER < 1912)
/*
* XXX - workaround for offsetof issue in VS 15.3,
* it has been fixed since Visual Studio 2017 Version 15.5
* (_MSC_VER == 1912)
*/
#ifdef PMEMOBJ_OFFSETOF_WA
#ifdef _CRT_USE_BUILTIN_OFFSETOF
#undef offsetof
#define offsetof(s, m) ((size_t)&reinterpret_cast < char const volatile& > \
((((s *)0)->m)))
#endif
#else
#ifdef _CRT_USE_BUILTIN_OFFSETOF
#error "Invalid definition of offsetof() macro - see: \
https://developercommunity.visualstudio.com/content/problem/96174/\
offsetof-macro-is-broken-for-nested-objects.html \
Please upgrade your VS, fix offsetof as described under the link or define \
PMEMOBJ_OFFSETOF_WA to enable workaround in libpmemobj.h"
#endif
#endif
#endif /* _MSC_VER */
#define TOID_EQUALS(lhs, rhs)\
((lhs).oid.off == (rhs).oid.off &&\
(lhs).oid.pool_uuid_lo == (rhs).oid.pool_uuid_lo)
/* type number of root object */
#define POBJ_ROOT_TYPE_NUM 0
#define _toid_struct
#define _toid_union
#define _toid_enum
#define _POBJ_LAYOUT_REF(name) (sizeof(_pobj_layout_##name##_ref))
/*
* Typed OID
*/
#define TOID(t)\
union _toid_##t##_toid
#ifdef __cplusplus
#define _TOID_CONSTR(t)\
_toid_##t##_toid()\
{ }\
_toid_##t##_toid(PMEMoid _oid) : oid(_oid)\
{ }
#else
#define _TOID_CONSTR(t)
#endif
/*
* Declaration of typed OID
*/
#define _TOID_DECLARE(t, i)\
typedef uint8_t _toid_##t##_toid_type_num[(i) + 1];\
TOID(t)\
{\
_TOID_CONSTR(t)\
PMEMoid oid;\
t *_type;\
_toid_##t##_toid_type_num *_type_num;\
}
/*
* Declaration of typed OID of an object
*/
#define TOID_DECLARE(t, i) _TOID_DECLARE(t, i)
/*
* Declaration of typed OID of a root object
*/
#define TOID_DECLARE_ROOT(t) _TOID_DECLARE(t, POBJ_ROOT_TYPE_NUM)
/*
* Type number of specified type
*/
#define TOID_TYPE_NUM(t) (sizeof(_toid_##t##_toid_type_num) - 1)
/*
* Type number of object read from typed OID
*/
#define TOID_TYPE_NUM_OF(o) (sizeof(*(o)._type_num) - 1)
/*
* NULL check
*/
#define TOID_IS_NULL(o) ((o).oid.off == 0)
/*
* Validates whether type number stored in typed OID is the same
* as type number stored in object's metadata
*/
#define TOID_VALID(o) (TOID_TYPE_NUM_OF(o) == pmemobj_type_num((o).oid))
/*
* Checks whether the object is of a given type
*/
#define OID_INSTANCEOF(o, t) (TOID_TYPE_NUM(t) == pmemobj_type_num(o))
/*
* Begin of layout declaration
*/
#define POBJ_LAYOUT_BEGIN(name)\
typedef uint8_t _pobj_layout_##name##_ref[__COUNTER__ + 1]
/*
* End of layout declaration
*/
#define POBJ_LAYOUT_END(name)\
typedef char _pobj_layout_##name##_cnt[__COUNTER__ + 1 -\
_POBJ_LAYOUT_REF(name)];
/*
* Number of types declared inside layout without the root object
*/
#define POBJ_LAYOUT_TYPES_NUM(name) (sizeof(_pobj_layout_##name##_cnt) - 1)
/*
* Declaration of typed OID inside layout declaration
*/
#define POBJ_LAYOUT_TOID(name, t)\
TOID_DECLARE(t, (__COUNTER__ + 1 - _POBJ_LAYOUT_REF(name)));
/*
* Declaration of typed OID of root inside layout declaration
*/
#define POBJ_LAYOUT_ROOT(name, t)\
TOID_DECLARE_ROOT(t);
/*
* Name of declared layout
*/
#define POBJ_LAYOUT_NAME(name) #name
#define TOID_TYPEOF(o) __typeof__(*(o)._type)
#define TOID_OFFSETOF(o, field) offsetof(TOID_TYPEOF(o), field)
/*
* XXX - DIRECT_RW and DIRECT_RO are not available when compiled using VC++
* as C code (/TC). Use /TP option.
*/
#ifndef _MSC_VER
#define DIRECT_RW(o) (\
{__typeof__(o) _o; _o._type = NULL; (void)_o;\
(__typeof__(*(o)._type) *)pmemobj_direct((o).oid); })
#define DIRECT_RO(o) ((const __typeof__(*(o)._type) *)pmemobj_direct((o).oid))
#elif defined(__cplusplus)
/*
* XXX - On Windows, these macros do not behave exactly the same as on Linux.
*/
#define DIRECT_RW(o) \
(reinterpret_cast < __typeof__((o)._type) > (pmemobj_direct((o).oid)))
#define DIRECT_RO(o) \
(reinterpret_cast < const __typeof__((o)._type) > \
(pmemobj_direct((o).oid)))
#endif /* (defined(_MSC_VER) || defined(__cplusplus)) */
#define D_RW DIRECT_RW
#define D_RO DIRECT_RO
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/types.h */
| 4,701 | 21.825243 | 78 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj/base.h -- definitions of base libpmemobj entry points
*/
#ifndef LIBPMEMOBJ_BASE_H
#define LIBPMEMOBJ_BASE_H 1
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <stddef.h>
#include <stdint.h>
#ifdef _WIN32
#include <pmemcompat.h>
#ifndef PMDK_UTF8_API
#define pmemobj_check_version pmemobj_check_versionW
#define pmemobj_errormsg pmemobj_errormsgW
#else
#define pmemobj_check_version pmemobj_check_versionU
#define pmemobj_errormsg pmemobj_errormsgU
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* opaque type internal to libpmemobj
*/
typedef struct pmemobjpool PMEMobjpool;
#define PMEMOBJ_MAX_ALLOC_SIZE ((size_t)0x3FFDFFFC0)
/*
* allocation functions flags
*/
#define POBJ_FLAG_ZERO (((uint64_t)1) << 0)
#define POBJ_FLAG_NO_FLUSH (((uint64_t)1) << 1)
#define POBJ_FLAG_NO_SNAPSHOT (((uint64_t)1) << 2)
#define POBJ_FLAG_ASSUME_INITIALIZED (((uint64_t)1) << 3)
#define POBJ_FLAG_TX_NO_ABORT (((uint64_t)1) << 4)
#define POBJ_CLASS_ID(id) (((uint64_t)(id)) << 48)
#define POBJ_ARENA_ID(id) (((uint64_t)(id)) << 32)
#define POBJ_XALLOC_CLASS_MASK ((((uint64_t)1 << 16) - 1) << 48)
#define POBJ_XALLOC_ARENA_MASK ((((uint64_t)1 << 16) - 1) << 32)
#define POBJ_XALLOC_ZERO POBJ_FLAG_ZERO
#define POBJ_XALLOC_NO_FLUSH POBJ_FLAG_NO_FLUSH
#define POBJ_XALLOC_NO_ABORT POBJ_FLAG_TX_NO_ABORT
/*
* pmemobj_mem* flags
*/
#define PMEMOBJ_F_MEM_NODRAIN (1U << 0)
#define PMEMOBJ_F_MEM_NONTEMPORAL (1U << 1)
#define PMEMOBJ_F_MEM_TEMPORAL (1U << 2)
#define PMEMOBJ_F_MEM_WC (1U << 3)
#define PMEMOBJ_F_MEM_WB (1U << 4)
#define PMEMOBJ_F_MEM_NOFLUSH (1U << 5)
/*
* pmemobj_mem*, pmemobj_xflush & pmemobj_xpersist flags
*/
#define PMEMOBJ_F_RELAXED (1U << 31)
/*
* Persistent memory object
*/
/*
* Object handle
*/
typedef struct pmemoid {
uint64_t pool_uuid_lo;
uint64_t off;
} PMEMoid;
static const PMEMoid OID_NULL = { 0, 0 };
#define OID_IS_NULL(o) ((o).off == 0)
#define OID_EQUALS(lhs, rhs)\
((lhs).off == (rhs).off &&\
(lhs).pool_uuid_lo == (rhs).pool_uuid_lo)
PMEMobjpool *pmemobj_pool_by_ptr(const void *addr);
PMEMobjpool *pmemobj_pool_by_oid(PMEMoid oid);
#ifndef _WIN32
extern int _pobj_cache_invalidate;
extern __thread struct _pobj_pcache {
PMEMobjpool *pop;
uint64_t uuid_lo;
int invalidate;
} _pobj_cached_pool;
/*
* Returns the direct pointer of an object.
*/
static inline void *
pmemobj_direct_inline(PMEMoid oid)
{
if (oid.off == 0 || oid.pool_uuid_lo == 0)
return NULL;
struct _pobj_pcache *cache = &_pobj_cached_pool;
if (_pobj_cache_invalidate != cache->invalidate ||
cache->uuid_lo != oid.pool_uuid_lo) {
cache->invalidate = _pobj_cache_invalidate;
if (!(cache->pop = pmemobj_pool_by_oid(oid))) {
cache->uuid_lo = 0;
return NULL;
}
cache->uuid_lo = oid.pool_uuid_lo;
}
return (void *)((uintptr_t)cache->pop + oid.off);
}
#endif /* _WIN32 */
/*
* Returns the direct pointer of an object.
*/
#if defined(_WIN32) || defined(_PMEMOBJ_INTRNL) ||\
defined(PMEMOBJ_DIRECT_NON_INLINE)
void *pmemobj_direct(PMEMoid oid);
#else
#define pmemobj_direct pmemobj_direct_inline
#endif
struct pmemvlt {
uint64_t runid;
};
#define PMEMvlt(T)\
struct {\
struct pmemvlt vlt;\
T value;\
}
/*
* Returns lazily initialized volatile variable. (EXPERIMENTAL)
*/
void *pmemobj_volatile(PMEMobjpool *pop, struct pmemvlt *vlt,
void *ptr, size_t size,
int (*constr)(void *ptr, void *arg), void *arg);
/*
* Returns the OID of the object pointed to by addr.
*/
PMEMoid pmemobj_oid(const void *addr);
/*
* Returns the number of usable bytes in the object. May be greater than
* the requested size of the object because of internal alignment.
*
* Can be used with objects allocated by any of the available methods.
*/
size_t pmemobj_alloc_usable_size(PMEMoid oid);
/*
* Returns the type number of the object.
*/
uint64_t pmemobj_type_num(PMEMoid oid);
/*
* Pmemobj specific low-level memory manipulation functions.
*
* These functions are meant to be used with pmemobj pools, because they provide
* additional functionality specific to this type of pool. These may include
* for example replication support. They also take advantage of the knowledge
* of the type of memory in the pool (pmem/non-pmem) to assure persistence.
*/
/*
* Pmemobj version of memcpy. Data copied is made persistent.
*/
void *pmemobj_memcpy_persist(PMEMobjpool *pop, void *dest, const void *src,
size_t len);
/*
* Pmemobj version of memset. Data range set is made persistent.
*/
void *pmemobj_memset_persist(PMEMobjpool *pop, void *dest, int c, size_t len);
/*
* Pmemobj version of memcpy. Data copied is made persistent (unless opted-out
* using flags).
*/
void *pmemobj_memcpy(PMEMobjpool *pop, void *dest, const void *src, size_t len,
unsigned flags);
/*
* Pmemobj version of memmove. Data copied is made persistent (unless opted-out
* using flags).
*/
void *pmemobj_memmove(PMEMobjpool *pop, void *dest, const void *src, size_t len,
unsigned flags);
/*
* Pmemobj version of memset. Data range set is made persistent (unless
* opted-out using flags).
*/
void *pmemobj_memset(PMEMobjpool *pop, void *dest, int c, size_t len,
unsigned flags);
/*
* Pmemobj version of pmem_persist.
*/
void pmemobj_persist(PMEMobjpool *pop, const void *addr, size_t len);
/*
* Pmemobj version of pmem_persist with additional flags argument.
*/
int pmemobj_xpersist(PMEMobjpool *pop, const void *addr, size_t len,
unsigned flags);
/*
* Pmemobj version of pmem_flush.
*/
void pmemobj_flush(PMEMobjpool *pop, const void *addr, size_t len);
/*
* Pmemobj version of pmem_flush with additional flags argument.
*/
int pmemobj_xflush(PMEMobjpool *pop, const void *addr, size_t len,
unsigned flags);
/*
* Pmemobj version of pmem_drain.
*/
void pmemobj_drain(PMEMobjpool *pop);
/*
* Version checking.
*/
/*
* PMEMOBJ_MAJOR_VERSION and PMEMOBJ_MINOR_VERSION provide the current version
* of the libpmemobj API as provided by this header file. Applications can
* verify that the version available at run-time is compatible with the version
* used at compile-time by passing these defines to pmemobj_check_version().
*/
#define PMEMOBJ_MAJOR_VERSION 2
#define PMEMOBJ_MINOR_VERSION 4
#ifndef _WIN32
const char *pmemobj_check_version(unsigned major_required,
unsigned minor_required);
#else
const char *pmemobj_check_versionU(unsigned major_required,
unsigned minor_required);
const wchar_t *pmemobj_check_versionW(unsigned major_required,
unsigned minor_required);
#endif
/*
* Passing NULL to pmemobj_set_funcs() tells libpmemobj to continue to use the
* default for that function. The replacement functions must not make calls
* back into libpmemobj.
*/
void pmemobj_set_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));
typedef int (*pmemobj_constr)(PMEMobjpool *pop, void *ptr, void *arg);
/*
* (debug helper function) logs notice message if used inside a transaction
*/
void _pobj_debug_notice(const char *func_name, const char *file, int line);
#ifndef _WIN32
const char *pmemobj_errormsg(void);
#else
const char *pmemobj_errormsgU(void);
const wchar_t *pmemobj_errormsgW(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/base.h */
| 7,415 | 23.72 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/tx.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj/tx.h -- definitions of libpmemobj transactional macros
*/
#ifndef LIBPMEMOBJ_TX_H
#define LIBPMEMOBJ_TX_H 1
#include <errno.h>
#include <string.h>
#include <libpmemobj/tx_base.h>
#include <libpmemobj/types.h>
extern uint64_t waitCycles;
extern uint64_t resetCycles;
#ifdef __cplusplus
extern "C" {
#endif
#ifdef POBJ_TX_CRASH_ON_NO_ONABORT
#define TX_ONABORT_CHECK do {\
if (_stage == TX_STAGE_ONABORT)\
abort();\
} while (0)
#else
#define TX_ONABORT_CHECK do {} while (0)
#endif
#define _POBJ_TX_BEGIN(pop, ...)\
{\
jmp_buf _tx_env;\
enum pobj_tx_stage _stage;\
int _pobj_errno;\
if (setjmp(_tx_env)) {\
errno = pmemobj_tx_errno();\
} else {\
_pobj_errno = pmemobj_tx_begin(pop, _tx_env, __VA_ARGS__,\
TX_PARAM_NONE);\
if (_pobj_errno)\
errno = _pobj_errno;\
}\
while ((_stage = pmemobj_tx_stage()) != TX_STAGE_NONE) {\
switch (_stage) {\
case TX_STAGE_WORK:
#define TX_BEGIN_PARAM(pop, ...)\
_POBJ_TX_BEGIN(pop, ##__VA_ARGS__)
#define TX_BEGIN_LOCK TX_BEGIN_PARAM
/* Just to let compiler warn when incompatible function pointer is used */
static inline pmemobj_tx_callback
_pobj_validate_cb_sig(pmemobj_tx_callback cb)
{
return cb;
}
#define TX_BEGIN_CB(pop, cb, arg, ...) _POBJ_TX_BEGIN(pop, TX_PARAM_CB,\
_pobj_validate_cb_sig(cb), arg, ##__VA_ARGS__)
#define TX_BEGIN(pop) _POBJ_TX_BEGIN(pop, TX_PARAM_NONE)
#define TX_ONABORT\
pmemobj_tx_process();\
break;\
case TX_STAGE_ONABORT:
#define TX_ONCOMMIT\
pmemobj_tx_process();\
break;\
case TX_STAGE_ONCOMMIT:
#define TX_FINALLY\
pmemobj_tx_process();\
break;\
case TX_STAGE_FINALLY:
#define TX_END\
pmemobj_tx_process();\
break;\
default:\
TX_ONABORT_CHECK;\
pmemobj_tx_process();\
break;\
}\
}\
_pobj_errno = pmemobj_tx_end();\
if (_pobj_errno)\
errno = _pobj_errno;\
}
#define TX_ADD(o)\
pmemobj_tx_add_range((o).oid, 0, sizeof(*(o)._type))
#define TX_ADD_FIELD(o, field)\
TX_ADD_DIRECT(&(D_RO(o)->field))
#define TX_ADD_DIRECT(p)\
pmemobj_tx_add_range_direct(p, sizeof(*(p)))
#define TX_ADD_FIELD_DIRECT(p, field)\
pmemobj_tx_add_range_direct(&(p)->field, sizeof((p)->field))
#define TX_XADD(o, flags)\
pmemobj_tx_xadd_range((o).oid, 0, sizeof(*(o)._type), flags)
#define TX_XADD_FIELD(o, field, flags)\
TX_XADD_DIRECT(&(D_RO(o)->field), flags)
#define TX_XADD_DIRECT(p, flags)\
pmemobj_tx_xadd_range_direct(p, sizeof(*(p)), flags)
#define TX_XADD_FIELD_DIRECT(p, field, flags)\
pmemobj_tx_xadd_range_direct(&(p)->field, sizeof((p)->field), flags)
#define TX_NEW(t)\
((TOID(t))pmemobj_tx_alloc(sizeof(t), TOID_TYPE_NUM(t)))
#define TX_ALLOC(t, size)\
((TOID(t))pmemobj_tx_alloc(size, TOID_TYPE_NUM(t)))
#define TX_ZNEW(t)\
((TOID(t))pmemobj_tx_zalloc(sizeof(t), TOID_TYPE_NUM(t)))
#define TX_ZALLOC(t, size)\
((TOID(t))pmemobj_tx_zalloc(size, TOID_TYPE_NUM(t)))
#define TX_XALLOC(t, size, flags)\
((TOID(t))pmemobj_tx_xalloc(size, TOID_TYPE_NUM(t), flags))
/* XXX - not available when compiled with VC++ as C code (/TC) */
#if !defined(_MSC_VER) || defined(__cplusplus)
#define TX_REALLOC(o, size)\
((__typeof__(o))pmemobj_tx_realloc((o).oid, size, TOID_TYPE_NUM_OF(o)))
#define TX_ZREALLOC(o, size)\
((__typeof__(o))pmemobj_tx_zrealloc((o).oid, size, TOID_TYPE_NUM_OF(o)))
#endif /* !defined(_MSC_VER) || defined(__cplusplus) */
#define TX_STRDUP(s, type_num)\
pmemobj_tx_strdup(s, type_num)
#define TX_XSTRDUP(s, type_num, flags)\
pmemobj_tx_xstrdup(s, type_num, flags)
#define TX_WCSDUP(s, type_num)\
pmemobj_tx_wcsdup(s, type_num)
#define TX_XWCSDUP(s, type_num, flags)\
pmemobj_tx_xwcsdup(s, type_num, flags)
#define TX_FREE(o)\
pmemobj_tx_free((o).oid)
#define TX_XFREE(o, flags)\
pmemobj_tx_xfree((o).oid, flags)
#define TX_SET(o, field, value) (\
TX_ADD_FIELD(o, field),\
D_RW(o)->field = (value))
#define TX_SET_DIRECT(p, field, value) (\
TX_ADD_FIELD_DIRECT(p, field),\
(p)->field = (value))
static inline void *
TX_MEMCPY(void *dest, const void *src, size_t num)
{
pmemobj_tx_add_range_direct(dest, num);
return memcpy(dest, src, num);
}
static inline void *
TX_MEMSET(void *dest, int c, size_t num)
{
pmemobj_tx_add_range_direct(dest, num);
return memset(dest, c, num);
}
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/tx.h */
| 4,353 | 22.037037 | 74 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/atomic_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj/atomic_base.h -- definitions of libpmemobj atomic entry points
*/
#ifndef LIBPMEMOBJ_ATOMIC_BASE_H
#define LIBPMEMOBJ_ATOMIC_BASE_H 1
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Non-transactional atomic allocations
*
* Those functions can be used outside transactions. The allocations are always
* aligned to the cache-line boundary.
*/
#define POBJ_XALLOC_VALID_FLAGS (POBJ_XALLOC_ZERO |\
POBJ_XALLOC_CLASS_MASK)
/*
* Allocates a new object from the pool and calls a constructor function before
* returning. It is guaranteed that allocated object is either properly
* initialized, or if it's interrupted before the constructor completes, the
* memory reserved for the object is automatically reclaimed.
*/
int pmemobj_alloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size,
uint64_t type_num, pmemobj_constr constructor, void *arg);
/*
* Allocates with flags a new object from the pool.
*/
int pmemobj_xalloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size,
uint64_t type_num, uint64_t flags,
pmemobj_constr constructor, void *arg);
/*
* Allocates a new zeroed object from the pool.
*/
int pmemobj_zalloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size,
uint64_t type_num);
/*
* Resizes an existing object.
*/
int pmemobj_realloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size,
uint64_t type_num);
/*
* Resizes an existing object, if extended new space is zeroed.
*/
int pmemobj_zrealloc(PMEMobjpool *pop, PMEMoid *oidp, size_t size,
uint64_t type_num);
/*
* Allocates a new object with duplicate of the string s.
*/
int pmemobj_strdup(PMEMobjpool *pop, PMEMoid *oidp, const char *s,
uint64_t type_num);
/*
* Allocates a new object with duplicate of the wide character string s.
*/
int pmemobj_wcsdup(PMEMobjpool *pop, PMEMoid *oidp, const wchar_t *s,
uint64_t type_num);
/*
* Frees an existing object.
*/
void pmemobj_free(PMEMoid *oidp);
struct pobj_defrag_result {
size_t total; /* number of processed objects */
size_t relocated; /* number of relocated objects */
};
/*
* Performs defragmentation on the provided array of objects.
*/
int pmemobj_defrag(PMEMobjpool *pop, PMEMoid **oidv, size_t oidcnt,
struct pobj_defrag_result *result);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/atomic_base.h */
| 2,386 | 24.393617 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/thread.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* libpmemobj/thread.h -- definitions of libpmemobj thread/locking entry points
*/
#ifndef LIBPMEMOBJ_THREAD_H
#define LIBPMEMOBJ_THREAD_H 1
#include <time.h>
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Locking.
*/
#define _POBJ_CL_SIZE 64 /* cache line size */
typedef union {
long long align;
char padding[_POBJ_CL_SIZE];
} PMEMmutex;
typedef union {
long long align;
char padding[_POBJ_CL_SIZE];
} PMEMrwlock;
typedef union {
long long align;
char padding[_POBJ_CL_SIZE];
} PMEMcond;
void pmemobj_mutex_zero(PMEMobjpool *pop, PMEMmutex *mutexp);
int pmemobj_mutex_lock(PMEMobjpool *pop, PMEMmutex *mutexp);
int pmemobj_mutex_timedlock(PMEMobjpool *pop, PMEMmutex *__restrict mutexp,
const struct timespec *__restrict abs_timeout);
int pmemobj_mutex_trylock(PMEMobjpool *pop, PMEMmutex *mutexp);
int pmemobj_mutex_unlock(PMEMobjpool *pop, PMEMmutex *mutexp);
void pmemobj_rwlock_zero(PMEMobjpool *pop, PMEMrwlock *rwlockp);
int pmemobj_rwlock_rdlock(PMEMobjpool *pop, PMEMrwlock *rwlockp);
int pmemobj_rwlock_wrlock(PMEMobjpool *pop, PMEMrwlock *rwlockp);
int pmemobj_rwlock_timedrdlock(PMEMobjpool *pop,
PMEMrwlock *__restrict rwlockp,
const struct timespec *__restrict abs_timeout);
int pmemobj_rwlock_timedwrlock(PMEMobjpool *pop,
PMEMrwlock *__restrict rwlockp,
const struct timespec *__restrict abs_timeout);
int pmemobj_rwlock_tryrdlock(PMEMobjpool *pop, PMEMrwlock *rwlockp);
int pmemobj_rwlock_trywrlock(PMEMobjpool *pop, PMEMrwlock *rwlockp);
int pmemobj_rwlock_unlock(PMEMobjpool *pop, PMEMrwlock *rwlockp);
void pmemobj_cond_zero(PMEMobjpool *pop, PMEMcond *condp);
int pmemobj_cond_broadcast(PMEMobjpool *pop, PMEMcond *condp);
int pmemobj_cond_signal(PMEMobjpool *pop, PMEMcond *condp);
int pmemobj_cond_timedwait(PMEMobjpool *pop, PMEMcond *__restrict condp,
PMEMmutex *__restrict mutexp,
const struct timespec *__restrict abs_timeout);
int pmemobj_cond_wait(PMEMobjpool *pop, PMEMcond *condp,
PMEMmutex *__restrict mutexp);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/thread.h */
| 2,150 | 28.875 | 79 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/action.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2018, Intel Corporation */
/*
* libpmemobj/action.h -- definitions of libpmemobj action interface
*/
#ifndef LIBPMEMOBJ_ACTION_H
#define LIBPMEMOBJ_ACTION_H 1
#include <libpmemobj/action_base.h>
#ifdef __cplusplus
extern "C" {
#endif
#define POBJ_RESERVE_NEW(pop, t, act)\
((TOID(t))pmemobj_reserve(pop, act, sizeof(t), TOID_TYPE_NUM(t)))
#define POBJ_RESERVE_ALLOC(pop, t, size, act)\
((TOID(t))pmemobj_reserve(pop, act, size, TOID_TYPE_NUM(t)))
#define POBJ_XRESERVE_NEW(pop, t, act, flags)\
((TOID(t))pmemobj_xreserve(pop, act, sizeof(t), TOID_TYPE_NUM(t), flags))
#define POBJ_XRESERVE_ALLOC(pop, t, size, act, flags)\
((TOID(t))pmemobj_xreserve(pop, act, size, TOID_TYPE_NUM(t), flags))
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/action_base.h */
| 829 | 23.411765 | 73 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/atomic.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2017, Intel Corporation */
/*
* libpmemobj/atomic.h -- definitions of libpmemobj atomic macros
*/
#ifndef LIBPMEMOBJ_ATOMIC_H
#define LIBPMEMOBJ_ATOMIC_H 1
#include <libpmemobj/atomic_base.h>
#include <libpmemobj/types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define POBJ_NEW(pop, o, t, constr, arg)\
pmemobj_alloc((pop), (PMEMoid *)(o), sizeof(t), TOID_TYPE_NUM(t),\
(constr), (arg))
#define POBJ_ALLOC(pop, o, t, size, constr, arg)\
pmemobj_alloc((pop), (PMEMoid *)(o), (size), TOID_TYPE_NUM(t),\
(constr), (arg))
#define POBJ_ZNEW(pop, o, t)\
pmemobj_zalloc((pop), (PMEMoid *)(o), sizeof(t), TOID_TYPE_NUM(t))
#define POBJ_ZALLOC(pop, o, t, size)\
pmemobj_zalloc((pop), (PMEMoid *)(o), (size), TOID_TYPE_NUM(t))
#define POBJ_REALLOC(pop, o, t, size)\
pmemobj_realloc((pop), (PMEMoid *)(o), (size), TOID_TYPE_NUM(t))
#define POBJ_ZREALLOC(pop, o, t, size)\
pmemobj_zrealloc((pop), (PMEMoid *)(o), (size), TOID_TYPE_NUM(t))
#define POBJ_FREE(o)\
pmemobj_free((PMEMoid *)(o))
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/atomic.h */
| 1,115 | 23.26087 | 66 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdkArrSwapNDP/src/include/libpmemobj/iterator_base.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* libpmemobj/iterator_base.h -- definitions of libpmemobj iterator entry points
*/
#ifndef LIBPMEMOBJ_ITERATOR_BASE_H
#define LIBPMEMOBJ_ITERATOR_BASE_H 1
#include <libpmemobj/base.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* The following functions allow access to the entire collection of objects.
*
* Use with conjunction with non-transactional allocations. Pmemobj pool acts
* as a generic container (list) of objects that are not assigned to any
* user-defined data structures.
*/
/*
* Returns the first object of the specified type number.
*/
PMEMoid pmemobj_first(PMEMobjpool *pop);
/*
* Returns the next object of the same type.
*/
PMEMoid pmemobj_next(PMEMoid oid);
#ifdef __cplusplus
}
#endif
#endif /* libpmemobj/iterator_base.h */
| 855 | 20.4 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/src/tools/rpmemd/rpmemd.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd.c -- rpmemd main source file
*/
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "librpmem.h"
#include "rpmemd.h"
#include "rpmemd_log.h"
#include "rpmemd_config.h"
#include "rpmem_common.h"
#include "rpmemd_fip.h"
#include "rpmemd_obc.h"
#include "rpmemd_db.h"
#include "rpmemd_util.h"
#include "pool_hdr.h"
#include "os.h"
#include "os_thread.h"
#include "util.h"
#include "uuid.h"
#include "set.h"
/*
* rpmemd -- rpmem handle
*/
struct rpmemd {
struct rpmemd_obc *obc; /* out-of-band connection handle */
struct rpmemd_db *db; /* pool set database handle */
struct rpmemd_db_pool *pool; /* pool handle */
char *pool_desc; /* pool descriptor */
struct rpmemd_fip *fip; /* fabric provider handle */
struct rpmemd_config config; /* configuration */
enum rpmem_persist_method persist_method;
int closing; /* set when closing connection */
int created; /* pool created */
os_thread_t fip_thread;
int fip_running;
};
#ifdef DEBUG
/*
* bool2str -- convert bool to yes/no string
*/
static inline const char *
bool2str(int v)
{
return v ? "yes" : "no";
}
#endif
/*
* str_or_null -- return null string instead of NULL pointer
*/
static inline const char *
_str(const char *str)
{
if (!str)
return "(null)";
return str;
}
/*
* uuid2str -- convert uuid to string
*/
static const char *
uuid2str(const uuid_t uuid)
{
static char uuid_str[64] = {0, };
int ret = util_uuid_to_string(uuid, uuid_str);
if (ret != 0) {
return "(error)";
}
return uuid_str;
}
/*
* rpmemd_get_pm -- returns persist method based on configuration
*/
static enum rpmem_persist_method
rpmemd_get_pm(struct rpmemd_config *config)
{
enum rpmem_persist_method ret = RPMEM_PM_GPSPM;
if (config->persist_apm)
ret = RPMEM_PM_APM;
return ret;
}
/*
* rpmemd_db_get_status -- convert error number to status for db operation
*/
static int
rpmemd_db_get_status(int err)
{
switch (err) {
case EEXIST:
return RPMEM_ERR_EXISTS;
case EACCES:
return RPMEM_ERR_NOACCESS;
case ENOENT:
return RPMEM_ERR_NOEXIST;
case EWOULDBLOCK:
return RPMEM_ERR_BUSY;
case EBADF:
return RPMEM_ERR_BADNAME;
case EINVAL:
return RPMEM_ERR_POOL_CFG;
default:
return RPMEM_ERR_FATAL;
}
}
/*
* rpmemd_check_pool -- verify pool parameters
*/
static int
rpmemd_check_pool(struct rpmemd *rpmemd, const struct rpmem_req_attr *req,
int *status)
{
if (rpmemd->pool->pool_size < RPMEM_MIN_POOL) {
RPMEMD_LOG(ERR, "invalid pool size -- must be >= %zu",
RPMEM_MIN_POOL);
*status = RPMEM_ERR_POOL_CFG;
return -1;
}
if (rpmemd->pool->pool_size < req->pool_size) {
RPMEMD_LOG(ERR, "requested size is too big");
*status = RPMEM_ERR_BADSIZE;
return -1;
}
return 0;
}
/*
* rpmemd_deep_persist -- perform deep persist operation
*/
static int
rpmemd_deep_persist(const void *addr, size_t size, void *ctx)
{
struct rpmemd *rpmemd = (struct rpmemd *)ctx;
return util_replica_deep_persist(addr, size, rpmemd->pool->set, 0);
}
/*
* rpmemd_common_fip_init -- initialize fabric provider
*/
static int
rpmemd_common_fip_init(struct rpmemd *rpmemd, const struct rpmem_req_attr *req,
struct rpmem_resp_attr *resp, int *status)
{
/* register the whole pool with header in RDMA */
void *addr = (void *)((uintptr_t)rpmemd->pool->pool_addr);
struct rpmemd_fip_attr fip_attr = {
.addr = addr,
.size = req->pool_size,
.nlanes = req->nlanes,
.nthreads = rpmemd->config.nthreads,
.provider = req->provider,
.persist_method = rpmemd->persist_method,
.deep_persist = rpmemd_deep_persist,
.ctx = rpmemd,
.buff_size = req->buff_size,
};
const int is_pmem = rpmemd_db_pool_is_pmem(rpmemd->pool);
if (rpmemd_apply_pm_policy(&fip_attr.persist_method,
&fip_attr.persist,
&fip_attr.memcpy_persist,
is_pmem)) {
*status = RPMEM_ERR_FATAL;
goto err_fip_init;
}
const char *node = rpmem_get_ssh_conn_addr();
enum rpmem_err err;
rpmemd->fip = rpmemd_fip_init(node, NULL, &fip_attr, resp, &err);
if (!rpmemd->fip) {
*status = (int)err;
goto err_fip_init;
}
return 0;
err_fip_init:
return -1;
}
/*
* rpmemd_print_req_attr -- print request attributes
*/
static void
rpmemd_print_req_attr(const struct rpmem_req_attr *req)
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool descriptor: '%s'",
_str(req->pool_desc));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool size: %lu", req->pool_size);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "nlanes: %u", req->nlanes);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "provider: %s",
rpmem_provider_to_str(req->provider));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "buff_size: %lu", req->buff_size);
}
/*
* rpmemd_print_pool_attr -- print pool attributes
*/
static void
rpmemd_print_pool_attr(const struct rpmem_pool_attr *attr)
{
if (attr == NULL) {
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "NULL");
} else {
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "signature: '%s'",
_str(attr->signature));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "major: %u", attr->major);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "compat_features: 0x%x",
attr->compat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "incompat_features: 0x%x",
attr->incompat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "ro_compat_features: 0x%x",
attr->ro_compat_features);
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "poolset_uuid: %s",
uuid2str(attr->poolset_uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "uuid: %s",
uuid2str(attr->uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "next_uuid: %s",
uuid2str(attr->next_uuid));
RPMEMD_LOG(INFO, RPMEMD_LOG_INDENT "prev_uuid: %s",
uuid2str(attr->prev_uuid));
}
}
/*
* rpmemd_print_resp_attr -- print response attributes
*/
static void
rpmemd_print_resp_attr(const struct rpmem_resp_attr *attr)
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "port: %u", attr->port);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "rkey: 0x%lx", attr->rkey);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "raddr: 0x%lx", attr->raddr);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "nlanes: %u", attr->nlanes);
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(attr->persist_method));
}
/*
* rpmemd_fip_thread -- background thread for establishing in-band connection
*/
static void *
rpmemd_fip_thread(void *arg)
{
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
RPMEMD_LOG(INFO, "waiting for in-band connection");
ret = rpmemd_fip_accept(rpmemd->fip, RPMEM_ACCEPT_TIMEOUT);
if (ret)
goto err_accept;
RPMEMD_LOG(NOTICE, "in-band connection established");
ret = rpmemd_fip_process_start(rpmemd->fip);
if (ret)
goto err_process_start;
return NULL;
err_process_start:
rpmemd_fip_close(rpmemd->fip);
err_accept:
return (void *)(uintptr_t)ret;
}
/*
* rpmemd_fip_start_thread -- start background thread for establishing
* in-band connection
*/
static int
rpmemd_fip_start_thread(struct rpmemd *rpmemd)
{
errno = os_thread_create(&rpmemd->fip_thread, NULL,
rpmemd_fip_thread, rpmemd);
if (errno) {
RPMEMD_LOG(ERR, "!creating in-band thread");
goto err_os_thread_create;
}
rpmemd->fip_running = 1;
return 0;
err_os_thread_create:
return -1;
}
/*
* rpmemd_fip_stop_thread -- stop background thread for in-band connection
*/
static int
rpmemd_fip_stop_thread(struct rpmemd *rpmemd)
{
RPMEMD_ASSERT(rpmemd->fip_running);
void *tret;
errno = os_thread_join(&rpmemd->fip_thread, &tret);
if (errno)
RPMEMD_LOG(ERR, "!waiting for in-band thread");
int ret = (int)(uintptr_t)tret;
if (ret)
RPMEMD_LOG(ERR, "in-band thread failed -- '%d'", ret);
return ret;
}
/*
* rpmemd_fip-stop -- stop in-band thread and stop processing thread
*/
static int
rpmemd_fip_stop(struct rpmemd *rpmemd)
{
int ret;
int fip_ret = rpmemd_fip_stop_thread(rpmemd);
if (fip_ret) {
RPMEMD_LOG(ERR, "!in-band thread failed");
}
if (!fip_ret) {
ret = rpmemd_fip_process_stop(rpmemd->fip);
if (ret) {
RPMEMD_LOG(ERR, "!stopping fip process failed");
}
}
rpmemd->fip_running = 0;
return fip_ret;
}
/*
* rpmemd_close_pool -- close pool and remove it if required
*/
static int
rpmemd_close_pool(struct rpmemd *rpmemd, int remove)
{
int ret = 0;
RPMEMD_LOG(NOTICE, "closing pool");
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
RPMEMD_LOG(INFO, "pool closed");
if (remove) {
RPMEMD_LOG(NOTICE, "removing '%s'", rpmemd->pool_desc);
ret = rpmemd_db_pool_remove(rpmemd->db,
rpmemd->pool_desc, 0, 0);
if (ret) {
RPMEMD_LOG(ERR, "!removing pool '%s' failed",
rpmemd->pool_desc);
} else {
RPMEMD_LOG(INFO, "removed '%s'", rpmemd->pool_desc);
}
}
free(rpmemd->pool_desc);
return ret;
}
/*
* rpmemd_req_cleanup -- cleanup in-band connection and all resources allocated
* during open/create requests
*/
static void
rpmemd_req_cleanup(struct rpmemd *rpmemd)
{
if (!rpmemd->fip_running)
return;
int ret;
ret = rpmemd_fip_stop(rpmemd);
if (!ret) {
rpmemd_fip_close(rpmemd->fip);
rpmemd_fip_fini(rpmemd->fip);
}
int remove = rpmemd->created && ret;
rpmemd_close_pool(rpmemd, remove);
}
/*
* rpmemd_req_create -- handle create request
*/
static int
rpmemd_req_create(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req,
const struct rpmem_pool_attr *pool_attr)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "create request:");
rpmemd_print_req_attr(req);
RPMEMD_LOG(NOTICE, "pool attributes:");
rpmemd_print_pool_attr(pool_attr);
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
int status = 0;
int err_send = 1;
struct rpmem_resp_attr resp;
memset(&resp, 0, sizeof(resp));
if (rpmemd->pool) {
RPMEMD_LOG(ERR, "pool already opened");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_pool_opened;
}
rpmemd->pool_desc = strdup(req->pool_desc);
if (!rpmemd->pool_desc) {
RPMEMD_LOG(ERR, "!allocating pool descriptor");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_strdup;
}
rpmemd->pool = rpmemd_db_pool_create(rpmemd->db,
req->pool_desc, 0, pool_attr);
if (!rpmemd->pool) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_pool_create;
}
rpmemd->created = 1;
ret = rpmemd_check_pool(rpmemd, req, &status);
if (ret)
goto err_pool_check;
ret = rpmemd_common_fip_init(rpmemd, req, &resp, &status);
if (ret)
goto err_fip_init;
RPMEMD_LOG(NOTICE, "create request response: (status = %u)", status);
if (!status)
rpmemd_print_resp_attr(&resp);
ret = rpmemd_obc_create_resp(obc, status, &resp);
if (ret)
goto err_create_resp;
ret = rpmemd_fip_start_thread(rpmemd);
if (ret)
goto err_fip_start;
return 0;
err_fip_start:
err_create_resp:
err_send = 0;
rpmemd_fip_fini(rpmemd->fip);
err_fip_init:
err_pool_check:
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
rpmemd_db_pool_remove(rpmemd->db, req->pool_desc, 0, 0);
err_pool_create:
free(rpmemd->pool_desc);
err_strdup:
err_pool_opened:
if (err_send)
ret = rpmemd_obc_create_resp(obc, status, &resp);
rpmemd->closing = 1;
return ret;
}
/*
* rpmemd_req_open -- handle open request
*/
static int
rpmemd_req_open(struct rpmemd_obc *obc, void *arg,
const struct rpmem_req_attr *req)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "open request:");
rpmemd_print_req_attr(req);
struct rpmemd *rpmemd = (struct rpmemd *)arg;
int ret;
int status = 0;
int err_send = 1;
struct rpmem_resp_attr resp;
memset(&resp, 0, sizeof(resp));
struct rpmem_pool_attr pool_attr;
memset(&pool_attr, 0, sizeof(pool_attr));
if (rpmemd->pool) {
RPMEMD_LOG(ERR, "pool already opened");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_pool_opened;
}
rpmemd->pool_desc = strdup(req->pool_desc);
if (!rpmemd->pool_desc) {
RPMEMD_LOG(ERR, "!allocating pool descriptor");
ret = -1;
status = RPMEM_ERR_FATAL;
goto err_strdup;
}
rpmemd->pool = rpmemd_db_pool_open(rpmemd->db,
req->pool_desc, 0, &pool_attr);
if (!rpmemd->pool) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_pool_open;
}
RPMEMD_LOG(NOTICE, "pool attributes:");
rpmemd_print_pool_attr(&pool_attr);
ret = rpmemd_check_pool(rpmemd, req, &status);
if (ret)
goto err_pool_check;
ret = rpmemd_common_fip_init(rpmemd, req, &resp, &status);
if (ret)
goto err_fip_init;
RPMEMD_LOG(NOTICE, "open request response: (status = %u)", status);
if (!status)
rpmemd_print_resp_attr(&resp);
ret = rpmemd_obc_open_resp(obc, status, &resp, &pool_attr);
if (ret)
goto err_open_resp;
ret = rpmemd_fip_start_thread(rpmemd);
if (ret)
goto err_fip_start;
return 0;
err_fip_start:
err_open_resp:
err_send = 0;
rpmemd_fip_fini(rpmemd->fip);
err_fip_init:
err_pool_check:
rpmemd_db_pool_close(rpmemd->db, rpmemd->pool);
err_pool_open:
free(rpmemd->pool_desc);
err_strdup:
err_pool_opened:
if (err_send)
ret = rpmemd_obc_open_resp(obc, status, &resp, &pool_attr);
rpmemd->closing = 1;
return ret;
}
/*
* rpmemd_req_close -- handle close request
*/
static int
rpmemd_req_close(struct rpmemd_obc *obc, void *arg, int flags)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "close request");
struct rpmemd *rpmemd = (struct rpmemd *)arg;
rpmemd->closing = 1;
int ret;
int status = 0;
if (!rpmemd->pool) {
RPMEMD_LOG(ERR, "pool not opened");
status = RPMEM_ERR_FATAL;
return rpmemd_obc_close_resp(obc, status);
}
ret = rpmemd_fip_stop(rpmemd);
if (ret) {
status = RPMEM_ERR_FATAL;
} else {
rpmemd_fip_close(rpmemd->fip);
rpmemd_fip_fini(rpmemd->fip);
}
int remove = rpmemd->created &&
(status || (flags & RPMEM_CLOSE_FLAGS_REMOVE));
if (rpmemd_close_pool(rpmemd, remove))
RPMEMD_LOG(ERR, "closing pool failed");
RPMEMD_LOG(NOTICE, "close request response (status = %u)", status);
ret = rpmemd_obc_close_resp(obc, status);
return ret;
}
/*
* rpmemd_req_set_attr -- handle set attributes request
*/
static int
rpmemd_req_set_attr(struct rpmemd_obc *obc, void *arg,
const struct rpmem_pool_attr *pool_attr)
{
RPMEMD_ASSERT(arg != NULL);
RPMEMD_LOG(NOTICE, "set attributes request");
struct rpmemd *rpmemd = (struct rpmemd *)arg;
RPMEMD_ASSERT(rpmemd->pool != NULL);
int ret;
int status = 0;
int err_send = 1;
ret = rpmemd_db_pool_set_attr(rpmemd->pool, pool_attr);
if (ret) {
ret = -1;
status = rpmemd_db_get_status(errno);
goto err_set_attr;
}
RPMEMD_LOG(NOTICE, "new pool attributes:");
rpmemd_print_pool_attr(pool_attr);
ret = rpmemd_obc_set_attr_resp(obc, status);
if (ret)
goto err_set_attr_resp;
return ret;
err_set_attr_resp:
err_send = 0;
err_set_attr:
if (err_send)
ret = rpmemd_obc_set_attr_resp(obc, status);
return ret;
}
static struct rpmemd_obc_requests rpmemd_req = {
.create = rpmemd_req_create,
.open = rpmemd_req_open,
.close = rpmemd_req_close,
.set_attr = rpmemd_req_set_attr,
};
/*
* rpmemd_print_info -- print basic info and configuration
*/
static void
rpmemd_print_info(struct rpmemd *rpmemd)
{
RPMEMD_LOG(NOTICE, "ssh connection: %s",
_str(os_getenv("SSH_CONNECTION")));
RPMEMD_LOG(NOTICE, "user: %s", _str(os_getenv("USER")));
RPMEMD_LOG(NOTICE, "configuration");
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "pool set directory: '%s'",
_str(rpmemd->config.poolset_dir));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(rpmemd->persist_method));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "number of threads: %lu",
rpmemd->config.nthreads);
RPMEMD_DBG(RPMEMD_LOG_INDENT "persist APM: %s",
bool2str(rpmemd->config.persist_apm));
RPMEMD_DBG(RPMEMD_LOG_INDENT "persist GPSPM: %s",
bool2str(rpmemd->config.persist_general));
RPMEMD_DBG(RPMEMD_LOG_INDENT "use syslog: %s",
bool2str(rpmemd->config.use_syslog));
RPMEMD_DBG(RPMEMD_LOG_INDENT "log file: %s",
_str(rpmemd->config.log_file));
RPMEMD_DBG(RPMEMD_LOG_INDENT "log level: %s",
rpmemd_log_level_to_str(rpmemd->config.log_level));
}
int
main(int argc, char *argv[])
{
util_init();
int send_status = 1;
int ret = 1;
struct rpmemd *rpmemd = calloc(1, sizeof(*rpmemd));
if (!rpmemd) {
RPMEMD_LOG(ERR, "!calloc");
goto err_rpmemd;
}
rpmemd->obc = rpmemd_obc_init(STDIN_FILENO, STDOUT_FILENO);
if (!rpmemd->obc) {
RPMEMD_LOG(ERR, "out-of-band connection initialization");
goto err_obc;
}
if (rpmemd_log_init(DAEMON_NAME, NULL, 0)) {
RPMEMD_LOG(ERR, "logging subsystem initialization failed");
goto err_log_init;
}
if (rpmemd_config_read(&rpmemd->config, argc, argv) != 0) {
RPMEMD_LOG(ERR, "reading configuration failed");
goto err_config;
}
rpmemd_log_close();
rpmemd_log_level = rpmemd->config.log_level;
if (rpmemd_log_init(DAEMON_NAME, rpmemd->config.log_file,
rpmemd->config.use_syslog)) {
RPMEMD_LOG(ERR, "logging subsystem initialization"
" failed (%s, %d)", rpmemd->config.log_file,
rpmemd->config.use_syslog);
goto err_log_init_config;
}
RPMEMD_LOG(INFO, "%s version %s", DAEMON_NAME, SRCVERSION);
rpmemd->persist_method = rpmemd_get_pm(&rpmemd->config);
rpmemd->db = rpmemd_db_init(rpmemd->config.poolset_dir, 0666);
if (!rpmemd->db) {
RPMEMD_LOG(ERR, "!pool set db initialization");
goto err_db_init;
}
if (rpmemd->config.rm_poolset) {
RPMEMD_LOG(INFO, "removing '%s'",
rpmemd->config.rm_poolset);
if (rpmemd_db_pool_remove(rpmemd->db,
rpmemd->config.rm_poolset,
rpmemd->config.force,
rpmemd->config.pool_set)) {
RPMEMD_LOG(ERR, "removing '%s' failed",
rpmemd->config.rm_poolset);
ret = errno;
} else {
RPMEMD_LOG(NOTICE, "removed '%s'",
rpmemd->config.rm_poolset);
ret = 0;
}
send_status = 0;
goto out_rm;
}
ret = rpmemd_obc_status(rpmemd->obc, 0);
if (ret) {
RPMEMD_LOG(ERR, "writing status failed");
goto err_status;
}
rpmemd_print_info(rpmemd);
while (!ret) {
ret = rpmemd_obc_process(rpmemd->obc, &rpmemd_req, rpmemd);
if (ret) {
RPMEMD_LOG(ERR, "out-of-band connection"
" process failed");
goto err;
}
if (rpmemd->closing)
break;
}
rpmemd_db_fini(rpmemd->db);
rpmemd_config_free(&rpmemd->config);
rpmemd_log_close();
rpmemd_obc_fini(rpmemd->obc);
free(rpmemd);
return 0;
err:
rpmemd_req_cleanup(rpmemd);
err_status:
out_rm:
rpmemd_db_fini(rpmemd->db);
err_db_init:
err_log_init_config:
rpmemd_config_free(&rpmemd->config);
err_config:
rpmemd_log_close();
err_log_init:
if (send_status) {
if (rpmemd_obc_status(rpmemd->obc, (uint32_t)errno))
RPMEMD_LOG(ERR, "writing status failed");
}
rpmemd_obc_fini(rpmemd->obc);
err_obc:
free(rpmemd);
err_rpmemd:
return ret;
}
| 18,497 | 22.007463 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/src/tools/rpmemd/rpmemd_util.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2018, Intel Corporation */
/*
* rpmemd_util.c -- rpmemd utility functions definitions
*/
#include <stdlib.h>
#include <unistd.h>
#include "libpmem.h"
#include "rpmem_common.h"
#include "rpmemd_log.h"
#include "rpmemd_util.h"
/*
* rpmemd_pmem_persist -- pmem_persist wrapper required to unify function
* pointer type with pmem_msync
*/
int
rpmemd_pmem_persist(const void *addr, size_t len)
{
pmem_persist(addr, len);
return 0;
}
/*
* rpmemd_flush_fatal -- APM specific flush function which should never be
* called because APM does not require flushes
*/
int
rpmemd_flush_fatal(const void *addr, size_t len)
{
RPMEMD_FATAL("rpmemd_flush_fatal should never be called");
}
/*
* rpmemd_persist_to_str -- convert persist function pointer to string
*/
static const char *
rpmemd_persist_to_str(int (*persist)(const void *addr, size_t len))
{
if (persist == rpmemd_pmem_persist) {
return "pmem_persist";
} else if (persist == pmem_msync) {
return "pmem_msync";
} else if (persist == rpmemd_flush_fatal) {
return "none";
} else {
return NULL;
}
}
/*
* rpmem_print_pm_policy -- print persistency method policy
*/
static void
rpmem_print_pm_policy(enum rpmem_persist_method persist_method,
int (*persist)(const void *addr, size_t len))
{
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist method: %s",
rpmem_persist_method_to_str(persist_method));
RPMEMD_LOG(NOTICE, RPMEMD_LOG_INDENT "persist flush: %s",
rpmemd_persist_to_str(persist));
}
/*
* rpmem_memcpy_msync -- memcpy and msync
*/
static void *
rpmem_memcpy_msync(void *pmemdest, const void *src, size_t len)
{
void *ret = pmem_memcpy(pmemdest, src, len, PMEM_F_MEM_NOFLUSH);
pmem_msync(pmemdest, len);
return ret;
}
/*
* rpmemd_apply_pm_policy -- choose the persistency method and the flush
* function according to the pool type and the persistency method read from the
* config
*/
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)
{
switch (*persist_method) {
case RPMEM_PM_APM:
if (is_pmem) {
*persist_method = RPMEM_PM_APM;
*persist = rpmemd_flush_fatal;
} else {
*persist_method = RPMEM_PM_GPSPM;
*persist = pmem_msync;
}
break;
case RPMEM_PM_GPSPM:
*persist_method = RPMEM_PM_GPSPM;
*persist = is_pmem ? rpmemd_pmem_persist : pmem_msync;
break;
default:
RPMEMD_FATAL("invalid persist method: %d", *persist_method);
return -1;
}
/* this is for RPMEM_PERSIST_INLINE */
if (is_pmem)
*memcpy_persist = pmem_memcpy_persist;
else
*memcpy_persist = rpmem_memcpy_msync;
RPMEMD_LOG(NOTICE, "persistency policy:");
rpmem_print_pm_policy(*persist_method, *persist);
return 0;
}
| 2,839 | 22.666667 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/src/tools/rpmemd/rpmemd_obc.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* rpmemd_obc.c -- rpmemd out-of-band connection definitions
*/
#include <stdlib.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include "librpmem.h"
#include "rpmemd_log.h"
#include "rpmem_proto.h"
#include "rpmem_common.h"
#include "rpmemd_obc.h"
struct rpmemd_obc {
int fd_in;
int fd_out;
};
/*
* rpmemd_obc_check_proto_ver -- check protocol version
*/
static int
rpmemd_obc_check_proto_ver(unsigned major, unsigned minor)
{
if (major != RPMEM_PROTO_MAJOR ||
minor != RPMEM_PROTO_MINOR) {
RPMEMD_LOG(ERR, "unsupported protocol version -- %u.%u",
major, minor);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_msg_hdr -- check message header
*/
static int
rpmemd_obc_check_msg_hdr(struct rpmem_msg_hdr *hdrp)
{
switch (hdrp->type) {
case RPMEM_MSG_TYPE_OPEN:
case RPMEM_MSG_TYPE_CREATE:
case RPMEM_MSG_TYPE_CLOSE:
case RPMEM_MSG_TYPE_SET_ATTR:
/* all messages from obc to server are fine */
break;
default:
RPMEMD_LOG(ERR, "invalid message type -- %u", hdrp->type);
return -1;
}
if (hdrp->size < sizeof(struct rpmem_msg_hdr)) {
RPMEMD_LOG(ERR, "invalid message size -- %lu", hdrp->size);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_pool_desc -- check pool descriptor
*/
static int
rpmemd_obc_check_pool_desc(struct rpmem_msg_hdr *hdrp, size_t msg_size,
struct rpmem_msg_pool_desc *pool_desc)
{
size_t body_size = msg_size + pool_desc->size;
if (hdrp->size != body_size) {
RPMEMD_LOG(ERR, "message and pool descriptor size mismatch "
"-- is %lu should be %lu", hdrp->size, body_size);
return -1;
}
if (pool_desc->size < 2) {
RPMEMD_LOG(ERR, "invalid pool descriptor size -- %u "
"(must be >= 2)", pool_desc->size);
return -1;
}
if (pool_desc->desc[pool_desc->size - 1] != '\0') {
RPMEMD_LOG(ERR, "invalid pool descriptor "
"(must be null-terminated string)");
return -1;
}
size_t len = strlen((char *)pool_desc->desc) + 1;
if (pool_desc->size != len) {
RPMEMD_LOG(ERR, "invalid pool descriptor size -- is %lu "
"should be %u", len, pool_desc->size);
return -1;
}
return 0;
}
/*
* rpmemd_obc_check_provider -- check provider value
*/
static int
rpmemd_obc_check_provider(uint32_t provider)
{
if (provider == 0 || provider >= MAX_RPMEM_PROV) {
RPMEMD_LOG(ERR, "invalid provider -- %u", provider);
return -1;
}
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_create -- convert and check create request message
*/
static int
rpmemd_obc_ntoh_check_msg_create(struct rpmem_msg_hdr *hdrp)
{
int ret;
struct rpmem_msg_create *msg = (struct rpmem_msg_create *)hdrp;
rpmem_ntoh_msg_create(msg);
ret = rpmemd_obc_check_proto_ver(msg->c.major, msg->c.minor);
if (ret)
return ret;
ret = rpmemd_obc_check_pool_desc(hdrp, sizeof(*msg), &msg->pool_desc);
if (ret)
return ret;
ret = rpmemd_obc_check_provider(msg->c.provider);
if (ret)
return ret;
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_open -- convert and check open request message
*/
static int
rpmemd_obc_ntoh_check_msg_open(struct rpmem_msg_hdr *hdrp)
{
int ret;
struct rpmem_msg_open *msg = (struct rpmem_msg_open *)hdrp;
rpmem_ntoh_msg_open(msg);
ret = rpmemd_obc_check_proto_ver(msg->c.major, msg->c.minor);
if (ret)
return ret;
ret = rpmemd_obc_check_pool_desc(hdrp, sizeof(*msg), &msg->pool_desc);
if (ret)
return ret;
ret = rpmemd_obc_check_provider(msg->c.provider);
if (ret)
return ret;
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_close -- convert and check close request message
*/
static int
rpmemd_obc_ntoh_check_msg_close(struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_close *msg = (struct rpmem_msg_close *)hdrp;
rpmem_ntoh_msg_close(msg);
/* nothing to do */
return 0;
}
/*
* rpmemd_obc_ntoh_check_msg_set_attr -- convert and check set attributes
* request message
*/
static int
rpmemd_obc_ntoh_check_msg_set_attr(struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_set_attr *msg = (struct rpmem_msg_set_attr *)hdrp;
rpmem_ntoh_msg_set_attr(msg);
/* nothing to do */
return 0;
}
typedef int (*rpmemd_obc_ntoh_check_msg_fn)(struct rpmem_msg_hdr *hdrp);
static rpmemd_obc_ntoh_check_msg_fn rpmemd_obc_ntoh_check_msg[] = {
[RPMEM_MSG_TYPE_CREATE] = rpmemd_obc_ntoh_check_msg_create,
[RPMEM_MSG_TYPE_OPEN] = rpmemd_obc_ntoh_check_msg_open,
[RPMEM_MSG_TYPE_CLOSE] = rpmemd_obc_ntoh_check_msg_close,
[RPMEM_MSG_TYPE_SET_ATTR] = rpmemd_obc_ntoh_check_msg_set_attr,
};
/*
* rpmemd_obc_process_create -- process create request
*/
static int
rpmemd_obc_process_create(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_create *msg = (struct rpmem_msg_create *)hdrp;
struct rpmem_req_attr req = {
.pool_size = msg->c.pool_size,
.nlanes = (unsigned)msg->c.nlanes,
.pool_desc = (char *)msg->pool_desc.desc,
.provider = (enum rpmem_provider)msg->c.provider,
.buff_size = msg->c.buff_size,
};
struct rpmem_pool_attr *rattr = NULL;
struct rpmem_pool_attr rpmem_attr;
unpack_rpmem_pool_attr(&msg->pool_attr, &rpmem_attr);
if (!util_is_zeroed(&rpmem_attr, sizeof(rpmem_attr)))
rattr = &rpmem_attr;
return req_cb->create(obc, arg, &req, rattr);
}
/*
* rpmemd_obc_process_open -- process open request
*/
static int
rpmemd_obc_process_open(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_open *msg = (struct rpmem_msg_open *)hdrp;
struct rpmem_req_attr req = {
.pool_size = msg->c.pool_size,
.nlanes = (unsigned)msg->c.nlanes,
.pool_desc = (const char *)msg->pool_desc.desc,
.provider = (enum rpmem_provider)msg->c.provider,
.buff_size = msg->c.buff_size,
};
return req_cb->open(obc, arg, &req);
}
/*
* rpmemd_obc_process_close -- process close request
*/
static int
rpmemd_obc_process_close(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_close *msg = (struct rpmem_msg_close *)hdrp;
return req_cb->close(obc, arg, (int)msg->flags);
}
/*
* rpmemd_obc_process_set_attr -- process set attributes request
*/
static int
rpmemd_obc_process_set_attr(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp)
{
struct rpmem_msg_set_attr *msg = (struct rpmem_msg_set_attr *)hdrp;
struct rpmem_pool_attr *rattr = NULL;
struct rpmem_pool_attr rpmem_attr;
unpack_rpmem_pool_attr(&msg->pool_attr, &rpmem_attr);
if (!util_is_zeroed(&rpmem_attr, sizeof(rpmem_attr)))
rattr = &rpmem_attr;
return req_cb->set_attr(obc, arg, rattr);
}
typedef int (*rpmemd_obc_process_fn)(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg,
struct rpmem_msg_hdr *hdrp);
static rpmemd_obc_process_fn rpmemd_obc_process_cb[] = {
[RPMEM_MSG_TYPE_CREATE] = rpmemd_obc_process_create,
[RPMEM_MSG_TYPE_OPEN] = rpmemd_obc_process_open,
[RPMEM_MSG_TYPE_CLOSE] = rpmemd_obc_process_close,
[RPMEM_MSG_TYPE_SET_ATTR] = rpmemd_obc_process_set_attr,
};
/*
* rpmemd_obc_recv -- wrapper for read and decode data function
*/
static inline int
rpmemd_obc_recv(struct rpmemd_obc *obc, void *buff, size_t len)
{
return rpmem_xread(obc->fd_in, buff, len, 0);
}
/*
* rpmemd_obc_send -- wrapper for encode and write data function
*/
static inline int
rpmemd_obc_send(struct rpmemd_obc *obc, const void *buff, size_t len)
{
return rpmem_xwrite(obc->fd_out, buff, len, 0);
}
/*
* rpmemd_obc_msg_recv -- receive and check request message
*
* Return values:
* 0 - success
* < 0 - error
* 1 - obc disconnected
*/
static int
rpmemd_obc_msg_recv(struct rpmemd_obc *obc,
struct rpmem_msg_hdr **hdrpp)
{
struct rpmem_msg_hdr hdr;
struct rpmem_msg_hdr nhdr;
struct rpmem_msg_hdr *hdrp;
int ret;
ret = rpmemd_obc_recv(obc, &nhdr, sizeof(nhdr));
if (ret == 1) {
RPMEMD_LOG(NOTICE, "out-of-band connection disconnected");
return 1;
}
if (ret < 0) {
RPMEMD_LOG(ERR, "!receiving message header failed");
return ret;
}
memcpy(&hdr, &nhdr, sizeof(hdr));
rpmem_ntoh_msg_hdr(&hdr);
ret = rpmemd_obc_check_msg_hdr(&hdr);
if (ret) {
RPMEMD_LOG(ERR, "parsing message header failed");
return ret;
}
hdrp = malloc(hdr.size);
if (!hdrp) {
RPMEMD_LOG(ERR, "!allocating message buffer failed");
return -1;
}
memcpy(hdrp, &nhdr, sizeof(*hdrp));
size_t body_size = hdr.size - sizeof(hdr);
ret = rpmemd_obc_recv(obc, hdrp->body, body_size);
if (ret) {
RPMEMD_LOG(ERR, "!receiving message body failed");
goto err_recv_body;
}
ret = rpmemd_obc_ntoh_check_msg[hdr.type](hdrp);
if (ret) {
RPMEMD_LOG(ERR, "parsing message body failed");
goto err_body;
}
*hdrpp = hdrp;
return 0;
err_body:
err_recv_body:
free(hdrp);
return -1;
}
/*
* rpmemd_obc_init -- initialize rpmemd
*/
struct rpmemd_obc *
rpmemd_obc_init(int fd_in, int fd_out)
{
struct rpmemd_obc *obc = calloc(1, sizeof(*obc));
if (!obc) {
RPMEMD_LOG(ERR, "!allocating obc failed");
goto err_calloc;
}
obc->fd_in = fd_in;
obc->fd_out = fd_out;
return obc;
err_calloc:
return NULL;
}
/*
* rpmemd_obc_fini -- destroy obc
*/
void
rpmemd_obc_fini(struct rpmemd_obc *obc)
{
free(obc);
}
/*
* rpmemd_obc_status -- sends initial status to the client
*/
int
rpmemd_obc_status(struct rpmemd_obc *obc, uint32_t status)
{
return rpmemd_obc_send(obc, &status, sizeof(status));
}
/*
* rpmemd_obc_process -- wait for and process a message from client
*
* Return values:
* 0 - success
* < 0 - error
* 1 - client disconnected
*/
int
rpmemd_obc_process(struct rpmemd_obc *obc,
struct rpmemd_obc_requests *req_cb, void *arg)
{
RPMEMD_ASSERT(req_cb != NULL);
RPMEMD_ASSERT(req_cb->create != NULL);
RPMEMD_ASSERT(req_cb->open != NULL);
RPMEMD_ASSERT(req_cb->close != NULL);
RPMEMD_ASSERT(req_cb->set_attr != NULL);
struct rpmem_msg_hdr *hdrp = NULL;
int ret;
ret = rpmemd_obc_msg_recv(obc, &hdrp);
if (ret)
return ret;
RPMEMD_ASSERT(hdrp != NULL);
ret = rpmemd_obc_process_cb[hdrp->type](obc, req_cb, arg, hdrp);
free(hdrp);
return ret;
}
/*
* rpmemd_obc_create_resp -- send create request response message
*/
int
rpmemd_obc_create_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res)
{
struct rpmem_msg_create_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_CREATE_RESP,
.size = sizeof(struct rpmem_msg_create_resp),
.status = (uint32_t)status,
},
.ibc = {
.port = res->port,
.rkey = res->rkey,
.raddr = res->raddr,
.persist_method = res->persist_method,
.nlanes = res->nlanes,
},
};
rpmem_hton_msg_create_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_open_resp -- send open request response message
*/
int
rpmemd_obc_open_resp(struct rpmemd_obc *obc,
int status, const struct rpmem_resp_attr *res,
const struct rpmem_pool_attr *pool_attr)
{
struct rpmem_msg_open_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_OPEN_RESP,
.size = sizeof(struct rpmem_msg_open_resp),
.status = (uint32_t)status,
},
.ibc = {
.port = res->port,
.rkey = res->rkey,
.raddr = res->raddr,
.persist_method = res->persist_method,
.nlanes = res->nlanes,
},
};
pack_rpmem_pool_attr(pool_attr, &resp.pool_attr);
rpmem_hton_msg_open_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_close_resp -- send close request response message
*/
int
rpmemd_obc_close_resp(struct rpmemd_obc *obc,
int status)
{
struct rpmem_msg_close_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_CLOSE_RESP,
.size = sizeof(struct rpmem_msg_close_resp),
.status = (uint32_t)status,
},
};
rpmem_hton_msg_close_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
/*
* rpmemd_obc_set_attr_resp -- send set attributes request response message
*/
int
rpmemd_obc_set_attr_resp(struct rpmemd_obc *obc, int status)
{
struct rpmem_msg_set_attr_resp resp = {
.hdr = {
.type = RPMEM_MSG_TYPE_SET_ATTR_RESP,
.size = sizeof(struct rpmem_msg_set_attr_resp),
.status = (uint32_t)status,
},
};
rpmem_hton_msg_set_attr_resp(&resp);
return rpmemd_obc_send(obc, &resp, sizeof(resp));
}
| 12,309 | 21.422587 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/rpmemd/rpmemd_config.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_config.c -- rpmemd config source file
*/
#include <pwd.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <inttypes.h>
#include "rpmemd.h"
#include "rpmemd_log.h"
#include "rpmemd_config.h"
#include "os.h"
#define CONFIG_LINE_SIZE_INIT 50
#define INVALID_CHAR_POS UINT64_MAX
struct rpmemd_special_chars_pos {
uint64_t equal_char;
uint64_t comment_char;
uint64_t EOL_char;
};
enum rpmemd_option {
RPD_OPT_LOG_FILE,
RPD_OPT_POOLSET_DIR,
RPD_OPT_PERSIST_APM,
RPD_OPT_PERSIST_GENERAL,
RPD_OPT_USE_SYSLOG,
RPD_OPT_LOG_LEVEL,
RPD_OPT_RM_POOLSET,
RPD_OPT_MAX_VALUE,
RPD_OPT_INVALID = UINT64_MAX,
};
static const char *optstr = "c:hVr:fst:";
/*
* options -- cl and config file options
*/
static const struct option options[] = {
{"config", required_argument, NULL, 'c'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{"log-file", required_argument, NULL, RPD_OPT_LOG_FILE},
{"poolset-dir", required_argument, NULL, RPD_OPT_POOLSET_DIR},
{"persist-apm", no_argument, NULL, RPD_OPT_PERSIST_APM},
{"persist-general", no_argument, NULL, RPD_OPT_PERSIST_GENERAL},
{"use-syslog", no_argument, NULL, RPD_OPT_USE_SYSLOG},
{"log-level", required_argument, NULL, RPD_OPT_LOG_LEVEL},
{"remove", required_argument, NULL, 'r'},
{"force", no_argument, NULL, 'f'},
{"pool-set", no_argument, NULL, 's'},
{"nthreads", required_argument, NULL, 't'},
{NULL, 0, NULL, 0},
};
#define VALUE_INDENT " "
static const char * const help_str =
"\n"
"Options:\n"
" -c, --config <path> configuration file location\n"
" -r, --remove <poolset> remove pool described by given poolset file\n"
" -f, --force ignore errors when removing a pool\n"
" -t, --nthreads <num> number of processing threads\n"
" -h, --help display help message and exit\n"
" -V, --version display target daemon version and exit\n"
" --log-file <path> log file location\n"
" --poolset-dir <path> pool set files directory\n"
" --persist-apm enable Appliance Persistency Method\n"
" --persist-general enable General Server Persistency Mechanism\n"
" --use-syslog use syslog(3) for logging messages\n"
" --log-level <level> set log level value\n"
VALUE_INDENT "err error conditions\n"
VALUE_INDENT "warn warning conditions\n"
VALUE_INDENT "notice normal, but significant, condition\n"
VALUE_INDENT "info informational message\n"
VALUE_INDENT "debug debug-level message\n"
"\n"
"For complete documentation see %s(1) manual page.";
/*
* print_version -- (internal) prints version message
*/
static void
print_version(void)
{
RPMEMD_LOG(ERR, "%s version %s", DAEMON_NAME, SRCVERSION);
}
/*
* print_usage -- (internal) prints usage message
*/
static void
print_usage(const char *name)
{
RPMEMD_LOG(ERR, "usage: %s [--version] [--help] [<args>]",
name);
}
/*
* print_help -- (internal) prints help message
*/
static void
print_help(const char *name)
{
print_usage(name);
print_version();
RPMEMD_LOG(ERR, help_str, DAEMON_NAME);
}
/*
* parse_config_string -- (internal) parse string value
*/
static inline char *
parse_config_string(const char *value)
{
if (strlen(value) == 0) {
errno = EINVAL;
return NULL;
}
char *output = strdup(value);
if (output == NULL)
RPMEMD_FATAL("!strdup");
return output;
}
/*
* parse_config_bool -- (internal) parse yes / no flag
*/
static inline int
parse_config_bool(bool *config_value, const char *value)
{
if (value == NULL)
*config_value = true;
else if (strcmp("yes", value) == 0)
*config_value = true;
else if (strcmp("no", value) == 0)
*config_value = false;
else {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* set_option -- (internal) set single config option
*/
static int
set_option(enum rpmemd_option option, const char *value,
struct rpmemd_config *config)
{
int ret = 0;
switch (option) {
case RPD_OPT_LOG_FILE:
free(config->log_file);
config->log_file = parse_config_string(value);
if (config->log_file == NULL)
return -1;
else
config->use_syslog = false;
break;
case RPD_OPT_POOLSET_DIR:
free(config->poolset_dir);
config->poolset_dir = parse_config_string(value);
if (config->poolset_dir == NULL)
return -1;
break;
case RPD_OPT_PERSIST_APM:
ret = parse_config_bool(&config->persist_apm, value);
break;
case RPD_OPT_PERSIST_GENERAL:
ret = parse_config_bool(&config->persist_general, value);
break;
case RPD_OPT_USE_SYSLOG:
ret = parse_config_bool(&config->use_syslog, value);
break;
case RPD_OPT_LOG_LEVEL:
config->log_level = rpmemd_log_level_from_str(value);
if (config->log_level == MAX_RPD_LOG) {
errno = EINVAL;
return -1;
}
break;
default:
errno = EINVAL;
return -1;
}
return ret;
}
/*
* get_config_line -- (internal) read single line from file
*/
static int
get_config_line(FILE *file, char **line, uint64_t *line_max,
uint8_t *line_max_increased, struct rpmemd_special_chars_pos *pos)
{
uint8_t line_complete = 0;
uint64_t line_length = 0;
char *line_part = *line;
do {
char *ret = fgets(line_part,
(int)(*line_max - line_length), file);
if (ret == NULL)
return 0;
for (uint64_t i = 0; i < *line_max; ++i) {
if (line_part[i] == '\n')
line_complete = 1;
else if (line_part[i] == '\0') {
line_length += i;
if (line_length + 1 < *line_max)
line_complete = 1;
break;
} else if (line_part[i] == '#' &&
pos->comment_char == UINT64_MAX)
pos->comment_char = line_length + i;
else if (line_part[i] == '=' &&
pos->equal_char == UINT64_MAX)
pos->equal_char = line_length + i;
}
if (line_complete == 0) {
*line = realloc(*line, sizeof(char) * (*line_max) * 2);
if (*line == NULL) {
RPMEMD_FATAL("!realloc");
}
line_part = *line + *line_max - 1;
line_length = *line_max - 1;
*line_max *= 2;
*line_max_increased = 1;
}
} while (line_complete != 1);
pos->EOL_char = line_length;
return 0;
}
/*
* trim_line_element -- (internal) remove white characters
*/
static char *
trim_line_element(char *line, uint64_t start, uint64_t end)
{
for (; start <= end; ++start) {
if (!isspace(line[start]))
break;
}
for (; end > start; --end) {
if (!isspace(line[end - 1]))
break;
}
if (start == end)
return NULL;
line[end] = '\0';
return &line[start];
}
/*
* parse_config_key -- (internal) lookup config key
*/
static enum rpmemd_option
parse_config_key(const char *key)
{
for (int i = 0; options[i].name != 0; ++i) {
if (strcmp(key, options[i].name) == 0)
return (enum rpmemd_option)options[i].val;
}
return RPD_OPT_INVALID;
}
/*
* parse_config_line -- (internal) parse single config line
*
* Return newly written option flag. Store possible errors in errno.
*/
static int
parse_config_line(char *line, struct rpmemd_special_chars_pos *pos,
struct rpmemd_config *config, uint64_t disabled)
{
if (pos->comment_char < pos->equal_char)
pos->equal_char = INVALID_CHAR_POS;
uint64_t end_of_content = pos->comment_char != INVALID_CHAR_POS ?
pos->comment_char : pos->EOL_char;
if (pos->equal_char == INVALID_CHAR_POS) {
char *leftover = trim_line_element(line, 0, end_of_content);
if (leftover != NULL) {
errno = EINVAL;
return -1;
} else {
return 0;
}
}
char *key_name = trim_line_element(line, 0, pos->equal_char);
char *value = trim_line_element(line, pos->equal_char + 1,
end_of_content);
if (key_name == NULL || value == NULL) {
errno = EINVAL;
return -1;
}
enum rpmemd_option key = parse_config_key(key_name);
if (key != RPD_OPT_INVALID) {
if ((disabled & (uint64_t)(1 << key)) == 0)
if (set_option(key, value, config) != 0)
return -1;
} else {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* parse_config_file -- (internal) parse config file
*/
static int
parse_config_file(const char *filename, struct rpmemd_config *config,
uint64_t disabled, int required)
{
RPMEMD_ASSERT(filename != NULL);
FILE *file = os_fopen(filename, "r");
if (file == NULL) {
if (required) {
RPMEMD_LOG(ERR, "!%s", filename);
goto error_fopen;
} else {
goto optional_config_missing;
}
}
uint8_t line_max_increased = 0;
uint64_t line_max = CONFIG_LINE_SIZE_INIT;
uint64_t line_num = 1;
char *line = (char *)malloc(sizeof(char) * line_max);
if (line == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error_malloc_line;
}
char *line_copy = (char *)malloc(sizeof(char) * line_max);
if (line_copy == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error_malloc_line_copy;
}
struct rpmemd_special_chars_pos pos;
do {
memset(&pos, 0xff, sizeof(pos));
if (get_config_line(file, &line, &line_max,
&line_max_increased, &pos) != 0)
goto error;
if (line_max_increased) {
char *line_new = (char *)realloc(line_copy,
sizeof(char) * line_max);
if (line_new == NULL) {
RPMEMD_LOG(ERR, "!malloc");
goto error;
}
line_copy = line_new;
line_max_increased = 0;
}
if (pos.EOL_char != INVALID_CHAR_POS) {
strcpy(line_copy, line);
int ret = parse_config_line(line_copy, &pos, config,
disabled);
if (ret != 0) {
size_t len = strlen(line);
if (len > 0 && line[len - 1] == '\n')
line[len - 1] = '\0';
RPMEMD_LOG(ERR, "Invalid config file line at "
"%s:%lu\n%s",
filename, line_num, line);
goto error;
}
}
++line_num;
} while (pos.EOL_char != INVALID_CHAR_POS);
free(line_copy);
free(line);
fclose(file);
optional_config_missing:
return 0;
error:
free(line_copy);
error_malloc_line_copy:
free(line);
error_malloc_line:
fclose(file);
error_fopen:
return -1;
}
/*
* parse_cl_args -- (internal) parse command line arguments
*/
static void
parse_cl_args(int argc, char *argv[], struct rpmemd_config *config,
const char **config_file, uint64_t *cl_options)
{
RPMEMD_ASSERT(argv != NULL);
RPMEMD_ASSERT(config != NULL);
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, optstr, options,
&option_index)) != -1) {
switch (opt) {
case 'c':
(*config_file) = optarg;
break;
case 'r':
config->rm_poolset = optarg;
break;
case 'f':
config->force = true;
break;
case 's':
config->pool_set = true;
break;
case 't':
errno = 0;
char *endptr;
config->nthreads = strtoul(optarg, &endptr, 10);
if (errno || *endptr != '\0') {
RPMEMD_LOG(ERR,
"invalid number of threads -- '%s'",
optarg);
exit(-1);
}
break;
case 'h':
print_help(argv[0]);
exit(0);
case 'V':
print_version();
exit(0);
break;
default:
if (set_option((enum rpmemd_option)opt, optarg, config)
== 0) {
*cl_options |= (UINT64_C(1) << opt);
} else {
print_usage(argv[0]);
exit(-1);
}
}
}
}
/*
* get_home_dir -- (internal) return user home directory
*
* Function will lookup user home directory in order:
* 1. HOME environment variable
* 2. Password file entry using real user ID
*/
static void
get_home_dir(char *str, size_t size)
{
char *home = os_getenv(HOME_ENV);
if (home) {
int r = util_snprintf(str, size, "%s", home);
if (r < 0)
RPMEMD_FATAL("!snprintf");
} else {
uid_t uid = getuid();
struct passwd *pw = getpwuid(uid);
if (pw == NULL)
RPMEMD_FATAL("!getpwuid");
int r = util_snprintf(str, size, "%s", pw->pw_dir);
if (r < 0)
RPMEMD_FATAL("!snprintf");
}
}
/*
* concat_dir_and_file_name -- (internal) concatenate directory and file name
* into single string path
*/
static void
concat_dir_and_file_name(char *path, size_t size, const char *dir,
const char *file)
{
int r = util_snprintf(path, size, "%s/%s", dir, file);
if (r < 0)
RPMEMD_FATAL("!snprintf");
}
/*
* str_replace_home -- (internal) replace $HOME string with user home directory
*
* If function does not find $HOME string it will return haystack untouched.
* Otherwise it will allocate new string with $HOME replaced with provided
* home_dir path. haystack will be released and newly created string returned.
*/
static char *
str_replace_home(char *haystack, const char *home_dir)
{
const size_t placeholder_len = strlen(HOME_STR_PLACEHOLDER);
const size_t home_len = strlen(home_dir);
size_t haystack_len = strlen(haystack);
char *pos = strstr(haystack, HOME_STR_PLACEHOLDER);
if (!pos)
return haystack;
const char *after = pos + placeholder_len;
if (isalnum(*after))
return haystack;
haystack_len += home_len - placeholder_len + 1;
char *buf = malloc(sizeof(char) * haystack_len);
if (!buf)
RPMEMD_FATAL("!malloc");
*pos = '\0';
int r = util_snprintf(buf, haystack_len, "%s%s%s", haystack, home_dir,
after);
if (r < 0)
RPMEMD_FATAL("!snprintf");
free(haystack);
return buf;
}
/*
* config_set_default -- (internal) load default config
*/
static void
config_set_default(struct rpmemd_config *config, const char *poolset_dir)
{
config->log_file = strdup(RPMEMD_DEFAULT_LOG_FILE);
if (!config->log_file)
RPMEMD_FATAL("!strdup");
config->poolset_dir = strdup(poolset_dir);
if (!config->poolset_dir)
RPMEMD_FATAL("!strdup");
config->persist_apm = false;
config->persist_general = true;
config->use_syslog = true;
config->max_lanes = RPMEM_DEFAULT_MAX_LANES;
config->log_level = RPD_LOG_ERR;
config->rm_poolset = NULL;
config->force = false;
config->nthreads = RPMEM_DEFAULT_NTHREADS;
}
/*
* rpmemd_config_read -- read config from cl and config files
*
* cl param overwrites configuration from any config file. Config file are read
* in order:
* 1. Global config file
* 2. User config file
* or
* cl provided config file
*/
int
rpmemd_config_read(struct rpmemd_config *config, int argc, char *argv[])
{
const char *cl_config_file = NULL;
char user_config_file[PATH_MAX];
char home_dir[PATH_MAX];
uint64_t cl_options = 0;
get_home_dir(home_dir, PATH_MAX);
config_set_default(config, home_dir);
parse_cl_args(argc, argv, config, &cl_config_file, &cl_options);
if (cl_config_file) {
if (parse_config_file(cl_config_file, config, cl_options, 1)) {
rpmemd_config_free(config);
return 1;
}
} else {
if (parse_config_file(RPMEMD_GLOBAL_CONFIG_FILE, config,
cl_options, 0)) {
rpmemd_config_free(config);
return 1;
}
concat_dir_and_file_name(user_config_file, PATH_MAX, home_dir,
RPMEMD_USER_CONFIG_FILE);
if (parse_config_file(user_config_file, config, cl_options,
0)) {
rpmemd_config_free(config);
return 1;
}
}
config->poolset_dir = str_replace_home(config->poolset_dir, home_dir);
return 0;
}
/*
* rpmemd_config_free -- rpmemd config release
*/
void
rpmemd_config_free(struct rpmemd_config *config)
{
free(config->log_file);
free(config->poolset_dir);
}
| 15,007 | 22.413417 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/rpmemd/rpmemd_db.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* rpmemd_db.c -- rpmemd database of pool set files
*/
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/file.h>
#include <sys/mman.h>
#include "queue.h"
#include "set.h"
#include "os.h"
#include "out.h"
#include "file.h"
#include "sys_util.h"
#include "librpmem.h"
#include "rpmemd_db.h"
#include "rpmemd_log.h"
/*
* struct rpmemd_db -- pool set database structure
*/
struct rpmemd_db {
os_mutex_t lock;
char *root_dir;
mode_t mode;
};
/*
* declaration of the 'struct list_head' type
*/
PMDK_LIST_HEAD(list_head, rpmemd_db_entry);
/*
* struct rpmemd_db_entry -- entry in the pool set list
*/
struct rpmemd_db_entry {
PMDK_LIST_ENTRY(rpmemd_db_entry) next;
char *pool_desc;
struct pool_set *set;
};
/*
* rpmemd_db_init -- initialize the rpmem database of pool set files
*/
struct rpmemd_db *
rpmemd_db_init(const char *root_dir, mode_t mode)
{
if (root_dir[0] != '/') {
RPMEMD_LOG(ERR, "root directory is not an absolute path"
" -- '%s'", root_dir);
errno = EINVAL;
return NULL;
}
struct rpmemd_db *db = calloc(1, sizeof(*db));
if (!db) {
RPMEMD_LOG(ERR, "!allocating the rpmem database structure");
return NULL;
}
db->root_dir = strdup(root_dir);
if (!db->root_dir) {
RPMEMD_LOG(ERR, "!allocating the root dir path");
free(db);
return NULL;
}
db->mode = mode;
util_mutex_init(&db->lock);
return db;
}
/*
* rpmemd_db_concat -- (internal) concatenate two paths
*/
static char *
rpmemd_db_concat(const char *path1, const char *path2)
{
size_t len1 = strlen(path1);
size_t len2 = strlen(path2);
size_t new_len = len1 + len2 + 2; /* +1 for '/' in snprintf() */
if (path1[0] != '/') {
RPMEMD_LOG(ERR, "the first path is not an absolute one -- '%s'",
path1);
errno = EINVAL;
return NULL;
}
if (path2[0] == '/') {
RPMEMD_LOG(ERR, "the second path is not a relative one -- '%s'",
path2);
/* set to EBADF to distinguish this case from other errors */
errno = EBADF;
return NULL;
}
char *new_str = malloc(new_len);
if (new_str == NULL) {
RPMEMD_LOG(ERR, "!allocating path buffer");
return NULL;
}
int ret = util_snprintf(new_str, new_len, "%s/%s", path1, path2);
if (ret < 0) {
RPMEMD_LOG(ERR, "!snprintf");
free(new_str);
errno = EINVAL;
return NULL;
}
return new_str;
}
/*
* rpmemd_db_get_path -- (internal) get the full path of the pool set file
*/
static char *
rpmemd_db_get_path(struct rpmemd_db *db, const char *pool_desc)
{
return rpmemd_db_concat(db->root_dir, pool_desc);
}
/*
* rpmemd_db_pool_madvise -- (internal) workaround device dax alignment issue
*/
static int
rpmemd_db_pool_madvise(struct pool_set *set)
{
/*
* This is a workaround for an issue with using device dax with
* libibverbs. The problem is that we use ibv_fork_init(3) which
* makes all registered memory being madvised with MADV_DONTFORK
* flag. In libpmemobj the remote replication is performed without
* pool header (first 4k). In such case the address passed to
* madvise(2) is aligned to 4k, but device dax can require different
* alignment (default is 2MB). This workaround madvises the entire
* memory region before registering it by ibv_reg_mr(3).
*/
const struct pool_set_part *part = &set->replica[0]->part[0];
if (part->is_dev_dax) {
int ret = os_madvise(part->addr, part->filesize,
MADV_DONTFORK);
if (ret) {
ERR("!madvise");
return -1;
}
}
return 0;
}
/*
* rpmemd_get_attr -- (internal) get pool attributes from remote pool attributes
*/
static void
rpmemd_get_attr(struct pool_attr *attr, const struct rpmem_pool_attr *rattr)
{
LOG(3, "attr %p, rattr %p", attr, rattr);
memcpy(attr->signature, rattr->signature, POOL_HDR_SIG_LEN);
attr->major = rattr->major;
attr->features.compat = rattr->compat_features;
attr->features.incompat = rattr->incompat_features;
attr->features.ro_compat = rattr->ro_compat_features;
memcpy(attr->poolset_uuid, rattr->poolset_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->first_part_uuid, rattr->uuid, POOL_HDR_UUID_LEN);
memcpy(attr->prev_repl_uuid, rattr->prev_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->next_repl_uuid, rattr->next_uuid, POOL_HDR_UUID_LEN);
memcpy(attr->arch_flags, rattr->user_flags, POOL_HDR_ARCH_LEN);
}
/*
* rpmemd_db_pool_create -- create a new pool set
*/
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)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
struct rpmemd_db_pool *prp = NULL;
struct pool_set *set;
char *path;
int ret;
prp = malloc(sizeof(struct rpmemd_db_pool));
if (!prp) {
RPMEMD_LOG(ERR, "!allocating pool set db entry");
goto err_unlock;
}
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
goto err_free_prp;
}
struct pool_attr attr;
struct pool_attr *pattr = NULL;
if (rattr != NULL) {
rpmemd_get_attr(&attr, rattr);
pattr = &attr;
}
ret = util_pool_create_uuids(&set, path, 0, RPMEM_MIN_POOL,
RPMEM_MIN_PART, pattr, NULL, REPLICAS_DISABLED,
POOL_REMOTE);
if (ret) {
RPMEMD_LOG(ERR, "!cannot create pool set -- '%s'", path);
goto err_free_path;
}
ret = util_poolset_chmod(set, db->mode);
if (ret) {
RPMEMD_LOG(ERR, "!cannot change pool set mode bits to 0%o",
db->mode);
}
if (rpmemd_db_pool_madvise(set))
goto err_poolset_close;
/* mark as opened */
prp->pool_addr = set->replica[0]->part[0].addr;
prp->pool_size = set->poolsize;
prp->set = set;
free(path);
util_mutex_unlock(&db->lock);
return prp;
err_poolset_close:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_path:
free(path);
err_free_prp:
free(prp);
err_unlock:
util_mutex_unlock(&db->lock);
return NULL;
}
/*
* rpmemd_db_pool_open -- open a pool set
*/
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)
{
RPMEMD_ASSERT(db != NULL);
RPMEMD_ASSERT(rattr != NULL);
util_mutex_lock(&db->lock);
struct rpmemd_db_pool *prp = NULL;
struct pool_set *set;
char *path;
int ret;
prp = malloc(sizeof(struct rpmemd_db_pool));
if (!prp) {
RPMEMD_LOG(ERR, "!allocating pool set db entry");
goto err_unlock;
}
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
goto err_free_prp;
}
ret = util_pool_open_remote(&set, path, 0, RPMEM_MIN_PART, rattr);
if (ret) {
RPMEMD_LOG(ERR, "!cannot open pool set -- '%s'", path);
goto err_free_path;
}
if (rpmemd_db_pool_madvise(set))
goto err_poolset_close;
/* mark as opened */
prp->pool_addr = set->replica[0]->part[0].addr;
prp->pool_size = set->poolsize;
prp->set = set;
free(path);
util_mutex_unlock(&db->lock);
return prp;
err_poolset_close:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_path:
free(path);
err_free_prp:
free(prp);
err_unlock:
util_mutex_unlock(&db->lock);
return NULL;
}
/*
* rpmemd_db_pool_close -- close a pool set
*/
void
rpmemd_db_pool_close(struct rpmemd_db *db, struct rpmemd_db_pool *prp)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
util_poolset_close(prp->set, DO_NOT_DELETE_PARTS);
free(prp);
util_mutex_unlock(&db->lock);
}
/*
* rpmemd_db_pool_set_attr -- overwrite pool attributes
*/
int
rpmemd_db_pool_set_attr(struct rpmemd_db_pool *prp,
const struct rpmem_pool_attr *rattr)
{
RPMEMD_ASSERT(prp != NULL);
RPMEMD_ASSERT(prp->set != NULL);
RPMEMD_ASSERT(prp->set->nreplicas == 1);
return util_replica_set_attr(prp->set->replica[0], rattr);
}
struct rm_cb_args {
int force;
int ret;
};
/*
* rm_poolset_cb -- (internal) callback for removing part files
*/
static int
rm_poolset_cb(struct part_file *pf, void *arg)
{
struct rm_cb_args *args = (struct rm_cb_args *)arg;
if (pf->is_remote) {
RPMEMD_LOG(ERR, "removing remote replica not supported");
return -1;
}
int ret = util_unlink_flock(pf->part->path);
if (!args->force && ret) {
RPMEMD_LOG(ERR, "!unlink -- '%s'", pf->part->path);
args->ret = ret;
}
return 0;
}
/*
* rpmemd_db_pool_remove -- remove a pool set
*/
int
rpmemd_db_pool_remove(struct rpmemd_db *db, const char *pool_desc,
int force, int pool_set)
{
RPMEMD_ASSERT(db != NULL);
RPMEMD_ASSERT(pool_desc != NULL);
util_mutex_lock(&db->lock);
struct rm_cb_args args;
args.force = force;
args.ret = 0;
char *path;
path = rpmemd_db_get_path(db, pool_desc);
if (!path) {
args.ret = -1;
goto err_unlock;
}
int ret = util_poolset_foreach_part(path, rm_poolset_cb, &args);
if (!force && ret) {
RPMEMD_LOG(ERR, "!removing '%s' failed", path);
args.ret = ret;
goto err_free_path;
}
if (pool_set)
os_unlink(path);
err_free_path:
free(path);
err_unlock:
util_mutex_unlock(&db->lock);
return args.ret;
}
/*
* rpmemd_db_fini -- deinitialize the rpmem database of pool set files
*/
void
rpmemd_db_fini(struct rpmemd_db *db)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_destroy(&db->lock);
free(db->root_dir);
free(db);
}
/*
* rpmemd_db_check_dups_set -- (internal) check for duplicates in the database
*/
static inline int
rpmemd_db_check_dups_set(struct pool_set *set, const char *path)
{
for (unsigned r = 0; r < set->nreplicas; r++) {
struct pool_replica *rep = set->replica[r];
for (unsigned p = 0; p < rep->nparts; p++) {
if (strcmp(path, rep->part[p].path) == 0)
return -1;
}
}
return 0;
}
/*
* rpmemd_db_check_dups -- (internal) check for duplicates in the database
*/
static int
rpmemd_db_check_dups(struct list_head *head, struct rpmemd_db *db,
const char *pool_desc, struct pool_set *set)
{
struct rpmemd_db_entry *edb;
PMDK_LIST_FOREACH(edb, head, next) {
for (unsigned r = 0; r < edb->set->nreplicas; r++) {
struct pool_replica *rep = edb->set->replica[r];
for (unsigned p = 0; p < rep->nparts; p++) {
if (rpmemd_db_check_dups_set(set,
rep->part[p].path)) {
RPMEMD_LOG(ERR, "part file '%s' from "
"pool set '%s' duplicated in "
"pool set '%s'",
rep->part[p].path,
pool_desc,
edb->pool_desc);
errno = EEXIST;
return -1;
}
}
}
}
return 0;
}
/*
* rpmemd_db_add -- (internal) add an entry for a given set to the database
*/
static struct rpmemd_db_entry *
rpmemd_db_add(struct list_head *head, struct rpmemd_db *db,
const char *pool_desc, struct pool_set *set)
{
struct rpmemd_db_entry *edb;
edb = calloc(1, sizeof(*edb));
if (!edb) {
RPMEMD_LOG(ERR, "!allocating database entry");
goto err_calloc;
}
edb->set = set;
edb->pool_desc = strdup(pool_desc);
if (!edb->pool_desc) {
RPMEMD_LOG(ERR, "!allocating path for database entry");
goto err_strdup;
}
PMDK_LIST_INSERT_HEAD(head, edb, next);
return edb;
err_strdup:
free(edb);
err_calloc:
return NULL;
}
/*
* new_paths -- (internal) create two new paths
*/
static int
new_paths(const char *dir, const char *name, const char *old_desc,
char **path, char **new_desc)
{
*path = rpmemd_db_concat(dir, name);
if (!(*path))
return -1;
if (old_desc[0] != 0)
*new_desc = rpmemd_db_concat(old_desc, name);
else {
*new_desc = strdup(name);
if (!(*new_desc)) {
RPMEMD_LOG(ERR, "!allocating new descriptor");
}
}
if (!(*new_desc)) {
free(*path);
return -1;
}
return 0;
}
/*
* rpmemd_db_check_dir_r -- (internal) recursively check given directory
* for duplicates
*/
static int
rpmemd_db_check_dir_r(struct list_head *head, struct rpmemd_db *db,
const char *dir, char *pool_desc)
{
char *new_dir, *new_desc, *full_path;
struct dirent *dentry;
struct pool_set *set = NULL;
DIR *dirp;
int ret = 0;
dirp = opendir(dir);
if (dirp == NULL) {
RPMEMD_LOG(ERR, "cannot open the directory -- %s", dir);
return -1;
}
while ((dentry = readdir(dirp)) != NULL) {
if (strcmp(dentry->d_name, ".") == 0 ||
strcmp(dentry->d_name, "..") == 0)
continue;
if (dentry->d_type == DT_DIR) { /* directory */
if (new_paths(dir, dentry->d_name, pool_desc,
&new_dir, &new_desc))
goto err_closedir;
/* call recursively for a new directory */
ret = rpmemd_db_check_dir_r(head, db, new_dir,
new_desc);
free(new_dir);
free(new_desc);
if (ret)
goto err_closedir;
continue;
}
if (new_paths(dir, dentry->d_name, pool_desc,
&full_path, &new_desc)) {
goto err_closedir;
}
if (util_poolset_read(&set, full_path)) {
RPMEMD_LOG(ERR, "!error reading pool set file -- %s",
full_path);
goto err_free_paths;
}
if (rpmemd_db_check_dups(head, db, new_desc, set)) {
RPMEMD_LOG(ERR, "!duplicate found in pool set file"
" -- %s", full_path);
goto err_free_set;
}
if (rpmemd_db_add(head, db, new_desc, set) == NULL) {
goto err_free_set;
}
free(new_desc);
free(full_path);
}
closedir(dirp);
return 0;
err_free_set:
util_poolset_close(set, DO_NOT_DELETE_PARTS);
err_free_paths:
free(new_desc);
free(full_path);
err_closedir:
closedir(dirp);
return -1;
}
/*
* rpmemd_db_check_dir -- check given directory for duplicates
*/
int
rpmemd_db_check_dir(struct rpmemd_db *db)
{
RPMEMD_ASSERT(db != NULL);
util_mutex_lock(&db->lock);
struct list_head head;
PMDK_LIST_INIT(&head);
int ret = rpmemd_db_check_dir_r(&head, db, db->root_dir, "");
while (!PMDK_LIST_EMPTY(&head)) {
struct rpmemd_db_entry *edb = PMDK_LIST_FIRST(&head);
PMDK_LIST_REMOVE(edb, next);
util_poolset_close(edb->set, DO_NOT_DELETE_PARTS);
free(edb->pool_desc);
free(edb);
}
util_mutex_unlock(&db->lock);
return ret;
}
/*
* rpmemd_db_pool_is_pmem -- true if pool is in PMEM
*/
int
rpmemd_db_pool_is_pmem(struct rpmemd_db_pool *pool)
{
return REP(pool->set, 0)->is_pmem;
}
| 13,747 | 20.616352 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/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/logging/pmdk/src/tools/pmempool/create.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* create.c -- pmempool create command source file
*/
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <errno.h>
#include <libgen.h>
#include <err.h>
#include "common.h"
#include "file.h"
#include "create.h"
#include "os.h"
#include "set.h"
#include "output.h"
#include "libpmemblk.h"
#include "libpmemlog.h"
#include "libpmempool.h"
#define DEFAULT_MODE 0664
/*
* pmempool_create -- context and args for create command
*/
struct pmempool_create {
int verbose;
char *fname;
int fexists;
char *inherit_fname;
int max_size;
char *str_type;
struct pmem_pool_params params;
struct pmem_pool_params inherit_params;
char *str_size;
char *str_mode;
char *str_bsize;
uint64_t csize;
int write_btt_layout;
int force;
char *layout;
struct options *opts;
int clearbadblocks;
};
/*
* pmempool_create_default -- default args for create command
*/
static const struct pmempool_create pmempool_create_default = {
.verbose = 0,
.fname = NULL,
.fexists = 0,
.inherit_fname = NULL,
.max_size = 0,
.str_type = NULL,
.str_bsize = NULL,
.csize = 0,
.write_btt_layout = 0,
.force = 0,
.layout = NULL,
.clearbadblocks = 0,
.params = {
.type = PMEM_POOL_TYPE_UNKNOWN,
.size = 0,
.mode = DEFAULT_MODE,
}
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Create pmem pool of specified size, type and name\n"
"\n"
"Common options:\n"
" -s, --size <size> size of pool\n"
" -M, --max-size use maximum available space on file system\n"
" -m, --mode <octal> set permissions to <octal> (the default is 0664)\n"
" -i, --inherit <file> take required parameters from specified pool file\n"
" -b, --clear-bad-blocks clear bad blocks in existing files\n"
" -f, --force remove the pool first\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"Options for PMEMBLK:\n"
" -w, --write-layout force writing the BTT layout\n"
"\n"
"Options for PMEMOBJ:\n"
" -l, --layout <name> layout name stored in pool's header\n"
"\n"
"For complete documentation see %s-create(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"size", required_argument, NULL, 's' | OPT_ALL},
{"verbose", no_argument, NULL, 'v' | OPT_ALL},
{"help", no_argument, NULL, 'h' | OPT_ALL},
{"max-size", no_argument, NULL, 'M' | OPT_ALL},
{"inherit", required_argument, NULL, 'i' | OPT_ALL},
{"mode", required_argument, NULL, 'm' | OPT_ALL},
{"write-layout", no_argument, NULL, 'w' | OPT_BLK},
{"layout", required_argument, NULL, 'l' | OPT_OBJ},
{"force", no_argument, NULL, 'f' | OPT_ALL},
{"clear-bad-blocks", no_argument, NULL, 'b' | OPT_ALL},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s create [<args>] <blk|log|obj> [<bsize>] <file>\n",
appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_create_help -- print help message for create command
*/
void
pmempool_create_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_create_obj -- create pmem obj pool
*/
static int
pmempool_create_obj(struct pmempool_create *pcp)
{
PMEMobjpool *pop = pmemobj_create(pcp->fname, pcp->layout,
pcp->params.size, pcp->params.mode);
if (!pop) {
outv_err("'%s' -- %s\n", pcp->fname, pmemobj_errormsg());
return -1;
}
pmemobj_close(pop);
return 0;
}
/*
* pmempool_create_blk -- create pmem blk pool
*/
static int
pmempool_create_blk(struct pmempool_create *pcp)
{
ASSERTne(pcp->params.blk.bsize, 0);
int ret = 0;
PMEMblkpool *pbp = pmemblk_create(pcp->fname, pcp->params.blk.bsize,
pcp->params.size, pcp->params.mode);
if (!pbp) {
outv_err("'%s' -- %s\n", pcp->fname, pmemblk_errormsg());
return -1;
}
if (pcp->write_btt_layout) {
outv(1, "Writing BTT layout using block %d.\n",
pcp->write_btt_layout);
if (pmemblk_set_error(pbp, 0) || pmemblk_set_zero(pbp, 0)) {
outv_err("writing BTT layout to block 0 failed\n");
ret = -1;
}
}
pmemblk_close(pbp);
return ret;
}
/*
* pmempool_create_log -- create pmem log pool
*/
static int
pmempool_create_log(struct pmempool_create *pcp)
{
PMEMlogpool *plp = pmemlog_create(pcp->fname,
pcp->params.size, pcp->params.mode);
if (!plp) {
outv_err("'%s' -- %s\n", pcp->fname, pmemlog_errormsg());
return -1;
}
pmemlog_close(plp);
return 0;
}
/*
* pmempool_get_max_size -- return maximum allowed size of file
*/
#ifndef _WIN32
static int
pmempool_get_max_size(const char *fname, uint64_t *sizep)
{
struct statvfs buf;
int ret = 0;
char *name = strdup(fname);
if (name == NULL) {
return -1;
}
char *dir = dirname(name);
if (statvfs(dir, &buf))
ret = -1;
else
*sizep = buf.f_bsize * buf.f_bavail;
free(name);
return ret;
}
#else
static int
pmempool_get_max_size(const char *fname, uint64_t *sizep)
{
int ret = 0;
ULARGE_INTEGER freespace;
char *name = strdup(fname);
if (name == NULL) {
return -1;
}
char *dir = dirname(name);
wchar_t *str = util_toUTF16(dir);
if (str == NULL) {
free(name);
return -1;
}
if (GetDiskFreeSpaceExW(str, &freespace, NULL, NULL) == 0)
ret = -1;
else
*sizep = freespace.QuadPart;
free(str);
free(name);
return ret;
}
#endif
/*
* print_pool_params -- print some parameters of a pool
*/
static void
print_pool_params(struct pmem_pool_params *params)
{
outv(1, "\ttype : %s\n", out_get_pool_type_str(params->type));
outv(1, "\tsize : %s\n", out_get_size_str(params->size, 2));
outv(1, "\tmode : 0%o\n", params->mode);
switch (params->type) {
case PMEM_POOL_TYPE_BLK:
outv(1, "\tbsize : %s\n",
out_get_size_str(params->blk.bsize, 0));
break;
case PMEM_POOL_TYPE_OBJ:
outv(1, "\tlayout: '%s'\n", params->obj.layout);
break;
default:
break;
}
}
/*
* inherit_pool_params -- inherit pool parameters from specified file
*/
static int
inherit_pool_params(struct pmempool_create *pcp)
{
outv(1, "Parsing pool: '%s'\n", pcp->inherit_fname);
/*
* If no type string passed, --inherit option must be passed
* so parse file and get required parameters.
*/
if (pmem_pool_parse_params(pcp->inherit_fname,
&pcp->inherit_params, 1)) {
if (errno)
perror(pcp->inherit_fname);
else
outv_err("%s: cannot determine type of pool\n",
pcp->inherit_fname);
return -1;
}
if (PMEM_POOL_TYPE_UNKNOWN == pcp->inherit_params.type) {
outv_err("'%s' -- unknown pool type\n",
pcp->inherit_fname);
return -1;
}
print_pool_params(&pcp->inherit_params);
return 0;
}
/*
* pmempool_create_parse_args -- parse command line args
*/
static int
pmempool_create_parse_args(struct pmempool_create *pcp, const char *appname,
int argc, char *argv[], struct options *opts)
{
int opt, ret;
while ((opt = util_options_getopt(argc, argv, "vhi:s:Mm:l:wfb",
opts)) != -1) {
switch (opt) {
case 'v':
pcp->verbose = 1;
break;
case 'h':
pmempool_create_help(appname);
exit(EXIT_SUCCESS);
case 's':
pcp->str_size = optarg;
ret = util_parse_size(optarg,
(size_t *)&pcp->params.size);
if (ret || pcp->params.size == 0) {
outv_err("invalid size value specified '%s'\n",
optarg);
return -1;
}
break;
case 'M':
pcp->max_size = 1;
break;
case 'm':
pcp->str_mode = optarg;
if (util_parse_mode(optarg, &pcp->params.mode)) {
outv_err("invalid mode value specified '%s'\n",
optarg);
return -1;
}
break;
case 'i':
pcp->inherit_fname = optarg;
break;
case 'w':
pcp->write_btt_layout = 1;
break;
case 'l':
pcp->layout = optarg;
break;
case 'f':
pcp->force = 1;
break;
case 'b':
pcp->clearbadblocks = 1;
break;
default:
print_usage(appname);
return -1;
}
}
/* check for <type>, <bsize> and <file> strings */
if (optind + 2 < argc) {
pcp->str_type = argv[optind];
pcp->str_bsize = argv[optind + 1];
pcp->fname = argv[optind + 2];
} else if (optind + 1 < argc) {
pcp->str_type = argv[optind];
pcp->fname = argv[optind + 1];
} else if (optind < argc) {
pcp->fname = argv[optind];
pcp->str_type = NULL;
} else {
print_usage(appname);
return -1;
}
return 0;
}
static int
allocate_max_size_available_file(const char *name_of_file, mode_t mode,
os_off_t max_size)
{
int fd = os_open(name_of_file, O_CREAT | O_EXCL | O_RDWR, mode);
if (fd == -1) {
outv_err("!open '%s' failed", name_of_file);
return -1;
}
os_off_t offset = 0;
os_off_t length = max_size - (max_size % (os_off_t)Pagesize);
int ret;
do {
ret = os_posix_fallocate(fd, offset, length);
if (ret == 0)
offset += length;
else if (ret != ENOSPC) {
os_close(fd);
if (os_unlink(name_of_file) == -1)
outv_err("!unlink '%s' failed", name_of_file);
errno = ret;
outv_err("!space allocation for '%s' failed",
name_of_file);
return -1;
}
length /= 2;
length -= (length % (os_off_t)Pagesize);
} while (length > (os_off_t)Pagesize);
os_close(fd);
return 0;
}
/*
* pmempool_create_func -- main function for create command
*/
int
pmempool_create_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
struct pmempool_create pc = pmempool_create_default;
pc.opts = util_options_alloc(long_options, sizeof(long_options) /
sizeof(long_options[0]), NULL);
/* parse command line arguments */
ret = pmempool_create_parse_args(&pc, appname, argc, argv, pc.opts);
if (ret)
exit(EXIT_FAILURE);
/* set verbosity level */
out_set_vlevel(pc.verbose);
umask(0);
int exists = util_file_exists(pc.fname);
if (exists < 0)
return -1;
pc.fexists = exists;
int is_poolset = util_is_poolset_file(pc.fname) == 1;
if (pc.inherit_fname) {
if (inherit_pool_params(&pc)) {
outv_err("parsing pool '%s' failed\n",
pc.inherit_fname);
return -1;
}
}
/*
* Parse pool type and other parameters if --inherit option
* passed. It is possible to either pass --inherit option
* or pool type string in command line arguments. This is
* validated here.
*/
if (pc.str_type) {
/* parse pool type string if passed in command line arguments */
pc.params.type = pmem_pool_type_parse_str(pc.str_type);
if (PMEM_POOL_TYPE_UNKNOWN == pc.params.type) {
outv_err("'%s' -- unknown pool type\n", pc.str_type);
return -1;
}
if (PMEM_POOL_TYPE_BLK == pc.params.type) {
if (pc.str_bsize == NULL) {
outv_err("blk pool requires <bsize> "
"argument\n");
return -1;
}
if (util_parse_size(pc.str_bsize,
(size_t *)&pc.params.blk.bsize)) {
outv_err("cannot parse '%s' as block size\n",
pc.str_bsize);
return -1;
}
}
if (PMEM_POOL_TYPE_OBJ == pc.params.type && pc.layout != NULL) {
size_t max_layout = PMEMOBJ_MAX_LAYOUT;
if (strlen(pc.layout) >= max_layout) {
outv_err(
"Layout name is too long, maximum number of characters (including the terminating null byte) is %zu\n",
max_layout);
return -1;
}
size_t len = sizeof(pc.params.obj.layout);
strncpy(pc.params.obj.layout, pc.layout, len);
pc.params.obj.layout[len - 1] = '\0';
}
} else if (pc.inherit_fname) {
pc.params.type = pc.inherit_params.type;
} else {
/* neither pool type string nor --inherit options passed */
print_usage(appname);
return -1;
}
if (util_options_verify(pc.opts, pc.params.type))
return -1;
if (pc.params.type != PMEM_POOL_TYPE_BLK && pc.str_bsize != NULL) {
outv_err("invalid option specified for %s pool type"
" -- block size\n",
out_get_pool_type_str(pc.params.type));
return -1;
}
if (is_poolset) {
if (pc.params.size) {
outv_err("-s|--size cannot be used with "
"poolset file\n");
return -1;
}
if (pc.max_size) {
outv_err("-M|--max-size cannot be used with "
"poolset file\n");
return -1;
}
}
if (pc.params.size && pc.max_size) {
outv_err("-M|--max-size option cannot be used with -s|--size"
" option\n");
return -1;
}
if (pc.inherit_fname) {
if (!pc.str_size && !pc.max_size)
pc.params.size = pc.inherit_params.size;
if (!pc.str_mode)
pc.params.mode = pc.inherit_params.mode;
switch (pc.params.type) {
case PMEM_POOL_TYPE_BLK:
if (!pc.str_bsize)
pc.params.blk.bsize =
pc.inherit_params.blk.bsize;
break;
case PMEM_POOL_TYPE_OBJ:
if (!pc.layout) {
memcpy(pc.params.obj.layout,
pc.inherit_params.obj.layout,
sizeof(pc.params.obj.layout));
} else {
size_t len = sizeof(pc.params.obj.layout);
strncpy(pc.params.obj.layout, pc.layout,
len - 1);
pc.params.obj.layout[len - 1] = '\0';
}
break;
default:
break;
}
}
/*
* If neither --size nor --inherit options passed, check
* for --max-size option - if not passed use minimum pool size.
*/
uint64_t min_size = pmem_pool_get_min_size(pc.params.type);
if (pc.params.size == 0) {
if (pc.max_size) {
outv(1, "Maximum size option passed "
"- getting available space of file system.\n");
ret = pmempool_get_max_size(pc.fname,
&pc.params.size);
if (ret) {
outv_err("cannot get available space of fs\n");
return -1;
}
if (pc.params.size == 0) {
outv_err("No space left on device\n");
return -1;
}
outv(1, "Available space is %s\n",
out_get_size_str(pc.params.size, 2));
if (allocate_max_size_available_file(pc.fname,
pc.params.mode,
(os_off_t)pc.params.size))
return -1;
/*
* We are going to create pool based
* on file size instead of the pc.params.size.
*/
pc.params.size = 0;
} else {
if (!pc.fexists) {
outv(1, "No size option passed "
"- picking minimum pool size.\n");
pc.params.size = min_size;
}
}
} else {
if (pc.params.size < min_size) {
outv_err("size must be >= %lu bytes\n", min_size);
return -1;
}
}
if (pc.force)
pmempool_rm(pc.fname, PMEMPOOL_RM_FORCE);
outv(1, "Creating pool: %s\n", pc.fname);
print_pool_params(&pc.params);
if (pc.clearbadblocks) {
int ret = util_pool_clear_badblocks(pc.fname,
1 /* ignore non-existing */);
if (ret) {
outv_err("'%s' -- clearing bad blocks failed\n",
pc.fname);
return -1;
}
}
switch (pc.params.type) {
case PMEM_POOL_TYPE_BLK:
ret = pmempool_create_blk(&pc);
break;
case PMEM_POOL_TYPE_LOG:
ret = pmempool_create_log(&pc);
break;
case PMEM_POOL_TYPE_OBJ:
ret = pmempool_create_obj(&pc);
break;
default:
ret = -1;
break;
}
if (ret) {
outv_err("creating pool file failed\n");
if (!pc.fexists)
util_unlink(pc.fname);
}
util_options_free(pc.opts);
return ret;
}
| 14,987 | 21.403587 | 109 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/pmempool/transform.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* transform.c -- pmempool transform command source file
*/
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <endian.h>
#include "common.h"
#include "output.h"
#include "transform.h"
#include "libpmempool.h"
/*
* pmempool_transform_context -- context and arguments for transform command
*/
struct pmempool_transform_context {
unsigned flags; /* flags which modify the command execution */
char *poolset_file_src; /* a path to a source poolset file */
char *poolset_file_dst; /* a path to a target poolset file */
};
/*
* pmempool_transform_default -- default arguments for transform command
*/
static const struct pmempool_transform_context pmempool_transform_default = {
.flags = 0,
.poolset_file_src = NULL,
.poolset_file_dst = NULL,
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Modify internal structure of a poolset\n"
"\n"
"Common options:\n"
" -d, --dry-run do not apply changes, only check for viability of"
" transformation\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-transform(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"dry-run", no_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("usage: %s transform [<options>] <poolset_file_src>"
" <poolset_file_dst>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_transform_help -- print help message for the transform command
*/
void
pmempool_transform_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_check_parse_args -- parse command line arguments
*/
static int
pmempool_transform_parse_args(struct pmempool_transform_context *ctx,
const char *appname, int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "dhv",
long_options, NULL)) != -1) {
switch (opt) {
case 'd':
ctx->flags = PMEMPOOL_TRANSFORM_DRY_RUN;
break;
case 'h':
pmempool_transform_help(appname);
exit(EXIT_SUCCESS);
case 'v':
out_set_vlevel(1);
break;
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind + 1 < argc) {
ctx->poolset_file_src = argv[optind];
ctx->poolset_file_dst = argv[optind + 1];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* pmempool_transform_func -- main function for the transform command
*/
int
pmempool_transform_func(const char *appname, int argc, char *argv[])
{
int ret;
struct pmempool_transform_context ctx = pmempool_transform_default;
/* parse command line arguments */
if ((ret = pmempool_transform_parse_args(&ctx, appname, argc, argv)))
return ret;
ret = pmempool_transform(ctx.poolset_file_src, ctx.poolset_file_dst,
ctx.flags);
if (ret) {
if (errno)
outv_err("%s\n", strerror(errno));
outv_err("failed to transform %s -> %s: %s\n",
ctx.poolset_file_src, ctx.poolset_file_dst,
pmempool_errormsg());
return -1;
} else {
outv(1, "%s -> %s: transformed\n", ctx.poolset_file_src,
ctx.poolset_file_dst);
return 0;
}
}
| 3,689 | 21.919255 | 77 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/pmempool/info_blk.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, 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.
*/
/*
* info_blk.c -- pmempool info command source file for blk pool
*/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <sys/param.h>
#include <endian.h>
#include "os.h"
#include "common.h"
#include "output.h"
#include "info.h"
#include "btt.h"
/*
* pmempool_info_get_range -- get blocks/data chunk range
*
* Get range based on command line arguments and maximum value.
* Return value:
* 0 - range is empty
* 1 - range is not empty
*/
static int
pmempool_info_get_range(struct pmem_info *pip, struct range *rangep,
struct range *curp, uint32_t max, uint64_t offset)
{
/* not using range */
if (!pip->args.use_range) {
rangep->first = 0;
rangep->last = max;
return 1;
}
if (curp->first > offset + max)
return 0;
if (curp->first >= offset)
rangep->first = curp->first - offset;
else
rangep->first = 0;
if (curp->last < offset)
return 0;
if (curp->last <= offset + max)
rangep->last = curp->last - offset;
else
rangep->last = max;
return 1;
}
/*
* info_blk_skip_block -- get action type for block/data chunk
*
* Return value indicating whether processing block/data chunk
* should be skipped.
*
* Return values:
* 0 - continue processing
* 1 - skip current block
*/
static int
info_blk_skip_block(struct pmem_info *pip, int is_zero,
int is_error)
{
if (pip->args.blk.skip_no_flag && !is_zero && !is_error)
return 1;
if (is_zero && pip->args.blk.skip_zeros)
return 1;
if (is_error && pip->args.blk.skip_error)
return 1;
return 0;
}
/*
* info_btt_data -- print block data and corresponding flags from map
*/
static int
info_btt_data(struct pmem_info *pip, int v, struct btt_info *infop,
uint64_t arena_off, uint64_t offset, uint64_t *countp)
{
if (!outv_check(v))
return 0;
int ret = 0;
size_t mapsize = infop->external_nlba * BTT_MAP_ENTRY_SIZE;
uint32_t *map = malloc(mapsize);
if (!map)
err(1, "Cannot allocate memory for BTT map");
uint8_t *block_buff = malloc(infop->external_lbasize);
if (!block_buff)
err(1, "Cannot allocate memory for pmemblk block buffer");
/* read btt map area */
if (pmempool_info_read(pip, (uint8_t *)map, mapsize,
arena_off + infop->mapoff)) {
outv_err("wrong BTT Map size or offset\n");
ret = -1;
goto error;
}
uint64_t i;
struct range *curp = NULL;
struct range range;
FOREACH_RANGE(curp, &pip->args.ranges) {
if (pmempool_info_get_range(pip, &range, curp,
infop->external_nlba - 1, offset) == 0)
continue;
for (i = range.first; i <= range.last; i++) {
uint32_t map_entry = le32toh(map[i]);
int is_init = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== 0;
int is_zero = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== BTT_MAP_ENTRY_ZERO || is_init;
int is_error = (map_entry & ~BTT_MAP_ENTRY_LBA_MASK)
== BTT_MAP_ENTRY_ERROR;
uint64_t blockno = is_init ? i :
map_entry & BTT_MAP_ENTRY_LBA_MASK;
if (info_blk_skip_block(pip,
is_zero, is_error))
continue;
/* compute block's data address */
uint64_t block_off = arena_off + infop->dataoff +
blockno * infop->internal_lbasize;
if (pmempool_info_read(pip, block_buff,
infop->external_lbasize, block_off)) {
outv_err("cannot read %lu block\n", i);
ret = -1;
goto error;
}
if (*countp == 0)
outv_title(v, "PMEM BLK blocks data");
/*
* Print block number, offset and flags
* from map entry.
*/
outv(v, "Block %10lu: offset: %s\n",
offset + i,
out_get_btt_map_entry(map_entry));
/* dump block's data */
outv_hexdump(v, block_buff, infop->external_lbasize,
block_off, 1);
*countp = *countp + 1;
}
}
error:
free(map);
free(block_buff);
return ret;
}
/*
* info_btt_map -- print all map entries
*/
static int
info_btt_map(struct pmem_info *pip, int v,
struct btt_info *infop, uint64_t arena_off,
uint64_t offset, uint64_t *count)
{
if (!outv_check(v) && !outv_check(pip->args.vstats))
return 0;
int ret = 0;
size_t mapsize = infop->external_nlba * BTT_MAP_ENTRY_SIZE;
uint32_t *map = malloc(mapsize);
if (!map)
err(1, "Cannot allocate memory for BTT map");
/* read btt map area */
if (pmempool_info_read(pip, (uint8_t *)map, mapsize,
arena_off + infop->mapoff)) {
outv_err("wrong BTT Map size or offset\n");
ret = -1;
goto error;
}
uint32_t arena_count = 0;
uint64_t i;
struct range *curp = NULL;
struct range range;
FOREACH_RANGE(curp, &pip->args.ranges) {
if (pmempool_info_get_range(pip, &range, curp,
infop->external_nlba - 1, offset) == 0)
continue;
for (i = range.first; i <= range.last; i++) {
uint32_t entry = le32toh(map[i]);
int is_zero = (entry & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ZERO ||
(entry & ~BTT_MAP_ENTRY_LBA_MASK) == 0;
int is_error = (entry & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ERROR;
if (info_blk_skip_block(pip,
is_zero, is_error) == 0) {
if (arena_count == 0)
outv_title(v, "PMEM BLK BTT Map");
if (is_zero)
pip->blk.stats.zeros++;
if (is_error)
pip->blk.stats.errors++;
if (!is_zero && !is_error)
pip->blk.stats.noflag++;
pip->blk.stats.total++;
arena_count++;
(*count)++;
outv(v, "%010lu: %s\n", offset + i,
out_get_btt_map_entry(entry));
}
}
}
error:
free(map);
return ret;
}
/*
* info_btt_flog -- print all flog entries
*/
static int
info_btt_flog(struct pmem_info *pip, int v,
struct btt_info *infop, uint64_t arena_off)
{
if (!outv_check(v))
return 0;
int ret = 0;
struct btt_flog *flogp = NULL;
struct btt_flog *flogpp = NULL;
uint64_t flog_size = infop->nfree *
roundup(2 * sizeof(struct btt_flog), BTT_FLOG_PAIR_ALIGN);
flog_size = roundup(flog_size, BTT_ALIGNMENT);
uint8_t *buff = malloc(flog_size);
if (!buff)
err(1, "Cannot allocate memory for FLOG entries");
if (pmempool_info_read(pip, buff, flog_size,
arena_off + infop->flogoff)) {
outv_err("cannot read BTT FLOG");
ret = -1;
goto error;
}
outv_title(v, "PMEM BLK BTT FLOG");
uint8_t *ptr = buff;
uint32_t i;
for (i = 0; i < infop->nfree; i++) {
flogp = (struct btt_flog *)ptr;
flogpp = flogp + 1;
btt_flog_convert2h(flogp);
btt_flog_convert2h(flogpp);
outv(v, "%010d:\n", i);
outv_field(v, "LBA", "0x%08x", flogp->lba);
outv_field(v, "Old map", "0x%08x: %s", flogp->old_map,
out_get_btt_map_entry(flogp->old_map));
outv_field(v, "New map", "0x%08x: %s", flogp->new_map,
out_get_btt_map_entry(flogp->new_map));
outv_field(v, "Seq", "0x%x", flogp->seq);
outv_field(v, "LBA'", "0x%08x", flogpp->lba);
outv_field(v, "Old map'", "0x%08x: %s", flogpp->old_map,
out_get_btt_map_entry(flogpp->old_map));
outv_field(v, "New map'", "0x%08x: %s", flogpp->new_map,
out_get_btt_map_entry(flogpp->new_map));
outv_field(v, "Seq'", "0x%x", flogpp->seq);
ptr += BTT_FLOG_PAIR_ALIGN;
}
error:
free(buff);
return ret;
}
/*
* info_btt_stats -- print btt related statistics
*/
static void
info_btt_stats(struct pmem_info *pip, int v)
{
if (pip->blk.stats.total > 0) {
outv_title(v, "PMEM BLK Statistics");
double perc_zeros = (double)pip->blk.stats.zeros /
(double)pip->blk.stats.total * 100.0;
double perc_errors = (double)pip->blk.stats.errors /
(double)pip->blk.stats.total * 100.0;
double perc_noflag = (double)pip->blk.stats.noflag /
(double)pip->blk.stats.total * 100.0;
outv_field(v, "Total blocks", "%u", pip->blk.stats.total);
outv_field(v, "Zeroed blocks", "%u [%s]", pip->blk.stats.zeros,
out_get_percentage(perc_zeros));
outv_field(v, "Error blocks", "%u [%s]", pip->blk.stats.errors,
out_get_percentage(perc_errors));
outv_field(v, "Blocks without flag", "%u [%s]",
pip->blk.stats.noflag,
out_get_percentage(perc_noflag));
}
}
/*
* info_btt_info -- print btt_info structure fields
*/
static int
info_btt_info(struct pmem_info *pip, int v, struct btt_info *infop)
{
outv_field(v, "Signature", "%.*s", BTTINFO_SIG_LEN, infop->sig);
outv_field(v, "UUID of container", "%s",
out_get_uuid_str(infop->parent_uuid));
outv_field(v, "Flags", "0x%x", infop->flags);
outv_field(v, "Major", "%d", infop->major);
outv_field(v, "Minor", "%d", infop->minor);
outv_field(v, "External LBA size", "%s",
out_get_size_str(infop->external_lbasize,
pip->args.human));
outv_field(v, "External LBA count", "%u", infop->external_nlba);
outv_field(v, "Internal LBA size", "%s",
out_get_size_str(infop->internal_lbasize,
pip->args.human));
outv_field(v, "Internal LBA count", "%u", infop->internal_nlba);
outv_field(v, "Free blocks", "%u", infop->nfree);
outv_field(v, "Info block size", "%s",
out_get_size_str(infop->infosize, pip->args.human));
outv_field(v, "Next arena offset", "0x%lx", infop->nextoff);
outv_field(v, "Arena data offset", "0x%lx", infop->dataoff);
outv_field(v, "Area map offset", "0x%lx", infop->mapoff);
outv_field(v, "Area flog offset", "0x%lx", infop->flogoff);
outv_field(v, "Info block backup offset", "0x%lx", infop->infooff);
outv_field(v, "Checksum", "%s", out_get_checksum(infop,
sizeof(*infop), &infop->checksum, 0));
return 0;
}
/*
* info_btt_layout -- print information about BTT layout
*/
static int
info_btt_layout(struct pmem_info *pip, os_off_t btt_off)
{
int ret = 0;
if (btt_off <= 0) {
outv_err("wrong BTT layout offset\n");
return -1;
}
struct btt_info *infop = NULL;
infop = malloc(sizeof(struct btt_info));
if (!infop)
err(1, "Cannot allocate memory for BTT Info structure");
int narena = 0;
uint64_t cur_lba = 0;
uint64_t count_data = 0;
uint64_t count_map = 0;
uint64_t offset = (uint64_t)btt_off;
uint64_t nextoff = 0;
do {
/* read btt info area */
if (pmempool_info_read(pip, infop, sizeof(*infop), offset)) {
ret = -1;
outv_err("cannot read BTT Info header\n");
goto err;
}
if (util_check_memory((uint8_t *)infop,
sizeof(*infop), 0) == 0) {
outv(1, "\n<No BTT layout>\n");
break;
}
outv(1, "\n[ARENA %d]", narena);
outv_title(1, "PMEM BLK BTT Info Header");
outv_hexdump(pip->args.vhdrdump, infop,
sizeof(*infop), offset, 1);
btt_info_convert2h(infop);
nextoff = infop->nextoff;
/* print btt info fields */
if (info_btt_info(pip, 1, infop)) {
ret = -1;
goto err;
}
/* dump blocks data */
if (info_btt_data(pip, pip->args.vdata,
infop, offset, cur_lba, &count_data)) {
ret = -1;
goto err;
}
/* print btt map entries and get statistics */
if (info_btt_map(pip, pip->args.blk.vmap, infop,
offset, cur_lba, &count_map)) {
ret = -1;
goto err;
}
/* print flog entries */
if (info_btt_flog(pip, pip->args.blk.vflog, infop,
offset)) {
ret = -1;
goto err;
}
/* increment LBA's counter before reading info backup */
cur_lba += infop->external_nlba;
/* read btt info backup area */
if (pmempool_info_read(pip, infop, sizeof(*infop),
offset + infop->infooff)) {
outv_err("wrong BTT Info Backup size or offset\n");
ret = -1;
goto err;
}
outv_title(pip->args.blk.vbackup,
"PMEM BLK BTT Info Header Backup");
if (outv_check(pip->args.blk.vbackup))
outv_hexdump(pip->args.vhdrdump, infop,
sizeof(*infop),
offset + infop->infooff, 1);
btt_info_convert2h(infop);
info_btt_info(pip, pip->args.blk.vbackup, infop);
offset += nextoff;
narena++;
} while (nextoff > 0);
info_btt_stats(pip, pip->args.vstats);
err:
if (infop)
free(infop);
return ret;
}
/*
* info_blk_descriptor -- print pmemblk descriptor
*/
static void
info_blk_descriptor(struct pmem_info *pip, int v, struct pmemblk *pbp)
{
size_t pmemblk_size;
#ifdef DEBUG
pmemblk_size = offsetof(struct pmemblk, write_lock);
#else
pmemblk_size = sizeof(*pbp);
#endif
outv_title(v, "PMEM BLK Header");
/* dump pmemblk header without pool_hdr */
outv_hexdump(pip->args.vhdrdump, (uint8_t *)pbp + sizeof(pbp->hdr),
pmemblk_size - sizeof(pbp->hdr), sizeof(pbp->hdr), 1);
outv_field(v, "Block size", "%s",
out_get_size_str(pbp->bsize, pip->args.human));
outv_field(v, "Is zeroed", pbp->is_zeroed ? "true" : "false");
}
/*
* pmempool_info_blk -- print information about block type pool
*/
int
pmempool_info_blk(struct pmem_info *pip)
{
int ret;
struct pmemblk *pbp = malloc(sizeof(struct pmemblk));
if (!pbp)
err(1, "Cannot allocate memory for pmemblk structure");
if (pmempool_info_read(pip, pbp, sizeof(struct pmemblk), 0)) {
outv_err("cannot read pmemblk header\n");
free(pbp);
return -1;
}
info_blk_descriptor(pip, VERBOSE_DEFAULT, pbp);
ssize_t btt_off = (char *)pbp->data - (char *)pbp->addr;
ret = info_btt_layout(pip, btt_off);
free(pbp);
return ret;
}
/*
* pmempool_info_btt -- print information about btt device
*/
int
pmempool_info_btt(struct pmem_info *pip)
{
int ret;
outv(1, "\nBTT Device");
ret = info_btt_layout(pip, DEFAULT_HDR_SIZE);
return ret;
}
| 14,565 | 24.644366 | 74 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/pmempool/info_obj.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info_obj.c -- pmempool info command source file for obj pool
*/
#include <stdlib.h>
#include <stdbool.h>
#include <err.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <assert.h>
#include <inttypes.h>
#include "alloc_class.h"
#include "set.h"
#include "common.h"
#include "output.h"
#include "info.h"
#include "util.h"
#define BITMAP_BUFF_SIZE 1024
#define OFF_TO_PTR(pop, off) ((void *)((uintptr_t)(pop) + (off)))
#define PTR_TO_OFF(pop, ptr) ((uintptr_t)(ptr) - (uintptr_t)(pop))
/*
* lane_need_recovery -- return 1 if lane section needs recovery
*/
static int
lane_need_recovery(struct pmem_info *pip, struct lane_layout *lane)
{
return ulog_recovery_needed((struct ulog *)&lane->external, 1) ||
ulog_recovery_needed((struct ulog *)&lane->internal, 1) ||
ulog_recovery_needed((struct ulog *)&lane->undo, 0);
}
#define RUN_BITMAP_SEPARATOR_DISTANCE 8
/*
* get_bitmap_str -- get bitmap single value string
*/
static const char *
get_bitmap_str(uint64_t val, unsigned values)
{
static char buff[BITMAP_BUFF_SIZE];
unsigned j = 0;
for (unsigned i = 0; i < values && j < BITMAP_BUFF_SIZE - 3; i++) {
buff[j++] = ((val & ((uint64_t)1 << i)) ? 'x' : '.');
if ((i + 1) % RUN_BITMAP_SEPARATOR_DISTANCE == 0)
buff[j++] = ' ';
}
buff[j] = '\0';
return buff;
}
/*
* pmem_obj_stats_get_type -- get stats for specified type number
*/
static struct pmem_obj_type_stats *
pmem_obj_stats_get_type(struct pmem_obj_stats *stats, uint64_t type_num)
{
struct pmem_obj_type_stats *type;
struct pmem_obj_type_stats *type_dest = NULL;
PMDK_TAILQ_FOREACH(type, &stats->type_stats, next) {
if (type->type_num == type_num)
return type;
if (!type_dest && type->type_num > type_num)
type_dest = type;
}
type = calloc(1, sizeof(*type));
if (!type) {
outv_err("cannot allocate memory for type stats\n");
exit(EXIT_FAILURE);
}
type->type_num = type_num;
if (type_dest)
PMDK_TAILQ_INSERT_BEFORE(type_dest, type, next);
else
PMDK_TAILQ_INSERT_TAIL(&stats->type_stats, type, next);
return type;
}
struct info_obj_redo_args {
int v;
size_t i;
struct pmem_info *pip;
};
/*
* info_obj_redo_entry - print redo log entry info
*/
static int
info_obj_redo_entry(struct ulog_entry_base *e, void *arg,
const struct pmem_ops *p_ops)
{
struct info_obj_redo_args *a = arg;
struct ulog_entry_val *ev;
struct ulog_entry_buf *eb;
switch (ulog_entry_type(e)) {
case ULOG_OPERATION_AND:
case ULOG_OPERATION_OR:
case ULOG_OPERATION_SET:
ev = (struct ulog_entry_val *)e;
outv(a->v, "%010zu: "
"Offset: 0x%016jx "
"Value: 0x%016jx ",
a->i++,
ulog_entry_offset(e),
ev->value);
break;
case ULOG_OPERATION_BUF_CPY:
case ULOG_OPERATION_BUF_SET:
eb = (struct ulog_entry_buf *)e;
outv(a->v, "%010zu: "
"Offset: 0x%016jx "
"Size: %s ",
a->i++,
ulog_entry_offset(e),
out_get_size_str(eb->size,
a->pip->args.human));
break;
default:
ASSERT(0); /* unreachable */
}
return 0;
}
/*
* info_obj_redo -- print ulog log entries
*/
static void
info_obj_ulog(struct pmem_info *pip, int v, struct ulog *ulog,
const struct pmem_ops *ops)
{
outv_title(v, "Log entries");
struct info_obj_redo_args args = {v, 0, pip};
ulog_foreach_entry(ulog, info_obj_redo_entry, &args, ops,NULL);
}
/*
* info_obj_alloc_hdr -- print allocation header
*/
static void
info_obj_alloc_hdr(struct pmem_info *pip, int v,
const struct memory_block *m)
{
outv_title(v, "Allocation Header");
outv_field(v, "Size", "%s", out_get_size_str(m->m_ops->get_user_size(m),
pip->args.human));
outv_field(v, "Extra", "%lu", m->m_ops->get_extra(m));
outv_field(v, "Flags", "0x%x", m->m_ops->get_flags(m));
}
/*
* info_obj_object_hdr -- print object headers and data
*/
static void
info_obj_object_hdr(struct pmem_info *pip, int v, int vid,
const struct memory_block *m, uint64_t id)
{
struct pmemobjpool *pop = pip->obj.pop;
void *data = m->m_ops->get_user_data(m);
outv_nl(vid);
outv_field(vid, "Object", "%lu", id);
outv_field(vid, "Offset", "0x%016lx", PTR_TO_OFF(pop, data));
int vahdr = v && pip->args.obj.valloc;
int voobh = v && pip->args.obj.voobhdr;
outv_indent(vahdr || voobh, 1);
info_obj_alloc_hdr(pip, vahdr, m);
outv_hexdump(v && pip->args.vdata, data,
m->m_ops->get_real_size(m),
PTR_TO_OFF(pip->obj.pop, data), 1);
outv_indent(vahdr || voobh, -1);
}
/*
* info_obj_lane_section -- print lane's section
*/
static void
info_obj_lane(struct pmem_info *pip, int v, struct lane_layout *lane)
{
struct pmem_ops p_ops;
p_ops.base = pip->obj.pop;
outv_title(v, "Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->undo, &p_ops);
outv_indent(v, -1);
outv_nl(v);
outv_title(v, "Internal Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->internal, &p_ops);
outv_indent(v, -1);
outv_title(v, "External Undo Log");
outv_indent(v, 1);
info_obj_ulog(pip, v, (struct ulog *)&lane->external, &p_ops);
outv_indent(v, -1);
}
/*
* info_obj_lanes -- print lanes structures
*/
static void
info_obj_lanes(struct pmem_info *pip)
{
int v = pip->args.obj.vlanes;
if (!outv_check(v))
return;
struct pmemobjpool *pop = pip->obj.pop;
/*
* Iterate through all lanes from specified range and print
* specified sections.
*/
struct lane_layout *lanes = (void *)((char *)pip->obj.pop +
pop->lanes_offset);
struct range *curp = NULL;
FOREACH_RANGE(curp, &pip->args.obj.lane_ranges) {
for (uint64_t i = curp->first;
i <= curp->last && i < pop->nlanes; i++) {
/* For -R check print lane only if needs recovery */
if (pip->args.obj.lanes_recovery &&
!lane_need_recovery(pip, &lanes[i]))
continue;
outv_title(v, "Lane %" PRIu64, i);
outv_indent(v, 1);
info_obj_lane(pip, v, &lanes[i]);
outv_indent(v, -1);
}
}
}
/*
* info_obj_heap -- print pmemobj heap headers
*/
static void
info_obj_heap(struct pmem_info *pip)
{
int v = pip->args.obj.vheap;
struct pmemobjpool *pop = pip->obj.pop;
struct heap_layout *layout = OFF_TO_PTR(pop, pop->heap_offset);
struct heap_header *heap = &layout->header;
outv(v, "\nPMEMOBJ Heap Header:\n");
outv_hexdump(v && pip->args.vhdrdump, heap, sizeof(*heap),
pop->heap_offset, 1);
outv_field(v, "Signature", "%s", heap->signature);
outv_field(v, "Major", "%ld", heap->major);
outv_field(v, "Minor", "%ld", heap->minor);
outv_field(v, "Chunk size", "%s",
out_get_size_str(heap->chunksize, pip->args.human));
outv_field(v, "Chunks per zone", "%ld", heap->chunks_per_zone);
outv_field(v, "Checksum", "%s", out_get_checksum(heap, sizeof(*heap),
&heap->checksum, 0));
}
/*
* info_obj_zone -- print information about zone
*/
static void
info_obj_zone_hdr(struct pmem_info *pip, int v, struct zone_header *zone)
{
outv_hexdump(v && pip->args.vhdrdump, zone, sizeof(*zone),
PTR_TO_OFF(pip->obj.pop, zone), 1);
outv_field(v, "Magic", "%s", out_get_zone_magic_str(zone->magic));
outv_field(v, "Size idx", "%u", zone->size_idx);
}
/*
* info_obj_object -- print information about object
*/
static void
info_obj_object(struct pmem_info *pip, const struct memory_block *m,
uint64_t objid)
{
if (!util_ranges_contain(&pip->args.ranges, objid))
return;
uint64_t type_num = m->m_ops->get_extra(m);
if (!util_ranges_contain(&pip->args.obj.type_ranges, type_num))
return;
uint64_t real_size = m->m_ops->get_real_size(m);
pip->obj.stats.n_total_objects++;
pip->obj.stats.n_total_bytes += real_size;
struct pmem_obj_type_stats *type_stats =
pmem_obj_stats_get_type(&pip->obj.stats, type_num);
type_stats->n_objects++;
type_stats->n_bytes += real_size;
int vid = pip->args.obj.vobjects;
int v = pip->args.obj.vobjects;
outv_indent(v, 1);
info_obj_object_hdr(pip, v, vid, m, objid);
outv_indent(v, -1);
}
/*
* info_obj_run_bitmap -- print chunk run's bitmap
*/
static void
info_obj_run_bitmap(int v, struct run_bitmap *b)
{
/* print only used values for lower verbosity */
uint32_t i;
for (i = 0; i < b->nbits / RUN_BITS_PER_VALUE; i++)
outv(v, "%s\n", get_bitmap_str(b->values[i],
RUN_BITS_PER_VALUE));
unsigned mod = b->nbits % RUN_BITS_PER_VALUE;
if (mod != 0) {
outv(v, "%s\n", get_bitmap_str(b->values[i], mod));
}
}
/*
* info_obj_memblock_is_root -- (internal) checks whether the object is root
*/
static int
info_obj_memblock_is_root(struct pmem_info *pip, const struct memory_block *m)
{
uint64_t roff = pip->obj.pop->root_offset;
if (roff == 0)
return 0;
struct memory_block rm = memblock_from_offset(pip->obj.heap, roff);
return MEMORY_BLOCK_EQUALS(*m, rm);
}
/*
* info_obj_run_cb -- (internal) run object callback
*/
static int
info_obj_run_cb(const struct memory_block *m, void *arg)
{
struct pmem_info *pip = arg;
if (info_obj_memblock_is_root(pip, m))
return 0;
info_obj_object(pip, m, pip->obj.objid++);
return 0;
}
static struct pmem_obj_class_stats *
info_obj_class_stats_get_or_insert(struct pmem_obj_zone_stats *stats,
uint64_t unit_size, uint64_t alignment,
uint32_t nallocs, uint16_t flags)
{
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
if (cstats->alignment == alignment &&
cstats->flags == flags &&
cstats->nallocs == nallocs &&
cstats->unit_size == unit_size)
return cstats;
}
struct pmem_obj_class_stats s = {0, 0, unit_size,
alignment, nallocs, flags};
if (VEC_PUSH_BACK(&stats->class_stats, s) != 0)
return NULL;
return &VEC_BACK(&stats->class_stats);
}
/*
* info_obj_chunk -- print chunk info
*/
static void
info_obj_chunk(struct pmem_info *pip, uint64_t c, uint64_t z,
struct chunk_header *chunk_hdr, struct chunk *chunk,
struct pmem_obj_zone_stats *stats)
{
int v = pip->args.obj.vchunkhdr;
outv(v, "\n");
outv_field(v, "Chunk", "%lu", c);
struct pmemobjpool *pop = pip->obj.pop;
outv_hexdump(v && pip->args.vhdrdump, chunk_hdr, sizeof(*chunk_hdr),
PTR_TO_OFF(pop, chunk_hdr), 1);
outv_field(v, "Type", "%s", out_get_chunk_type_str(chunk_hdr->type));
outv_field(v, "Flags", "0x%x %s", chunk_hdr->flags,
out_get_chunk_flags(chunk_hdr->flags));
outv_field(v, "Size idx", "%u", chunk_hdr->size_idx);
struct memory_block m = MEMORY_BLOCK_NONE;
m.zone_id = (uint32_t)z;
m.chunk_id = (uint32_t)c;
m.size_idx = (uint32_t)chunk_hdr->size_idx;
memblock_rebuild_state(pip->obj.heap, &m);
if (chunk_hdr->type == CHUNK_TYPE_USED ||
chunk_hdr->type == CHUNK_TYPE_FREE) {
VEC_FRONT(&stats->class_stats).n_units +=
chunk_hdr->size_idx;
if (chunk_hdr->type == CHUNK_TYPE_USED) {
VEC_FRONT(&stats->class_stats).n_used +=
chunk_hdr->size_idx;
/* skip root object */
if (!info_obj_memblock_is_root(pip, &m)) {
info_obj_object(pip, &m, pip->obj.objid++);
}
}
} else if (chunk_hdr->type == CHUNK_TYPE_RUN) {
struct chunk_run *run = (struct chunk_run *)chunk;
outv_hexdump(v && pip->args.vhdrdump, run,
sizeof(run->hdr.block_size) +
sizeof(run->hdr.alignment),
PTR_TO_OFF(pop, run), 1);
struct run_bitmap bitmap;
m.m_ops->get_bitmap(&m, &bitmap);
struct pmem_obj_class_stats *cstats =
info_obj_class_stats_get_or_insert(stats,
run->hdr.block_size, run->hdr.alignment, bitmap.nbits,
chunk_hdr->flags);
if (cstats == NULL) {
outv_err("out of memory, can't allocate statistics");
return;
}
outv_field(v, "Block size", "%s",
out_get_size_str(run->hdr.block_size,
pip->args.human));
uint32_t units = bitmap.nbits;
uint32_t free_space = 0;
uint32_t max_free_block = 0;
m.m_ops->calc_free(&m, &free_space, &max_free_block);
uint32_t used = units - free_space;
cstats->n_units += units;
cstats->n_used += used;
outv_field(v, "Bitmap", "%u / %u", used, units);
info_obj_run_bitmap(v && pip->args.obj.vbitmap, &bitmap);
m.m_ops->iterate_used(&m, info_obj_run_cb, pip);
}
}
/*
* info_obj_zone_chunks -- print chunk headers from specified zone
*/
static void
info_obj_zone_chunks(struct pmem_info *pip, struct zone *zone, uint64_t z,
struct pmem_obj_zone_stats *stats)
{
VEC_INIT(&stats->class_stats);
struct pmem_obj_class_stats default_class_stats = {0, 0,
CHUNKSIZE, 0, 0, 0};
VEC_PUSH_BACK(&stats->class_stats, default_class_stats);
uint64_t c = 0;
while (c < zone->header.size_idx) {
enum chunk_type type = zone->chunk_headers[c].type;
uint64_t size_idx = zone->chunk_headers[c].size_idx;
if (util_ranges_contain(&pip->args.obj.chunk_ranges, c)) {
if (pip->args.obj.chunk_types & (1ULL << type)) {
stats->n_chunks++;
stats->n_chunks_type[type]++;
stats->size_chunks += size_idx;
stats->size_chunks_type[type] += size_idx;
info_obj_chunk(pip, c, z,
&zone->chunk_headers[c],
&zone->chunks[c], stats);
}
if (size_idx > 1 && type != CHUNK_TYPE_RUN &&
pip->args.obj.chunk_types &
(1 << CHUNK_TYPE_FOOTER)) {
size_t f = c + size_idx - 1;
info_obj_chunk(pip, f, z,
&zone->chunk_headers[f],
&zone->chunks[f], stats);
}
}
c += size_idx;
}
}
/*
* info_obj_root_obj -- print root object
*/
static void
info_obj_root_obj(struct pmem_info *pip)
{
int v = pip->args.obj.vroot;
struct pmemobjpool *pop = pip->obj.pop;
if (!pop->root_offset) {
outv(v, "\nNo root object...\n");
return;
}
outv_title(v, "Root object");
outv_field(v, "Offset", "0x%016zx", pop->root_offset);
uint64_t root_size = pop->root_size;
outv_field(v, "Size", "%s",
out_get_size_str(root_size, pip->args.human));
struct memory_block m = memblock_from_offset(
pip->obj.heap, pop->root_offset);
/* do not print object id and offset for root object */
info_obj_object_hdr(pip, v, VERBOSE_SILENT, &m, 0);
}
/*
* info_obj_zones -- print zones and chunks
*/
static void
info_obj_zones_chunks(struct pmem_info *pip)
{
if (!outv_check(pip->args.obj.vheap) &&
!outv_check(pip->args.vstats) &&
!outv_check(pip->args.obj.vobjects))
return;
struct pmemobjpool *pop = pip->obj.pop;
struct heap_layout *layout = OFF_TO_PTR(pop, pop->heap_offset);
size_t maxzone = util_heap_max_zone(pop->heap_size);
pip->obj.stats.n_zones = maxzone;
pip->obj.stats.zone_stats = calloc(maxzone,
sizeof(struct pmem_obj_zone_stats));
if (!pip->obj.stats.zone_stats)
err(1, "Cannot allocate memory for zone stats");
for (size_t i = 0; i < maxzone; i++) {
struct zone *zone = ZID_TO_ZONE(layout, i);
if (util_ranges_contain(&pip->args.obj.zone_ranges, i)) {
int vvv = pip->args.obj.vheap &&
(pip->args.obj.vzonehdr ||
pip->args.obj.vchunkhdr);
outv_title(vvv, "Zone %zu", i);
if (zone->header.magic == ZONE_HEADER_MAGIC)
pip->obj.stats.n_zones_used++;
info_obj_zone_hdr(pip, pip->args.obj.vheap &&
pip->args.obj.vzonehdr,
&zone->header);
outv_indent(vvv, 1);
info_obj_zone_chunks(pip, zone, i,
&pip->obj.stats.zone_stats[i]);
outv_indent(vvv, -1);
}
}
}
/*
* info_obj_descriptor -- print pmemobj descriptor
*/
static void
info_obj_descriptor(struct pmem_info *pip)
{
int v = VERBOSE_DEFAULT;
if (!outv_check(v))
return;
outv(v, "\nPMEM OBJ Header:\n");
struct pmemobjpool *pop = pip->obj.pop;
uint8_t *hdrptr = (uint8_t *)pop + sizeof(pop->hdr);
size_t hdrsize = sizeof(*pop) - sizeof(pop->hdr);
size_t hdroff = sizeof(pop->hdr);
outv_hexdump(pip->args.vhdrdump, hdrptr, hdrsize, hdroff, 1);
/* check if layout is zeroed */
char *layout = util_check_memory((uint8_t *)pop->layout,
sizeof(pop->layout), 0) ?
pop->layout : "(null)";
/* address for checksum */
void *dscp = (void *)((uintptr_t)(pop) + sizeof(struct pool_hdr));
outv_field(v, "Layout", "%s", layout);
outv_field(v, "Lanes offset", "0x%lx", pop->lanes_offset);
outv_field(v, "Number of lanes", "%lu", pop->nlanes);
outv_field(v, "Heap offset", "0x%lx", pop->heap_offset);
outv_field(v, "Heap size", "%lu", pop->heap_size);
outv_field(v, "Checksum", "%s", out_get_checksum(dscp, OBJ_DSC_P_SIZE,
&pop->checksum, 0));
outv_field(v, "Root offset", "0x%lx", pop->root_offset);
/* run id with -v option */
outv_field(v + 1, "Run id", "%lu", pop->run_id);
}
/*
* info_obj_stats_objjects -- print objects' statistics
*/
static void
info_obj_stats_objects(struct pmem_info *pip, int v,
struct pmem_obj_stats *stats)
{
outv_field(v, "Number of objects", "%lu",
stats->n_total_objects);
outv_field(v, "Number of bytes", "%s", out_get_size_str(
stats->n_total_bytes, pip->args.human));
outv_title(v, "Objects by type");
outv_indent(v, 1);
struct pmem_obj_type_stats *type_stats;
PMDK_TAILQ_FOREACH(type_stats, &pip->obj.stats.type_stats, next) {
if (!type_stats->n_objects)
continue;
double n_objects_perc = 100.0 *
(double)type_stats->n_objects /
(double)stats->n_total_objects;
double n_bytes_perc = 100.0 *
(double)type_stats->n_bytes /
(double)stats->n_total_bytes;
outv_nl(v);
outv_field(v, "Type number", "%lu", type_stats->type_num);
outv_field(v, "Number of objects", "%lu [%s]",
type_stats->n_objects,
out_get_percentage(n_objects_perc));
outv_field(v, "Number of bytes", "%s [%s]",
out_get_size_str(
type_stats->n_bytes,
pip->args.human),
out_get_percentage(n_bytes_perc));
}
outv_indent(v, -1);
}
/*
* info_boj_stats_alloc_classes -- print allocation classes' statistics
*/
static void
info_obj_stats_alloc_classes(struct pmem_info *pip, int v,
struct pmem_obj_zone_stats *stats)
{
uint64_t total_bytes = 0;
uint64_t total_used = 0;
outv_indent(v, 1);
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
if (cstats->n_units == 0)
continue;
double used_perc = 100.0 *
(double)cstats->n_used / (double)cstats->n_units;
outv_nl(v);
outv_field(v, "Unit size", "%s", out_get_size_str(
cstats->unit_size, pip->args.human));
outv_field(v, "Units", "%lu", cstats->n_units);
outv_field(v, "Used units", "%lu [%s]",
cstats->n_used,
out_get_percentage(used_perc));
uint64_t bytes = cstats->unit_size *
cstats->n_units;
uint64_t used = cstats->unit_size *
cstats->n_used;
total_bytes += bytes;
total_used += used;
double used_bytes_perc = 100.0 * (double)used / (double)bytes;
outv_field(v, "Bytes", "%s",
out_get_size_str(bytes, pip->args.human));
outv_field(v, "Used bytes", "%s [%s]",
out_get_size_str(used, pip->args.human),
out_get_percentage(used_bytes_perc));
}
outv_indent(v, -1);
double used_bytes_perc = total_bytes ? 100.0 *
(double)total_used / (double)total_bytes : 0.0;
outv_nl(v);
outv_field(v, "Total bytes", "%s",
out_get_size_str(total_bytes, pip->args.human));
outv_field(v, "Total used bytes", "%s [%s]",
out_get_size_str(total_used, pip->args.human),
out_get_percentage(used_bytes_perc));
}
/*
* info_obj_stats_chunks -- print chunks' statistics
*/
static void
info_obj_stats_chunks(struct pmem_info *pip, int v,
struct pmem_obj_zone_stats *stats)
{
outv_field(v, "Number of chunks", "%lu", stats->n_chunks);
outv_indent(v, 1);
for (unsigned type = 0; type < MAX_CHUNK_TYPE; type++) {
double type_perc = 100.0 *
(double)stats->n_chunks_type[type] /
(double)stats->n_chunks;
if (stats->n_chunks_type[type]) {
outv_field(v, out_get_chunk_type_str(type),
"%lu [%s]",
stats->n_chunks_type[type],
out_get_percentage(type_perc));
}
}
outv_indent(v, -1);
outv_nl(v);
outv_field(v, "Total chunks size", "%s", out_get_size_str(
stats->size_chunks, pip->args.human));
outv_indent(v, 1);
for (unsigned type = 0; type < MAX_CHUNK_TYPE; type++) {
double type_perc = 100.0 *
(double)stats->size_chunks_type[type] /
(double)stats->size_chunks;
if (stats->size_chunks_type[type]) {
outv_field(v, out_get_chunk_type_str(type),
"%lu [%s]",
stats->size_chunks_type[type],
out_get_percentage(type_perc));
}
}
outv_indent(v, -1);
}
/*
* info_obj_add_zone_stats -- add stats to total
*/
static void
info_obj_add_zone_stats(struct pmem_obj_zone_stats *total,
struct pmem_obj_zone_stats *stats)
{
total->n_chunks += stats->n_chunks;
total->size_chunks += stats->size_chunks;
for (int type = 0; type < MAX_CHUNK_TYPE; type++) {
total->n_chunks_type[type] +=
stats->n_chunks_type[type];
total->size_chunks_type[type] +=
stats->size_chunks_type[type];
}
struct pmem_obj_class_stats *cstats;
VEC_FOREACH_BY_PTR(cstats, &stats->class_stats) {
struct pmem_obj_class_stats *ctotal =
info_obj_class_stats_get_or_insert(total, cstats->unit_size,
cstats->alignment, cstats->nallocs, cstats->flags);
if (ctotal == NULL) {
outv_err("out of memory, can't allocate statistics");
return;
}
ctotal->n_units += cstats->n_units;
ctotal->n_used += cstats->n_used;
}
}
/*
* info_obj_stats_zones -- print zones' statistics
*/
static void
info_obj_stats_zones(struct pmem_info *pip, int v, struct pmem_obj_stats *stats,
struct pmem_obj_zone_stats *total)
{
double used_zones_perc = 100.0 * (double)stats->n_zones_used /
(double)stats->n_zones;
outv_field(v, "Number of zones", "%lu", stats->n_zones);
outv_field(v, "Number of used zones", "%lu [%s]", stats->n_zones_used,
out_get_percentage(used_zones_perc));
outv_indent(v, 1);
for (uint64_t i = 0; i < stats->n_zones_used; i++) {
outv_title(v, "Zone %" PRIu64, i);
struct pmem_obj_zone_stats *zstats = &stats->zone_stats[i];
info_obj_stats_chunks(pip, v, zstats);
outv_title(v, "Zone's allocation classes");
info_obj_stats_alloc_classes(pip, v, zstats);
info_obj_add_zone_stats(total, zstats);
}
outv_indent(v, -1);
}
/*
* info_obj_stats -- print statistics
*/
static void
info_obj_stats(struct pmem_info *pip)
{
int v = pip->args.vstats;
if (!outv_check(v))
return;
struct pmem_obj_stats *stats = &pip->obj.stats;
struct pmem_obj_zone_stats total;
memset(&total, 0, sizeof(total));
outv_title(v, "Statistics");
outv_title(v, "Objects");
info_obj_stats_objects(pip, v, stats);
outv_title(v, "Heap");
info_obj_stats_zones(pip, v, stats, &total);
if (stats->n_zones_used > 1) {
outv_title(v, "Total zone's statistics");
outv_title(v, "Chunks statistics");
info_obj_stats_chunks(pip, v, &total);
outv_title(v, "Allocation classes");
info_obj_stats_alloc_classes(pip, v, &total);
}
VEC_DELETE(&total.class_stats);
}
static struct pmem_info *Pip;
#ifndef _WIN32
static void
info_obj_sa_sigaction(int signum, siginfo_t *info, void *context)
{
uintptr_t offset = (uintptr_t)info->si_addr - (uintptr_t)Pip->obj.pop;
outv_err("Invalid offset 0x%lx\n", offset);
exit(EXIT_FAILURE);
}
static struct sigaction info_obj_sigaction = {
.sa_sigaction = info_obj_sa_sigaction,
.sa_flags = SA_SIGINFO
};
#else
#define CALL_FIRST 1
static LONG CALLBACK
exception_handler(_In_ PEXCEPTION_POINTERS ExceptionInfo)
{
PEXCEPTION_RECORD record = ExceptionInfo->ExceptionRecord;
if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) {
return EXCEPTION_CONTINUE_SEARCH;
}
uintptr_t offset = (uintptr_t)record->ExceptionInformation[1] -
(uintptr_t)Pip->obj.pop;
outv_err("Invalid offset 0x%lx\n", offset);
exit(EXIT_FAILURE);
}
#endif
/*
* info_obj -- print information about obj pool type
*/
int
pmempool_info_obj(struct pmem_info *pip)
{
pip->obj.pop = pool_set_file_map(pip->pfile, 0);
if (pip->obj.pop == NULL)
return -1;
pip->obj.size = pip->pfile->size;
struct palloc_heap *heap = calloc(1, sizeof(*heap));
if (heap == NULL)
err(1, "Cannot allocate memory for heap data");
heap->layout = OFF_TO_PTR(pip->obj.pop, pip->obj.pop->heap_offset);
heap->base = pip->obj.pop;
pip->obj.alloc_classes = alloc_class_collection_new();
pip->obj.heap = heap;
Pip = pip;
#ifndef _WIN32
if (sigaction(SIGSEGV, &info_obj_sigaction, NULL)) {
#else
if (AddVectoredExceptionHandler(CALL_FIRST, exception_handler) ==
NULL) {
#endif
perror("sigaction");
return -1;
}
pip->obj.uuid_lo = pmemobj_get_uuid_lo(pip->obj.pop);
info_obj_descriptor(pip);
info_obj_lanes(pip);
info_obj_root_obj(pip);
info_obj_heap(pip);
info_obj_zones_chunks(pip);
info_obj_stats(pip);
free(heap);
alloc_class_collection_delete(pip->obj.alloc_classes);
return 0;
}
| 24,182 | 24.11215 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/pmempool/check.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* check.c -- pmempool check command source file
*/
#include <getopt.h>
#include <stdlib.h>
#include "common.h"
#include "check.h"
#include "output.h"
#include "set.h"
#include "file.h"
#include "libpmempool.h"
typedef enum
{
CHECK_RESULT_CONSISTENT,
CHECK_RESULT_NOT_CONSISTENT,
CHECK_RESULT_REPAIRED,
CHECK_RESULT_CANNOT_REPAIR,
CHECK_RESULT_SYNC_REQ,
CHECK_RESULT_ERROR
} check_result_t;
/*
* pmempool_check_context -- context and arguments for check command
*/
struct pmempool_check_context {
int verbose; /* verbosity level */
char *fname; /* file name */
struct pool_set_file *pfile;
bool repair; /* do repair */
bool backup; /* do backup */
bool advanced; /* do advanced repairs */
char *backup_fname; /* backup file name */
bool exec; /* do execute */
char ans; /* default answer on all questions or '?' */
};
/*
* pmempool_check_default -- default arguments for check command
*/
static const struct pmempool_check_context pmempool_check_default = {
.verbose = 1,
.fname = NULL,
.repair = false,
.backup = false,
.backup_fname = NULL,
.advanced = false,
.exec = true,
.ans = '?',
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Check consistency of a pool\n"
"\n"
"Common options:\n"
" -r, --repair try to repair a pool file if possible\n"
" -y, --yes answer yes to all questions\n"
" -d, --dry-run don't execute, just show what would be done\n"
" -b, --backup <file> create backup of a pool file before executing\n"
" -a, --advanced perform advanced repairs\n"
" -q, --quiet be quiet and don't print any messages\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-check(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"repair", no_argument, NULL, 'r'},
{"yes", no_argument, NULL, 'y'},
{"dry-run", no_argument, NULL, 'd'},
{"no-exec", no_argument, NULL, 'N'}, /* deprecated */
{"backup", required_argument, NULL, 'b'},
{"advanced", no_argument, NULL, 'a'},
{"quiet", no_argument, NULL, 'q'},
{"verbose", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print short description of application's usage
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s check [<args>] <file>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_check_help -- print help message for check command
*/
void
pmempool_check_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_check_parse_args -- parse command line arguments
*/
static int
pmempool_check_parse_args(struct pmempool_check_context *pcp,
const char *appname, int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "ahvrdNb:qy",
long_options, NULL)) != -1) {
switch (opt) {
case 'r':
pcp->repair = true;
break;
case 'y':
pcp->ans = 'y';
break;
case 'd':
case 'N':
pcp->exec = false;
break;
case 'b':
pcp->backup = true;
pcp->backup_fname = optarg;
break;
case 'a':
pcp->advanced = true;
break;
case 'q':
pcp->verbose = 0;
break;
case 'v':
pcp->verbose = 2;
break;
case 'h':
pmempool_check_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
pcp->fname = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
if (!pcp->repair && !pcp->exec) {
outv_err("'-N' option requires '-r'\n");
exit(EXIT_FAILURE);
}
if (!pcp->repair && pcp->backup) {
outv_err("'-b' option requires '-r'\n");
exit(EXIT_FAILURE);
}
return 0;
}
static check_result_t pmempool_check_2_check_res_t[] =
{
[PMEMPOOL_CHECK_RESULT_CONSISTENT] = CHECK_RESULT_CONSISTENT,
[PMEMPOOL_CHECK_RESULT_NOT_CONSISTENT] = CHECK_RESULT_NOT_CONSISTENT,
[PMEMPOOL_CHECK_RESULT_REPAIRED] = CHECK_RESULT_REPAIRED,
[PMEMPOOL_CHECK_RESULT_CANNOT_REPAIR] = CHECK_RESULT_CANNOT_REPAIR,
[PMEMPOOL_CHECK_RESULT_SYNC_REQ] = CHECK_RESULT_SYNC_REQ,
[PMEMPOOL_CHECK_RESULT_ERROR] = CHECK_RESULT_ERROR,
};
static const char *
check_ask(const char *msg)
{
char answer = ask_Yn('?', "%s", msg);
switch (answer) {
case 'y':
return "yes";
case 'n':
return "no";
default:
return "?";
}
}
static check_result_t
pmempool_check_perform(struct pmempool_check_context *pc)
{
struct pmempool_check_args args = {
.path = pc->fname,
.backup_path = pc->backup_fname,
.pool_type = PMEMPOOL_POOL_TYPE_DETECT,
.flags = PMEMPOOL_CHECK_FORMAT_STR
};
if (pc->repair)
args.flags |= PMEMPOOL_CHECK_REPAIR;
if (!pc->exec)
args.flags |= PMEMPOOL_CHECK_DRY_RUN;
if (pc->advanced)
args.flags |= PMEMPOOL_CHECK_ADVANCED;
if (pc->ans == 'y')
args.flags |= PMEMPOOL_CHECK_ALWAYS_YES;
if (pc->verbose == 2)
args.flags |= PMEMPOOL_CHECK_VERBOSE;
PMEMpoolcheck *ppc = pmempool_check_init(&args, sizeof(args));
if (ppc == NULL)
return CHECK_RESULT_ERROR;
struct pmempool_check_status *status = NULL;
while ((status = pmempool_check(ppc)) != NULL) {
switch (status->type) {
case PMEMPOOL_CHECK_MSG_TYPE_ERROR:
outv(1, "%s\n", status->str.msg);
break;
case PMEMPOOL_CHECK_MSG_TYPE_INFO:
outv(2, "%s\n", status->str.msg);
break;
case PMEMPOOL_CHECK_MSG_TYPE_QUESTION:
status->str.answer = check_ask(status->str.msg);
break;
default:
pmempool_check_end(ppc);
exit(EXIT_FAILURE);
}
}
enum pmempool_check_result ret = pmempool_check_end(ppc);
return pmempool_check_2_check_res_t[ret];
}
/*
* pmempool_check_func -- main function for check command
*/
int
pmempool_check_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
check_result_t res = CHECK_RESULT_CONSISTENT;
struct pmempool_check_context pc = pmempool_check_default;
/* parse command line arguments */
ret = pmempool_check_parse_args(&pc, appname, argc, argv);
if (ret)
return ret;
/* set verbosity level */
out_set_vlevel(pc.verbose);
res = pmempool_check_perform(&pc);
switch (res) {
case CHECK_RESULT_CONSISTENT:
outv(2, "%s: consistent\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_NOT_CONSISTENT:
outv(1, "%s: not consistent\n", pc.fname);
ret = -1;
break;
case CHECK_RESULT_REPAIRED:
outv(1, "%s: repaired\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_CANNOT_REPAIR:
outv(1, "%s: cannot repair\n", pc.fname);
ret = -1;
break;
case CHECK_RESULT_SYNC_REQ:
outv(1, "%s: sync required\n", pc.fname);
ret = 0;
break;
case CHECK_RESULT_ERROR:
if (errno)
outv_err("%s\n", strerror(errno));
if (pc.repair)
outv_err("repairing failed\n");
else
outv_err("checking consistency failed\n");
ret = -1;
break;
default:
outv_err("status unknown\n");
ret = -1;
break;
}
return ret;
}
| 7,163 | 21.670886 | 72 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/src/tools/pmempool/info_log.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* info_log.c -- pmempool info command source file for log pool
*/
#include <stdbool.h>
#include <stdlib.h>
#include <err.h>
#include <sys/mman.h>
#include "common.h"
#include "output.h"
#include "info.h"
/*
* info_log_data -- print used data from log pool
*/
static int
info_log_data(struct pmem_info *pip, int v, struct pmemlog *plp)
{
if (!outv_check(v))
return 0;
uint64_t size_used = plp->write_offset - plp->start_offset;
if (size_used == 0)
return 0;
uint8_t *addr = pool_set_file_map(pip->pfile, plp->start_offset);
if (addr == MAP_FAILED) {
warn("%s", pip->file_name);
outv_err("cannot read pmem log data\n");
return -1;
}
if (pip->args.log.walk == 0) {
outv_title(v, "PMEMLOG data");
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &pip->args.ranges.head, next) {
uint8_t *ptr = addr + curp->first;
if (curp->last >= size_used)
curp->last = size_used - 1;
uint64_t count = curp->last - curp->first + 1;
outv_hexdump(v, ptr, count, curp->first +
plp->start_offset, 1);
size_used -= count;
if (!size_used)
break;
}
} else {
/*
* Walk through used data with fixed chunk size
* passed by user.
*/
uint64_t nchunks = size_used / pip->args.log.walk;
outv_title(v, "PMEMLOG data [chunks: total = %lu size = %ld]",
nchunks, pip->args.log.walk);
struct range *curp = NULL;
PMDK_LIST_FOREACH(curp, &pip->args.ranges.head, next) {
uint64_t i;
for (i = curp->first; i <= curp->last &&
i < nchunks; i++) {
outv(v, "Chunk %10lu:\n", i);
outv_hexdump(v, addr + i * pip->args.log.walk,
pip->args.log.walk,
plp->start_offset +
i * pip->args.log.walk,
1);
}
}
}
return 0;
}
/*
* info_logs_stats -- print log type pool statistics
*/
static void
info_log_stats(struct pmem_info *pip, int v, struct pmemlog *plp)
{
uint64_t size_total = plp->end_offset - plp->start_offset;
uint64_t size_used = plp->write_offset - plp->start_offset;
uint64_t size_avail = size_total - size_used;
if (size_total == 0)
return;
double perc_used = (double)size_used / (double)size_total * 100.0;
double perc_avail = 100.0 - perc_used;
outv_title(v, "PMEM LOG Statistics");
outv_field(v, "Total", "%s",
out_get_size_str(size_total, pip->args.human));
outv_field(v, "Available", "%s [%s]",
out_get_size_str(size_avail, pip->args.human),
out_get_percentage(perc_avail));
outv_field(v, "Used", "%s [%s]",
out_get_size_str(size_used, pip->args.human),
out_get_percentage(perc_used));
}
/*
* info_log_descriptor -- print pmemlog descriptor and return 1 if
* write offset is valid
*/
static int
info_log_descriptor(struct pmem_info *pip, int v, struct pmemlog *plp)
{
outv_title(v, "PMEM LOG Header");
/* dump pmemlog header without pool_hdr */
outv_hexdump(pip->args.vhdrdump, (uint8_t *)plp + sizeof(plp->hdr),
sizeof(*plp) - sizeof(plp->hdr),
sizeof(plp->hdr), 1);
log_convert2h(plp);
int write_offset_valid = plp->write_offset >= plp->start_offset &&
plp->write_offset <= plp->end_offset;
outv_field(v, "Start offset", "0x%lx", plp->start_offset);
outv_field(v, "Write offset", "0x%lx [%s]", plp->write_offset,
write_offset_valid ? "OK":"ERROR");
outv_field(v, "End offset", "0x%lx", plp->end_offset);
return write_offset_valid;
}
/*
* pmempool_info_log -- print information about log type pool
*/
int
pmempool_info_log(struct pmem_info *pip)
{
int ret = 0;
struct pmemlog *plp = malloc(sizeof(struct pmemlog));
if (!plp)
err(1, "Cannot allocate memory for pmemlog structure");
if (pmempool_info_read(pip, plp, sizeof(struct pmemlog), 0)) {
outv_err("cannot read pmemlog header\n");
free(plp);
return -1;
}
if (info_log_descriptor(pip, VERBOSE_DEFAULT, plp)) {
info_log_stats(pip, pip->args.vstats, plp);
ret = info_log_data(pip, pip->args.vdata, plp);
}
free(plp);
return ret;
}
| 3,972 | 23.677019 | 70 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/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/logging/pmdk/src/tools/pmempool/synchronize.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2018, Intel Corporation */
/*
* synchronize.c -- pmempool sync command source file
*/
#include "synchronize.h"
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <endian.h>
#include "common.h"
#include "output.h"
#include "libpmempool.h"
/*
* pmempool_sync_context -- context and arguments for sync command
*/
struct pmempool_sync_context {
unsigned flags; /* flags which modify the command execution */
char *poolset_file; /* a path to a poolset file */
};
/*
* pmempool_sync_default -- default arguments for sync command
*/
static const struct pmempool_sync_context pmempool_sync_default = {
.flags = 0,
.poolset_file = NULL,
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Check consistency of a pool\n"
"\n"
"Common options:\n"
" -b, --bad-blocks fix bad blocks - it requires creating or reading special recovery files\n"
" -d, --dry-run do not apply changes, only check for viability of synchronization\n"
" -v, --verbose increase verbosity level\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-sync(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"bad-blocks", no_argument, NULL, 'b'},
{"dry-run", no_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- (internal) print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("usage: %s sync [<options>] <poolset_file>\n", appname);
}
/*
* print_version -- (internal) print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_sync_help -- print help message for the sync command
*/
void
pmempool_sync_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_sync_parse_args -- (internal) parse command line arguments
*/
static int
pmempool_sync_parse_args(struct pmempool_sync_context *ctx, const char *appname,
int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "bdhv",
long_options, NULL)) != -1) {
switch (opt) {
case 'd':
ctx->flags |= PMEMPOOL_SYNC_DRY_RUN;
break;
case 'b':
ctx->flags |= PMEMPOOL_SYNC_FIX_BAD_BLOCKS;
break;
case 'h':
pmempool_sync_help(appname);
exit(EXIT_SUCCESS);
case 'v':
out_set_vlevel(1);
break;
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
ctx->poolset_file = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
return 0;
}
/*
* pmempool_sync_func -- main function for the sync command
*/
int
pmempool_sync_func(const char *appname, int argc, char *argv[])
{
int ret = 0;
struct pmempool_sync_context ctx = pmempool_sync_default;
/* parse command line arguments */
if ((ret = pmempool_sync_parse_args(&ctx, appname, argc, argv)))
return ret;
ret = pmempool_sync(ctx.poolset_file, ctx.flags);
if (ret) {
outv_err("failed to synchronize: %s\n", pmempool_errormsg());
if (errno)
outv_err("%s\n", strerror(errno));
return -1;
} else {
outv(1, "%s: synchronized\n", ctx.poolset_file);
return 0;
}
}
| 3,499 | 21.151899 | 98 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/tools/daxio/daxio.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* daxio.c -- simple app for reading and writing data from/to
* Device DAX device using mmap instead of file I/O API
*/
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <limits.h>
#include <string.h>
#include <ndctl/libndctl.h>
#include <ndctl/libdaxctl.h>
#include <libpmem.h>
#include "util.h"
#include "os.h"
#include "badblocks.h"
#define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1))
#define ALIGN_DOWN(size, align) ((size) & ~((align) - 1))
#define ERR(fmt, ...)\
do {\
fprintf(stderr, "daxio: " fmt, ##__VA_ARGS__);\
} while (0)
#define FAIL(func)\
do {\
fprintf(stderr, "daxio: %s:%d: %s: %s\n",\
__func__, __LINE__, func, strerror(errno));\
} while (0)
#define USAGE_MESSAGE \
"Usage: daxio [option] ...\n"\
"Valid options:\n"\
" -i, --input=FILE - input device/file (default stdin)\n"\
" -o, --output=FILE - output device/file (default stdout)\n"\
" -k, --skip=BYTES - skip offset for input (default 0)\n"\
" -s, --seek=BYTES - seek offset for output (default 0)\n"\
" -l, --len=BYTES - total length to perform the I/O\n"\
" -b, --clear-bad-blocks=<yes|no> - clear bad blocks (default: yes)\n"\
" -z, --zero - zeroing the device\n"\
" -h. --help - print this help\n"\
" -V, --version - display version of daxio\n"
struct daxio_device {
char *path;
int fd;
size_t size; /* actual file/device size */
int is_devdax;
/* Device DAX only */
size_t align; /* internal device alignment */
char *addr; /* mapping base address */
size_t maplen; /* mapping length */
size_t offset; /* seek or skip */
unsigned major;
unsigned minor;
struct ndctl_ctx *ndctl_ctx;
struct ndctl_region *region; /* parent region */
};
/*
* daxio_context -- context and arguments
*/
struct daxio_context {
size_t len; /* total length of I/O */
int zero;
int clear_bad_blocks;
struct daxio_device src;
struct daxio_device dst;
};
/*
* default context
*/
static struct daxio_context Ctx = {
SIZE_MAX, /* len */
0, /* zero */
1, /* clear_bad_blocks */
{ NULL, -1, SIZE_MAX, 0, 0, NULL, 0, 0, 0, 0, NULL, NULL },
{ NULL, -1, SIZE_MAX, 0, 0, NULL, 0, 0, 0, 0, NULL, NULL },
};
/*
* print_version -- print daxio version
*/
static void
print_version(void)
{
printf("%s\n", SRCVERSION);
}
/*
* print_usage -- print short description of usage
*/
static void
print_usage(void)
{
fprintf(stderr, USAGE_MESSAGE);
}
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"skip", required_argument, NULL, 'k'},
{"seek", required_argument, NULL, 's'},
{"len", required_argument, NULL, 'l'},
{"clear-bad-blocks", required_argument, NULL, 'b'},
{"zero", no_argument, NULL, 'z'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{NULL, 0, NULL, 0 },
};
/*
* parse_args -- (internal) parse command line arguments
*/
static int
parse_args(struct daxio_context *ctx, int argc, char * const argv[])
{
int opt;
size_t offset;
size_t len;
while ((opt = getopt_long(argc, argv, "i:o:k:s:l:b:zhV",
long_options, NULL)) != -1) {
switch (opt) {
case 'i':
ctx->src.path = optarg;
break;
case 'o':
ctx->dst.path = optarg;
break;
case 'k':
if (util_parse_size(optarg, &offset)) {
ERR("'%s' -- invalid input offset\n", optarg);
return -1;
}
ctx->src.offset = offset;
break;
case 's':
if (util_parse_size(optarg, &offset)) {
ERR("'%s' -- invalid output offset\n", optarg);
return -1;
}
ctx->dst.offset = offset;
break;
case 'l':
if (util_parse_size(optarg, &len)) {
ERR("'%s' -- invalid length\n", optarg);
return -1;
}
ctx->len = len;
break;
case 'z':
ctx->zero = 1;
break;
case 'b':
if (strcmp(optarg, "no") == 0) {
ctx->clear_bad_blocks = 0;
} else if (strcmp(optarg, "yes") == 0) {
ctx->clear_bad_blocks = 1;
} else {
ERR(
"'%s' -- invalid argument of the '--clear-bad-blocks' option\n",
optarg);
return -1;
}
break;
case 'h':
print_usage();
exit(EXIT_SUCCESS);
case 'V':
print_version();
exit(EXIT_SUCCESS);
default:
print_usage();
exit(EXIT_FAILURE);
}
}
return 0;
}
/*
* validate_args -- (internal) validate command line arguments
*/
static int
validate_args(struct daxio_context *ctx)
{
if (ctx->zero && ctx->dst.path == NULL) {
ERR("zeroing flag specified but no output file provided\n");
return -1;
}
if (!ctx->zero && ctx->src.path == NULL && ctx->dst.path == NULL) {
ERR("an input file and/or an output file must be provided\n");
return -1;
}
/* if no input file provided, use stdin */
if (ctx->src.path == NULL) {
if (ctx->src.offset != 0) {
ERR(
"skip offset specified but no input file provided\n");
return -1;
}
ctx->src.fd = STDIN_FILENO;
ctx->src.path = "STDIN";
}
/* if no output file provided, use stdout */
if (ctx->dst.path == NULL) {
if (ctx->dst.offset != 0) {
ERR(
"seek offset specified but no output file provided\n");
return -1;
}
ctx->dst.fd = STDOUT_FILENO;
ctx->dst.path = "STDOUT";
}
return 0;
}
/*
* match_dev_dax -- (internal) find Device DAX by major/minor device number
*/
static int
match_dev_dax(struct daxio_device *dev, struct daxctl_region *dax_region)
{
struct daxctl_dev *d;
daxctl_dev_foreach(dax_region, d) {
if (dev->major == (unsigned)daxctl_dev_get_major(d) &&
dev->minor == (unsigned)daxctl_dev_get_minor(d)) {
dev->size = daxctl_dev_get_size(d);
return 1;
}
}
return 0;
}
/*
* find_dev_dax -- (internal) check if device is Device DAX
*
* If there is matching Device DAX, find its region, size and alignment.
*/
static int
find_dev_dax(struct ndctl_ctx *ndctl_ctx, struct daxio_device *dev)
{
struct ndctl_bus *bus = NULL;
struct ndctl_region *region = NULL;
struct ndctl_dax *dax = NULL;
struct daxctl_region *dax_region = NULL;
ndctl_bus_foreach(ndctl_ctx, bus) {
ndctl_region_foreach(bus, region) {
ndctl_dax_foreach(region, dax) {
dax_region = ndctl_dax_get_daxctl_region(dax);
if (match_dev_dax(dev, dax_region)) {
dev->is_devdax = 1;
dev->align = ndctl_dax_get_align(dax);
dev->region = region;
return 1;
}
}
}
}
/* try with dax regions */
struct daxctl_ctx *daxctl_ctx;
if (daxctl_new(&daxctl_ctx))
return 0;
int ret = 0;
daxctl_region_foreach(daxctl_ctx, dax_region) {
if (match_dev_dax(dev, dax_region)) {
dev->is_devdax = 1;
dev->align = daxctl_region_get_align(dax_region);
dev->region = region;
ret = 1;
goto end;
}
}
end:
daxctl_unref(daxctl_ctx);
return ret;
}
/*
* setup_device -- (internal) open/mmap file/device
*/
static int
setup_device(struct ndctl_ctx *ndctl_ctx, struct daxio_device *dev, int is_dst,
int clear_bad_blocks)
{
int ret;
int flags = O_RDWR;
int prot = is_dst ? PROT_WRITE : PROT_READ;
if (dev->fd != -1) {
dev->size = SIZE_MAX;
return 0; /* stdin/stdout */
}
/* try to open file/device (if exists) */
dev->fd = os_open(dev->path, flags, S_IRUSR|S_IWUSR);
if (dev->fd == -1) {
ret = errno;
if (ret == ENOENT && is_dst) {
/* file does not exist - create it */
flags = O_CREAT|O_WRONLY|O_TRUNC;
dev->size = SIZE_MAX;
dev->fd = os_open(dev->path, flags, S_IRUSR|S_IWUSR);
if (dev->fd == -1) {
FAIL("open");
return -1;
}
return 0;
} else {
ERR("failed to open '%s': %s\n", dev->path,
strerror(errno));
return -1;
}
}
struct stat stbuf;
ret = fstat(dev->fd, &stbuf);
if (ret == -1) {
FAIL("stat");
return -1;
}
/* check if this is regular file or device */
if (S_ISREG(stbuf.st_mode)) {
if (is_dst)
dev->size = SIZE_MAX;
else
dev->size = (size_t)stbuf.st_size;
} else if (S_ISBLK(stbuf.st_mode)) {
dev->size = (size_t)stbuf.st_size;
} else if (S_ISCHR(stbuf.st_mode)) {
dev->size = SIZE_MAX;
dev->major = major(stbuf.st_rdev);
dev->minor = minor(stbuf.st_rdev);
} else {
return -1;
}
/* check if this is Device DAX */
if (S_ISCHR(stbuf.st_mode))
find_dev_dax(ndctl_ctx, dev);
if (!dev->is_devdax)
return 0;
if (is_dst && clear_bad_blocks) {
/* XXX - clear only badblocks in range bound by offset/len */
if (badblocks_clear_all(dev->path)) {
ERR("failed to clear bad blocks on \"%s\"\n"
" Probably you have not enough permissions to do that.\n"
" You can choose one of three options now:\n"
" 1) run 'daxio' with 'sudo' or as 'root',\n"
" 2) turn off clearing bad blocks using\n"
" the '-b/--clear-bad-blocks=no' option or\n"
" 3) change permissions of some resource files -\n"
" - for details see the description of the CHECK_BAD_BLOCKS\n"
" compat feature in the pmempool-feature(1) man page.\n",
dev->path);
return -1;
}
}
if (dev->align == ULONG_MAX) {
ERR("cannot determine device alignment for \"%s\"\n",
dev->path);
return -1;
}
if (dev->offset > dev->size) {
ERR("'%zu' -- offset beyond device size (%zu)\n",
dev->offset, dev->size);
return -1;
}
/* align len/offset to the internal device alignment */
dev->maplen = ALIGN_UP(dev->size, dev->align);
size_t offset = ALIGN_DOWN(dev->offset, dev->align);
dev->offset = dev->offset - offset;
dev->maplen = dev->maplen - offset;
dev->addr = mmap(NULL, dev->maplen, prot, MAP_SHARED, dev->fd,
(off_t)offset);
if (dev->addr == MAP_FAILED) {
FAIL("mmap");
return -1;
}
return 0;
}
/*
* setup_devices -- (internal) open/mmap input and output
*/
static int
setup_devices(struct ndctl_ctx *ndctl_ctx, struct daxio_context *ctx)
{
if (!ctx->zero &&
setup_device(ndctl_ctx, &ctx->src, 0, ctx->clear_bad_blocks))
return -1;
return setup_device(ndctl_ctx, &ctx->dst, 1, ctx->clear_bad_blocks);
}
/*
* adjust_io_len -- (internal) calculate I/O length if not specified
*/
static void
adjust_io_len(struct daxio_context *ctx)
{
size_t src_len = ctx->src.maplen - ctx->src.offset;
size_t dst_len = ctx->dst.maplen - ctx->dst.offset;
size_t max_len = SIZE_MAX;
if (ctx->zero)
assert(ctx->dst.is_devdax);
else
assert(ctx->src.is_devdax || ctx->dst.is_devdax);
if (ctx->src.is_devdax)
max_len = src_len;
if (ctx->dst.is_devdax)
max_len = max_len < dst_len ? max_len : dst_len;
/* if length is specified and is not bigger than mmapped region */
if (ctx->len != SIZE_MAX && ctx->len <= max_len)
return;
/* adjust len to device size */
ctx->len = max_len;
}
/*
* cleanup_device -- (internal) unmap/close file/device
*/
static void
cleanup_device(struct daxio_device *dev)
{
if (dev->addr)
(void) munmap(dev->addr, dev->maplen);
if (dev->path && dev->fd != -1)
(void) close(dev->fd);
}
/*
* cleanup_devices -- (internal) unmap/close input and output
*/
static void
cleanup_devices(struct daxio_context *ctx)
{
cleanup_device(&ctx->dst);
if (!ctx->zero)
cleanup_device(&ctx->src);
}
/*
* do_io -- (internal) write data to device/file
*/
static int
do_io(struct ndctl_ctx *ndctl_ctx, struct daxio_context *ctx)
{
ssize_t cnt = 0;
assert(ctx->src.is_devdax || ctx->dst.is_devdax);
if (ctx->zero) {
if (ctx->dst.offset > ctx->dst.maplen) {
ERR("output offset larger than device size");
return -1;
}
if (ctx->dst.offset + ctx->len > ctx->dst.maplen) {
ERR("output offset beyond device size");
return -1;
}
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
pmem_memset_persist(dst_addr, 0, ctx->len);
cnt = (ssize_t)ctx->len;
} else if (ctx->src.is_devdax && ctx->dst.is_devdax) {
/* memcpy between src and dst */
char *src_addr = ctx->src.addr + ctx->src.offset;
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
pmem_memcpy_persist(dst_addr, src_addr, ctx->len);
cnt = (ssize_t)ctx->len;
} else if (ctx->src.is_devdax) {
/* write to file directly from mmap'ed src */
char *src_addr = ctx->src.addr + ctx->src.offset;
if (ctx->dst.offset) {
if (lseek(ctx->dst.fd, (off_t)ctx->dst.offset,
SEEK_SET) < 0) {
FAIL("lseek");
goto err;
}
}
do {
ssize_t wcnt = write(ctx->dst.fd, src_addr + cnt,
ctx->len - (size_t)cnt);
if (wcnt == -1) {
FAIL("write");
goto err;
}
cnt += wcnt;
} while ((size_t)cnt < ctx->len);
} else if (ctx->dst.is_devdax) {
/* read from file directly to mmap'ed dst */
char *dst_addr = ctx->dst.addr + ctx->dst.offset;
if (ctx->src.offset) {
if (lseek(ctx->src.fd, (off_t)ctx->src.offset,
SEEK_SET) < 0) {
FAIL("lseek");
return -1;
}
}
do {
ssize_t rcnt = read(ctx->src.fd, dst_addr + cnt,
ctx->len - (size_t)cnt);
if (rcnt == -1) {
FAIL("read");
goto err;
}
/* end of file */
if (rcnt == 0)
break;
cnt = cnt + rcnt;
} while ((size_t)cnt < ctx->len);
pmem_persist(dst_addr, (size_t)cnt);
if ((size_t)cnt != ctx->len)
ERR("requested size %zu larger than source\n",
ctx->len);
}
ERR("copied %zd bytes to device \"%s\"\n", cnt, ctx->dst.path);
return 0;
err:
ERR("failed to perform I/O\n");
return -1;
}
int
main(int argc, char **argv)
{
struct ndctl_ctx *ndctl_ctx;
int ret = EXIT_SUCCESS;
if (parse_args(&Ctx, argc, argv))
return EXIT_FAILURE;
if (validate_args(&Ctx))
return EXIT_FAILURE;
if (ndctl_new(&ndctl_ctx))
return EXIT_FAILURE;
if (setup_devices(ndctl_ctx, &Ctx)) {
ret = EXIT_FAILURE;
goto err;
}
if (!Ctx.src.is_devdax && !Ctx.dst.is_devdax) {
ERR("neither input nor output is device dax\n");
ret = EXIT_FAILURE;
goto err;
}
adjust_io_len(&Ctx);
if (do_io(ndctl_ctx, &Ctx))
ret = EXIT_FAILURE;
err:
cleanup_devices(&Ctx);
ndctl_unref(ndctl_ctx);
return ret;
}
| 14,160 | 22.291118 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/src/libpmemlog/log.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* log.c -- log memory pool entry points for libpmem
*/
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <stdint.h>
#include <stdbool.h>
#include "libpmem.h"
#include "libpmemlog.h"
#include "ctl_global.h"
#include "os.h"
#include "set.h"
#include "out.h"
#include "log.h"
#include "mmap.h"
#include "sys_util.h"
#include "util_pmem.h"
#include "valgrind_internal.h"
static const struct pool_attr Log_create_attr = {
LOG_HDR_SIG,
LOG_FORMAT_MAJOR,
LOG_FORMAT_FEAT_DEFAULT,
{0}, {0}, {0}, {0}, {0}
};
static const struct pool_attr Log_open_attr = {
LOG_HDR_SIG,
LOG_FORMAT_MAJOR,
LOG_FORMAT_FEAT_CHECK,
{0}, {0}, {0}, {0}, {0}
};
/*
* log_descr_create -- (internal) create log memory pool descriptor
*/
static void
log_descr_create(PMEMlogpool *plp, size_t poolsize)
{
LOG(3, "plp %p poolsize %zu", plp, poolsize);
ASSERTeq(poolsize % Pagesize, 0);
/* create required metadata */
plp->start_offset = htole64(roundup(sizeof(*plp),
LOG_FORMAT_DATA_ALIGN));
plp->end_offset = htole64(poolsize);
plp->write_offset = plp->start_offset;
/* store non-volatile part of pool's descriptor */
util_persist(plp->is_pmem, &plp->start_offset, 3 * sizeof(uint64_t));
}
/*
* log_descr_check -- (internal) validate log memory pool descriptor
*/
static int
log_descr_check(PMEMlogpool *plp, size_t poolsize)
{
LOG(3, "plp %p poolsize %zu", plp, poolsize);
struct pmemlog hdr = *plp;
log_convert2h(&hdr);
if ((hdr.start_offset !=
roundup(sizeof(*plp), LOG_FORMAT_DATA_ALIGN)) ||
(hdr.end_offset != poolsize) ||
(hdr.start_offset > hdr.end_offset)) {
ERR("wrong start/end offsets "
"(start: %" PRIu64 " end: %" PRIu64 "), "
"pool size %zu",
hdr.start_offset, hdr.end_offset, poolsize);
errno = EINVAL;
return -1;
}
if ((hdr.write_offset > hdr.end_offset) || (hdr.write_offset <
hdr.start_offset)) {
ERR("wrong write offset (start: %" PRIu64 " end: %" PRIu64
" write: %" PRIu64 ")",
hdr.start_offset, hdr.end_offset, hdr.write_offset);
errno = EINVAL;
return -1;
}
LOG(3, "start: %" PRIu64 ", end: %" PRIu64 ", write: %" PRIu64 "",
hdr.start_offset, hdr.end_offset, hdr.write_offset);
return 0;
}
/*
* log_runtime_init -- (internal) initialize log memory pool runtime data
*/
static int
log_runtime_init(PMEMlogpool *plp, int rdonly)
{
LOG(3, "plp %p rdonly %d", plp, rdonly);
/* remove volatile part of header */
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
sizeof(struct pool_hdr) -
3 * sizeof(uint64_t));
/*
* Use some of the memory pool area for run-time info. This
* run-time state is never loaded from the file, it is always
* created here, so no need to worry about byte-order.
*/
plp->rdonly = rdonly;
if ((plp->rwlockp = Malloc(sizeof(*plp->rwlockp))) == NULL) {
ERR("!Malloc for a RW lock");
return -1;
}
util_rwlock_init(plp->rwlockp);
/*
* If possible, turn off all permissions on the pool header page.
*
* The prototype PMFS doesn't allow this when large pages are in
* use. It is not considered an error if this fails.
*/
RANGE_NONE(plp->addr, sizeof(struct pool_hdr), plp->is_dev_dax);
/* the rest should be kept read-only (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
plp->size - sizeof(struct pool_hdr), plp->is_dev_dax);
return 0;
}
/*
* pmemlog_createU -- create a log memory pool
*/
#ifndef _WIN32
static inline
#endif
PMEMlogpool *
pmemlog_createU(const char *path, size_t poolsize, mode_t mode)
{
LOG(3, "path %s poolsize %zu mode %d", path, poolsize, mode);
struct pool_set *set;
struct pool_attr adj_pool_attr = Log_create_attr;
/* force set SDS feature */
if (SDS_at_create)
adj_pool_attr.features.incompat |= POOL_FEAT_SDS;
else
adj_pool_attr.features.incompat &= ~POOL_FEAT_SDS;
if (util_pool_create(&set, path, poolsize, PMEMLOG_MIN_POOL,
PMEMLOG_MIN_PART, &adj_pool_attr, NULL,
REPLICAS_DISABLED) != 0) {
LOG(2, "cannot create pool or pool set");
return NULL;
}
ASSERT(set->nreplicas > 0);
struct pool_replica *rep = set->replica[0];
PMEMlogpool *plp = rep->part[0].addr;
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
((uintptr_t)&plp->addr - (uintptr_t)&plp->hdr));
plp->addr = plp;
plp->size = rep->repsize;
plp->set = set;
plp->is_pmem = rep->is_pmem;
plp->is_dev_dax = rep->part[0].is_dev_dax;
/* is_dev_dax implies is_pmem */
ASSERT(!plp->is_dev_dax || plp->is_pmem);
/* create pool descriptor */
log_descr_create(plp, rep->repsize);
/* initialize runtime parts */
if (log_runtime_init(plp, 0) != 0) {
ERR("pool initialization failed");
goto err;
}
if (util_poolset_chmod(set, mode))
goto err;
util_poolset_fdclose(set);
LOG(3, "plp %p", plp);
return plp;
err:
LOG(4, "error clean up");
int oerrno = errno;
util_poolset_close(set, DELETE_CREATED_PARTS);
errno = oerrno;
return NULL;
}
#ifndef _WIN32
/*
* pmemlog_create -- create a log memory pool
*/
PMEMlogpool *
pmemlog_create(const char *path, size_t poolsize, mode_t mode)
{
return pmemlog_createU(path, poolsize, mode);
}
#else
/*
* pmemlog_createW -- create a log memory pool
*/
PMEMlogpool *
pmemlog_createW(const wchar_t *path, size_t poolsize, mode_t mode)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return NULL;
PMEMlogpool *ret = pmemlog_createU(upath, poolsize, mode);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* log_open_common -- (internal) open a log memory pool
*
* This routine does all the work, but takes a cow flag so internal
* calls can map a read-only pool if required.
*/
static PMEMlogpool *
log_open_common(const char *path, unsigned flags)
{
LOG(3, "path %s flags 0x%x", path, flags);
struct pool_set *set;
if (util_pool_open(&set, path, PMEMLOG_MIN_PART, &Log_open_attr,
NULL, NULL, flags) != 0) {
LOG(2, "cannot open pool or pool set");
return NULL;
}
ASSERT(set->nreplicas > 0);
struct pool_replica *rep = set->replica[0];
PMEMlogpool *plp = rep->part[0].addr;
VALGRIND_REMOVE_PMEM_MAPPING(&plp->addr,
sizeof(struct pmemlog) -
((uintptr_t)&plp->addr - (uintptr_t)&plp->hdr));
plp->addr = plp;
plp->size = rep->repsize;
plp->set = set;
plp->is_pmem = rep->is_pmem;
plp->is_dev_dax = rep->part[0].is_dev_dax;
/* is_dev_dax implies is_pmem */
ASSERT(!plp->is_dev_dax || plp->is_pmem);
if (set->nreplicas > 1) {
errno = ENOTSUP;
ERR("!replicas not supported");
goto err;
}
/* validate pool descriptor */
if (log_descr_check(plp, rep->repsize) != 0) {
LOG(2, "descriptor check failed");
goto err;
}
/* initialize runtime parts */
if (log_runtime_init(plp, set->rdonly) != 0) {
ERR("pool initialization failed");
goto err;
}
util_poolset_fdclose(set);
LOG(3, "plp %p", plp);
return plp;
err:
LOG(4, "error clean up");
int oerrno = errno;
util_poolset_close(set, DO_NOT_DELETE_PARTS);
errno = oerrno;
return NULL;
}
/*
* pmemlog_openU -- open an existing log memory pool
*/
#ifndef _WIN32
static inline
#endif
PMEMlogpool *
pmemlog_openU(const char *path)
{
LOG(3, "path %s", path);
return log_open_common(path, COW_at_open ? POOL_OPEN_COW : 0);
}
#ifndef _WIN32
/*
* pmemlog_open -- open an existing log memory pool
*/
PMEMlogpool *
pmemlog_open(const char *path)
{
return pmemlog_openU(path);
}
#else
/*
* pmemlog_openW -- open an existing log memory pool
*/
PMEMlogpool *
pmemlog_openW(const wchar_t *path)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return NULL;
PMEMlogpool *ret = pmemlog_openU(upath);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* pmemlog_close -- close a log memory pool
*/
void
pmemlog_close(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_destroy(plp->rwlockp);
Free((void *)plp->rwlockp);
util_poolset_close(plp->set, DO_NOT_DELETE_PARTS);
}
/*
* pmemlog_nbyte -- return usable size of a log memory pool
*/
size_t
pmemlog_nbyte(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_rdlock(plp->rwlockp);
size_t size = le64toh(plp->end_offset) - le64toh(plp->start_offset);
LOG(4, "plp %p nbyte %zu", plp, size);
util_rwlock_unlock(plp->rwlockp);
return size;
}
/*
* log_persist -- (internal) persist data, then metadata
*
* On entry, the write lock should be held.
*/
static void
log_persist(PMEMlogpool *plp, uint64_t new_write_offset)
{
uint64_t old_write_offset = le64toh(plp->write_offset);
size_t length = new_write_offset - old_write_offset;
/* unprotect the log space range (debug version only) */
RANGE_RW((char *)plp->addr + old_write_offset, length, plp->is_dev_dax);
/* persist the data */
if (plp->is_pmem)
pmem_drain(); /* data already flushed */
else
pmem_msync((char *)plp->addr + old_write_offset, length);
/* protect the log space range (debug version only) */
RANGE_RO((char *)plp->addr + old_write_offset, length, plp->is_dev_dax);
/* unprotect the pool descriptor (debug version only) */
RANGE_RW((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
/* write the metadata */
plp->write_offset = htole64(new_write_offset);
/* persist the metadata */
if (plp->is_pmem)
pmem_persist(&plp->write_offset, sizeof(plp->write_offset));
else
pmem_msync(&plp->write_offset, sizeof(plp->write_offset));
/* set the write-protection again (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
}
/*
* pmemlog_append -- add data to a log memory pool
*/
int
pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count)
{
int ret = 0;
LOG(3, "plp %p buf %p count %zu", plp, buf, count);
if (plp->rdonly) {
ERR("can't append to read-only log");
errno = EROFS;
return -1;
}
util_rwlock_wrlock(plp->rwlockp);
/* get the current values */
uint64_t end_offset = le64toh(plp->end_offset);
uint64_t write_offset = le64toh(plp->write_offset);
if (write_offset >= end_offset) {
/* no space left */
errno = ENOSPC;
ERR("!pmemlog_append");
ret = -1;
goto end;
}
/* make sure we don't write past the available space */
if (count > (end_offset - write_offset)) {
errno = ENOSPC;
ERR("!pmemlog_append");
ret = -1;
goto end;
}
char *data = plp->addr;
/*
* unprotect the log space range, where the new data will be stored
* (debug version only)
*/
RANGE_RW(&data[write_offset], count, plp->is_dev_dax);
if (plp->is_pmem)
pmem_memcpy_nodrain(&data[write_offset], buf, count);
else
memcpy(&data[write_offset], buf, count);
/* protect the log space range (debug version only) */
RANGE_RO(&data[write_offset], count, plp->is_dev_dax);
write_offset += count;
/* persist the data and the metadata */
log_persist(plp, write_offset);
end:
util_rwlock_unlock(plp->rwlockp);
return ret;
}
/*
* pmemlog_appendv -- add gathered data to a log memory pool
*/
int
pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt)
{
LOG(3, "plp %p iovec %p iovcnt %d", plp, iov, iovcnt);
int ret = 0;
int i;
if (iovcnt < 0) {
errno = EINVAL;
ERR("iovcnt is less than zero: %d", iovcnt);
return -1;
}
if (plp->rdonly) {
ERR("can't append to read-only log");
errno = EROFS;
return -1;
}
util_rwlock_wrlock(plp->rwlockp);
/* get the current values */
uint64_t end_offset = le64toh(plp->end_offset);
uint64_t write_offset = le64toh(plp->write_offset);
if (write_offset >= end_offset) {
/* no space left */
errno = ENOSPC;
ERR("!pmemlog_appendv");
ret = -1;
goto end;
}
char *data = plp->addr;
uint64_t count = 0;
char *buf;
/* calculate required space */
for (i = 0; i < iovcnt; ++i)
count += iov[i].iov_len;
/* check if there is enough free space */
if (count > (end_offset - write_offset)) {
errno = ENOSPC;
ret = -1;
goto end;
}
/* append the data */
for (i = 0; i < iovcnt; ++i) {
buf = iov[i].iov_base;
count = iov[i].iov_len;
/*
* unprotect the log space range, where the new data will be
* stored (debug version only)
*/
RANGE_RW(&data[write_offset], count, plp->is_dev_dax);
if (plp->is_pmem)
pmem_memcpy_nodrain(&data[write_offset], buf, count);
else
memcpy(&data[write_offset], buf, count);
/*
* protect the log space range (debug version only)
*/
RANGE_RO(&data[write_offset], count, plp->is_dev_dax);
write_offset += count;
}
/* persist the data and the metadata */
log_persist(plp, write_offset);
end:
util_rwlock_unlock(plp->rwlockp);
return ret;
}
/*
* pmemlog_tell -- return current write point in a log memory pool
*/
long long
pmemlog_tell(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
util_rwlock_rdlock(plp->rwlockp);
ASSERT(le64toh(plp->write_offset) >= le64toh(plp->start_offset));
long long wp = (long long)(le64toh(plp->write_offset) -
le64toh(plp->start_offset));
LOG(4, "write offset %lld", wp);
util_rwlock_unlock(plp->rwlockp);
return wp;
}
/*
* pmemlog_rewind -- discard all data, resetting a log memory pool to empty
*/
void
pmemlog_rewind(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
if (plp->rdonly) {
ERR("can't rewind read-only log");
errno = EROFS;
return;
}
util_rwlock_wrlock(plp->rwlockp);
/* unprotect the pool descriptor (debug version only) */
RANGE_RW((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
plp->write_offset = plp->start_offset;
if (plp->is_pmem)
pmem_persist(&plp->write_offset, sizeof(uint64_t));
else
pmem_msync(&plp->write_offset, sizeof(uint64_t));
/* set the write-protection again (debug version only) */
RANGE_RO((char *)plp->addr + sizeof(struct pool_hdr),
LOG_FORMAT_DATA_ALIGN, plp->is_dev_dax);
util_rwlock_unlock(plp->rwlockp);
}
/*
* pmemlog_walk -- walk through all data in a log memory pool
*
* chunksize of 0 means process_chunk gets called once for all data
* as a single chunk.
*/
void
pmemlog_walk(PMEMlogpool *plp, size_t chunksize,
int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg)
{
LOG(3, "plp %p chunksize %zu", plp, chunksize);
/*
* We are assuming that the walker doesn't change the data it's reading
* in place. We prevent everyone from changing the data behind our back
* until we are done with processing it.
*/
util_rwlock_rdlock(plp->rwlockp);
char *data = plp->addr;
uint64_t write_offset = le64toh(plp->write_offset);
uint64_t data_offset = le64toh(plp->start_offset);
size_t len;
if (chunksize == 0) {
/* most common case: process everything at once */
len = write_offset - data_offset;
LOG(3, "length %zu", len);
(*process_chunk)(&data[data_offset], len, arg);
} else {
/*
* Walk through the complete record, chunk by chunk.
* The callback returns 0 to terminate the walk.
*/
while (data_offset < write_offset) {
len = MIN(chunksize, write_offset - data_offset);
if (!(*process_chunk)(&data[data_offset], len, arg))
break;
data_offset += chunksize;
}
}
util_rwlock_unlock(plp->rwlockp);
}
/*
* pmemlog_checkU -- log memory pool consistency check
*
* Returns true if consistent, zero if inconsistent, -1/error if checking
* cannot happen due to other errors.
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_checkU(const char *path)
{
LOG(3, "path \"%s\"", path);
PMEMlogpool *plp = log_open_common(path, POOL_OPEN_COW);
if (plp == NULL)
return -1; /* errno set by log_open_common() */
int consistent = 1;
/* validate pool descriptor */
uint64_t hdr_start = le64toh(plp->start_offset);
uint64_t hdr_end = le64toh(plp->end_offset);
uint64_t hdr_write = le64toh(plp->write_offset);
if (hdr_start != roundup(sizeof(*plp), LOG_FORMAT_DATA_ALIGN)) {
ERR("wrong value of start_offset");
consistent = 0;
}
if (hdr_end != plp->size) {
ERR("wrong value of end_offset");
consistent = 0;
}
if (hdr_start > hdr_end) {
ERR("start_offset greater than end_offset");
consistent = 0;
}
if (hdr_start > hdr_write) {
ERR("start_offset greater than write_offset");
consistent = 0;
}
if (hdr_write > hdr_end) {
ERR("write_offset greater than end_offset");
consistent = 0;
}
pmemlog_close(plp);
if (consistent)
LOG(4, "pool consistency check OK");
return consistent;
}
#ifndef _WIN32
/*
* pmemlog_check -- log memory pool consistency check
*
* Returns true if consistent, zero if inconsistent, -1/error if checking
* cannot happen due to other errors.
*/
int
pmemlog_check(const char *path)
{
return pmemlog_checkU(path);
}
#else
/*
* pmemlog_checkW -- log memory pool consistency check
*/
int
pmemlog_checkW(const wchar_t *path)
{
char *upath = util_toUTF8(path);
if (upath == NULL)
return -1;
int ret = pmemlog_checkU(upath);
util_free_UTF8(upath);
return ret;
}
#endif
/*
* pmemlog_ctl_getU -- programmatically executes a read ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_getU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_READ, arg);
}
/*
* pmemblk_ctl_setU -- programmatically executes a write ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_setU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_WRITE, arg);
}
/*
* pmemlog_ctl_execU -- programmatically executes a runnable ctl query
*/
#ifndef _WIN32
static inline
#endif
int
pmemlog_ctl_execU(PMEMlogpool *plp, const char *name, void *arg)
{
LOG(3, "plp %p name %s arg %p", plp, name, arg);
return ctl_query(plp == NULL ? NULL : plp->ctl, plp,
CTL_QUERY_PROGRAMMATIC, name, CTL_QUERY_RUNNABLE, arg);
}
#ifndef _WIN32
/*
* pmemlog_ctl_get -- programmatically executes a read ctl query
*/
int
pmemlog_ctl_get(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_getU(plp, name, arg);
}
/*
* pmemlog_ctl_set -- programmatically executes a write ctl query
*/
int
pmemlog_ctl_set(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_setU(plp, name, arg);
}
/*
* pmemlog_ctl_exec -- programmatically executes a runnable ctl query
*/
int
pmemlog_ctl_exec(PMEMlogpool *plp, const char *name, void *arg)
{
return pmemlog_ctl_execU(plp, name, arg);
}
#else
/*
* pmemlog_ctl_getW -- programmatically executes a read ctl query
*/
int
pmemlog_ctl_getW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_getU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
/*
* pmemlog_ctl_setW -- programmatically executes a write ctl query
*/
int
pmemlog_ctl_setW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_setU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
/*
* pmemlog_ctl_execW -- programmatically executes a runnable ctl query
*/
int
pmemlog_ctl_execW(PMEMlogpool *plp, const wchar_t *name, void *arg)
{
char *uname = util_toUTF8(name);
if (uname == NULL)
return -1;
int ret = pmemlog_ctl_execU(plp, uname, arg);
util_free_UTF8(uname);
return ret;
}
#endif
#if FAULT_INJECTION
void
pmemlog_inject_fault_at(enum pmem_allocation_type type, int nth,
const char *at)
{
core_inject_fault_at(type, nth, at);
}
int
pmemlog_fault_injection_enabled(void)
{
return core_fault_injection_enabled();
}
#endif
| 19,695 | 20.982143 | 75 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/libpmemlog/libpmemlog.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* libpmemlog.c -- pmem entry points for libpmemlog
*/
#include <stdio.h>
#include <stdint.h>
#include "libpmemlog.h"
#include "ctl_global.h"
#include "pmemcommon.h"
#include "log.h"
/*
* The variable from which the config is directly loaded. The string
* cannot contain any comments or extraneous white characters.
*/
#define LOG_CONFIG_ENV_VARIABLE "PMEMLOG_CONF"
/*
* The variable that points to a config file from which the config is loaded.
*/
#define LOG_CONFIG_FILE_ENV_VARIABLE "PMEMLOG_CONF_FILE"
/*
* log_ctl_init_and_load -- (static) initializes CTL and loads configuration
* from env variable and file
*/
static int
log_ctl_init_and_load(PMEMlogpool *plp)
{
LOG(3, "plp %p", plp);
if (plp != NULL && (plp->ctl = ctl_new()) == NULL) {
LOG(2, "!ctl_new");
return -1;
}
char *env_config = os_getenv(LOG_CONFIG_ENV_VARIABLE);
if (env_config != NULL) {
if (ctl_load_config_from_string(plp ? plp->ctl : NULL,
plp, env_config) != 0) {
LOG(2, "unable to parse config stored in %s "
"environment variable",
LOG_CONFIG_ENV_VARIABLE);
goto err;
}
}
char *env_config_file = os_getenv(LOG_CONFIG_FILE_ENV_VARIABLE);
if (env_config_file != NULL && env_config_file[0] != '\0') {
if (ctl_load_config_from_file(plp ? plp->ctl : NULL,
plp, env_config_file) != 0) {
LOG(2, "unable to parse config stored in %s "
"file (from %s environment variable)",
env_config_file,
LOG_CONFIG_FILE_ENV_VARIABLE);
goto err;
}
}
return 0;
err:
if (plp)
ctl_delete(plp->ctl);
return -1;
}
/*
* log_init -- load-time initialization for log
*
* Called automatically by the run-time loader.
*/
ATTR_CONSTRUCTOR
void
libpmemlog_init(void)
{
ctl_global_register();
if (log_ctl_init_and_load(NULL))
FATAL("error: %s", pmemlog_errormsg());
common_init(PMEMLOG_LOG_PREFIX, PMEMLOG_LOG_LEVEL_VAR,
PMEMLOG_LOG_FILE_VAR, PMEMLOG_MAJOR_VERSION,
PMEMLOG_MINOR_VERSION);
LOG(3, NULL);
}
/*
* libpmemlog_fini -- libpmemlog cleanup routine
*
* Called automatically when the process terminates.
*/
ATTR_DESTRUCTOR
void
libpmemlog_fini(void)
{
LOG(3, NULL);
common_fini();
}
/*
* pmemlog_check_versionU -- see if lib meets application version requirements
*/
#ifndef _WIN32
static inline
#endif
const char *
pmemlog_check_versionU(unsigned major_required, unsigned minor_required)
{
LOG(3, "major_required %u minor_required %u",
major_required, minor_required);
if (major_required != PMEMLOG_MAJOR_VERSION) {
ERR("libpmemlog major version mismatch (need %u, found %u)",
major_required, PMEMLOG_MAJOR_VERSION);
return out_get_errormsg();
}
if (minor_required > PMEMLOG_MINOR_VERSION) {
ERR("libpmemlog minor version mismatch (need %u, found %u)",
minor_required, PMEMLOG_MINOR_VERSION);
return out_get_errormsg();
}
return NULL;
}
#ifndef _WIN32
/*
* pmemlog_check_version -- see if lib meets application version requirements
*/
const char *
pmemlog_check_version(unsigned major_required, unsigned minor_required)
{
return pmemlog_check_versionU(major_required, minor_required);
}
#else
/*
* pmemlog_check_versionW -- see if lib meets application version requirements
*/
const wchar_t *
pmemlog_check_versionW(unsigned major_required, unsigned minor_required)
{
if (pmemlog_check_versionU(major_required, minor_required) != NULL)
return out_get_errormsgW();
else
return NULL;
}
#endif
/*
* pmemlog_set_funcs -- allow overriding libpmemlog's call to malloc, etc.
*/
void
pmemlog_set_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))
{
LOG(3, NULL);
util_set_alloc_funcs(malloc_func, free_func, realloc_func, strdup_func);
}
/*
* pmemlog_errormsgU -- return last error message
*/
#ifndef _WIN32
static inline
#endif
const char *
pmemlog_errormsgU(void)
{
return out_get_errormsg();
}
#ifndef _WIN32
/*
* pmemlog_errormsg -- return last error message
*/
const char *
pmemlog_errormsg(void)
{
return pmemlog_errormsgU();
}
#else
/*
* pmemlog_errormsgW -- return last error message as wchar_t
*/
const wchar_t *
pmemlog_errormsgW(void)
{
return out_get_errormsgW();
}
#endif
| 4,301 | 20.29703 | 78 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/os_windows.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-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_windows.c -- windows abstraction layer
*/
#include <io.h>
#include <sys/locking.h>
#include <errno.h>
#include <pmemcompat.h>
#include <windows.h>
#include "alloc.h"
#include "util.h"
#include "os.h"
#include "out.h"
#define UTF8_BOM "\xEF\xBB\xBF"
/*
* os_open -- open abstraction layer
*/
int
os_open(const char *pathname, int flags, ...)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret;
if (flags & O_CREAT) {
va_list arg;
va_start(arg, flags);
mode_t mode = va_arg(arg, mode_t);
va_end(arg);
ret = _wopen(path, flags, mode);
} else {
ret = _wopen(path, flags);
}
util_free_UTF16(path);
/* BOM skipping should not modify errno */
int orig_errno = errno;
/*
* text files on windows can contain BOM. As we open files
* in binary mode we have to detect bom and skip it
*/
if (ret != -1) {
char bom[3];
if (_read(ret, bom, sizeof(bom)) != 3 ||
memcmp(bom, UTF8_BOM, 3) != 0) {
/* UTF-8 bom not found - reset file to the beginning */
_lseek(ret, 0, SEEK_SET);
}
}
errno = orig_errno;
return ret;
}
/*
* os_fsync -- fsync abstraction layer
*/
int
os_fsync(int fd)
{
HANDLE handle = (HANDLE) _get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
if (!FlushFileBuffers(handle)) {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* os_fsync_dir -- fsync the directory
*/
int
os_fsync_dir(const char *dir_name)
{
/* XXX not used and not implemented */
ASSERT(0);
return -1;
}
/*
* os_stat -- stat abstraction layer
*/
int
os_stat(const char *pathname, os_stat_t *buf)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wstat64(path, buf);
util_free_UTF16(path);
return ret;
}
/*
* os_unlink -- unlink abstraction layer
*/
int
os_unlink(const char *pathname)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wunlink(path);
util_free_UTF16(path);
return ret;
}
/*
* os_access -- access abstraction layer
*/
int
os_access(const char *pathname, int mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _waccess(path, mode);
util_free_UTF16(path);
return ret;
}
/*
* os_skipBOM -- (internal) Skip BOM in file stream
*
* text files on windows can contain BOM. We have to detect bom and skip it.
*/
static void
os_skipBOM(FILE *file)
{
if (file == NULL)
return;
/* BOM skipping should not modify errno */
int orig_errno = errno;
/* UTF-8 BOM */
uint8_t bom[3];
size_t read_num = fread(bom, sizeof(bom[0]), sizeof(bom), file);
if (read_num != ARRAY_SIZE(bom))
goto out;
if (memcmp(bom, UTF8_BOM, ARRAY_SIZE(bom)) != 0) {
/* UTF-8 bom not found - reset file to the beginning */
fseek(file, 0, SEEK_SET);
}
out:
errno = orig_errno;
}
/*
* os_fopen -- fopen abstraction layer
*/
FILE *
os_fopen(const char *pathname, const char *mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return NULL;
wchar_t *wmode = util_toUTF16(mode);
if (wmode == NULL) {
util_free_UTF16(path);
return NULL;
}
FILE *ret = _wfopen(path, wmode);
util_free_UTF16(path);
util_free_UTF16(wmode);
os_skipBOM(ret);
return ret;
}
/*
* os_fdopen -- fdopen abstraction layer
*/
FILE *
os_fdopen(int fd, const char *mode)
{
FILE *ret = fdopen(fd, mode);
os_skipBOM(ret);
return ret;
}
/*
* os_chmod -- chmod abstraction layer
*/
int
os_chmod(const char *pathname, mode_t mode)
{
wchar_t *path = util_toUTF16(pathname);
if (path == NULL)
return -1;
int ret = _wchmod(path, mode);
util_free_UTF16(path);
return ret;
}
/*
* os_mkstemp -- generate a unique temporary filename from template
*/
int
os_mkstemp(char *temp)
{
unsigned rnd;
wchar_t *utemp = util_toUTF16(temp);
if (utemp == NULL)
return -1;
wchar_t *path = _wmktemp(utemp);
if (path == NULL) {
util_free_UTF16(utemp);
return -1;
}
wchar_t *npath = Malloc(sizeof(*npath) * wcslen(path) + _MAX_FNAME);
if (npath == NULL) {
util_free_UTF16(utemp);
return -1;
}
wcscpy(npath, path);
util_free_UTF16(utemp);
/*
* Use rand_s to generate more unique tmp file name than _mktemp do.
* In case with multiple threads and multiple files even after close()
* file name conflicts occurred.
* It resolved issue with synchronous removing
* multiples files by system.
*/
rand_s(&rnd);
int ret = _snwprintf(npath + wcslen(npath), _MAX_FNAME, L"%u", rnd);
if (ret < 0)
goto out;
/*
* Use O_TEMPORARY flag to make sure the file is deleted when
* the last file descriptor is closed. Also, it prevents opening
* this file from another process.
*/
ret = _wopen(npath, O_RDWR | O_CREAT | O_EXCL | O_TEMPORARY,
S_IWRITE | S_IREAD);
out:
Free(npath);
return ret;
}
/*
* os_posix_fallocate -- allocate file space
*/
int
os_posix_fallocate(int fd, os_off_t offset, os_off_t len)
{
/*
* From POSIX:
* "EINVAL -- The len argument was zero or the offset argument was
* less than zero."
*
* From Linux man-page:
* "EINVAL -- offset was less than 0, or len was less than or
* equal to 0"
*/
if (offset < 0 || len <= 0)
return EINVAL;
/*
* From POSIX:
* "EFBIG -- The value of offset+len is greater than the maximum
* file size."
*
* Overflow can't be checked for by _chsize_s, since it only gets
* the sum.
*/
if (offset + len < offset)
return EFBIG;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
return errno;
}
FILE_ATTRIBUTE_TAG_INFO attributes;
if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo,
&attributes, sizeof(attributes))) {
return EINVAL;
}
/*
* To physically allocate space on windows we have to remove
* sparsefile and file compressed flags. This method is much faster
* than using _chsize_s which has terrible performance. Dax on
* windows doesn't support sparse files and file compression so
* this workaround is acceptable.
*/
if (attributes.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) {
DWORD unused;
FILE_SET_SPARSE_BUFFER buffer;
buffer.SetSparse = FALSE;
if (!DeviceIoControl(handle, FSCTL_SET_SPARSE, &buffer,
sizeof(buffer), NULL, 0, &unused,
NULL)) {
return EINVAL;
}
}
if (attributes.FileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
DWORD unused;
USHORT buffer = 0; /* magic undocumented value */
if (!DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
&buffer, sizeof(buffer), NULL, 0,
&unused, NULL)) {
return EINVAL;
}
}
/*
* posix_fallocate should not clobber errno, but
* _filelengthi64 might set errno.
*/
int orig_errno = errno;
__int64 current_size = _filelengthi64(fd);
int file_length_errno = errno;
errno = orig_errno;
if (current_size < 0)
return file_length_errno;
__int64 requested_size = offset + len;
if (requested_size <= current_size)
return 0;
int ret = os_ftruncate(fd, requested_size);
if (ret) {
errno = ret;
return -1;
}
return 0;
}
/*
* os_ftruncate -- truncate a file to a specified length
*/
int
os_ftruncate(int fd, os_off_t length)
{
LARGE_INTEGER distanceToMove = {0};
distanceToMove.QuadPart = length;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!SetFilePointerEx(handle, distanceToMove, NULL, FILE_BEGIN)) {
errno = EINVAL;
return -1;
}
if (!SetEndOfFile(handle)) {
errno = EINVAL;
return -1;
}
return 0;
}
/*
* os_flock -- apply or remove an advisory lock on an open file
*/
int
os_flock(int fd, int operation)
{
int flags = 0;
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
switch (operation & (OS_LOCK_EX | OS_LOCK_SH | OS_LOCK_UN)) {
case OS_LOCK_EX:
case OS_LOCK_SH:
if (operation & OS_LOCK_NB)
flags = _LK_NBLCK;
else
flags = _LK_LOCK;
break;
case OS_LOCK_UN:
flags = _LK_UNLCK;
break;
default:
errno = EINVAL;
return -1;
}
os_off_t filelen = _filelengthi64(fd);
if (filelen < 0)
return -1;
/* for our purpose it's enough to lock the first page of the file */
long len = (filelen > systemInfo.dwPageSize) ?
systemInfo.dwPageSize : (long)filelen;
int res = _locking(fd, flags, len);
if (res != 0 && errno == EACCES)
errno = EWOULDBLOCK; /* for consistency with flock() */
return res;
}
/*
* os_writev -- windows version of writev function
*
* XXX: _write and other similar functions are 32 bit on windows
* if size of data is bigger then 2^32, this function
* will be not atomic.
*/
ssize_t
os_writev(int fd, const struct iovec *iov, int iovcnt)
{
size_t size = 0;
/* XXX: _write is 32 bit on windows */
for (int i = 0; i < iovcnt; i++)
size += iov[i].iov_len;
void *buf = malloc(size);
if (buf == NULL)
return ENOMEM;
char *it_buf = buf;
for (int i = 0; i < iovcnt; i++) {
memcpy(it_buf, iov[i].iov_base, iov[i].iov_len);
it_buf += iov[i].iov_len;
}
ssize_t written = 0;
while (size > 0) {
int ret = _write(fd, buf, size >= MAXUINT ?
MAXUINT : (unsigned)size);
if (ret == -1) {
written = -1;
break;
}
written += ret;
size -= ret;
}
free(buf);
return written;
}
#define NSEC_IN_SEC 1000000000ull
/* number of useconds between 1970-01-01T00:00:00Z and 1601-01-01T00:00:00Z */
#define DELTA_WIN2UNIX (11644473600000000ull)
/*
* clock_gettime -- returns elapsed time since the system was restarted
* or since Epoch, depending on the mode id
*/
int
os_clock_gettime(int id, struct timespec *ts)
{
switch (id) {
case CLOCK_MONOTONIC:
{
LARGE_INTEGER time;
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&time);
ts->tv_sec = time.QuadPart / frequency.QuadPart;
ts->tv_nsec = (long)(
(time.QuadPart % frequency.QuadPart) *
NSEC_IN_SEC / frequency.QuadPart);
}
break;
case CLOCK_REALTIME:
{
FILETIME ctime_ft;
GetSystemTimeAsFileTime(&ctime_ft);
ULARGE_INTEGER ctime = {
.HighPart = ctime_ft.dwHighDateTime,
.LowPart = ctime_ft.dwLowDateTime,
};
ts->tv_sec = (ctime.QuadPart - DELTA_WIN2UNIX * 10)
/ 10000000;
ts->tv_nsec = ((ctime.QuadPart - DELTA_WIN2UNIX * 10)
% 10000000) * 100;
}
break;
default:
SetLastError(EINVAL);
return -1;
}
return 0;
}
/*
* os_setenv -- change or add an environment variable
*/
int
os_setenv(const char *name, const char *value, int overwrite)
{
errno_t err;
/*
* If caller doesn't want to overwrite make sure that a environment
* variable with the same name doesn't exist.
*/
if (!overwrite && getenv(name))
return 0;
/*
* _putenv_s returns a non-zero error code on failure but setenv
* needs to return -1 on failure, let's translate the error code.
*/
if ((err = _putenv_s(name, value)) != 0) {
errno = err;
return -1;
}
return 0;
}
/*
* os_unsetenv -- remove an environment variable
*/
int
os_unsetenv(const char *name)
{
errno_t err;
if ((err = _putenv_s(name, "")) != 0) {
errno = err;
return -1;
}
return 0;
}
/*
* os_getenv -- getenv abstraction layer
*/
char *
os_getenv(const char *name)
{
return getenv(name);
}
/*
* rand_r -- rand_r for windows
*
* XXX: RAND_MAX is equal 0x7fff on Windows, so to get 32 bit random number
* we need to merge two numbers returned by rand_s().
* It is not to the best solution as subsequences returned by rand_s are
* not guaranteed to be independent.
*
* XXX: Windows doesn't implement deterministic thread-safe pseudorandom
* generator (generator which can be initialized by seed ).
* We have to chose between a deterministic nonthread-safe generator
* (rand(), srand()) or a non-deterministic thread-safe generator(rand_s())
* as thread-safety is more important, a seed parameter is ignored in this
* implementation.
*/
unsigned
os_rand_r(unsigned *seedp)
{
UNREFERENCED_PARAMETER(seedp);
unsigned part1, part2;
rand_s(&part1);
rand_s(&part2);
return part1 << 16 | part2;
}
/*
* sys_siglist -- map of signal to human readable messages like sys_siglist
*/
const char * const sys_siglist[] = {
"Unknown signal 0", /* 0 */
"Hangup", /* 1 */
"Interrupt", /* 2 */
"Quit", /* 3 */
"Illegal instruction", /* 4 */
"Trace/breakpoint trap", /* 5 */
"Aborted", /* 6 */
"Bus error", /* 7 */
"Floating point exception", /* 8 */
"Killed", /* 9 */
"User defined signal 1", /* 10 */
"Segmentation fault", /* 11 */
"User defined signal 2", /* 12 */
"Broken pipe", /* 13 */
"Alarm clock", /* 14 */
"Terminated", /* 15 */
"Stack fault", /* 16 */
"Child exited", /* 17 */
"Continued", /* 18 */
"Stopped (signal)", /* 19 */
"Stopped", /* 20 */
"Stopped (tty input)", /* 21 */
"Stopped (tty output)", /* 22 */
"Urgent I/O condition", /* 23 */
"CPU time limit exceeded", /* 24 */
"File size limit exceeded", /* 25 */
"Virtual timer expired", /* 26 */
"Profiling timer expired", /* 27 */
"Window changed", /* 28 */
"I/O possible", /* 29 */
"Power failure", /* 30 */
"Bad system call", /* 31 */
"Unknown signal 32" /* 32 */
};
int sys_siglist_size = ARRAYSIZE(sys_siglist);
/*
* string constants for strsignal
* XXX: ideally this should have the signal number as the suffix but then we
* should use a buffer from thread local storage, so deferring the same till
* we need it
* NOTE: In Linux strsignal uses TLS for the same reason but if it fails to get
* a thread local buffer it falls back to using a static buffer trading the
* thread safety.
*/
#define STR_REALTIME_SIGNAL "Real-time signal"
#define STR_UNKNOWN_SIGNAL "Unknown signal"
/*
* strsignal -- returns a string describing the signal number 'sig'
*
* XXX: According to POSIX, this one is of type 'char *', but in our
* implementation it returns 'const char *'.
*/
const char *
os_strsignal(int sig)
{
if (sig >= 0 && sig < ARRAYSIZE(sys_siglist))
return sys_siglist[sig];
else if (sig >= 34 && sig <= 64)
return STR_REALTIME_SIGNAL;
else
return STR_UNKNOWN_SIGNAL;
}
int
os_execv(const char *path, char *const argv[])
{
wchar_t *wpath = util_toUTF16(path);
if (wpath == NULL)
return -1;
int argc = 0;
while (argv[argc])
argc++;
int ret;
wchar_t **wargv = Zalloc((argc + 1) * sizeof(wargv[0]));
if (!wargv) {
ret = -1;
goto wargv_alloc_failed;
}
for (int i = 0; i < argc; ++i) {
wargv[i] = util_toUTF16(argv[i]);
if (!wargv[i]) {
ret = -1;
goto end;
}
}
intptr_t iret = _wexecv(wpath, wargv);
if (iret == 0)
ret = 0;
else
ret = -1;
end:
for (int i = 0; i < argc; ++i)
util_free_UTF16(wargv[i]);
Free(wargv);
wargv_alloc_failed:
util_free_UTF16(wpath);
return ret;
}
| 16,299 | 20.967655 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/os_thread_posix.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* os_thread_posix.c -- Posix thread abstraction layer
*/
#define _GNU_SOURCE
#include <pthread.h>
#ifdef __FreeBSD__
#include <pthread_np.h>
#endif
#include <semaphore.h>
#include "os_thread.h"
#include "util.h"
typedef struct {
pthread_t thread;
} internal_os_thread_t;
/*
* os_once -- pthread_once abstraction layer
*/
int
os_once(os_once_t *o, void (*func)(void))
{
COMPILE_ERROR_ON(sizeof(os_once_t) < sizeof(pthread_once_t));
return pthread_once((pthread_once_t *)o, func);
}
/*
* os_tls_key_create -- pthread_key_create abstraction layer
*/
int
os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *))
{
COMPILE_ERROR_ON(sizeof(os_tls_key_t) < sizeof(pthread_key_t));
return pthread_key_create((pthread_key_t *)key, destructor);
}
/*
* os_tls_key_delete -- pthread_key_delete abstraction layer
*/
int
os_tls_key_delete(os_tls_key_t key)
{
return pthread_key_delete((pthread_key_t)key);
}
/*
* os_tls_setspecific -- pthread_key_setspecific abstraction layer
*/
int
os_tls_set(os_tls_key_t key, const void *value)
{
return pthread_setspecific((pthread_key_t)key, value);
}
/*
* os_tls_get -- pthread_key_getspecific abstraction layer
*/
void *
os_tls_get(os_tls_key_t key)
{
return pthread_getspecific((pthread_key_t)key);
}
/*
* os_mutex_init -- pthread_mutex_init abstraction layer
*/
int
os_mutex_init(os_mutex_t *__restrict mutex)
{
COMPILE_ERROR_ON(sizeof(os_mutex_t) < sizeof(pthread_mutex_t));
return pthread_mutex_init((pthread_mutex_t *)mutex, NULL);
}
/*
* os_mutex_destroy -- pthread_mutex_destroy abstraction layer
*/
int
os_mutex_destroy(os_mutex_t *__restrict mutex)
{
return pthread_mutex_destroy((pthread_mutex_t *)mutex);
}
/*
* os_mutex_lock -- pthread_mutex_lock abstraction layer
*/
int
os_mutex_lock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_lock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_trylock -- pthread_mutex_trylock abstraction layer
*/
int
os_mutex_trylock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_trylock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_unlock -- pthread_mutex_unlock abstraction layer
*/
int
os_mutex_unlock(os_mutex_t *__restrict mutex)
{
return pthread_mutex_unlock((pthread_mutex_t *)mutex);
}
/*
* os_mutex_timedlock -- pthread_mutex_timedlock abstraction layer
*/
int
os_mutex_timedlock(os_mutex_t *__restrict mutex,
const struct timespec *abstime)
{
return pthread_mutex_timedlock((pthread_mutex_t *)mutex, abstime);
}
/*
* os_rwlock_init -- pthread_rwlock_init abstraction layer
*/
int
os_rwlock_init(os_rwlock_t *__restrict rwlock)
{
COMPILE_ERROR_ON(sizeof(os_rwlock_t) < sizeof(pthread_rwlock_t));
return pthread_rwlock_init((pthread_rwlock_t *)rwlock, NULL);
}
/*
* os_rwlock_destroy -- pthread_rwlock_destroy abstraction layer
*/
int
os_rwlock_destroy(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_destroy((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_rdlock - pthread_rwlock_rdlock abstraction layer
*/
int
os_rwlock_rdlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_rdlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_wrlock -- pthread_rwlock_wrlock abstraction layer
*/
int
os_rwlock_wrlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_wrlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_unlock -- pthread_rwlock_unlock abstraction layer
*/
int
os_rwlock_unlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_tryrdlock -- pthread_rwlock_tryrdlock abstraction layer
*/
int
os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_tryrdlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_tryrwlock -- pthread_rwlock_trywrlock abstraction layer
*/
int
os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock)
{
return pthread_rwlock_trywrlock((pthread_rwlock_t *)rwlock);
}
/*
* os_rwlock_timedrdlock -- pthread_rwlock_timedrdlock abstraction layer
*/
int
os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
return pthread_rwlock_timedrdlock((pthread_rwlock_t *)rwlock, abstime);
}
/*
* os_rwlock_timedwrlock -- pthread_rwlock_timedwrlock abstraction layer
*/
int
os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
return pthread_rwlock_timedwrlock((pthread_rwlock_t *)rwlock, abstime);
}
/*
* os_spin_init -- pthread_spin_init abstraction layer
*/
int
os_spin_init(os_spinlock_t *lock, int pshared)
{
COMPILE_ERROR_ON(sizeof(os_spinlock_t) < sizeof(pthread_spinlock_t));
return pthread_spin_init((pthread_spinlock_t *)lock, pshared);
}
/*
* os_spin_destroy -- pthread_spin_destroy abstraction layer
*/
int
os_spin_destroy(os_spinlock_t *lock)
{
return pthread_spin_destroy((pthread_spinlock_t *)lock);
}
/*
* os_spin_lock -- pthread_spin_lock abstraction layer
*/
int
os_spin_lock(os_spinlock_t *lock)
{
return pthread_spin_lock((pthread_spinlock_t *)lock);
}
/*
* os_spin_unlock -- pthread_spin_unlock abstraction layer
*/
int
os_spin_unlock(os_spinlock_t *lock)
{
return pthread_spin_unlock((pthread_spinlock_t *)lock);
}
/*
* os_spin_trylock -- pthread_spin_trylock abstraction layer
*/
int
os_spin_trylock(os_spinlock_t *lock)
{
return pthread_spin_trylock((pthread_spinlock_t *)lock);
}
/*
* os_cond_init -- pthread_cond_init abstraction layer
*/
int
os_cond_init(os_cond_t *__restrict cond)
{
COMPILE_ERROR_ON(sizeof(os_cond_t) < sizeof(pthread_cond_t));
return pthread_cond_init((pthread_cond_t *)cond, NULL);
}
/*
* os_cond_destroy -- pthread_cond_destroy abstraction layer
*/
int
os_cond_destroy(os_cond_t *__restrict cond)
{
return pthread_cond_destroy((pthread_cond_t *)cond);
}
/*
* os_cond_broadcast -- pthread_cond_broadcast abstraction layer
*/
int
os_cond_broadcast(os_cond_t *__restrict cond)
{
return pthread_cond_broadcast((pthread_cond_t *)cond);
}
/*
* os_cond_signal -- pthread_cond_signal abstraction layer
*/
int
os_cond_signal(os_cond_t *__restrict cond)
{
return pthread_cond_signal((pthread_cond_t *)cond);
}
/*
* os_cond_timedwait -- pthread_cond_timedwait abstraction layer
*/
int
os_cond_timedwait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex, const struct timespec *abstime)
{
return pthread_cond_timedwait((pthread_cond_t *)cond,
(pthread_mutex_t *)mutex, abstime);
}
/*
* os_cond_wait -- pthread_cond_wait abstraction layer
*/
int
os_cond_wait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex)
{
return pthread_cond_wait((pthread_cond_t *)cond,
(pthread_mutex_t *)mutex);
}
/*
* os_thread_create -- pthread_create abstraction layer
*/
int
os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
COMPILE_ERROR_ON(sizeof(os_thread_t) < sizeof(internal_os_thread_t));
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_create(&thread_info->thread, (pthread_attr_t *)attr,
start_routine, arg);
}
/*
* os_thread_join -- pthread_join abstraction layer
*/
int
os_thread_join(os_thread_t *thread, void **result)
{
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_join(thread_info->thread, result);
}
/*
* os_thread_self -- pthread_self abstraction layer
*/
void
os_thread_self(os_thread_t *thread)
{
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
thread_info->thread = pthread_self();
}
/*
* os_thread_atfork -- pthread_atfork abstraction layer
*/
int
os_thread_atfork(void (*prepare)(void), void (*parent)(void),
void (*child)(void))
{
return pthread_atfork(prepare, parent, child);
}
/*
* os_thread_setaffinity_np -- pthread_atfork abstraction layer
*/
int
os_thread_setaffinity_np(os_thread_t *thread, size_t set_size,
const os_cpu_set_t *set)
{
COMPILE_ERROR_ON(sizeof(os_cpu_set_t) < sizeof(cpu_set_t));
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
return pthread_setaffinity_np(thread_info->thread, set_size,
(cpu_set_t *)set);
}
/*
* os_cpu_zero -- CP_ZERO abstraction layer
*/
void
os_cpu_zero(os_cpu_set_t *set)
{
CPU_ZERO((cpu_set_t *)set);
}
/*
* os_cpu_set -- CP_SET abstraction layer
*/
void
os_cpu_set(size_t cpu, os_cpu_set_t *set)
{
CPU_SET(cpu, (cpu_set_t *)set);
}
/*
* os_semaphore_init -- initializes semaphore instance
*/
int
os_semaphore_init(os_semaphore_t *sem, unsigned value)
{
COMPILE_ERROR_ON(sizeof(os_semaphore_t) < sizeof(sem_t));
return sem_init((sem_t *)sem, 0, value);
}
/*
* os_semaphore_destroy -- destroys a semaphore instance
*/
int
os_semaphore_destroy(os_semaphore_t *sem)
{
return sem_destroy((sem_t *)sem);
}
/*
* os_semaphore_wait -- decreases the value of the semaphore
*/
int
os_semaphore_wait(os_semaphore_t *sem)
{
return sem_wait((sem_t *)sem);
}
/*
* os_semaphore_trywait -- tries to decrease the value of the semaphore
*/
int
os_semaphore_trywait(os_semaphore_t *sem)
{
return sem_trywait((sem_t *)sem);
}
/*
* os_semaphore_post -- increases the value of the semaphore
*/
int
os_semaphore_post(os_semaphore_t *sem)
{
return sem_post((sem_t *)sem);
}
| 9,190 | 20.032037 | 72 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/util.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* util.c -- very basic utilities
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <endian.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#include "util.h"
#include "os.h"
#include "valgrind_internal.h"
#include "alloc.h"
/* library-wide page size */
unsigned long long Pagesize;
/* allocation/mmap granularity */
unsigned long long Mmap_align;
#if ANY_VG_TOOL_ENABLED
/* Initialized to true if the process is running inside Valgrind. */
unsigned _On_valgrind;
#endif
#if VG_HELGRIND_ENABLED
/* Initialized to true if the process is running inside Valgrind helgrind. */
unsigned _On_helgrind;
#endif
#if VG_DRD_ENABLED
/* Initialized to true if the process is running inside Valgrind drd. */
unsigned _On_drd;
#endif
#if VG_HELGRIND_ENABLED || VG_DRD_ENABLED
/* Initialized to true if the process is running inside Valgrind drd or hg. */
unsigned _On_drd_or_hg;
#endif
#if VG_MEMCHECK_ENABLED
/* Initialized to true if the process is running inside Valgrind memcheck. */
unsigned _On_memcheck;
#endif
#if VG_PMEMCHECK_ENABLED
/* Initialized to true if the process is running inside Valgrind pmemcheck. */
unsigned _On_pmemcheck;
#define LIB_LOG_LEN 20
#define FUNC_LOG_LEN 50
#define SUFFIX_LEN 7
/* true if pmreorder instrumentation has to be enabled */
int _Pmreorder_emit;
/*
* util_emit_log -- emits lib and func name with appropriate suffix
* to pmemcheck store log file
*/
void
util_emit_log(const char *lib, const char *func, int order)
{
char lib_name[LIB_LOG_LEN];
char func_name[FUNC_LOG_LEN];
char suffix[SUFFIX_LEN];
size_t lib_len = strlen(lib);
size_t func_len = strlen(func);
if (order == 0)
strcpy(suffix, ".BEGIN");
else
strcpy(suffix, ".END");
size_t suffix_len = strlen(suffix);
if (lib_len + suffix_len + 1 > LIB_LOG_LEN) {
VALGRIND_EMIT_LOG("Library name is too long");
return;
}
if (func_len + suffix_len + 1 > FUNC_LOG_LEN) {
VALGRIND_EMIT_LOG("Function name is too long");
return;
}
strcpy(lib_name, lib);
strcat(lib_name, suffix);
strcpy(func_name, func);
strcat(func_name, suffix);
if (order == 0) {
VALGRIND_EMIT_LOG(func_name);
VALGRIND_EMIT_LOG(lib_name);
} else {
VALGRIND_EMIT_LOG(lib_name);
VALGRIND_EMIT_LOG(func_name);
}
}
#endif
/*
* util_is_zeroed -- check if given memory range is all zero
*/
int
util_is_zeroed(const void *addr, size_t len)
{
const char *a = addr;
if (len == 0)
return 1;
if (a[0] == 0 && memcmp(a, a + 1, len - 1) == 0)
return 1;
return 0;
}
/*
* util_checksum_compute -- compute Fletcher64-like checksum
*
* csump points to where the checksum lives, so that location
* is treated as zeros while calculating the checksum. The
* checksummed data is assumed to be in little endian order.
*/
uint64_t
util_checksum_compute(void *addr, size_t len, uint64_t *csump, size_t skip_off)
{
if (len % 4 != 0)
abort();
uint32_t *p32 = addr;
uint32_t *p32end = (uint32_t *)((char *)addr + len);
uint32_t *skip;
uint32_t lo32 = 0;
uint32_t hi32 = 0;
if (skip_off)
skip = (uint32_t *)((char *)addr + skip_off);
else
skip = (uint32_t *)((char *)addr + len);
while (p32 < p32end)
if (p32 == (uint32_t *)csump || p32 >= skip) {
/* lo32 += 0; treat first 32-bits as zero */
p32++;
hi32 += lo32;
/* lo32 += 0; treat second 32-bits as zero */
p32++;
hi32 += lo32;
} else {
lo32 += le32toh(*p32);
++p32;
hi32 += lo32;
}
return (uint64_t)hi32 << 32 | lo32;
}
/*
* util_checksum -- compute Fletcher64-like checksum
*
* csump points to where the checksum lives, so that location
* is treated as zeros while calculating the checksum.
* If insert is true, the calculated checksum is inserted into
* the range at *csump. Otherwise the calculated checksum is
* checked against *csump and the result returned (true means
* the range checksummed correctly).
*/
int
util_checksum(void *addr, size_t len, uint64_t *csump,
int insert, size_t skip_off)
{
uint64_t csum = util_checksum_compute(addr, len, csump, skip_off);
if (insert) {
*csump = htole64(csum);
return 1;
}
return *csump == htole64(csum);
}
/*
* util_checksum_seq -- compute sequential Fletcher64-like checksum
*
* Merges checksum from the old buffer with checksum for current buffer.
*/
uint64_t
util_checksum_seq(const void *addr, size_t len, uint64_t csum)
{
if (len % 4 != 0)
abort();
const uint32_t *p32 = addr;
const uint32_t *p32end = (const uint32_t *)((const char *)addr + len);
uint32_t lo32 = (uint32_t)csum;
uint32_t hi32 = (uint32_t)(csum >> 32);
while (p32 < p32end) {
lo32 += le32toh(*p32);
++p32;
hi32 += lo32;
}
return (uint64_t)hi32 << 32 | lo32;
}
/*
* util_fgets -- fgets wrapper with conversion CRLF to LF
*/
char *
util_fgets(char *buffer, int max, FILE *stream)
{
char *str = fgets(buffer, max, stream);
if (str == NULL)
goto end;
int len = (int)strlen(str);
if (len < 2)
goto end;
if (str[len - 2] == '\r' && str[len - 1] == '\n') {
str[len - 2] = '\n';
str[len - 1] = '\0';
}
end:
return str;
}
struct suff {
const char *suff;
uint64_t mag;
};
/*
* util_parse_size -- parse size from string
*/
int
util_parse_size(const char *str, size_t *sizep)
{
const struct suff suffixes[] = {
{ "B", 1ULL },
{ "K", 1ULL << 10 }, /* JEDEC */
{ "M", 1ULL << 20 },
{ "G", 1ULL << 30 },
{ "T", 1ULL << 40 },
{ "P", 1ULL << 50 },
{ "KiB", 1ULL << 10 }, /* IEC */
{ "MiB", 1ULL << 20 },
{ "GiB", 1ULL << 30 },
{ "TiB", 1ULL << 40 },
{ "PiB", 1ULL << 50 },
{ "kB", 1000ULL }, /* SI */
{ "MB", 1000ULL * 1000 },
{ "GB", 1000ULL * 1000 * 1000 },
{ "TB", 1000ULL * 1000 * 1000 * 1000 },
{ "PB", 1000ULL * 1000 * 1000 * 1000 * 1000 }
};
int res = -1;
unsigned i;
size_t size = 0;
char unit[9] = {0};
int ret = sscanf(str, "%zu%8s", &size, unit);
if (ret == 1) {
res = 0;
} else if (ret == 2) {
for (i = 0; i < ARRAY_SIZE(suffixes); ++i) {
if (strcmp(suffixes[i].suff, unit) == 0) {
size = size * suffixes[i].mag;
res = 0;
break;
}
}
} else {
return -1;
}
if (sizep && res == 0)
*sizep = size;
return res;
}
/*
* util_init -- initialize the utils
*
* This is called from the library initialization code.
*/
void
util_init(void)
{
/* XXX - replace sysconf() with util_get_sys_xxx() */
if (Pagesize == 0)
Pagesize = (unsigned long) sysconf(_SC_PAGESIZE);
#ifndef _WIN32
Mmap_align = Pagesize;
#else
if (Mmap_align == 0) {
SYSTEM_INFO si;
GetSystemInfo(&si);
Mmap_align = si.dwAllocationGranularity;
}
#endif
#if ANY_VG_TOOL_ENABLED
_On_valgrind = RUNNING_ON_VALGRIND;
#endif
#if VG_MEMCHECK_ENABLED
if (_On_valgrind) {
unsigned tmp;
unsigned result;
unsigned res = VALGRIND_GET_VBITS(&tmp, &result, sizeof(tmp));
_On_memcheck = res ? 1 : 0;
} else {
_On_memcheck = 0;
}
#endif
#if VG_DRD_ENABLED
if (_On_valgrind)
_On_drd = DRD_GET_DRD_THREADID ? 1 : 0;
else
_On_drd = 0;
#endif
#if VG_HELGRIND_ENABLED
if (_On_valgrind) {
unsigned tmp;
unsigned result;
/*
* As of now (pmem-3.15) VALGRIND_HG_GET_ABITS is broken on
* the upstream version of Helgrind headers. It generates
* a sign-conversion error and actually returns UINT32_MAX-1
* when not running under Helgrind.
*/
long res = VALGRIND_HG_GET_ABITS(&tmp, &result, sizeof(tmp));
_On_helgrind = res != -2 ? 1 : 0;
} else {
_On_helgrind = 0;
}
#endif
#if VG_DRD_ENABLED || VG_HELGRIND_ENABLED
_On_drd_or_hg = (unsigned)(On_helgrind + On_drd);
#endif
#if VG_PMEMCHECK_ENABLED
if (On_valgrind) {
char *pmreorder_env = os_getenv("PMREORDER_EMIT_LOG");
if (pmreorder_env)
_Pmreorder_emit = atoi(pmreorder_env);
VALGRIND_PMC_REGISTER_PMEM_MAPPING(&_On_pmemcheck,
sizeof(_On_pmemcheck));
unsigned pmc = (unsigned)VALGRIND_PMC_CHECK_IS_PMEM_MAPPING(
&_On_pmemcheck, sizeof(_On_pmemcheck));
VALGRIND_PMC_REMOVE_PMEM_MAPPING(&_On_pmemcheck,
sizeof(_On_pmemcheck));
_On_pmemcheck = pmc ? 1 : 0;
} else {
_On_pmemcheck = 0;
_Pmreorder_emit = 0;
}
#endif
}
/*
* util_concat_str -- concatenate two strings
*/
char *
util_concat_str(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1);
if (!result)
return NULL;
strcpy(result, s1);
strcat(result, s2);
return result;
}
/*
* util_localtime -- a wrapper for localtime function
*
* localtime can set nonzero errno even if it succeeds (e.g. when there is no
* /etc/localtime file under Linux) and we do not want the errno to be polluted
* in such cases.
*/
struct tm *
util_localtime(const time_t *timep)
{
int oerrno = errno;
struct tm *tm = localtime(timep);
if (tm != NULL)
errno = oerrno;
return tm;
}
/*
* util_safe_strcpy -- copies string from src to dst, returns -1
* when length of source string (including null-terminator)
* is greater than max_length, 0 otherwise
*
* For gcc (found in version 8.1.1) calling this function with
* max_length equal to dst size produces -Wstringop-truncation warning
*
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85902
*/
#ifdef STRINGOP_TRUNCATION_SUPPORTED
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
#endif
int
util_safe_strcpy(char *dst, const char *src, size_t max_length)
{
if (max_length == 0)
return -1;
strncpy(dst, src, max_length);
return dst[max_length - 1] == '\0' ? 0 : -1;
}
#ifdef STRINGOP_TRUNCATION_SUPPORTED
#pragma GCC diagnostic pop
#endif
#define PARSER_MAX_LINE (PATH_MAX + 1024)
/*
* util_snprintf -- run snprintf; in case of truncation or a failure
* return a negative value, or the number of characters printed otherwise.
*/
int
util_snprintf(char *str, size_t size, const char *format, ...)
{
va_list ap;
va_start(ap, format);
int ret = vsnprintf(str, size, format, ap);
va_end(ap);
if (ret < 0) {
if (!errno)
errno = EIO;
goto err;
} else if ((size_t)ret >= size) {
errno = ENOBUFS;
goto err;
}
return ret;
err:
return -1;
}
/*
* util_readline -- read line from stream
*/
char *
util_readline(FILE *fh)
{
size_t bufsize = PARSER_MAX_LINE;
size_t position = 0;
char *buffer = NULL;
do {
char *tmp = buffer;
buffer = Realloc(buffer, bufsize);
if (buffer == NULL) {
Free(tmp);
return NULL;
}
/* ensure if we can cast bufsize to int */
char *s = util_fgets(buffer + position, (int)bufsize / 2, fh);
if (s == NULL) {
Free(buffer);
return NULL;
}
position = strlen(buffer);
bufsize *= 2;
} while (!feof(fh) && buffer[position - 1] != '\n');
return buffer;
}
| 10,620 | 20.456566 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/os_thread_windows.c
|
// 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_windows.c -- (imperfect) POSIX-like threads for Windows
*
* Loosely inspired by:
* http://locklessinc.com/articles/pthreads_on_windows/
*/
#include <time.h>
#include <synchapi.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include "os_thread.h"
#include "util.h"
#include "out.h"
typedef struct {
unsigned attr;
CRITICAL_SECTION lock;
} internal_os_mutex_t;
typedef struct {
unsigned attr;
char is_write;
SRWLOCK lock;
} internal_os_rwlock_t;
typedef struct {
unsigned attr;
CONDITION_VARIABLE cond;
} internal_os_cond_t;
typedef long long internal_os_once_t;
typedef struct {
HANDLE handle;
} internal_semaphore_t;
typedef struct {
GROUP_AFFINITY affinity;
} internal_os_cpu_set_t;
typedef struct {
HANDLE thread_handle;
void *arg;
void *(*start_routine)(void *);
void *result;
} internal_os_thread_t;
/* number of useconds between 1970-01-01T00:00:00Z and 1601-01-01T00:00:00Z */
#define DELTA_WIN2UNIX (11644473600000000ull)
#define TIMED_LOCK(action, ts) {\
if ((action) == TRUE)\
return 0;\
unsigned long long et = (ts)->tv_sec * 1000000000 + (ts)->tv_nsec;\
while (1) {\
FILETIME _t;\
GetSystemTimeAsFileTime(&_t);\
ULARGE_INTEGER _UI = {\
.HighPart = _t.dwHighDateTime,\
.LowPart = _t.dwLowDateTime,\
};\
if (100 * _UI.QuadPart - 1000 * DELTA_WIN2UNIX >= et)\
return ETIMEDOUT;\
if ((action) == TRUE)\
return 0;\
Sleep(1);\
}\
return ETIMEDOUT;\
}
/*
* os_mutex_init -- initializes mutex
*/
int
os_mutex_init(os_mutex_t *__restrict mutex)
{
COMPILE_ERROR_ON(sizeof(os_mutex_t) < sizeof(internal_os_mutex_t));
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
InitializeCriticalSection(&mutex_internal->lock);
return 0;
}
/*
* os_mutex_destroy -- destroys mutex
*/
int
os_mutex_destroy(os_mutex_t *__restrict mutex)
{
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
DeleteCriticalSection(&mutex_internal->lock);
return 0;
}
/*
* os_mutex_lock -- locks mutex
*/
_Use_decl_annotations_
int
os_mutex_lock(os_mutex_t *__restrict mutex)
{
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
EnterCriticalSection(&mutex_internal->lock);
if (mutex_internal->lock.RecursionCount > 1) {
LeaveCriticalSection(&mutex_internal->lock);
FATAL("deadlock detected");
}
return 0;
}
/*
* os_mutex_trylock -- tries lock mutex
*/
_Use_decl_annotations_
int
os_mutex_trylock(os_mutex_t *__restrict mutex)
{
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
if (TryEnterCriticalSection(&mutex_internal->lock) == FALSE)
return EBUSY;
if (mutex_internal->lock.RecursionCount > 1) {
LeaveCriticalSection(&mutex_internal->lock);
return EBUSY;
}
return 0;
}
/*
* os_mutex_timedlock -- tries lock mutex with timeout
*/
int
os_mutex_timedlock(os_mutex_t *__restrict mutex,
const struct timespec *abstime)
{
TIMED_LOCK((os_mutex_trylock(mutex) == 0), abstime);
}
/*
* os_mutex_unlock -- unlocks mutex
*/
int
os_mutex_unlock(os_mutex_t *__restrict mutex)
{
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
LeaveCriticalSection(&mutex_internal->lock);
return 0;
}
/*
* os_rwlock_init -- initializes rwlock
*/
int
os_rwlock_init(os_rwlock_t *__restrict rwlock)
{
COMPILE_ERROR_ON(sizeof(os_rwlock_t) < sizeof(internal_os_rwlock_t));
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
InitializeSRWLock(&rwlock_internal->lock);
return 0;
}
/*
* os_rwlock_destroy -- destroys rwlock
*/
int
os_rwlock_destroy(os_rwlock_t *__restrict rwlock)
{
/* do nothing */
UNREFERENCED_PARAMETER(rwlock);
return 0;
}
/*
* os_rwlock_rdlock -- get shared lock
*/
int
os_rwlock_rdlock(os_rwlock_t *__restrict rwlock)
{
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
AcquireSRWLockShared(&rwlock_internal->lock);
rwlock_internal->is_write = 0;
return 0;
}
/*
* os_rwlock_wrlock -- get exclusive lock
*/
int
os_rwlock_wrlock(os_rwlock_t *__restrict rwlock)
{
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
AcquireSRWLockExclusive(&rwlock_internal->lock);
rwlock_internal->is_write = 1;
return 0;
}
/*
* os_rwlock_tryrdlock -- tries get shared lock
*/
int
os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock)
{
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
if (TryAcquireSRWLockShared(&rwlock_internal->lock) == FALSE) {
return EBUSY;
} else {
rwlock_internal->is_write = 0;
return 0;
}
}
/*
* os_rwlock_trywrlock -- tries get exclusive lock
*/
_Use_decl_annotations_
int
os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock)
{
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
if (TryAcquireSRWLockExclusive(&rwlock_internal->lock) == FALSE) {
return EBUSY;
} else {
rwlock_internal->is_write = 1;
return 0;
}
}
/*
* os_rwlock_timedrdlock -- gets shared lock with timeout
*/
int
os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
TIMED_LOCK((os_rwlock_tryrdlock(rwlock) == 0), abstime);
}
/*
* os_rwlock_timedwrlock -- gets exclusive lock with timeout
*/
int
os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock,
const struct timespec *abstime)
{
TIMED_LOCK((os_rwlock_trywrlock(rwlock) == 0), abstime);
}
/*
* os_rwlock_unlock -- unlocks rwlock
*/
_Use_decl_annotations_
int
os_rwlock_unlock(os_rwlock_t *__restrict rwlock)
{
internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock;
if (rwlock_internal->is_write)
ReleaseSRWLockExclusive(&rwlock_internal->lock);
else
ReleaseSRWLockShared(&rwlock_internal->lock);
return 0;
}
/*
* os_cond_init -- initializes condition variable
*/
int
os_cond_init(os_cond_t *__restrict cond)
{
COMPILE_ERROR_ON(sizeof(os_cond_t) < sizeof(internal_os_cond_t));
internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond;
InitializeConditionVariable(&cond_internal->cond);
return 0;
}
/*
* os_cond_destroy -- destroys condition variable
*/
int
os_cond_destroy(os_cond_t *__restrict cond)
{
/* do nothing */
UNREFERENCED_PARAMETER(cond);
return 0;
}
/*
* os_cond_broadcast -- broadcast condition variable
*/
int
os_cond_broadcast(os_cond_t *__restrict cond)
{
internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond;
WakeAllConditionVariable(&cond_internal->cond);
return 0;
}
/*
* os_cond_wait -- signal condition variable
*/
int
os_cond_signal(os_cond_t *__restrict cond)
{
internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond;
WakeConditionVariable(&cond_internal->cond);
return 0;
}
/*
* get_rel_wait -- (internal) convert timespec to windows timeout
*/
static DWORD
get_rel_wait(const struct timespec *abstime)
{
struct __timeb64 t;
_ftime64_s(&t);
time_t now_ms = t.time * 1000 + t.millitm;
time_t ms = (time_t)(abstime->tv_sec * 1000 +
abstime->tv_nsec / 1000000);
DWORD rel_wait = (DWORD)(ms - now_ms);
return rel_wait < 0 ? 0 : rel_wait;
}
/*
* os_cond_timedwait -- waits on condition variable with timeout
*/
int
os_cond_timedwait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex, const struct timespec *abstime)
{
internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond;
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
BOOL ret;
SetLastError(0);
ret = SleepConditionVariableCS(&cond_internal->cond,
&mutex_internal->lock, get_rel_wait(abstime));
if (ret == FALSE)
return (GetLastError() == ERROR_TIMEOUT) ? ETIMEDOUT : EINVAL;
return 0;
}
/*
* os_cond_wait -- waits on condition variable
*/
int
os_cond_wait(os_cond_t *__restrict cond,
os_mutex_t *__restrict mutex)
{
internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond;
internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex;
/* XXX - return error code based on GetLastError() */
BOOL ret;
ret = SleepConditionVariableCS(&cond_internal->cond,
&mutex_internal->lock, INFINITE);
return (ret == FALSE) ? EINVAL : 0;
}
/*
* os_once -- once-only function call
*/
int
os_once(os_once_t *once, void (*func)(void))
{
internal_os_once_t *once_internal = (internal_os_once_t *)once;
internal_os_once_t tmp;
while ((tmp = *once_internal) != 2) {
if (tmp == 1)
continue; /* another thread is already calling func() */
/* try to be the first one... */
if (!util_bool_compare_and_swap64(once_internal, tmp, 1))
continue; /* sorry, another thread was faster */
func();
if (!util_bool_compare_and_swap64(once_internal, 1, 2)) {
ERR("error setting once");
return -1;
}
}
return 0;
}
/*
* os_tls_key_create -- creates a new tls key
*/
int
os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *))
{
*key = FlsAlloc(destructor);
if (*key == TLS_OUT_OF_INDEXES)
return EAGAIN;
return 0;
}
/*
* os_tls_key_delete -- deletes key from tls
*/
int
os_tls_key_delete(os_tls_key_t key)
{
if (!FlsFree(key))
return EINVAL;
return 0;
}
/*
* os_tls_set -- sets a value in tls
*/
int
os_tls_set(os_tls_key_t key, const void *value)
{
if (!FlsSetValue(key, (LPVOID)value))
return ENOENT;
return 0;
}
/*
* os_tls_get -- gets a value from tls
*/
void *
os_tls_get(os_tls_key_t key)
{
return FlsGetValue(key);
}
/* threading */
/*
* os_thread_start_routine_wrapper is a start routine for _beginthreadex() and
* it helps:
*
* - wrap the os_thread_create's start function
*/
static unsigned __stdcall
os_thread_start_routine_wrapper(void *arg)
{
internal_os_thread_t *thread_info = (internal_os_thread_t *)arg;
thread_info->result = thread_info->start_routine(thread_info->arg);
return 0;
}
/*
* os_thread_create -- starts a new thread
*/
int
os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
COMPILE_ERROR_ON(sizeof(os_thread_t) < sizeof(internal_os_thread_t));
internal_os_thread_t *thread_info = (internal_os_thread_t *)thread;
thread_info->start_routine = start_routine;
thread_info->arg = arg;
thread_info->thread_handle = (HANDLE)_beginthreadex(NULL, 0,
os_thread_start_routine_wrapper, thread_info, CREATE_SUSPENDED,
NULL);
if (thread_info->thread_handle == 0) {
free(thread_info);
return errno;
}
if (ResumeThread(thread_info->thread_handle) == -1) {
free(thread_info);
return EAGAIN;
}
return 0;
}
/*
* os_thread_join -- joins a thread
*/
int
os_thread_join(os_thread_t *thread, void **result)
{
internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread;
WaitForSingleObject(internal_thread->thread_handle, INFINITE);
CloseHandle(internal_thread->thread_handle);
if (result != NULL)
*result = internal_thread->result;
return 0;
}
/*
* os_thread_self -- returns handle to calling thread
*/
void
os_thread_self(os_thread_t *thread)
{
internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread;
internal_thread->thread_handle = GetCurrentThread();
}
/*
* os_cpu_zero -- clears cpu set
*/
void
os_cpu_zero(os_cpu_set_t *set)
{
internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set;
memset(&internal_set->affinity, 0, sizeof(internal_set->affinity));
}
/*
* os_cpu_set -- adds cpu to set
*/
void
os_cpu_set(size_t cpu, os_cpu_set_t *set)
{
internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set;
int sum = 0;
int group_max = GetActiveProcessorGroupCount();
int group = 0;
while (group < group_max) {
sum += GetActiveProcessorCount(group);
if (sum > cpu) {
/*
* XXX: can't set affinity to two different cpu groups
*/
if (internal_set->affinity.Group != group) {
internal_set->affinity.Mask = 0;
internal_set->affinity.Group = group;
}
cpu -= sum - GetActiveProcessorCount(group);
internal_set->affinity.Mask |= 1LL << cpu;
return;
}
group++;
}
FATAL("os_cpu_set cpu out of bounds");
}
/*
* os_thread_setaffinity_np -- sets affinity of the thread
*/
int
os_thread_setaffinity_np(os_thread_t *thread, size_t set_size,
const os_cpu_set_t *set)
{
internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set;
internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread;
int ret = SetThreadGroupAffinity(internal_thread->thread_handle,
&internal_set->affinity, NULL);
return ret != 0 ? 0 : EINVAL;
}
/*
* os_semaphore_init -- initializes a new semaphore instance
*/
int
os_semaphore_init(os_semaphore_t *sem, unsigned value)
{
internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem;
internal_sem->handle = CreateSemaphore(NULL,
value, LONG_MAX, NULL);
return internal_sem->handle != 0 ? 0 : -1;
}
/*
* os_semaphore_destroy -- destroys a semaphore instance
*/
int
os_semaphore_destroy(os_semaphore_t *sem)
{
internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem;
BOOL ret = CloseHandle(internal_sem->handle);
return ret ? 0 : -1;
}
/*
* os_semaphore_wait -- decreases the value of the semaphore
*/
int
os_semaphore_wait(os_semaphore_t *sem)
{
internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem;
DWORD ret = WaitForSingleObject(internal_sem->handle, INFINITE);
return ret == WAIT_OBJECT_0 ? 0 : -1;
}
/*
* os_semaphore_trywait -- tries to decrease the value of the semaphore
*/
int
os_semaphore_trywait(os_semaphore_t *sem)
{
internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem;
DWORD ret = WaitForSingleObject(internal_sem->handle, 0);
if (ret == WAIT_TIMEOUT)
errno = EAGAIN;
return ret == WAIT_OBJECT_0 ? 0 : -1;
}
/*
* os_semaphore_post -- increases the value of the semaphore
*/
int
os_semaphore_post(os_semaphore_t *sem)
{
internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem;
BOOL ret = ReleaseSemaphore(internal_sem->handle, 1, NULL);
return ret ? 0 : -1;
}
| 15,425 | 22.443769 | 78 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/out.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* out.c -- support for logging, tracing, and assertion output
*
* Macros like LOG(), OUT, ASSERT(), etc. end up here.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include "out.h"
#include "os.h"
#include "os_thread.h"
#include "valgrind_internal.h"
#include "util.h"
/* XXX - modify Linux makefiles to generate srcversion.h and remove #ifdef */
#ifdef _WIN32
#include "srcversion.h"
#endif
static const char *Log_prefix;
static int Log_level;
static FILE *Out_fp;
static unsigned Log_alignment;
#ifndef NO_LIBPTHREAD
#define MAXPRINT 8192 /* maximum expected log line */
#else
#define MAXPRINT 256 /* maximum expected log line for libpmem */
#endif
struct errormsg
{
char msg[MAXPRINT];
#ifdef _WIN32
wchar_t wmsg[MAXPRINT];
#endif
};
#ifndef NO_LIBPTHREAD
static os_once_t Last_errormsg_key_once = OS_ONCE_INIT;
static os_tls_key_t Last_errormsg_key;
static void
_Last_errormsg_key_alloc(void)
{
int pth_ret = os_tls_key_create(&Last_errormsg_key, free);
if (pth_ret)
FATAL("!os_thread_key_create");
VALGRIND_ANNOTATE_HAPPENS_BEFORE(&Last_errormsg_key_once);
}
static void
Last_errormsg_key_alloc(void)
{
os_once(&Last_errormsg_key_once, _Last_errormsg_key_alloc);
/*
* Workaround Helgrind's bug:
* https://bugs.kde.org/show_bug.cgi?id=337735
*/
VALGRIND_ANNOTATE_HAPPENS_AFTER(&Last_errormsg_key_once);
}
static inline void
Last_errormsg_fini(void)
{
void *p = os_tls_get(Last_errormsg_key);
if (p) {
free(p);
(void) os_tls_set(Last_errormsg_key, NULL);
}
(void) os_tls_key_delete(Last_errormsg_key);
}
static inline struct errormsg *
Last_errormsg_get(void)
{
Last_errormsg_key_alloc();
struct errormsg *errormsg = os_tls_get(Last_errormsg_key);
if (errormsg == NULL) {
errormsg = malloc(sizeof(struct errormsg));
if (errormsg == NULL)
FATAL("!malloc");
/* make sure it contains empty string initially */
errormsg->msg[0] = '\0';
int ret = os_tls_set(Last_errormsg_key, errormsg);
if (ret)
FATAL("!os_tls_set");
}
return errormsg;
}
#else
/*
* We don't want libpmem to depend on libpthread. Instead of using pthread
* API to dynamically allocate thread-specific error message buffer, we put
* it into TLS. However, keeping a pretty large static buffer (8K) in TLS
* may lead to some issues, so the maximum message length is reduced.
* Fortunately, it looks like the longest error message in libpmem should
* not be longer than about 90 chars (in case of pmem_check_version()).
*/
static __thread struct errormsg Last_errormsg;
static inline void
Last_errormsg_key_alloc(void)
{
}
static inline void
Last_errormsg_fini(void)
{
}
static inline const struct errormsg *
Last_errormsg_get(void)
{
return &Last_errormsg;
}
#endif /* NO_LIBPTHREAD */
/*
* out_init -- initialize the log
*
* This is called from the library initialization code.
*/
void
out_init(const char *log_prefix, const char *log_level_var,
const char *log_file_var, int major_version,
int minor_version)
{
static int once;
/* only need to initialize the out module once */
if (once)
return;
once++;
Log_prefix = log_prefix;
#ifdef DEBUG
char *log_level;
char *log_file;
if ((log_level = os_getenv(log_level_var)) != NULL) {
Log_level = atoi(log_level);
if (Log_level < 0) {
Log_level = 0;
}
}
if ((log_file = os_getenv(log_file_var)) != NULL &&
log_file[0] != '\0') {
/* reserve more than enough space for a PID + '\0' */
char log_file_pid[PATH_MAX];
size_t len = strlen(log_file);
if (len > 0 && log_file[len - 1] == '-') {
if (util_snprintf(log_file_pid, PATH_MAX, "%s%d",
log_file, getpid()) < 0) {
ERR("snprintf: %d", errno);
abort();
}
log_file = log_file_pid;
}
if ((Out_fp = os_fopen(log_file, "w")) == NULL) {
char buff[UTIL_MAX_ERR_MSG];
util_strerror(errno, buff, UTIL_MAX_ERR_MSG);
fprintf(stderr, "Error (%s): %s=%s: %s\n",
log_prefix, log_file_var,
log_file, buff);
abort();
}
}
#endif /* DEBUG */
char *log_alignment = os_getenv("PMDK_LOG_ALIGN");
if (log_alignment) {
int align = atoi(log_alignment);
if (align > 0)
Log_alignment = (unsigned)align;
}
if (Out_fp == NULL)
Out_fp = stderr;
else
setlinebuf(Out_fp);
#ifdef DEBUG
static char namepath[PATH_MAX];
LOG(1, "pid %d: program: %s", getpid(),
util_getexecname(namepath, PATH_MAX));
#endif
LOG(1, "%s version %d.%d", log_prefix, major_version, minor_version);
static __attribute__((used)) const char *version_msg =
"src version: " SRCVERSION;
LOG(1, "%s", version_msg);
#if VG_PMEMCHECK_ENABLED
/*
* Attribute "used" to prevent compiler from optimizing out the variable
* when LOG expands to no code (!DEBUG)
*/
static __attribute__((used)) const char *pmemcheck_msg =
"compiled with support for Valgrind pmemcheck";
LOG(1, "%s", pmemcheck_msg);
#endif /* VG_PMEMCHECK_ENABLED */
#if VG_HELGRIND_ENABLED
static __attribute__((used)) const char *helgrind_msg =
"compiled with support for Valgrind helgrind";
LOG(1, "%s", helgrind_msg);
#endif /* VG_HELGRIND_ENABLED */
#if VG_MEMCHECK_ENABLED
static __attribute__((used)) const char *memcheck_msg =
"compiled with support for Valgrind memcheck";
LOG(1, "%s", memcheck_msg);
#endif /* VG_MEMCHECK_ENABLED */
#if VG_DRD_ENABLED
static __attribute__((used)) const char *drd_msg =
"compiled with support for Valgrind drd";
LOG(1, "%s", drd_msg);
#endif /* VG_DRD_ENABLED */
#if SDS_ENABLED
static __attribute__((used)) const char *shutdown_state_msg =
"compiled with support for shutdown state";
LOG(1, "%s", shutdown_state_msg);
#endif
#if NDCTL_ENABLED
static __attribute__((used)) const char *ndctl_ge_63_msg =
"compiled with libndctl 63+";
LOG(1, "%s", ndctl_ge_63_msg);
#endif
Last_errormsg_key_alloc();
}
/*
* out_fini -- close the log file
*
* This is called to close log file before process stop.
*/
void
out_fini(void)
{
if (Out_fp != NULL && Out_fp != stderr) {
fclose(Out_fp);
Out_fp = stderr;
}
Last_errormsg_fini();
}
/*
* out_print_func -- default print_func, goes to stderr or Out_fp
*/
static void
out_print_func(const char *s)
{
/* to suppress drd false-positive */
/* XXX: confirm real nature of this issue: pmem/issues#863 */
#ifdef SUPPRESS_FPUTS_DRD_ERROR
VALGRIND_ANNOTATE_IGNORE_READS_BEGIN();
VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN();
#endif
fputs(s, Out_fp);
#ifdef SUPPRESS_FPUTS_DRD_ERROR
VALGRIND_ANNOTATE_IGNORE_READS_END();
VALGRIND_ANNOTATE_IGNORE_WRITES_END();
#endif
}
/*
* calling Print(s) calls the current print_func...
*/
typedef void (*Print_func)(const char *s);
typedef int (*Vsnprintf_func)(char *str, size_t size, const char *format,
va_list ap);
static Print_func Print = out_print_func;
static Vsnprintf_func Vsnprintf = vsnprintf;
/*
* out_set_print_func -- allow override of print_func used by out module
*/
void
out_set_print_func(void (*print_func)(const char *s))
{
LOG(3, "print %p", print_func);
Print = (print_func == NULL) ? out_print_func : print_func;
}
/*
* out_set_vsnprintf_func -- allow override of vsnprintf_func used by out module
*/
void
out_set_vsnprintf_func(int (*vsnprintf_func)(char *str, size_t size,
const char *format, va_list ap))
{
LOG(3, "vsnprintf %p", vsnprintf_func);
Vsnprintf = (vsnprintf_func == NULL) ? vsnprintf : vsnprintf_func;
}
/*
* out_snprintf -- (internal) custom snprintf implementation
*/
FORMAT_PRINTF(3, 4)
static int
out_snprintf(char *str, size_t size, const char *format, ...)
{
int ret;
va_list ap;
va_start(ap, format);
ret = Vsnprintf(str, size, format, ap);
va_end(ap);
return (ret);
}
/*
* out_common -- common output code, all output goes through here
*/
static void
out_common(const char *file, int line, const char *func, int level,
const char *suffix, const char *fmt, va_list ap)
{
int oerrno = errno;
char buf[MAXPRINT];
unsigned cc = 0;
int ret;
const char *sep = "";
char errstr[UTIL_MAX_ERR_MSG] = "";
unsigned long olast_error = 0;
#ifdef _WIN32
if (fmt && fmt[0] == '!' && fmt[1] == '!')
olast_error = GetLastError();
#endif
if (file) {
char *f = strrchr(file, OS_DIR_SEPARATOR);
if (f)
file = f + 1;
ret = out_snprintf(&buf[cc], MAXPRINT - cc,
"<%s>: <%d> [%s:%d %s] ",
Log_prefix, level, file, line, func);
if (ret < 0) {
Print("out_snprintf failed");
goto end;
}
cc += (unsigned)ret;
if (cc < Log_alignment) {
memset(buf + cc, ' ', Log_alignment - cc);
cc = Log_alignment;
}
}
if (fmt) {
if (*fmt == '!') {
sep = ": ";
fmt++;
if (*fmt == '!') {
fmt++;
/* it will abort on non Windows OS */
util_strwinerror(olast_error, errstr,
UTIL_MAX_ERR_MSG);
} else {
util_strerror(oerrno, errstr, UTIL_MAX_ERR_MSG);
}
}
ret = Vsnprintf(&buf[cc], MAXPRINT - cc, fmt, ap);
if (ret < 0) {
Print("Vsnprintf failed");
goto end;
}
cc += (unsigned)ret;
}
out_snprintf(&buf[cc], MAXPRINT - cc, "%s%s%s", sep, errstr, suffix);
Print(buf);
end:
errno = oerrno;
#ifdef _WIN32
SetLastError(olast_error);
#endif
}
/*
* out_error -- common error output code, all error messages go through here
*/
static void
out_error(const char *file, int line, const char *func,
const char *suffix, const char *fmt, va_list ap)
{
int oerrno = errno;
unsigned long olast_error = 0;
#ifdef _WIN32
olast_error = GetLastError();
#endif
unsigned cc = 0;
int ret;
const char *sep = "";
char errstr[UTIL_MAX_ERR_MSG] = "";
char *errormsg = (char *)out_get_errormsg();
if (fmt) {
if (*fmt == '!') {
sep = ": ";
fmt++;
if (*fmt == '!') {
fmt++;
/* it will abort on non Windows OS */
util_strwinerror(olast_error, errstr,
UTIL_MAX_ERR_MSG);
} else {
util_strerror(oerrno, errstr, UTIL_MAX_ERR_MSG);
}
}
ret = Vsnprintf(&errormsg[cc], MAXPRINT, fmt, ap);
if (ret < 0) {
strcpy(errormsg, "Vsnprintf failed");
goto end;
}
cc += (unsigned)ret;
out_snprintf(&errormsg[cc], MAXPRINT - cc, "%s%s",
sep, errstr);
}
#ifdef DEBUG
if (Log_level >= 1) {
char buf[MAXPRINT];
cc = 0;
if (file) {
char *f = strrchr(file, OS_DIR_SEPARATOR);
if (f)
file = f + 1;
ret = out_snprintf(&buf[cc], MAXPRINT,
"<%s>: <1> [%s:%d %s] ",
Log_prefix, file, line, func);
if (ret < 0) {
Print("out_snprintf failed");
goto end;
}
cc += (unsigned)ret;
if (cc < Log_alignment) {
memset(buf + cc, ' ', Log_alignment - cc);
cc = Log_alignment;
}
}
out_snprintf(&buf[cc], MAXPRINT - cc, "%s%s", errormsg,
suffix);
Print(buf);
}
#endif
end:
errno = oerrno;
#ifdef _WIN32
SetLastError(olast_error);
#endif
}
/*
* out -- output a line, newline added automatically
*/
void
out(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
out_common(NULL, 0, NULL, 0, "\n", fmt, ap);
va_end(ap);
}
/*
* out_nonl -- output a line, no newline added automatically
*/
void
out_nonl(int level, const char *fmt, ...)
{
va_list ap;
if (Log_level < level)
return;
va_start(ap, fmt);
out_common(NULL, 0, NULL, level, "", fmt, ap);
va_end(ap);
}
/*
* out_log -- output a log line if Log_level >= level
*/
void
out_log(const char *file, int line, const char *func, int level,
const char *fmt, ...)
{
va_list ap;
if (Log_level < level)
return;
va_start(ap, fmt);
out_common(file, line, func, level, "\n", fmt, ap);
va_end(ap);
}
/*
* out_fatal -- output a fatal error & die (i.e. assertion failure)
*/
void
out_fatal(const char *file, int line, const char *func,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
out_common(file, line, func, 1, "\n", fmt, ap);
va_end(ap);
abort();
}
/*
* out_err -- output an error message
*/
void
out_err(const char *file, int line, const char *func,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
out_error(file, line, func, "\n", fmt, ap);
va_end(ap);
}
/*
* out_get_errormsg -- get the last error message
*/
const char *
out_get_errormsg(void)
{
const struct errormsg *errormsg = Last_errormsg_get();
return &errormsg->msg[0];
}
#ifdef _WIN32
/*
* out_get_errormsgW -- get the last error message in wchar_t
*/
const wchar_t *
out_get_errormsgW(void)
{
struct errormsg *errormsg = Last_errormsg_get();
const char *utf8 = &errormsg->msg[0];
wchar_t *utf16 = &errormsg->wmsg[0];
if (util_toUTF16_buff(utf8, utf16, sizeof(errormsg->wmsg)) != 0)
FATAL("!Failed to convert string");
return (const wchar_t *)utf16;
}
#endif
| 12,602 | 20.252951 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/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/logging/pmdk/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/logging/pmdk/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/logging/pmdk/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/logging/pmdk/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/logging/pmdk/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
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/core/valgrind/pmemcheck.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2015, Intel Corporation */
#ifndef __PMEMCHECK_H
#define __PMEMCHECK_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__PMC_REGISTER_PMEM_MAPPING = VG_USERREQ_TOOL_BASE('P','C'),
VG_USERREQ__PMC_REGISTER_PMEM_FILE,
VG_USERREQ__PMC_REMOVE_PMEM_MAPPING,
VG_USERREQ__PMC_CHECK_IS_PMEM_MAPPING,
VG_USERREQ__PMC_PRINT_PMEM_MAPPINGS,
VG_USERREQ__PMC_DO_FLUSH,
VG_USERREQ__PMC_DO_FENCE,
VG_USERREQ__PMC_RESERVED1, /* Do not use. */
VG_USERREQ__PMC_WRITE_STATS,
VG_USERREQ__PMC_RESERVED2, /* Do not use. */
VG_USERREQ__PMC_RESERVED3, /* Do not use. */
VG_USERREQ__PMC_RESERVED4, /* Do not use. */
VG_USERREQ__PMC_RESERVED5, /* Do not use. */
VG_USERREQ__PMC_RESERVED7, /* Do not use. */
VG_USERREQ__PMC_RESERVED8, /* Do not use. */
VG_USERREQ__PMC_RESERVED9, /* Do not use. */
VG_USERREQ__PMC_RESERVED10, /* Do not use. */
VG_USERREQ__PMC_SET_CLEAN,
/* transaction support */
VG_USERREQ__PMC_START_TX,
VG_USERREQ__PMC_START_TX_N,
VG_USERREQ__PMC_END_TX,
VG_USERREQ__PMC_END_TX_N,
VG_USERREQ__PMC_ADD_TO_TX,
VG_USERREQ__PMC_ADD_TO_TX_N,
VG_USERREQ__PMC_REMOVE_FROM_TX,
VG_USERREQ__PMC_REMOVE_FROM_TX_N,
VG_USERREQ__PMC_ADD_THREAD_TO_TX_N,
VG_USERREQ__PMC_REMOVE_THREAD_FROM_TX_N,
VG_USERREQ__PMC_ADD_TO_GLOBAL_TX_IGNORE,
VG_USERREQ__PMC_RESERVED6, /* Do not use. */
VG_USERREQ__PMC_EMIT_LOG,
} Vg_PMemCheckClientRequest;
/* Client-code macros to manipulate pmem mappings */
/** Register a persistent memory mapping region */
#define VALGRIND_PMC_REGISTER_PMEM_MAPPING(_qzz_addr, _qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REGISTER_PMEM_MAPPING, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Register a persistent memory file */
#define VALGRIND_PMC_REGISTER_PMEM_FILE(_qzz_desc, _qzz_addr_base, \
_qzz_size, _qzz_offset) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REGISTER_PMEM_FILE, \
(_qzz_desc), (_qzz_addr_base), (_qzz_size), \
(_qzz_offset), 0)
/** Remove a persistent memory mapping region */
#define VALGRIND_PMC_REMOVE_PMEM_MAPPING(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REMOVE_PMEM_MAPPING, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Check if the given range is a registered persistent memory mapping */
#define VALGRIND_PMC_CHECK_IS_PMEM_MAPPING(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_CHECK_IS_PMEM_MAPPING, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Register an SFENCE */
#define VALGRIND_PMC_PRINT_PMEM_MAPPINGS \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_PRINT_PMEM_MAPPINGS, \
0, 0, 0, 0, 0)
/** Register a CLFLUSH-like operation */
#define VALGRIND_PMC_DO_FLUSH(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_DO_FLUSH, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Register an SFENCE */
#define VALGRIND_PMC_DO_FENCE \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_DO_FENCE, \
0, 0, 0, 0, 0)
/** Write tool stats */
#define VALGRIND_PMC_WRITE_STATS \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_WRITE_STATS, \
0, 0, 0, 0, 0)
/** Emit user log */
#define VALGRIND_PMC_EMIT_LOG(_qzz_emit_log) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_EMIT_LOG, \
(_qzz_emit_log), 0, 0, 0, 0)
/** Set a region of persistent memory as clean */
#define VALGRIND_PMC_SET_CLEAN(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_SET_CLEAN, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Support for transactions */
/** Start an implicit persistent memory transaction */
#define VALGRIND_PMC_START_TX \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_START_TX, \
0, 0, 0, 0, 0)
/** Start an explicit persistent memory transaction */
#define VALGRIND_PMC_START_TX_N(_qzz_txn) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_START_TX_N, \
(_qzz_txn), 0, 0, 0, 0)
/** End an implicit persistent memory transaction */
#define VALGRIND_PMC_END_TX \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_END_TX, \
0, 0, 0, 0, 0)
/** End an explicit persistent memory transaction */
#define VALGRIND_PMC_END_TX_N(_qzz_txn) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_END_TX_N, \
(_qzz_txn), 0, 0, 0, 0)
/** Add a persistent memory region to the implicit transaction */
#define VALGRIND_PMC_ADD_TO_TX(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_ADD_TO_TX, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Add a persistent memory region to an explicit transaction */
#define VALGRIND_PMC_ADD_TO_TX_N(_qzz_txn,_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_ADD_TO_TX_N, \
(_qzz_txn), (_qzz_addr), (_qzz_len), 0, 0)
/** Remove a persistent memory region from the implicit transaction */
#define VALGRIND_PMC_REMOVE_FROM_TX(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REMOVE_FROM_TX, \
(_qzz_addr), (_qzz_len), 0, 0, 0)
/** Remove a persistent memory region from an explicit transaction */
#define VALGRIND_PMC_REMOVE_FROM_TX_N(_qzz_txn,_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REMOVE_FROM_TX_N, \
(_qzz_txn), (_qzz_addr), (_qzz_len), 0, 0)
/** End an explicit persistent memory transaction */
#define VALGRIND_PMC_ADD_THREAD_TX_N(_qzz_txn) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_ADD_THREAD_TO_TX_N, \
(_qzz_txn), 0, 0, 0, 0)
/** End an explicit persistent memory transaction */
#define VALGRIND_PMC_REMOVE_THREAD_FROM_TX_N(_qzz_txn) \
VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \
VG_USERREQ__PMC_REMOVE_THREAD_FROM_TX_N, \
(_qzz_txn), 0, 0, 0, 0)
/** Remove a persistent memory region from the implicit transaction */
#define VALGRIND_PMC_ADD_TO_GLOBAL_TX_IGNORE(_qzz_addr,_qzz_len) \
VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_ADD_TO_GLOBAL_TX_IGNORE,\
(_qzz_addr), (_qzz_len), 0, 0, 0)
#endif
| 9,085 | 47.588235 | 77 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/ctl.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2019, Intel Corporation */
/*
* ctl.h -- internal declaration of statistics and control related structures
*/
#ifndef PMDK_CTL_H
#define PMDK_CTL_H 1
#include "queue.h"
#include "errno.h"
#include "out.h"
#ifdef __cplusplus
extern "C" {
#endif
struct ctl;
struct ctl_index {
const char *name;
long value;
PMDK_SLIST_ENTRY(ctl_index) entry;
};
PMDK_SLIST_HEAD(ctl_indexes, ctl_index);
enum ctl_query_source {
CTL_UNKNOWN_QUERY_SOURCE,
/* query executed directly from the program */
CTL_QUERY_PROGRAMMATIC,
/* query executed from the config file */
CTL_QUERY_CONFIG_INPUT,
MAX_CTL_QUERY_SOURCE
};
enum ctl_query_type {
CTL_QUERY_READ,
CTL_QUERY_WRITE,
CTL_QUERY_RUNNABLE,
MAX_CTL_QUERY_TYPE
};
typedef int (*node_callback)(void *ctx, enum ctl_query_source type,
void *arg, struct ctl_indexes *indexes);
enum ctl_node_type {
CTL_NODE_UNKNOWN,
CTL_NODE_NAMED,
CTL_NODE_LEAF,
CTL_NODE_INDEXED,
MAX_CTL_NODE
};
typedef int (*ctl_arg_parser)(const void *arg, void *dest, size_t dest_size);
struct ctl_argument_parser {
size_t dest_offset; /* offset of the field inside of the argument */
size_t dest_size; /* size of the field inside of the argument */
ctl_arg_parser parser;
};
struct ctl_argument {
size_t dest_size; /* sizeof the entire argument */
struct ctl_argument_parser parsers[]; /* array of 'fields' in arg */
};
#define sizeof_member(t, m) sizeof(((t *)0)->m)
#define CTL_ARG_PARSER(t, p)\
{0, sizeof(t), p}
#define CTL_ARG_PARSER_STRUCT(t, m, p)\
{offsetof(t, m), sizeof_member(t, m), p}
#define CTL_ARG_PARSER_END {0, 0, NULL}
/*
* CTL Tree node structure, do not use directly. All the necessary functionality
* is provided by the included macros.
*/
struct ctl_node {
const char *name;
enum ctl_node_type type;
node_callback cb[MAX_CTL_QUERY_TYPE];
const struct ctl_argument *arg;
const struct ctl_node *children;
};
struct ctl *ctl_new(void);
void ctl_delete(struct ctl *stats);
int ctl_load_config_from_string(struct ctl *ctl, void *ctx,
const char *cfg_string);
int ctl_load_config_from_file(struct ctl *ctl, void *ctx,
const char *cfg_file);
/* Use through CTL_REGISTER_MODULE, never directly */
void ctl_register_module_node(struct ctl *c,
const char *name, struct ctl_node *n);
int ctl_arg_boolean(const void *arg, void *dest, size_t dest_size);
#define CTL_ARG_BOOLEAN {sizeof(int),\
{{0, sizeof(int), ctl_arg_boolean},\
CTL_ARG_PARSER_END}};
int ctl_arg_integer(const void *arg, void *dest, size_t dest_size);
#define CTL_ARG_INT {sizeof(int),\
{{0, sizeof(int), ctl_arg_integer},\
CTL_ARG_PARSER_END}};
#define CTL_ARG_LONG_LONG {sizeof(long long),\
{{0, sizeof(long long), ctl_arg_integer},\
CTL_ARG_PARSER_END}};
int ctl_arg_string(const void *arg, void *dest, size_t dest_size);
#define CTL_ARG_STRING(len) {len,\
{{0, len, ctl_arg_string},\
CTL_ARG_PARSER_END}};
#define CTL_STR(name) #name
#define CTL_NODE_END {NULL, CTL_NODE_UNKNOWN, {NULL, NULL, NULL}, NULL, NULL}
#define CTL_NODE(name, ...)\
ctl_node_##__VA_ARGS__##_##name
int ctl_query(struct ctl *ctl, void *ctx, enum ctl_query_source source,
const char *name, enum ctl_query_type type, void *arg);
/* Declaration of a new child node */
#define CTL_CHILD(name, ...)\
{CTL_STR(name), CTL_NODE_NAMED, {NULL, NULL, NULL}, NULL,\
(struct ctl_node *)CTL_NODE(name, __VA_ARGS__)}
/* Declaration of a new indexed node */
#define CTL_INDEXED(name, ...)\
{CTL_STR(name), CTL_NODE_INDEXED, {NULL, NULL, NULL}, NULL,\
(struct ctl_node *)CTL_NODE(name, __VA_ARGS__)}
#define CTL_READ_HANDLER(name, ...)\
ctl_##__VA_ARGS__##_##name##_read
#define CTL_WRITE_HANDLER(name, ...)\
ctl_##__VA_ARGS__##_##name##_write
#define CTL_RUNNABLE_HANDLER(name, ...)\
ctl_##__VA_ARGS__##_##name##_runnable
#define CTL_ARG(name)\
ctl_arg_##name
/*
* Declaration of a new read-only leaf. If used the corresponding read function
* must be declared by CTL_READ_HANDLER macro.
*/
#define CTL_LEAF_RO(name, ...)\
{CTL_STR(name), CTL_NODE_LEAF, \
{CTL_READ_HANDLER(name, __VA_ARGS__), NULL, NULL}, NULL, NULL}
/*
* Declaration of a new write-only leaf. If used the corresponding write
* function must be declared by CTL_WRITE_HANDLER macro.
*/
#define CTL_LEAF_WO(name, ...)\
{CTL_STR(name), CTL_NODE_LEAF, \
{NULL, CTL_WRITE_HANDLER(name, __VA_ARGS__), NULL},\
&CTL_ARG(name), NULL}
/*
* Declaration of a new runnable leaf. If used the corresponding run
* function must be declared by CTL_RUNNABLE_HANDLER macro.
*/
#define CTL_LEAF_RUNNABLE(name, ...)\
{CTL_STR(name), CTL_NODE_LEAF, \
{NULL, NULL, CTL_RUNNABLE_HANDLER(name, __VA_ARGS__)},\
NULL, NULL}
/*
* Declaration of a new read-write leaf. If used both read and write function
* must be declared by CTL_READ_HANDLER and CTL_WRITE_HANDLER macros.
*/
#define CTL_LEAF_RW(name)\
{CTL_STR(name), CTL_NODE_LEAF,\
{CTL_READ_HANDLER(name), CTL_WRITE_HANDLER(name), NULL},\
&CTL_ARG(name), NULL}
#define CTL_REGISTER_MODULE(_ctl, name)\
ctl_register_module_node((_ctl), CTL_STR(name),\
(struct ctl_node *)CTL_NODE(name))
#ifdef __cplusplus
}
#endif
#endif
| 5,127 | 24.261084 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/file.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* file.h -- internal definitions for file module
*/
#ifndef PMDK_FILE_H
#define PMDK_FILE_H 1
#include <stddef.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <limits.h>
#include "os.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
#define NAME_MAX _MAX_FNAME
#endif
struct file_info {
char filename[NAME_MAX + 1];
int is_dir;
};
struct dir_handle {
const char *path;
#ifdef _WIN32
HANDLE handle;
char *_file;
#else
DIR *dirp;
#endif
};
enum file_type {
OTHER_ERROR = -2,
NOT_EXISTS = -1,
TYPE_NORMAL = 1,
TYPE_DEVDAX = 2
};
int util_file_dir_open(struct dir_handle *a, const char *path);
int util_file_dir_next(struct dir_handle *a, struct file_info *info);
int util_file_dir_close(struct dir_handle *a);
int util_file_dir_remove(const char *path);
int util_file_exists(const char *path);
enum file_type util_stat_get_type(const os_stat_t *st);
enum file_type util_fd_get_type(int fd);
enum file_type util_file_get_type(const char *path);
int util_ddax_region_find(const char *path, unsigned *region_id);
ssize_t util_file_get_size(const char *path);
ssize_t util_fd_get_size(int fd);
size_t util_file_device_dax_alignment(const char *path);
void *util_file_map_whole(const char *path);
int util_file_zero(const char *path, os_off_t off, size_t len);
ssize_t util_file_pread(const char *path, void *buffer, size_t size,
os_off_t offset);
ssize_t util_file_pwrite(const char *path, const void *buffer, size_t size,
os_off_t offset);
int util_tmpfile(const char *dir, const char *templ, int flags);
int util_is_absolute_path(const char *path);
int util_file_create(const char *path, size_t size, size_t minsize);
int util_file_open(const char *path, size_t *size, size_t minsize, int flags);
int util_unlink(const char *path);
int util_unlink_flock(const char *path);
int util_file_mkdir(const char *path, mode_t mode);
int util_write_all(int fd, const char *buf, size_t count);
#ifndef _WIN32
#define util_read read
#define util_write write
#else
static inline ssize_t
util_read(int fd, void *buf, size_t count)
{
/*
* Simulate short read, because Windows' _read uses "unsigned" as
* a type of the last argument and "int" as a return type.
* We have to limit "count" to what _read can return as a success,
* not what it can accept.
*/
if (count > INT_MAX)
count = INT_MAX;
return _read(fd, buf, (unsigned)count);
}
static inline ssize_t
util_write(int fd, const void *buf, size_t count)
{
/*
* Simulate short write, because Windows' _write uses "unsigned" as
* a type of the last argument and "int" as a return type.
* We have to limit "count" to what _write can return as a success,
* not what it can accept.
*/
if (count > INT_MAX)
count = INT_MAX;
return _write(fd, buf, (unsigned)count);
}
#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
#ifdef __cplusplus
}
#endif
#endif
| 3,013 | 24.982759 | 78 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/badblocks.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* badblocks.h -- bad blocks API based on the libpmem2 library
*/
#ifndef PMDK_BADBLOCKS_H
#define PMDK_BADBLOCKS_H 1
#include <string.h>
#include <stdint.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define B2SEC(n) ((n) >> 9) /* convert bytes to sectors */
#define SEC2B(n) ((n) << 9) /* convert sectors to bytes */
#define NO_HEALTHY_REPLICA ((int)(-1))
#define BB_NOT_SUPP \
"checking bad blocks is not supported on this OS, please switch off the CHECK_BAD_BLOCKS compat feature using 'pmempool-feature'"
/*
* 'struct badblock' is already defined in ndctl/libndctl.h,
* so we cannot use this name.
*
* libndctl returns offset relative to the beginning of the region,
* but in this structure we save offset relative to the beginning of:
* - namespace (before badblocks_get())
* and
* - file (before sync_recalc_badblocks())
* and
* - pool (after sync_recalc_badblocks())
*/
struct bad_block {
/*
* offset in bytes relative to the beginning of
* - namespace (before badblocks_get())
* and
* - file (before sync_recalc_badblocks())
* and
* - pool (after sync_recalc_badblocks())
*/
size_t offset;
/* length in bytes */
size_t length;
/* number of healthy replica to fix this bad block */
int nhealthy;
};
struct badblocks {
unsigned bb_cnt; /* number of bad blocks */
struct bad_block *bbv; /* array of bad blocks */
};
struct badblocks *badblocks_new(void);
void badblocks_delete(struct badblocks *bbs);
long badblocks_count(const char *path);
int badblocks_get(const char *file, struct badblocks *bbs);
int badblocks_clear(const char *path, struct badblocks *bbs);
int badblocks_clear_all(const char *file);
int badblocks_check_file(const char *path);
#ifdef __cplusplus
}
#endif
#endif /* PMDK_BADBLOCKS_H */
| 1,878 | 23.089744 | 130 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/ctl.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/*
* ctl.c -- implementation of the interface for examination and modification of
* the library's internal state
*/
#include "ctl.h"
#include "os.h"
#include "alloc.h"
#define CTL_MAX_ENTRIES 100
#define MAX_CONFIG_FILE_LEN (1 << 20) /* 1 megabyte */
#define CTL_STRING_QUERY_SEPARATOR ";"
#define CTL_NAME_VALUE_SEPARATOR "="
#define CTL_QUERY_NODE_SEPARATOR "."
#define CTL_VALUE_ARG_SEPARATOR ","
static int ctl_global_first_free = 0;
static struct ctl_node CTL_NODE(global)[CTL_MAX_ENTRIES];
/*
* This is the top level node of the ctl tree structure. Each node can contain
* children and leaf nodes.
*
* Internal nodes simply create a new path in the tree whereas child nodes are
* the ones providing the read/write functionality by the means of callbacks.
*
* Each tree node must be NULL-terminated, CTL_NODE_END macro is provided for
* convenience.
*/
struct ctl {
struct ctl_node root[CTL_MAX_ENTRIES];
int first_free;
};
/*
* ctl_find_node -- (internal) searches for a matching entry point in the
* provided nodes
*
* The caller is responsible for freeing all of the allocated indexes,
* regardless of the return value.
*/
static const struct ctl_node *
ctl_find_node(const struct ctl_node *nodes, const char *name,
struct ctl_indexes *indexes)
{
LOG(3, "nodes %p name %s indexes %p", nodes, name, indexes);
const struct ctl_node *n = NULL;
char *sptr = NULL;
char *parse_str = Strdup(name);
if (parse_str == NULL)
return NULL;
char *node_name = strtok_r(parse_str, CTL_QUERY_NODE_SEPARATOR, &sptr);
/*
* Go through the string and separate tokens that correspond to nodes
* in the main ctl tree.
*/
while (node_name != NULL) {
char *endptr;
/*
* Ignore errno from strtol: FreeBSD returns EINVAL if no
* conversion is performed. Linux does not, but endptr
* check is valid in both cases.
*/
int tmp_errno = errno;
long index_value = strtol(node_name, &endptr, 0);
errno = tmp_errno;
struct ctl_index *index_entry = NULL;
if (endptr != node_name) { /* a valid index */
index_entry = Malloc(sizeof(*index_entry));
if (index_entry == NULL)
goto error;
index_entry->value = index_value;
PMDK_SLIST_INSERT_HEAD(indexes, index_entry, entry);
}
for (n = &nodes[0]; n->name != NULL; ++n) {
if (index_entry && n->type == CTL_NODE_INDEXED)
break;
else if (strcmp(n->name, node_name) == 0)
break;
}
if (n->name == NULL)
goto error;
if (index_entry)
index_entry->name = n->name;
nodes = n->children;
node_name = strtok_r(NULL, CTL_QUERY_NODE_SEPARATOR, &sptr);
}
Free(parse_str);
return n;
error:
Free(parse_str);
return NULL;
}
/*
* ctl_delete_indexes --
* (internal) removes and frees all entries on the index list
*/
static void
ctl_delete_indexes(struct ctl_indexes *indexes)
{
while (!PMDK_SLIST_EMPTY(indexes)) {
struct ctl_index *index = PMDK_SLIST_FIRST(indexes);
PMDK_SLIST_REMOVE_HEAD(indexes, entry);
Free(index);
}
}
/*
* ctl_parse_args -- (internal) parses a string argument based on the node
* structure
*/
static void *
ctl_parse_args(const struct ctl_argument *arg_proto, char *arg)
{
ASSERTne(arg, NULL);
char *dest_arg = Malloc(arg_proto->dest_size);
if (dest_arg == NULL) {
ERR("!Malloc");
return NULL;
}
char *sptr = NULL;
char *arg_sep = strtok_r(arg, CTL_VALUE_ARG_SEPARATOR, &sptr);
for (const struct ctl_argument_parser *p = arg_proto->parsers;
p->parser != NULL; ++p) {
ASSERT(p->dest_offset + p->dest_size <= arg_proto->dest_size);
if (arg_sep == NULL) {
ERR("!strtok_r");
goto error_parsing;
}
if (p->parser(arg_sep, dest_arg + p->dest_offset,
p->dest_size) != 0)
goto error_parsing;
arg_sep = strtok_r(NULL, CTL_VALUE_ARG_SEPARATOR, &sptr);
}
return dest_arg;
error_parsing:
Free(dest_arg);
return NULL;
}
/*
* ctl_query_get_real_args -- (internal) returns a pointer with actual argument
* structure as required by the node callback
*/
static void *
ctl_query_get_real_args(const struct ctl_node *n, void *write_arg,
enum ctl_query_source source)
{
void *real_arg = NULL;
switch (source) {
case CTL_QUERY_CONFIG_INPUT:
real_arg = ctl_parse_args(n->arg, write_arg);
break;
case CTL_QUERY_PROGRAMMATIC:
real_arg = write_arg;
break;
default:
ASSERT(0);
break;
}
return real_arg;
}
/*
* ctl_query_cleanup_real_args -- (internal) cleanups relevant argument
* structures allocated as a result of the get_real_args call
*/
static void
ctl_query_cleanup_real_args(const struct ctl_node *n, void *real_arg,
enum ctl_query_source source)
{
switch (source) {
case CTL_QUERY_CONFIG_INPUT:
Free(real_arg);
break;
case CTL_QUERY_PROGRAMMATIC:
break;
default:
ASSERT(0);
break;
}
}
/*
* ctl_exec_query_read -- (internal) calls the read callback of a node
*/
static int
ctl_exec_query_read(void *ctx, const struct ctl_node *n,
enum ctl_query_source source, void *arg, struct ctl_indexes *indexes)
{
if (arg == NULL) {
ERR("read queries require non-NULL argument");
errno = EINVAL;
return -1;
}
return n->cb[CTL_QUERY_READ](ctx, source, arg, indexes);
}
/*
* ctl_exec_query_write -- (internal) calls the write callback of a node
*/
static int
ctl_exec_query_write(void *ctx, const struct ctl_node *n,
enum ctl_query_source source, void *arg, struct ctl_indexes *indexes)
{
if (arg == NULL) {
ERR("write queries require non-NULL argument");
errno = EINVAL;
return -1;
}
void *real_arg = ctl_query_get_real_args(n, arg, source);
if (real_arg == NULL) {
LOG(1, "Invalid arguments");
return -1;
}
int ret = n->cb[CTL_QUERY_WRITE](ctx, source, real_arg, indexes);
ctl_query_cleanup_real_args(n, real_arg, source);
return ret;
}
/*
* ctl_exec_query_runnable -- (internal) calls the run callback of a node
*/
static int
ctl_exec_query_runnable(void *ctx, const struct ctl_node *n,
enum ctl_query_source source, void *arg, struct ctl_indexes *indexes)
{
return n->cb[CTL_QUERY_RUNNABLE](ctx, source, arg, indexes);
}
static int (*ctl_exec_query[MAX_CTL_QUERY_TYPE])(void *ctx,
const struct ctl_node *n, enum ctl_query_source source, void *arg,
struct ctl_indexes *indexes) = {
ctl_exec_query_read,
ctl_exec_query_write,
ctl_exec_query_runnable,
};
/*
* ctl_query -- (internal) parses the name and calls the appropriate methods
* from the ctl tree
*/
int
ctl_query(struct ctl *ctl, void *ctx, enum ctl_query_source source,
const char *name, enum ctl_query_type type, void *arg)
{
LOG(3, "ctl %p ctx %p source %d name %s type %d arg %p",
ctl, ctx, source, name, type, arg);
if (name == NULL) {
ERR("invalid query");
errno = EINVAL;
return -1;
}
/*
* All of the indexes are put on this list so that the handlers can
* easily retrieve the index values. The list is cleared once the ctl
* query has been handled.
*/
struct ctl_indexes indexes;
PMDK_SLIST_INIT(&indexes);
int ret = -1;
const struct ctl_node *n = ctl_find_node(CTL_NODE(global),
name, &indexes);
if (n == NULL && ctl) {
ctl_delete_indexes(&indexes);
n = ctl_find_node(ctl->root, name, &indexes);
}
if (n == NULL || n->type != CTL_NODE_LEAF || n->cb[type] == NULL) {
ERR("invalid query entry point %s", name);
errno = EINVAL;
goto out;
}
ret = ctl_exec_query[type](ctx, n, source, arg, &indexes);
out:
ctl_delete_indexes(&indexes);
return ret;
}
/*
* ctl_register_module_node -- adds a new node to the CTL tree root.
*/
void
ctl_register_module_node(struct ctl *c, const char *name, struct ctl_node *n)
{
struct ctl_node *nnode = c == NULL ?
&CTL_NODE(global)[ctl_global_first_free++] :
&c->root[c->first_free++];
nnode->children = n;
nnode->type = CTL_NODE_NAMED;
nnode->name = name;
}
/*
* ctl_parse_query -- (internal) splits an entire query string
* into name and value
*/
static int
ctl_parse_query(char *qbuf, char **name, char **value)
{
if (qbuf == NULL)
return -1;
char *sptr;
*name = strtok_r(qbuf, CTL_NAME_VALUE_SEPARATOR, &sptr);
if (*name == NULL)
return -1;
*value = strtok_r(NULL, CTL_NAME_VALUE_SEPARATOR, &sptr);
if (*value == NULL)
return -1;
/* the value itself mustn't include CTL_NAME_VALUE_SEPARATOR */
char *extra = strtok_r(NULL, CTL_NAME_VALUE_SEPARATOR, &sptr);
if (extra != NULL)
return -1;
return 0;
}
/*
* ctl_load_config -- executes the entire query collection from a provider
*/
static int
ctl_load_config(struct ctl *ctl, void *ctx, char *buf)
{
int r = 0;
char *sptr = NULL; /* for internal use of strtok */
char *name;
char *value;
ASSERTne(buf, NULL);
char *qbuf = strtok_r(buf, CTL_STRING_QUERY_SEPARATOR, &sptr);
while (qbuf != NULL) {
r = ctl_parse_query(qbuf, &name, &value);
if (r != 0) {
ERR("failed to parse query %s", qbuf);
return -1;
}
r = ctl_query(ctl, ctx, CTL_QUERY_CONFIG_INPUT,
name, CTL_QUERY_WRITE, value);
if (r < 0 && ctx != NULL)
return -1;
qbuf = strtok_r(NULL, CTL_STRING_QUERY_SEPARATOR, &sptr);
}
return 0;
}
/*
* ctl_load_config_from_string -- loads obj configuration from string
*/
int
ctl_load_config_from_string(struct ctl *ctl, void *ctx, const char *cfg_string)
{
LOG(3, "ctl %p ctx %p cfg_string \"%s\"", ctl, ctx, cfg_string);
char *buf = Strdup(cfg_string);
if (buf == NULL) {
ERR("!Strdup");
return -1;
}
int ret = ctl_load_config(ctl, ctx, buf);
Free(buf);
return ret;
}
/*
* ctl_load_config_from_file -- loads obj configuration from file
*
* This function opens up the config file, allocates a buffer of size equal to
* the size of the file, reads its content and sanitizes it for ctl_load_config.
*/
int
ctl_load_config_from_file(struct ctl *ctl, void *ctx, const char *cfg_file)
{
LOG(3, "ctl %p ctx %p cfg_file \"%s\"", ctl, ctx, cfg_file);
int ret = -1;
FILE *fp = os_fopen(cfg_file, "r");
if (fp == NULL)
return ret;
int err;
if ((err = fseek(fp, 0, SEEK_END)) != 0)
goto error_file_parse;
long fsize = ftell(fp);
if (fsize == -1)
goto error_file_parse;
if (fsize > MAX_CONFIG_FILE_LEN) {
ERR("Config file too large");
goto error_file_parse;
}
if ((err = fseek(fp, 0, SEEK_SET)) != 0)
goto error_file_parse;
char *buf = Zalloc((size_t)fsize + 1); /* +1 for NULL-termination */
if (buf == NULL) {
ERR("!Zalloc");
goto error_file_parse;
}
size_t bufpos = 0;
int c;
int is_comment_section = 0;
while ((c = fgetc(fp)) != EOF) {
if (c == '#')
is_comment_section = 1;
else if (c == '\n')
is_comment_section = 0;
else if (!is_comment_section && !isspace(c))
buf[bufpos++] = (char)c;
}
ret = ctl_load_config(ctl, ctx, buf);
Free(buf);
error_file_parse:
(void) fclose(fp);
return ret;
}
/*
* ctl_new -- allocates and initializes ctl data structures
*/
struct ctl *
ctl_new(void)
{
struct ctl *c = Zalloc(sizeof(struct ctl));
if (c == NULL) {
ERR("!Zalloc");
return NULL;
}
c->first_free = 0;
return c;
}
/*
* ctl_delete -- deletes ctl
*/
void
ctl_delete(struct ctl *c)
{
Free(c);
}
/*
* ctl_parse_ll -- (internal) parses and returns a long long signed integer
*/
static long long
ctl_parse_ll(const char *str)
{
char *endptr;
int olderrno = errno;
errno = 0;
long long val = strtoll(str, &endptr, 0);
if (endptr == str || errno != 0)
return LLONG_MIN;
errno = olderrno;
return val;
}
/*
* ctl_arg_boolean -- checks whether the provided argument contains
* either a 1 or y or Y.
*/
int
ctl_arg_boolean(const void *arg, void *dest, size_t dest_size)
{
int *intp = dest;
char in = ((char *)arg)[0];
if (tolower(in) == 'y' || in == '1') {
*intp = 1;
return 0;
} else if (tolower(in) == 'n' || in == '0') {
*intp = 0;
return 0;
}
return -1;
}
/*
* ctl_arg_integer -- parses signed integer argument
*/
int
ctl_arg_integer(const void *arg, void *dest, size_t dest_size)
{
long long val = ctl_parse_ll(arg);
if (val == LLONG_MIN)
return -1;
switch (dest_size) {
case sizeof(int):
if (val > INT_MAX || val < INT_MIN)
return -1;
*(int *)dest = (int)val;
break;
case sizeof(long long):
*(long long *)dest = val;
break;
case sizeof(uint8_t):
if (val > UINT8_MAX || val < 0)
return -1;
*(uint8_t *)dest = (uint8_t)val;
break;
default:
ERR("invalid destination size %zu", dest_size);
errno = EINVAL;
return -1;
}
return 0;
}
/*
* ctl_arg_string -- verifies length and copies a string argument into a zeroed
* buffer
*/
int
ctl_arg_string(const void *arg, void *dest, size_t dest_size)
{
/* check if the incoming string is longer or equal to dest_size */
if (strnlen(arg, dest_size) == dest_size)
return -1;
strncpy(dest, arg, dest_size);
return 0;
}
| 12,706 | 20.946459 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/pool_hdr.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, Intel Corporation */
/*
* pool_hdr.c -- pool header utilities
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <endian.h>
#include "out.h"
#include "pool_hdr.h"
/* Determine ISA for which PMDK is currently compiled */
#if defined(__x86_64) || defined(_M_X64)
/* x86 -- 64 bit */
#define PMDK_MACHINE PMDK_MACHINE_X86_64
#define PMDK_MACHINE_CLASS PMDK_MACHINE_CLASS_64
#elif defined(__aarch64__)
/* 64 bit ARM not supported yet */
#define PMDK_MACHINE PMDK_MACHINE_AARCH64
#define PMDK_MACHINE_CLASS PMDK_MACHINE_CLASS_64
#elif defined(__PPC64__)
#define PMDK_MACHINE PMDK_MACHINE_PPC64
#define PMDK_MACHINE_CLASS PMDK_MACHINE_CLASS_64
#else
/* add appropriate definitions here when porting PMDK to another ISA */
#error unable to recognize ISA at compile time
#endif
/*
* arch_machine -- (internal) determine endianness
*/
static uint8_t
arch_data(void)
{
uint16_t word = (PMDK_DATA_BE << 8) + PMDK_DATA_LE;
return ((uint8_t *)&word)[0];
}
/*
* util_get_arch_flags -- get architecture identification flags
*/
void
util_get_arch_flags(struct arch_flags *arch_flags)
{
memset(arch_flags, 0, sizeof(*arch_flags));
arch_flags->machine = PMDK_MACHINE;
arch_flags->machine_class = PMDK_MACHINE_CLASS;
arch_flags->data = arch_data();
arch_flags->alignment_desc = alignment_desc();
}
/*
* util_convert2le_hdr -- convert pool_hdr into little-endian byte order
*/
void
util_convert2le_hdr(struct pool_hdr *hdrp)
{
hdrp->major = htole32(hdrp->major);
hdrp->features.compat = htole32(hdrp->features.compat);
hdrp->features.incompat = htole32(hdrp->features.incompat);
hdrp->features.ro_compat = htole32(hdrp->features.ro_compat);
hdrp->arch_flags.alignment_desc =
htole64(hdrp->arch_flags.alignment_desc);
hdrp->arch_flags.machine = htole16(hdrp->arch_flags.machine);
hdrp->crtime = htole64(hdrp->crtime);
hdrp->checksum = htole64(hdrp->checksum);
}
/*
* util_convert2h_hdr_nocheck -- convert pool_hdr into host byte order
*/
void
util_convert2h_hdr_nocheck(struct pool_hdr *hdrp)
{
hdrp->major = le32toh(hdrp->major);
hdrp->features.compat = le32toh(hdrp->features.compat);
hdrp->features.incompat = le32toh(hdrp->features.incompat);
hdrp->features.ro_compat = le32toh(hdrp->features.ro_compat);
hdrp->crtime = le64toh(hdrp->crtime);
hdrp->arch_flags.machine = le16toh(hdrp->arch_flags.machine);
hdrp->arch_flags.alignment_desc =
le64toh(hdrp->arch_flags.alignment_desc);
hdrp->checksum = le64toh(hdrp->checksum);
}
/*
* util_arch_flags_check -- validates arch_flags
*/
int
util_check_arch_flags(const struct arch_flags *arch_flags)
{
struct arch_flags cur_af;
int ret = 0;
util_get_arch_flags(&cur_af);
if (!util_is_zeroed(&arch_flags->reserved,
sizeof(arch_flags->reserved))) {
ERR("invalid reserved values");
ret = -1;
}
if (arch_flags->machine != cur_af.machine) {
ERR("invalid machine value");
ret = -1;
}
if (arch_flags->data != cur_af.data) {
ERR("invalid data value");
ret = -1;
}
if (arch_flags->machine_class != cur_af.machine_class) {
ERR("invalid machine_class value");
ret = -1;
}
if (arch_flags->alignment_desc != cur_af.alignment_desc) {
ERR("invalid alignment_desc value");
ret = -1;
}
return ret;
}
/*
* util_get_unknown_features -- filter out unknown features flags
*/
features_t
util_get_unknown_features(features_t features, features_t known)
{
features_t unknown;
unknown.compat = util_get_not_masked_bits(
features.compat, known.compat);
unknown.incompat = util_get_not_masked_bits(
features.incompat, known.incompat);
unknown.ro_compat = util_get_not_masked_bits(
features.ro_compat, known.ro_compat);
return unknown;
}
/*
* util_feature_check -- check features masks
*/
int
util_feature_check(struct pool_hdr *hdrp, features_t known)
{
LOG(3, "hdrp %p features {incompat %#x ro_compat %#x compat %#x}",
hdrp,
known.incompat, known.ro_compat, known.compat);
features_t unknown = util_get_unknown_features(hdrp->features, known);
/* check incompatible ("must support") features */
if (unknown.incompat) {
ERR("unsafe to continue due to unknown incompat "\
"features: %#x", unknown.incompat);
errno = EINVAL;
return -1;
}
/* check RO-compatible features (force RO if unsupported) */
if (unknown.ro_compat) {
ERR("switching to read-only mode due to unknown ro_compat "\
"features: %#x", unknown.ro_compat);
return 0;
}
/* check compatible ("may") features */
if (unknown.compat) {
LOG(3, "ignoring unknown compat features: %#x", unknown.compat);
}
return 1;
}
/*
* util_feature_cmp -- compares features with reference
*
* returns 1 if features and reference match and 0 otherwise
*/
int
util_feature_cmp(features_t features, features_t ref)
{
LOG(3, "features {incompat %#x ro_compat %#x compat %#x} "
"ref {incompat %#x ro_compat %#x compat %#x}",
features.incompat, features.ro_compat, features.compat,
ref.incompat, ref.ro_compat, ref.compat);
return features.compat == ref.compat &&
features.incompat == ref.incompat &&
features.ro_compat == ref.ro_compat;
}
/*
* util_feature_is_zero -- check if features flags are zeroed
*
* returns 1 if features is zeroed and 0 otherwise
*/
int
util_feature_is_zero(features_t features)
{
const uint32_t bits =
features.compat | features.incompat |
features.ro_compat;
return bits ? 0 : 1;
}
/*
* util_feature_is_set -- check if feature flag is set in features
*
* returns 1 if feature flag is set and 0 otherwise
*/
int
util_feature_is_set(features_t features, features_t flag)
{
uint32_t bits = 0;
bits |= features.compat & flag.compat;
bits |= features.incompat & flag.incompat;
bits |= features.ro_compat & flag.ro_compat;
return bits ? 1 : 0;
}
/*
* util_feature_enable -- enable feature
*/
void
util_feature_enable(features_t *features, features_t new_feature)
{
#define FEATURE_ENABLE(flags, X) \
(flags) |= (X)
FEATURE_ENABLE(features->compat, new_feature.compat);
FEATURE_ENABLE(features->incompat, new_feature.incompat);
FEATURE_ENABLE(features->ro_compat, new_feature.ro_compat);
#undef FEATURE_ENABLE
}
/*
* util_feature_disable -- (internal) disable feature
*/
void
util_feature_disable(features_t *features, features_t old_feature)
{
#define FEATURE_DISABLE(flags, X) \
(flags) &= ~(X)
FEATURE_DISABLE(features->compat, old_feature.compat);
FEATURE_DISABLE(features->incompat, old_feature.incompat);
FEATURE_DISABLE(features->ro_compat, old_feature.ro_compat);
#undef FEATURE_DISABLE
}
static const features_t feature_2_pmempool_feature_map[] = {
FEAT_INCOMPAT(SINGLEHDR), /* PMEMPOOL_FEAT_SINGLEHDR */
FEAT_INCOMPAT(CKSUM_2K), /* PMEMPOOL_FEAT_CKSUM_2K */
FEAT_INCOMPAT(SDS), /* PMEMPOOL_FEAT_SHUTDOWN_STATE */
FEAT_COMPAT(CHECK_BAD_BLOCKS), /* PMEMPOOL_FEAT_CHECK_BAD_BLOCKS */
};
#define FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE \
ARRAY_SIZE(feature_2_pmempool_feature_map)
static const char *str_2_pmempool_feature_map[] = {
"SINGLEHDR",
"CKSUM_2K",
"SHUTDOWN_STATE",
"CHECK_BAD_BLOCKS",
};
#define PMEMPOOL_FEATURE_2_STR_MAP_SIZE ARRAY_SIZE(str_2_pmempool_feature_map)
/*
* util_str2feature -- convert string to feat_flags value
*/
features_t
util_str2feature(const char *str)
{
/* all features have to be named in incompat_features_str array */
COMPILE_ERROR_ON(FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE !=
PMEMPOOL_FEATURE_2_STR_MAP_SIZE);
for (uint32_t f = 0; f < PMEMPOOL_FEATURE_2_STR_MAP_SIZE; ++f) {
if (strcmp(str, str_2_pmempool_feature_map[f]) == 0) {
return feature_2_pmempool_feature_map[f];
}
}
return features_zero;
}
/*
* util_feature2pmempool_feature -- convert feature to pmempool_feature
*/
uint32_t
util_feature2pmempool_feature(features_t feat)
{
for (uint32_t pf = 0; pf < FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE; ++pf) {
const features_t *record =
&feature_2_pmempool_feature_map[pf];
if (util_feature_cmp(feat, *record)) {
return pf;
}
}
return UINT32_MAX;
}
/*
* util_str2pmempool_feature -- convert string to uint32_t enum pmempool_feature
* equivalent
*/
uint32_t
util_str2pmempool_feature(const char *str)
{
features_t fval = util_str2feature(str);
if (util_feature_is_zero(fval))
return UINT32_MAX;
return util_feature2pmempool_feature(fval);
}
/*
* util_feature2str -- convert uint32_t feature to string
*/
const char *
util_feature2str(features_t features, features_t *found)
{
for (uint32_t i = 0; i < FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE; ++i) {
const features_t *record = &feature_2_pmempool_feature_map[i];
if (util_feature_is_set(features, *record)) {
if (found)
memcpy(found, record, sizeof(features_t));
return str_2_pmempool_feature_map[i];
}
}
return NULL;
}
| 8,733 | 24.242775 | 80 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/shutdown_state.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* shutdown_state.h -- unsafe shudown detection
*/
#ifndef PMDK_SHUTDOWN_STATE_H
#define PMDK_SHUTDOWN_STATE_H 1
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct pool_replica;
struct shutdown_state {
uint64_t usc;
uint64_t uuid; /* UID checksum */
uint8_t dirty;
uint8_t reserved[39];
uint64_t checksum;
};
int shutdown_state_init(struct shutdown_state *sds, struct pool_replica *rep);
int shutdown_state_add_part(struct shutdown_state *sds, int fd,
struct pool_replica *rep);
void shutdown_state_set_dirty(struct shutdown_state *sds,
struct pool_replica *rep);
void shutdown_state_clear_dirty(struct shutdown_state *sds,
struct pool_replica *rep);
int shutdown_state_check(struct shutdown_state *curr_sds,
struct shutdown_state *pool_sds, struct pool_replica *rep);
#ifdef __cplusplus
}
#endif
#endif /* shutdown_state.h */
| 950 | 21.642857 | 78 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/uuid.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* uuid.c -- uuid utilities
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "uuid.h"
#include "out.h"
/*
* util_uuid_to_string -- generate a string form of the uuid
*/
int
util_uuid_to_string(const uuid_t u, char *buf)
{
int len; /* size that is returned from sprintf call */
if (buf == NULL) {
LOG(2, "invalid buffer for uuid string");
return -1;
}
if (u == NULL) {
LOG(2, "invalid uuid structure");
return -1;
}
struct uuid *uuid = (struct uuid *)u;
len = snprintf(buf, POOL_HDR_UUID_STR_LEN,
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid->time_low, uuid->time_mid, uuid->time_hi_and_ver,
uuid->clock_seq_hi, uuid->clock_seq_low, uuid->node[0],
uuid->node[1], uuid->node[2], uuid->node[3], uuid->node[4],
uuid->node[5]);
if (len != POOL_HDR_UUID_STR_LEN - 1) {
LOG(2, "snprintf(uuid): %d", len);
return -1;
}
return 0;
}
/*
* util_uuid_from_string -- generate a binary form of the uuid
*
* uuid string read from /proc/sys/kernel/random/uuid. UUID string
* format example:
* f81d4fae-7dec-11d0-a765-00a0c91e6bf6
*/
int
util_uuid_from_string(const char *uuid, struct uuid *ud)
{
if (strlen(uuid) != 36) {
LOG(2, "invalid uuid string");
return -1;
}
if (uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' ||
uuid[23] != '-') {
LOG(2, "invalid uuid string");
return -1;
}
int n = sscanf(uuid,
"%08x-%04hx-%04hx-%02hhx%02hhx-"
"%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
&ud->time_low, &ud->time_mid, &ud->time_hi_and_ver,
&ud->clock_seq_hi, &ud->clock_seq_low, &ud->node[0],
&ud->node[1], &ud->node[2], &ud->node[3], &ud->node[4],
&ud->node[5]);
if (n != 11) {
LOG(2, "sscanf(uuid)");
return -1;
}
return 0;
}
| 1,818 | 20.654762 | 66 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/queue.h
|
/*
* Source: glibc 2.24 (git://sourceware.org/glibc.git /misc/sys/queue.h)
*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
* 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:
* 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.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
#ifndef _PMDK_QUEUE_H_
#define _PMDK_QUEUE_H_
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues, and circular queues.
*
* A singly-linked list is headed by a single forward pointer. The
* elements are singly linked for minimum space and pointer manipulation
* overhead at the expense of O(n) removal for arbitrary elements. New
* elements can be added to the list after an existing element or at the
* head of the list. Elements being removed from the head of the list
* should use the explicit macro for this purpose for optimum
* efficiency. A singly-linked list may only be traversed in the forward
* direction. Singly-linked lists are ideal for applications with large
* datasets and few or no removals or for implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* A circle queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A circle queue may be traversed in either direction, but has a more
* complex end of list detection.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
/*
* XXX This is a workaround for a bug in the llvm's static analyzer. For more
* info see https://github.com/pmem/issues/issues/309.
*/
#ifdef __clang_analyzer__
static void custom_assert(void)
{
abort();
}
#define ANALYZER_ASSERT(x) (__builtin_expect(!(x), 0) ? (void)0 : custom_assert())
#else
#define ANALYZER_ASSERT(x) do {} while (0)
#endif
/*
* List definitions.
*/
#define PMDK_LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define PMDK_LIST_HEAD_INITIALIZER(head) \
{ NULL }
#ifdef __cplusplus
#define PMDK__CAST_AND_ASSIGN(x, y) x = (__typeof__(x))y;
#else
#define PMDK__CAST_AND_ASSIGN(x, y) x = (void *)(y);
#endif
#define PMDK_LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
/*
* List functions.
*/
#define PMDK_LIST_INIT(head) do { \
(head)->lh_first = NULL; \
} while (/*CONSTCOND*/0)
#define PMDK_LIST_INSERT_AFTER(listelm, elm, field) do { \
if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
(listelm)->field.le_next->field.le_prev = \
&(elm)->field.le_next; \
(listelm)->field.le_next = (elm); \
(elm)->field.le_prev = &(listelm)->field.le_next; \
} while (/*CONSTCOND*/0)
#define PMDK_LIST_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.le_prev = (listelm)->field.le_prev; \
(elm)->field.le_next = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &(elm)->field.le_next; \
} while (/*CONSTCOND*/0)
#define PMDK_LIST_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.le_next = (head)->lh_first) != NULL) \
(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
(head)->lh_first = (elm); \
(elm)->field.le_prev = &(head)->lh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_LIST_REMOVE(elm, field) do { \
ANALYZER_ASSERT((elm) != NULL); \
if ((elm)->field.le_next != NULL) \
(elm)->field.le_next->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = (elm)->field.le_next; \
} while (/*CONSTCOND*/0)
#define PMDK_LIST_FOREACH(var, head, field) \
for ((var) = ((head)->lh_first); \
(var); \
(var) = ((var)->field.le_next))
/*
* List access methods.
*/
#define PMDK_LIST_EMPTY(head) ((head)->lh_first == NULL)
#define PMDK_LIST_FIRST(head) ((head)->lh_first)
#define PMDK_LIST_NEXT(elm, field) ((elm)->field.le_next)
/*
* Singly-linked List definitions.
*/
#define PMDK_SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define PMDK_SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define PMDK_SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List functions.
*/
#define PMDK_SLIST_INIT(head) do { \
(head)->slh_first = NULL; \
} while (/*CONSTCOND*/0)
#define PMDK_SLIST_INSERT_AFTER(slistelm, elm, field) do { \
(elm)->field.sle_next = (slistelm)->field.sle_next; \
(slistelm)->field.sle_next = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_SLIST_INSERT_HEAD(head, elm, field) do { \
(elm)->field.sle_next = (head)->slh_first; \
(head)->slh_first = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_SLIST_REMOVE_HEAD(head, field) do { \
(head)->slh_first = (head)->slh_first->field.sle_next; \
} while (/*CONSTCOND*/0)
#define PMDK_SLIST_REMOVE(head, elm, type, field) do { \
if ((head)->slh_first == (elm)) { \
PMDK_SLIST_REMOVE_HEAD((head), field); \
} \
else { \
struct type *curelm = (head)->slh_first; \
while(curelm->field.sle_next != (elm)) \
curelm = curelm->field.sle_next; \
curelm->field.sle_next = \
curelm->field.sle_next->field.sle_next; \
} \
} while (/*CONSTCOND*/0)
#define PMDK_SLIST_FOREACH(var, head, field) \
for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next)
/*
* Singly-linked List access methods.
*/
#define PMDK_SLIST_EMPTY(head) ((head)->slh_first == NULL)
#define PMDK_SLIST_FIRST(head) ((head)->slh_first)
#define PMDK_SLIST_NEXT(elm, field) ((elm)->field.sle_next)
/*
* Singly-linked Tail queue declarations.
*/
#define PMDK_STAILQ_HEAD(name, type) \
struct name { \
struct type *stqh_first; /* first element */ \
struct type **stqh_last; /* addr of last next element */ \
}
#define PMDK_STAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).stqh_first }
#define PMDK_STAILQ_ENTRY(type) \
struct { \
struct type *stqe_next; /* next element */ \
}
/*
* Singly-linked Tail queue functions.
*/
#define PMDK_STAILQ_INIT(head) do { \
(head)->stqh_first = NULL; \
(head)->stqh_last = &(head)->stqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \
(head)->stqh_last = &(elm)->field.stqe_next; \
(head)->stqh_first = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.stqe_next = NULL; \
*(head)->stqh_last = (elm); \
(head)->stqh_last = &(elm)->field.stqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\
(head)->stqh_last = &(elm)->field.stqe_next; \
(listelm)->field.stqe_next = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_REMOVE_HEAD(head, field) do { \
if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \
(head)->stqh_last = &(head)->stqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_REMOVE(head, elm, type, field) do { \
if ((head)->stqh_first == (elm)) { \
PMDK_STAILQ_REMOVE_HEAD((head), field); \
} else { \
struct type *curelm = (head)->stqh_first; \
while (curelm->field.stqe_next != (elm)) \
curelm = curelm->field.stqe_next; \
if ((curelm->field.stqe_next = \
curelm->field.stqe_next->field.stqe_next) == NULL) \
(head)->stqh_last = &(curelm)->field.stqe_next; \
} \
} while (/*CONSTCOND*/0)
#define PMDK_STAILQ_FOREACH(var, head, field) \
for ((var) = ((head)->stqh_first); \
(var); \
(var) = ((var)->field.stqe_next))
#define PMDK_STAILQ_CONCAT(head1, head2) do { \
if (!PMDK_STAILQ_EMPTY((head2))) { \
*(head1)->stqh_last = (head2)->stqh_first; \
(head1)->stqh_last = (head2)->stqh_last; \
PMDK_STAILQ_INIT((head2)); \
} \
} while (/*CONSTCOND*/0)
/*
* Singly-linked Tail queue access methods.
*/
#define PMDK_STAILQ_EMPTY(head) ((head)->stqh_first == NULL)
#define PMDK_STAILQ_FIRST(head) ((head)->stqh_first)
#define PMDK_STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
/*
* Simple queue definitions.
*/
#define PMDK_SIMPLEQ_HEAD(name, type) \
struct name { \
struct type *sqh_first; /* first element */ \
struct type **sqh_last; /* addr of last next element */ \
}
#define PMDK_SIMPLEQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).sqh_first }
#define PMDK_SIMPLEQ_ENTRY(type) \
struct { \
struct type *sqe_next; /* next element */ \
}
/*
* Simple queue functions.
*/
#define PMDK_SIMPLEQ_INIT(head) do { \
(head)->sqh_first = NULL; \
(head)->sqh_last = &(head)->sqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \
(head)->sqh_last = &(elm)->field.sqe_next; \
(head)->sqh_first = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.sqe_next = NULL; \
*(head)->sqh_last = (elm); \
(head)->sqh_last = &(elm)->field.sqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
(head)->sqh_last = &(elm)->field.sqe_next; \
(listelm)->field.sqe_next = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_REMOVE_HEAD(head, field) do { \
if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \
(head)->sqh_last = &(head)->sqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_REMOVE(head, elm, type, field) do { \
if ((head)->sqh_first == (elm)) { \
PMDK_SIMPLEQ_REMOVE_HEAD((head), field); \
} else { \
struct type *curelm = (head)->sqh_first; \
while (curelm->field.sqe_next != (elm)) \
curelm = curelm->field.sqe_next; \
if ((curelm->field.sqe_next = \
curelm->field.sqe_next->field.sqe_next) == NULL) \
(head)->sqh_last = &(curelm)->field.sqe_next; \
} \
} while (/*CONSTCOND*/0)
#define PMDK_SIMPLEQ_FOREACH(var, head, field) \
for ((var) = ((head)->sqh_first); \
(var); \
(var) = ((var)->field.sqe_next))
/*
* Simple queue access methods.
*/
#define PMDK_SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL)
#define PMDK_SIMPLEQ_FIRST(head) ((head)->sqh_first)
#define PMDK_SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next)
/*
* Tail queue definitions.
*/
#define PMDK__TAILQ_HEAD(name, type, qual) \
struct name { \
qual type *tqh_first; /* first element */ \
qual type *qual *tqh_last; /* addr of last next element */ \
}
#define PMDK_TAILQ_HEAD(name, type) PMDK__TAILQ_HEAD(name, struct type,)
#define PMDK_TAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).tqh_first }
#define PMDK__TAILQ_ENTRY(type, qual) \
struct { \
qual type *tqe_next; /* next element */ \
qual type *qual *tqe_prev; /* address of previous next element */\
}
#define PMDK_TAILQ_ENTRY(type) PMDK__TAILQ_ENTRY(struct type,)
/*
* Tail queue functions.
*/
#define PMDK_TAILQ_INIT(head) do { \
(head)->tqh_first = NULL; \
(head)->tqh_last = &(head)->tqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \
(head)->tqh_first->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(head)->tqh_first = (elm); \
(elm)->field.tqe_prev = &(head)->tqh_first; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.tqe_next = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
(elm)->field.tqe_next->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(listelm)->field.tqe_next = (elm); \
(elm)->field.tqe_prev = &(listelm)->field.tqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
(elm)->field.tqe_next = (listelm); \
*(listelm)->field.tqe_prev = (elm); \
(listelm)->field.tqe_prev = &(elm)->field.tqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_REMOVE(head, elm, field) do { \
ANALYZER_ASSERT((elm) != NULL); \
if (((elm)->field.tqe_next) != NULL) \
(elm)->field.tqe_next->field.tqe_prev = \
(elm)->field.tqe_prev; \
else \
(head)->tqh_last = (elm)->field.tqe_prev; \
*(elm)->field.tqe_prev = (elm)->field.tqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_TAILQ_FOREACH(var, head, field) \
for ((var) = ((head)->tqh_first); \
(var); \
(var) = ((var)->field.tqe_next))
#define PMDK_TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \
(var); \
(var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last)))
#define PMDK_TAILQ_CONCAT(head1, head2, field) do { \
if (!PMDK_TAILQ_EMPTY(head2)) { \
*(head1)->tqh_last = (head2)->tqh_first; \
(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
(head1)->tqh_last = (head2)->tqh_last; \
PMDK_TAILQ_INIT((head2)); \
} \
} while (/*CONSTCOND*/0)
/*
* Tail queue access methods.
*/
#define PMDK_TAILQ_EMPTY(head) ((head)->tqh_first == NULL)
#define PMDK_TAILQ_FIRST(head) ((head)->tqh_first)
#define PMDK_TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define PMDK_TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
#define PMDK_TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
/*
* Circular queue definitions.
*/
#define PMDK_CIRCLEQ_HEAD(name, type) \
struct name { \
struct type *cqh_first; /* first element */ \
struct type *cqh_last; /* last element */ \
}
#define PMDK_CIRCLEQ_HEAD_INITIALIZER(head) \
{ (void *)&(head), (void *)&(head) }
#define PMDK_CIRCLEQ_ENTRY(type) \
struct { \
struct type *cqe_next; /* next element */ \
struct type *cqe_prev; /* previous element */ \
}
/*
* Circular queue functions.
*/
#define PMDK_CIRCLEQ_INIT(head) do { \
PMDK__CAST_AND_ASSIGN((head)->cqh_first, (head)); \
PMDK__CAST_AND_ASSIGN((head)->cqh_last, (head)); \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
(elm)->field.cqe_next = (listelm)->field.cqe_next; \
(elm)->field.cqe_prev = (listelm); \
if ((listelm)->field.cqe_next == (void *)(head)) \
(head)->cqh_last = (elm); \
else \
(listelm)->field.cqe_next->field.cqe_prev = (elm); \
(listelm)->field.cqe_next = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \
(elm)->field.cqe_next = (listelm); \
(elm)->field.cqe_prev = (listelm)->field.cqe_prev; \
if ((listelm)->field.cqe_prev == (void *)(head)) \
(head)->cqh_first = (elm); \
else \
(listelm)->field.cqe_prev->field.cqe_next = (elm); \
(listelm)->field.cqe_prev = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_INSERT_HEAD(head, elm, field) do { \
(elm)->field.cqe_next = (head)->cqh_first; \
(elm)->field.cqe_prev = (void *)(head); \
if ((head)->cqh_last == (void *)(head)) \
(head)->cqh_last = (elm); \
else \
(head)->cqh_first->field.cqe_prev = (elm); \
(head)->cqh_first = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_INSERT_TAIL(head, elm, field) do { \
PMDK__CAST_AND_ASSIGN((elm)->field.cqe_next, (head)); \
(elm)->field.cqe_prev = (head)->cqh_last; \
if ((head)->cqh_first == (void *)(head)) \
(head)->cqh_first = (elm); \
else \
(head)->cqh_last->field.cqe_next = (elm); \
(head)->cqh_last = (elm); \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_REMOVE(head, elm, field) do { \
if ((elm)->field.cqe_next == (void *)(head)) \
(head)->cqh_last = (elm)->field.cqe_prev; \
else \
(elm)->field.cqe_next->field.cqe_prev = \
(elm)->field.cqe_prev; \
if ((elm)->field.cqe_prev == (void *)(head)) \
(head)->cqh_first = (elm)->field.cqe_next; \
else \
(elm)->field.cqe_prev->field.cqe_next = \
(elm)->field.cqe_next; \
} while (/*CONSTCOND*/0)
#define PMDK_CIRCLEQ_FOREACH(var, head, field) \
for ((var) = ((head)->cqh_first); \
(var) != (const void *)(head); \
(var) = ((var)->field.cqe_next))
#define PMDK_CIRCLEQ_FOREACH_REVERSE(var, head, field) \
for ((var) = ((head)->cqh_last); \
(var) != (const void *)(head); \
(var) = ((var)->field.cqe_prev))
/*
* Circular queue access methods.
*/
#define PMDK_CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head))
#define PMDK_CIRCLEQ_FIRST(head) ((head)->cqh_first)
#define PMDK_CIRCLEQ_LAST(head) ((head)->cqh_last)
#define PMDK_CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next)
#define PMDK_CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev)
#define PMDK_CIRCLEQ_LOOP_NEXT(head, elm, field) \
(((elm)->field.cqe_next == (void *)(head)) \
? ((head)->cqh_first) \
: ((elm)->field.cqe_next))
#define PMDK_CIRCLEQ_LOOP_PREV(head, elm, field) \
(((elm)->field.cqe_prev == (void *)(head)) \
? ((head)->cqh_last) \
: ((elm)->field.cqe_prev))
/*
* Sorted queue functions.
*/
#define PMDK_SORTEDQ_HEAD(name, type) PMDK_CIRCLEQ_HEAD(name, type)
#define PMDK_SORTEDQ_HEAD_INITIALIZER(head) PMDK_CIRCLEQ_HEAD_INITIALIZER(head)
#define PMDK_SORTEDQ_ENTRY(type) PMDK_CIRCLEQ_ENTRY(type)
#define PMDK_SORTEDQ_INIT(head) PMDK_CIRCLEQ_INIT(head)
#define PMDK_SORTEDQ_INSERT(head, elm, field, type, comparer) { \
type *_elm_it; \
for (_elm_it = (head)->cqh_first; \
((_elm_it != (void *)(head)) && \
(comparer(_elm_it, (elm)) < 0)); \
_elm_it = _elm_it->field.cqe_next) \
/*NOTHING*/; \
if (_elm_it == (void *)(head)) \
PMDK_CIRCLEQ_INSERT_TAIL(head, elm, field); \
else \
PMDK_CIRCLEQ_INSERT_BEFORE(head, _elm_it, elm, field); \
}
#define PMDK_SORTEDQ_REMOVE(head, elm, field) PMDK_CIRCLEQ_REMOVE(head, elm, field)
#define PMDK_SORTEDQ_FOREACH(var, head, field) PMDK_CIRCLEQ_FOREACH(var, head, field)
#define PMDK_SORTEDQ_FOREACH_REVERSE(var, head, field) \
PMDK_CIRCLEQ_FOREACH_REVERSE(var, head, field)
/*
* Sorted queue access methods.
*/
#define PMDK_SORTEDQ_EMPTY(head) PMDK_CIRCLEQ_EMPTY(head)
#define PMDK_SORTEDQ_FIRST(head) PMDK_CIRCLEQ_FIRST(head)
#define PMDK_SORTEDQ_LAST(head) PMDK_CIRCLEQ_LAST(head)
#define PMDK_SORTEDQ_NEXT(elm, field) PMDK_CIRCLEQ_NEXT(elm, field)
#define PMDK_SORTEDQ_PREV(elm, field) PMDK_CIRCLEQ_PREV(elm, field)
#endif /* sys/queue.h */
| 22,165 | 33.907087 | 85 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/set.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2019, 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.
*/
/*
* set.h -- internal definitions for set module
*/
#ifndef PMDK_SET_H
#define PMDK_SET_H 1
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/types.h>
#include "out.h"
#include "vec.h"
#include "pool_hdr.h"
#include "librpmem.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* pool sets & replicas
*/
#define POOLSET_HDR_SIG "PMEMPOOLSET"
#define POOLSET_HDR_SIG_LEN 11 /* does NOT include '\0' */
#define POOLSET_REPLICA_SIG "REPLICA"
#define POOLSET_REPLICA_SIG_LEN 7 /* does NOT include '\0' */
#define POOLSET_OPTION_SIG "OPTION"
#define POOLSET_OPTION_SIG_LEN 6 /* does NOT include '\0' */
/* pool set option flags */
enum pool_set_option_flag {
OPTION_UNKNOWN = 0x0,
OPTION_SINGLEHDR = 0x1, /* pool headers only in the first part */
OPTION_NOHDRS = 0x2, /* no pool headers, remote replicas only */
};
struct pool_set_option {
const char *name;
enum pool_set_option_flag flag;
};
#define POOL_LOCAL 0
#define POOL_REMOTE 1
#define REPLICAS_DISABLED 0
#define REPLICAS_ENABLED 1
/* util_pool_open flags */
#define POOL_OPEN_COW 1 /* copy-on-write mode */
#define POOL_OPEN_IGNORE_SDS 2 /* ignore shutdown state */
#define POOL_OPEN_IGNORE_BAD_BLOCKS 4 /* ignore bad blocks */
#define POOL_OPEN_CHECK_BAD_BLOCKS 8 /* check bad blocks */
enum del_parts_mode {
DO_NOT_DELETE_PARTS, /* do not delete part files */
DELETE_CREATED_PARTS, /* delete only newly created parts files */
DELETE_ALL_PARTS /* force delete all parts files */
};
struct pool_set_part {
/* populated by a pool set file parser */
const char *path;
size_t filesize; /* aligned to page size */
int fd;
int flags; /* stores flags used when opening the file */
/* valid only if fd >= 0 */
int is_dev_dax; /* indicates if the part is on device dax */
size_t alignment; /* internal alignment (Device DAX only) */
int created; /* indicates newly created (zeroed) file */
/* util_poolset_open/create */
void *remote_hdr; /* allocated header for remote replica */
void *hdr; /* base address of header */
size_t hdrsize; /* size of the header mapping */
int hdr_map_sync; /* header mapped with MAP_SYNC */
void *addr; /* base address of the mapping */
size_t size; /* size of the mapping - page aligned */
int map_sync; /* part has been mapped with MAP_SYNC flag */
int rdonly; /* is set based on compat features, affects */
/* the whole poolset */
uuid_t uuid;
int has_bad_blocks; /* part file contains bad blocks */
int sds_dirty_modified; /* sds dirty flag was set */
};
struct pool_set_directory {
const char *path;
size_t resvsize; /* size of the address space reservation */
};
struct remote_replica {
void *rpp; /* RPMEMpool opaque handle */
char *node_addr; /* address of a remote node */
/* poolset descriptor is a pool set file name on a remote node */
char *pool_desc; /* descriptor of a poolset */
};
struct pool_replica {
unsigned nparts;
unsigned nallocated;
unsigned nhdrs; /* should be 0, 1 or nparts */
size_t repsize; /* total size of all the parts (mappings) */
size_t resvsize; /* min size of the address space reservation */
int is_pmem; /* true if all the parts are in PMEM */
struct remote_replica *remote; /* not NULL if the replica */
/* is a remote one */
VEC(, struct pool_set_directory) directory;
struct pool_set_part part[];
};
struct pool_set {
char *path; /* path of the poolset file */
unsigned nreplicas;
uuid_t uuid;
int rdonly;
int zeroed; /* true if all the parts are new files */
size_t poolsize; /* the smallest replica size */
int has_bad_blocks; /* pool set contains bad blocks */
int remote; /* true if contains a remote replica */
unsigned options; /* enabled pool set options */
int directory_based;
size_t resvsize;
unsigned next_id;
unsigned next_directory_id;
int ignore_sds; /* don't use shutdown state */
struct pool_replica *replica[];
};
struct part_file {
int is_remote;
/*
* Pointer to the part file structure -
* - not-NULL only for a local part file
*/
struct pool_set_part *part;
/*
* Pointer to the replica structure -
* - not-NULL only for a remote replica
*/
struct remote_replica *remote;
};
struct pool_attr {
char signature[POOL_HDR_SIG_LEN]; /* pool signature */
uint32_t major; /* format major version number */
features_t features; /* features flags */
unsigned char poolset_uuid[POOL_HDR_UUID_LEN]; /* pool uuid */
unsigned char first_part_uuid[POOL_HDR_UUID_LEN]; /* first part uuid */
unsigned char prev_repl_uuid[POOL_HDR_UUID_LEN]; /* prev replica uuid */
unsigned char next_repl_uuid[POOL_HDR_UUID_LEN]; /* next replica uuid */
unsigned char arch_flags[POOL_HDR_ARCH_LEN]; /* arch flags */
};
/* get index of the (r)th replica */
static inline unsigned
REPidx(const struct pool_set *set, unsigned r)
{
ASSERTne(set->nreplicas, 0);
return r % set->nreplicas;
}
/* get index of the (r + 1)th replica */
static inline unsigned
REPNidx(const struct pool_set *set, unsigned r)
{
ASSERTne(set->nreplicas, 0);
return (r + 1) % set->nreplicas;
}
/* get index of the (r - 1)th replica */
static inline unsigned
REPPidx(const struct pool_set *set, unsigned r)
{
ASSERTne(set->nreplicas, 0);
return (set->nreplicas + r - 1) % set->nreplicas;
}
/* get index of the (r)th part */
static inline unsigned
PARTidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nparts, 0);
return p % rep->nparts;
}
/* get index of the (r + 1)th part */
static inline unsigned
PARTNidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nparts, 0);
return (p + 1) % rep->nparts;
}
/* get index of the (r - 1)th part */
static inline unsigned
PARTPidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nparts, 0);
return (rep->nparts + p - 1) % rep->nparts;
}
/* get index of the (r)th part */
static inline unsigned
HDRidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nhdrs, 0);
return p % rep->nhdrs;
}
/* get index of the (r + 1)th part */
static inline unsigned
HDRNidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nhdrs, 0);
return (p + 1) % rep->nhdrs;
}
/* get index of the (r - 1)th part */
static inline unsigned
HDRPidx(const struct pool_replica *rep, unsigned p)
{
ASSERTne(rep->nhdrs, 0);
return (rep->nhdrs + p - 1) % rep->nhdrs;
}
/* get (r)th replica */
static inline struct pool_replica *
REP(const struct pool_set *set, unsigned r)
{
return set->replica[REPidx(set, r)];
}
/* get (r + 1)th replica */
static inline struct pool_replica *
REPN(const struct pool_set *set, unsigned r)
{
return set->replica[REPNidx(set, r)];
}
/* get (r - 1)th replica */
static inline struct pool_replica *
REPP(const struct pool_set *set, unsigned r)
{
return set->replica[REPPidx(set, r)];
}
/* get (p)th part */
static inline struct pool_set_part *
PART(struct pool_replica *rep, unsigned p)
{
return &rep->part[PARTidx(rep, p)];
}
/* get (p + 1)th part */
static inline struct pool_set_part *
PARTN(struct pool_replica *rep, unsigned p)
{
return &rep->part[PARTNidx(rep, p)];
}
/* get (p - 1)th part */
static inline struct pool_set_part *
PARTP(struct pool_replica *rep, unsigned p)
{
return &rep->part[PARTPidx(rep, p)];
}
/* get (p)th header */
static inline struct pool_hdr *
HDR(struct pool_replica *rep, unsigned p)
{
return (struct pool_hdr *)(rep->part[HDRidx(rep, p)].hdr);
}
/* get (p + 1)th header */
static inline struct pool_hdr *
HDRN(struct pool_replica *rep, unsigned p)
{
return (struct pool_hdr *)(rep->part[HDRNidx(rep, p)].hdr);
}
/* get (p - 1)th header */
static inline struct pool_hdr *
HDRP(struct pool_replica *rep, unsigned p)
{
return (struct pool_hdr *)(rep->part[HDRPidx(rep, p)].hdr);
}
extern int Prefault_at_open;
extern int Prefault_at_create;
extern int SDS_at_create;
extern int Fallocate_at_create;
extern int COW_at_open;
int util_poolset_parse(struct pool_set **setp, const char *path, int fd);
int util_poolset_read(struct pool_set **setp, const char *path);
int util_poolset_create_set(struct pool_set **setp, const char *path,
size_t poolsize, size_t minsize, int ignore_sds);
int util_poolset_open(struct pool_set *set);
void util_poolset_close(struct pool_set *set, enum del_parts_mode del);
void util_poolset_free(struct pool_set *set);
int util_poolset_chmod(struct pool_set *set, mode_t mode);
void util_poolset_fdclose(struct pool_set *set);
void util_poolset_fdclose_always(struct pool_set *set);
int util_is_poolset_file(const char *path);
int util_poolset_foreach_part_struct(struct pool_set *set,
int (*cb)(struct part_file *pf, void *arg), void *arg);
int util_poolset_foreach_part(const char *path,
int (*cb)(struct part_file *pf, void *arg), void *arg);
size_t util_poolset_size(const char *path);
int util_replica_deep_common(const void *addr, size_t len,
struct pool_set *set, unsigned replica_id, int flush);
int util_replica_deep_persist(const void *addr, size_t len,
struct pool_set *set, unsigned replica_id);
int util_replica_deep_drain(const void *addr, size_t len,
struct pool_set *set, unsigned replica_id);
int util_pool_create(struct pool_set **setp, const char *path, size_t poolsize,
size_t minsize, size_t minpartsize, const struct pool_attr *attr,
unsigned *nlanes, int can_have_rep);
int util_pool_create_uuids(struct pool_set **setp, const char *path,
size_t poolsize, size_t minsize, size_t minpartsize,
const struct pool_attr *attr, unsigned *nlanes, int can_have_rep,
int remote);
int util_part_open(struct pool_set_part *part, size_t minsize, int create_part);
void util_part_fdclose(struct pool_set_part *part);
int util_replica_open(struct pool_set *set, unsigned repidx, int flags);
int util_replica_set_attr(struct pool_replica *rep,
const struct rpmem_pool_attr *rattr);
void util_pool_hdr2attr(struct pool_attr *attr, struct pool_hdr *hdr);
void util_pool_attr2hdr(struct pool_hdr *hdr,
const struct pool_attr *attr);
int util_replica_close(struct pool_set *set, unsigned repidx);
int util_map_part(struct pool_set_part *part, void *addr, size_t size,
size_t offset, int flags, int rdonly);
int util_unmap_part(struct pool_set_part *part);
int util_unmap_parts(struct pool_replica *rep, unsigned start_index,
unsigned end_index);
int util_header_create(struct pool_set *set, unsigned repidx, unsigned partidx,
const struct pool_attr *attr, int overwrite);
int util_map_hdr(struct pool_set_part *part, int flags, int rdonly);
void util_unmap_hdr(struct pool_set_part *part);
int util_pool_has_device_dax(struct pool_set *set);
int util_pool_open_nocheck(struct pool_set *set, unsigned flags);
int util_pool_open(struct pool_set **setp, const char *path, size_t minpartsize,
const struct pool_attr *attr, unsigned *nlanes, void *addr,
unsigned flags);
int util_pool_open_remote(struct pool_set **setp, const char *path, int cow,
size_t minpartsize, struct rpmem_pool_attr *rattr);
void *util_pool_extend(struct pool_set *set, size_t *size, size_t minpartsize);
void util_remote_init(void);
void util_remote_fini(void);
int util_update_remote_header(struct pool_set *set, unsigned repn);
void util_remote_init_lock(void);
void util_remote_destroy_lock(void);
int util_pool_close_remote(RPMEMpool *rpp);
void util_remote_unload(void);
void util_replica_fdclose(struct pool_replica *rep);
int util_poolset_remote_open(struct pool_replica *rep, unsigned repidx,
size_t minsize, int create, void *pool_addr,
size_t pool_size, unsigned *nlanes);
int util_remote_load(void);
int util_replica_open_remote(struct pool_set *set, unsigned repidx, int flags);
int util_poolset_remote_replica_open(struct pool_set *set, unsigned repidx,
size_t minsize, int create, unsigned *nlanes);
int util_replica_close_local(struct pool_replica *rep, unsigned repn,
enum del_parts_mode del);
int util_replica_close_remote(struct pool_replica *rep, unsigned repn,
enum del_parts_mode del);
extern int (*Rpmem_persist)(RPMEMpool *rpp, size_t offset, size_t length,
unsigned lane, unsigned flags);
extern int (*Rpmem_deep_persist)(RPMEMpool *rpp, size_t offset, size_t length,
unsigned lane);
extern int (*Rpmem_read)(RPMEMpool *rpp, void *buff, size_t offset,
size_t length, unsigned lane);
extern int (*Rpmem_close)(RPMEMpool *rpp);
extern int (*Rpmem_remove)(const char *target,
const char *pool_set_name, int flags);
extern int (*Rpmem_set_attr)(RPMEMpool *rpp,
const struct rpmem_pool_attr *rattr);
#ifdef __cplusplus
}
#endif
#endif
| 14,145 | 31.077098 | 80 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/shutdown_state.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* shutdown_state.c -- unsafe shudown detection
*/
#include <string.h>
#include <stdbool.h>
#include <endian.h>
#include "shutdown_state.h"
#include "out.h"
#include "util.h"
#include "os_deep.h"
#include "set.h"
#include "libpmem2.h"
#include "badblocks.h"
#include "../libpmem2/pmem2_utils.h"
#define FLUSH_SDS(sds, rep) \
if ((rep) != NULL) os_part_deep_common(rep, 0, sds, sizeof(*(sds)), 1)
/*
* shutdown_state_checksum -- (internal) counts SDS checksum and flush it
*/
static void
shutdown_state_checksum(struct shutdown_state *sds, struct pool_replica *rep)
{
LOG(3, "sds %p", sds);
util_checksum(sds, sizeof(*sds), &sds->checksum, 1, 0);
FLUSH_SDS(sds, rep);
}
/*
* shutdown_state_init -- initializes shutdown_state struct
*/
int
shutdown_state_init(struct shutdown_state *sds, struct pool_replica *rep)
{
/* check if we didn't change size of shutdown_state accidentally */
COMPILE_ERROR_ON(sizeof(struct shutdown_state) != 64);
LOG(3, "sds %p", sds);
memset(sds, 0, sizeof(*sds));
shutdown_state_checksum(sds, rep);
return 0;
}
/*
* shutdown_state_add_part -- adds file uuid and usc to shutdown_state struct
*
* if path does not exist it will fail which does NOT mean shutdown failure
*/
int
shutdown_state_add_part(struct shutdown_state *sds, int fd,
struct pool_replica *rep)
{
LOG(3, "sds %p, fd %d", sds, fd);
size_t len = 0;
char *uid;
uint64_t usc;
struct pmem2_source *src;
if (pmem2_source_from_fd(&src, fd))
return 1;
int ret = pmem2_source_device_usc(src, &usc);
if (ret == PMEM2_E_NOSUPP) {
usc = 0;
} else if (ret != 0) {
if (ret == -EPERM) {
/* overwrite error message */
ERR(
"Cannot read unsafe shutdown count. For more information please check https://github.com/pmem/pmdk/issues/4207");
}
LOG(2, "cannot read unsafe shutdown count for %d", fd);
goto err;
}
ret = pmem2_source_device_id(src, NULL, &len);
if (ret != PMEM2_E_NOSUPP && ret != 0) {
ERR("cannot read uuid of %d", fd);
goto err;
}
len += 4 - len % 4;
uid = Zalloc(len);
if (uid == NULL) {
ERR("!Zalloc");
goto err;
}
ret = pmem2_source_device_id(src, uid, &len);
if (ret != PMEM2_E_NOSUPP && ret != 0) {
ERR("cannot read uuid of %d", fd);
Free(uid);
goto err;
}
sds->usc = htole64(le64toh(sds->usc) + usc);
uint64_t tmp;
util_checksum(uid, len, &tmp, 1, 0);
sds->uuid = htole64(le64toh(sds->uuid) + tmp);
FLUSH_SDS(sds, rep);
Free(uid);
pmem2_source_delete(&src);
shutdown_state_checksum(sds, rep);
return 0;
err:
pmem2_source_delete(&src);
return 1;
}
/*
* shutdown_state_set_dirty -- sets dirty pool flag
*/
void
shutdown_state_set_dirty(struct shutdown_state *sds, struct pool_replica *rep)
{
LOG(3, "sds %p", sds);
sds->dirty = 1;
rep->part[0].sds_dirty_modified = 1;
FLUSH_SDS(sds, rep);
shutdown_state_checksum(sds, rep);
}
/*
* shutdown_state_clear_dirty -- clears dirty pool flag
*/
void
shutdown_state_clear_dirty(struct shutdown_state *sds, struct pool_replica *rep)
{
LOG(3, "sds %p", sds);
struct pool_set_part part = rep->part[0];
/*
* If a dirty flag was set in previous program execution it should be
* preserved as it stores information about potential ADR failure.
*/
if (part.sds_dirty_modified != 1)
return;
sds->dirty = 0;
part.sds_dirty_modified = 0;
FLUSH_SDS(sds, rep);
shutdown_state_checksum(sds, rep);
}
/*
* shutdown_state_reinit -- (internal) reinitializes shutdown_state struct
*/
static void
shutdown_state_reinit(struct shutdown_state *curr_sds,
struct shutdown_state *pool_sds, struct pool_replica *rep)
{
LOG(3, "curr_sds %p, pool_sds %p", curr_sds, pool_sds);
shutdown_state_init(pool_sds, rep);
pool_sds->uuid = htole64(curr_sds->uuid);
pool_sds->usc = htole64(curr_sds->usc);
pool_sds->dirty = 0;
FLUSH_SDS(pool_sds, rep);
shutdown_state_checksum(pool_sds, rep);
}
/*
* shutdown_state_check -- compares and fixes shutdown state
*/
int
shutdown_state_check(struct shutdown_state *curr_sds,
struct shutdown_state *pool_sds, struct pool_replica *rep)
{
LOG(3, "curr_sds %p, pool_sds %p", curr_sds, pool_sds);
if (util_is_zeroed(pool_sds, sizeof(*pool_sds)) &&
!util_is_zeroed(curr_sds, sizeof(*curr_sds))) {
shutdown_state_reinit(curr_sds, pool_sds, rep);
return 0;
}
bool is_uuid_usc_correct =
le64toh(pool_sds->usc) == le64toh(curr_sds->usc) &&
le64toh(pool_sds->uuid) == le64toh(curr_sds->uuid);
bool is_checksum_correct = util_checksum(pool_sds,
sizeof(*pool_sds), &pool_sds->checksum, 0, 0);
int dirty = pool_sds->dirty;
if (!is_checksum_correct) {
/* the program was killed during opening or closing the pool */
LOG(2, "incorrect checksum - SDS will be reinitialized");
shutdown_state_reinit(curr_sds, pool_sds, rep);
return 0;
}
if (is_uuid_usc_correct) {
if (dirty == 0)
return 0;
/*
* the program was killed when the pool was opened
* but there wasn't an ADR failure
*/
LOG(2,
"the pool was not closed - SDS will be reinitialized");
shutdown_state_reinit(curr_sds, pool_sds, rep);
return 0;
}
if (dirty == 0) {
/* an ADR failure but the pool was closed */
LOG(2,
"an ADR failure was detected but the pool was closed - SDS will be reinitialized");
shutdown_state_reinit(curr_sds, pool_sds, rep);
return 0;
}
/* an ADR failure - the pool might be corrupted */
ERR("an ADR failure was detected, the pool might be corrupted");
return 1;
}
| 5,491 | 22.370213 | 117 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/mmap.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* mmap.h -- internal definitions for mmap module
*/
#ifndef PMDK_MMAP_H
#define PMDK_MMAP_H 1
#include <stddef.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "out.h"
#include "queue.h"
#include "os.h"
#ifdef __cplusplus
extern "C" {
#endif
extern int Mmap_no_random;
extern void *Mmap_hint;
extern char *Mmap_mapfile;
void *util_map_sync(void *addr, size_t len, int proto, int flags, int fd,
os_off_t offset, int *map_sync);
void *util_map(int fd, os_off_t off, size_t len, int flags, int rdonly,
size_t req_align, int *map_sync);
int util_unmap(void *addr, size_t len);
#ifdef __FreeBSD__
#define MAP_NORESERVE 0
#define OS_MAPFILE "/proc/curproc/map"
#else
#define OS_MAPFILE "/proc/self/maps"
#endif
#ifndef MAP_SYNC
#define MAP_SYNC 0x80000
#endif
#ifndef MAP_SHARED_VALIDATE
#define MAP_SHARED_VALIDATE 0x03
#endif
/*
* macros for micromanaging range protections for the debug version
*/
#ifdef DEBUG
#define RANGE(addr, len, is_dev_dax, type) do {\
if (!is_dev_dax) ASSERT(util_range_##type(addr, len) >= 0);\
} while (0)
#else
#define RANGE(addr, len, is_dev_dax, type) do {} while (0)
#endif
#define RANGE_RO(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, ro)
#define RANGE_RW(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, rw)
#define RANGE_NONE(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, none)
/* pmem mapping type */
enum pmem_map_type {
PMEM_DEV_DAX, /* device dax */
PMEM_MAP_SYNC, /* mapping with MAP_SYNC flag on dax fs */
MAX_PMEM_TYPE
};
/*
* this structure tracks the file mappings outstanding per file handle
*/
struct map_tracker {
PMDK_SORTEDQ_ENTRY(map_tracker) entry;
uintptr_t base_addr;
uintptr_t end_addr;
unsigned region_id;
enum pmem_map_type type;
#ifdef _WIN32
/* Windows-specific data */
HANDLE FileHandle;
HANDLE FileMappingHandle;
DWORD Access;
os_off_t Offset;
size_t FileLen;
#endif
};
void util_mmap_init(void);
void util_mmap_fini(void);
int util_range_ro(void *addr, size_t len);
int util_range_rw(void *addr, size_t len);
int util_range_none(void *addr, size_t len);
char *util_map_hint_unused(void *minaddr, size_t len, size_t align);
char *util_map_hint(size_t len, size_t req_align);
#define KILOBYTE ((uintptr_t)1 << 10)
#define MEGABYTE ((uintptr_t)1 << 20)
#define GIGABYTE ((uintptr_t)1 << 30)
/*
* util_map_hint_align -- choose the desired mapping alignment
*
* The smallest supported alignment is 2 megabytes because of the object
* alignment requirements. Changing this value to 4 kilobytes constitues a
* layout change.
*
* Use 1GB page alignment only if the mapping length is at least
* twice as big as the page size.
*/
static inline size_t
util_map_hint_align(size_t len, size_t req_align)
{
size_t align = 2 * MEGABYTE;
if (req_align)
align = req_align;
else if (len >= 2 * GIGABYTE)
align = GIGABYTE;
return align;
}
int util_range_register(const void *addr, size_t len, const char *path,
enum pmem_map_type type);
int util_range_unregister(const void *addr, size_t len);
struct map_tracker *util_range_find(uintptr_t addr, size_t len);
int util_range_is_pmem(const void *addr, size_t len);
#ifdef __cplusplus
}
#endif
#endif
| 3,328 | 22.27972 | 76 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/ravl.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/*
* ravl.c -- implementation of a RAVL tree
* https://sidsen.azurewebsites.net//papers/ravl-trees-journal.pdf
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "out.h"
#include "ravl.h"
#include "alloc.h"
#define RAVL_DEFAULT_DATA_SIZE (sizeof(void *))
enum ravl_slot_type {
RAVL_LEFT,
RAVL_RIGHT,
MAX_SLOTS,
RAVL_ROOT
};
struct ravl_node {
struct ravl_node *parent;
struct ravl_node *slots[MAX_SLOTS];
int32_t rank; /* cannot be greater than height of the subtree */
int32_t pointer_based;
char data[];
};
struct ravl {
struct ravl_node *root;
ravl_compare *compare;
size_t data_size;
};
/*
* ravl_new -- creates a new ravl tree instance
*/
struct ravl *
ravl_new_sized(ravl_compare *compare, size_t data_size)
{
struct ravl *r = Malloc(sizeof(*r));
if (r == NULL) {
ERR("!Malloc");
return r;
}
r->compare = compare;
r->root = NULL;
r->data_size = data_size;
return r;
}
/*
* ravl_new -- creates a new tree that stores data pointers
*/
struct ravl *
ravl_new(ravl_compare *compare)
{
return ravl_new_sized(compare, RAVL_DEFAULT_DATA_SIZE);
}
/*
* ravl_clear_node -- (internal) recursively clears the given subtree,
* calls callback in an in-order fashion. Optionally frees the given node.
*/
static void
ravl_foreach_node(struct ravl_node *n, ravl_cb cb, void *arg, int free_node)
{
if (n == NULL)
return;
ravl_foreach_node(n->slots[RAVL_LEFT], cb, arg, free_node);
if (cb)
cb((void *)n->data, arg);
ravl_foreach_node(n->slots[RAVL_RIGHT], cb, arg, free_node);
if (free_node)
Free(n);
}
/*
* ravl_clear -- clears the entire tree, starting from the root
*/
void
ravl_clear(struct ravl *ravl)
{
ravl_foreach_node(ravl->root, NULL, NULL, 1);
ravl->root = NULL;
}
/*
* ravl_delete_cb -- clears and deletes the given ravl instance, calls callback
*/
void
ravl_delete_cb(struct ravl *ravl, ravl_cb cb, void *arg)
{
ravl_foreach_node(ravl->root, cb, arg, 1);
Free(ravl);
}
/*
* ravl_delete -- clears and deletes the given ravl instance
*/
void
ravl_delete(struct ravl *ravl)
{
ravl_delete_cb(ravl, NULL, NULL);
}
/*
* ravl_foreach -- traverses the entire tree, calling callback for every node
*/
void
ravl_foreach(struct ravl *ravl, ravl_cb cb, void *arg)
{
ravl_foreach_node(ravl->root, cb, arg, 0);
}
/*
* ravl_empty -- checks whether the given tree is empty
*/
int
ravl_empty(struct ravl *ravl)
{
return ravl->root == NULL;
}
/*
* ravl_node_insert_constructor -- node data constructor for ravl_insert
*/
static void
ravl_node_insert_constructor(void *data, size_t data_size, const void *arg)
{
/* copy only the 'arg' pointer */
memcpy(data, &arg, sizeof(arg));
}
/*
* ravl_node_copy_constructor -- node data constructor for ravl_emplace_copy
*/
static void
ravl_node_copy_constructor(void *data, size_t data_size, const void *arg)
{
memcpy(data, arg, data_size);
}
/*
* ravl_new_node -- (internal) allocates and initializes a new node
*/
static struct ravl_node *
ravl_new_node(struct ravl *ravl, ravl_constr constr, const void *arg)
{
struct ravl_node *n = Malloc(sizeof(*n) + ravl->data_size);
if (n == NULL) {
ERR("!Malloc");
return n;
}
n->parent = NULL;
n->slots[RAVL_LEFT] = NULL;
n->slots[RAVL_RIGHT] = NULL;
n->rank = 0;
n->pointer_based = constr == ravl_node_insert_constructor;
constr(n->data, ravl->data_size, arg);
return n;
}
/*
* ravl_slot_opposite -- (internal) returns the opposite slot type, cannot be
* called for root type
*/
static enum ravl_slot_type
ravl_slot_opposite(enum ravl_slot_type t)
{
ASSERTne(t, RAVL_ROOT);
return t == RAVL_LEFT ? RAVL_RIGHT : RAVL_LEFT;
}
/*
* ravl_node_slot_type -- (internal) returns the type of the given node:
* left child, right child or root
*/
static enum ravl_slot_type
ravl_node_slot_type(struct ravl_node *n)
{
if (n->parent == NULL)
return RAVL_ROOT;
return n->parent->slots[RAVL_LEFT] == n ? RAVL_LEFT : RAVL_RIGHT;
}
/*
* ravl_node_sibling -- (internal) returns the sibling of the given node,
* NULL if the node is root (has no parent)
*/
static struct ravl_node *
ravl_node_sibling(struct ravl_node *n)
{
enum ravl_slot_type t = ravl_node_slot_type(n);
if (t == RAVL_ROOT)
return NULL;
return n->parent->slots[t == RAVL_LEFT ? RAVL_RIGHT : RAVL_LEFT];
}
/*
* ravl_node_ref -- (internal) returns the pointer to the memory location in
* which the given node resides
*/
static struct ravl_node **
ravl_node_ref(struct ravl *ravl, struct ravl_node *n)
{
enum ravl_slot_type t = ravl_node_slot_type(n);
return t == RAVL_ROOT ? &ravl->root : &n->parent->slots[t];
}
/*
* ravl_rotate -- (internal) performs a rotation around a given node
*
* The node n swaps place with its parent. If n is right child, parent becomes
* the left child of n, otherwise parent becomes right child of n.
*/
static void
ravl_rotate(struct ravl *ravl, struct ravl_node *n)
{
ASSERTne(n->parent, NULL);
struct ravl_node *p = n->parent;
struct ravl_node **pref = ravl_node_ref(ravl, p);
enum ravl_slot_type t = ravl_node_slot_type(n);
enum ravl_slot_type t_opposite = ravl_slot_opposite(t);
n->parent = p->parent;
p->parent = n;
*pref = n;
if ((p->slots[t] = n->slots[t_opposite]) != NULL)
p->slots[t]->parent = p;
n->slots[t_opposite] = p;
}
/*
* ravl_node_rank -- (internal) returns the rank of the node
*
* For the purpose of balancing, NULL nodes have rank -1.
*/
static int
ravl_node_rank(struct ravl_node *n)
{
return n == NULL ? -1 : n->rank;
}
/*
* ravl_node_rank_difference_parent -- (internal) returns the rank different
* between parent node p and its child n
*
* Every rank difference must be positive.
*
* Either of these can be NULL.
*/
static int
ravl_node_rank_difference_parent(struct ravl_node *p, struct ravl_node *n)
{
return ravl_node_rank(p) - ravl_node_rank(n);
}
/*
* ravl_node_rank_differenced - (internal) returns the rank difference between
* parent and its child
*
* Can be used to check if a given node is an i-child.
*/
static int
ravl_node_rank_difference(struct ravl_node *n)
{
return ravl_node_rank_difference_parent(n->parent, n);
}
/*
* ravl_node_is_i_j -- (internal) checks if a given node is strictly i,j-node
*/
static int
ravl_node_is_i_j(struct ravl_node *n, int i, int j)
{
return (ravl_node_rank_difference_parent(n, n->slots[RAVL_LEFT]) == i &&
ravl_node_rank_difference_parent(n, n->slots[RAVL_RIGHT]) == j);
}
/*
* ravl_node_is -- (internal) checks if a given node is i,j-node or j,i-node
*/
static int
ravl_node_is(struct ravl_node *n, int i, int j)
{
return ravl_node_is_i_j(n, i, j) || ravl_node_is_i_j(n, j, i);
}
/*
* ravl_node_promote -- promotes a given node by increasing its rank
*/
static void
ravl_node_promote(struct ravl_node *n)
{
n->rank += 1;
}
/*
* ravl_node_promote -- demotes a given node by increasing its rank
*/
static void
ravl_node_demote(struct ravl_node *n)
{
ASSERT(n->rank > 0);
n->rank -= 1;
}
/*
* ravl_balance -- balances the tree after insert
*
* This function must restore the invariant that every rank
* difference is positive.
*/
static void
ravl_balance(struct ravl *ravl, struct ravl_node *n)
{
/* walk up the tree, promoting nodes */
while (n->parent && ravl_node_is(n->parent, 0, 1)) {
ravl_node_promote(n->parent);
n = n->parent;
}
/*
* Either the rank rule holds or n is a 0-child whose sibling is an
* i-child with i > 1.
*/
struct ravl_node *s = ravl_node_sibling(n);
if (!(ravl_node_rank_difference(n) == 0 &&
ravl_node_rank_difference_parent(n->parent, s) > 1))
return;
struct ravl_node *y = n->parent;
/* if n is a left child, let z be n's right child and vice versa */
enum ravl_slot_type t = ravl_slot_opposite(ravl_node_slot_type(n));
struct ravl_node *z = n->slots[t];
if (z == NULL || ravl_node_rank_difference(z) == 2) {
ravl_rotate(ravl, n);
ravl_node_demote(y);
} else if (ravl_node_rank_difference(z) == 1) {
ravl_rotate(ravl, z);
ravl_rotate(ravl, z);
ravl_node_promote(z);
ravl_node_demote(n);
ravl_node_demote(y);
}
}
/*
* ravl_insert -- insert data into the tree
*/
int
ravl_insert(struct ravl *ravl, const void *data)
{
return ravl_emplace(ravl, ravl_node_insert_constructor, data);
}
/*
* ravl_insert -- copy construct data inside of a new tree node
*/
int
ravl_emplace_copy(struct ravl *ravl, const void *data)
{
return ravl_emplace(ravl, ravl_node_copy_constructor, data);
}
/*
* ravl_emplace -- construct data inside of a new tree node
*/
int
ravl_emplace(struct ravl *ravl, ravl_constr constr, const void *arg)
{
LOG(6, NULL);
struct ravl_node *n = ravl_new_node(ravl, constr, arg);
if (n == NULL)
return -1;
/* walk down the tree and insert the new node into a missing slot */
struct ravl_node **dstp = &ravl->root;
struct ravl_node *dst = NULL;
while (*dstp != NULL) {
dst = (*dstp);
int cmp_result = ravl->compare(ravl_data(n), ravl_data(dst));
if (cmp_result == 0)
goto error_duplicate;
dstp = &dst->slots[cmp_result > 0];
}
n->parent = dst;
*dstp = n;
ravl_balance(ravl, n);
return 0;
error_duplicate:
errno = EEXIST;
Free(n);
return -1;
}
/*
* ravl_node_type_most -- (internal) returns left-most or right-most node in
* the subtree
*/
static struct ravl_node *
ravl_node_type_most(struct ravl_node *n, enum ravl_slot_type t)
{
while (n->slots[t] != NULL)
n = n->slots[t];
return n;
}
/*
* ravl_node_cessor -- (internal) returns the successor or predecessor of the
* node
*/
static struct ravl_node *
ravl_node_cessor(struct ravl_node *n, enum ravl_slot_type t)
{
/*
* If t child is present, we are looking for t-opposite-most node
* in t child subtree
*/
if (n->slots[t])
return ravl_node_type_most(n->slots[t], ravl_slot_opposite(t));
/* otherwise get the first parent on the t path */
while (n->parent != NULL && n == n->parent->slots[t])
n = n->parent;
return n->parent;
}
/*
* ravl_node_successor -- (internal) returns node's successor
*
* It's the first node larger than n.
*/
static struct ravl_node *
ravl_node_successor(struct ravl_node *n)
{
return ravl_node_cessor(n, RAVL_RIGHT);
}
/*
* ravl_node_successor -- (internal) returns node's successor
*
* It's the first node smaller than n.
*/
static struct ravl_node *
ravl_node_predecessor(struct ravl_node *n)
{
return ravl_node_cessor(n, RAVL_LEFT);
}
/*
* ravl_predicate_holds -- (internal) verifies the given predicate for
* the current node in the search path
*
* If the predicate holds for the given node or a node that can be directly
* derived from it, returns 1. Otherwise returns 0.
*/
static int
ravl_predicate_holds(struct ravl *ravl, int result, struct ravl_node **ret,
struct ravl_node *n, const void *data, enum ravl_predicate flags)
{
if (flags & RAVL_PREDICATE_EQUAL) {
if (result == 0) {
*ret = n;
return 1;
}
}
if (flags & RAVL_PREDICATE_GREATER) {
if (result < 0) { /* data < n->data */
*ret = n;
return 0;
} else if (result == 0) {
*ret = ravl_node_successor(n);
return 1;
}
}
if (flags & RAVL_PREDICATE_LESS) {
if (result > 0) { /* data > n->data */
*ret = n;
return 0;
} else if (result == 0) {
*ret = ravl_node_predecessor(n);
return 1;
}
}
return 0;
}
/*
* ravl_find -- searches for the node in the tree
*/
struct ravl_node *
ravl_find(struct ravl *ravl, const void *data, enum ravl_predicate flags)
{
LOG(6, NULL);
struct ravl_node *r = NULL;
struct ravl_node *n = ravl->root;
while (n) {
int result = ravl->compare(data, ravl_data(n));
if (ravl_predicate_holds(ravl, result, &r, n, data, flags))
return r;
n = n->slots[result > 0];
}
return r;
}
/*
* ravl_remove -- removes the given node from the tree
*/
void
ravl_remove(struct ravl *ravl, struct ravl_node *n)
{
LOG(6, NULL);
if (n->slots[RAVL_LEFT] != NULL && n->slots[RAVL_RIGHT] != NULL) {
/* if both children are present, remove the successor instead */
struct ravl_node *s = ravl_node_successor(n);
memcpy(n->data, s->data, ravl->data_size);
ravl_remove(ravl, s);
} else {
/* swap n with the child that may exist */
struct ravl_node *r = n->slots[RAVL_LEFT] ?
n->slots[RAVL_LEFT] : n->slots[RAVL_RIGHT];
if (r != NULL)
r->parent = n->parent;
*ravl_node_ref(ravl, n) = r;
Free(n);
}
}
/*
* ravl_data -- returns the data contained within the node
*/
void *
ravl_data(struct ravl_node *node)
{
if (node->pointer_based) {
void *data;
memcpy(&data, node->data, sizeof(void *));
return data;
} else {
return (void *)node->data;
}
}
| 12,600 | 20.801038 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/vecq.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2019, Intel Corporation */
/*
* vecq.h -- vector queue (FIFO) interface
*/
#ifndef PMDK_VECQ_H
#define PMDK_VECQ_H 1
#include <stddef.h>
#include "util.h"
#include "out.h"
#include "alloc.h"
#ifdef __cplusplus
extern "C" {
#endif
#define VECQ_INIT_SIZE (64)
#define VECQ(name, type)\
struct name {\
type *buffer;\
size_t capacity;\
size_t front;\
size_t back;\
}
#define VECQ_INIT(vec) do {\
(vec)->buffer = NULL;\
(vec)->capacity = 0;\
(vec)->front = 0;\
(vec)->back = 0;\
} while (0)
#define VECQ_REINIT(vec) do {\
VALGRIND_ANNOTATE_NEW_MEMORY((vec), sizeof(*vec));\
VALGRIND_ANNOTATE_NEW_MEMORY((vec)->buffer,\
(sizeof(*(vec)->buffer) * ((vec)->capacity)));\
(vec)->front = 0;\
(vec)->back = 0;\
} while (0)
#define VECQ_FRONT_POS(vec)\
((vec)->front & ((vec)->capacity - 1))
#define VECQ_BACK_POS(vec)\
((vec)->back & ((vec)->capacity - 1))
#define VECQ_FRONT(vec)\
(vec)->buffer[VECQ_FRONT_POS(vec)]
#define VECQ_BACK(vec)\
(vec)->buffer[VECQ_BACK_POS(vec)]
#define VECQ_DEQUEUE(vec)\
((vec)->buffer[(((vec)->front++) & ((vec)->capacity - 1))])
#define VECQ_SIZE(vec)\
((vec)->back - (vec)->front)
static inline int
realloc_set(void **buf, size_t s)
{
void *tbuf = Realloc(*buf, s);
if (tbuf == NULL) {
ERR("!Realloc");
return -1;
}
*buf = tbuf;
return 0;
}
#define VECQ_NCAPACITY(vec)\
((vec)->capacity == 0 ? VECQ_INIT_SIZE : (vec)->capacity * 2)
#define VECQ_GROW(vec)\
(realloc_set((void **)&(vec)->buffer,\
VECQ_NCAPACITY(vec) * sizeof(*(vec)->buffer)) ? -1 :\
(memcpy((vec)->buffer + (vec)->capacity, (vec)->buffer,\
VECQ_FRONT_POS(vec) * sizeof(*(vec)->buffer)),\
(vec)->front = VECQ_FRONT_POS(vec),\
(vec)->back = (vec)->front + (vec)->capacity,\
(vec)->capacity = VECQ_NCAPACITY(vec),\
0\
))
#define VECQ_INSERT(vec, element)\
(VECQ_BACK(vec) = element, (vec)->back += 1, 0)
#define VECQ_ENQUEUE(vec, element)\
((vec)->capacity == VECQ_SIZE(vec) ?\
(VECQ_GROW(vec) == 0 ? VECQ_INSERT(vec, element) : -1) :\
VECQ_INSERT(vec, element))
#define VECQ_CAPACITY(vec)\
((vec)->capacity)
#define VECQ_FOREACH(el, vec)\
for (size_t _vec_i = 0;\
_vec_i < VECQ_SIZE(vec) &&\
(((el) = (vec)->buffer[_vec_i & ((vec)->capacity - 1)]), 1);\
++_vec_i)
#define VECQ_FOREACH_REVERSE(el, vec)\
for (size_t _vec_i = VECQ_SIZE(vec);\
_vec_i > 0 &&\
(((el) = (vec)->buffer[(_vec_i - 1) & ((vec)->capacity - 1)]), 1);\
--_vec_i)
#define VECQ_CLEAR(vec) do {\
(vec)->front = 0;\
(vec)->back = 0;\
} while (0)
#define VECQ_DELETE(vec) do {\
Free((vec)->buffer);\
(vec)->buffer = NULL;\
(vec)->capacity = 0;\
(vec)->front = 0;\
(vec)->back = 0;\
} while (0)
#ifdef __cplusplus
}
#endif
#endif /* PMDK_VECQ_H */
| 2,731 | 20.178295 | 68 |
h
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/os_deep_linux.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2017-2020, Intel Corporation */
/*
* os_deep_linux.c -- Linux abstraction layer
*/
#define _GNU_SOURCE
#include <inttypes.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "out.h"
#include "os.h"
#include "mmap.h"
#include "file.h"
#include "libpmem.h"
#include "os_deep.h"
#include "../libpmem2/deep_flush.h"
/*
* os_deep_type -- (internal) perform deep operation based on a pmem
* mapping type
*/
static int
os_deep_type(const struct map_tracker *mt, void *addr, size_t len)
{
LOG(15, "mt %p addr %p len %zu", mt, addr, len);
switch (mt->type) {
case PMEM_DEV_DAX:
pmem_drain();
int ret = pmem2_deep_flush_write(mt->region_id);
if (ret < 0) {
if (ret == PMEM2_E_NOSUPP) {
errno = ENOTSUP;
LOG(1, "!deep_flush not supported");
} else {
errno = pmem2_err_to_errno(ret);
LOG(2, "cannot write to deep_flush"
"in region %u", mt->region_id);
}
return -1;
}
return 0;
case PMEM_MAP_SYNC:
return pmem_msync(addr, len);
default:
ASSERT(0);
return -1;
}
}
/*
* os_range_deep_common -- perform deep action of given address range
*/
int
os_range_deep_common(uintptr_t addr, size_t len)
{
LOG(3, "addr 0x%016" PRIxPTR " len %zu", addr, len);
while (len != 0) {
const struct map_tracker *mt = util_range_find(addr, len);
/* no more overlapping track regions or NOT a device DAX */
if (mt == NULL) {
LOG(15, "pmem_msync addr %p, len %lu",
(void *)addr, len);
return pmem_msync((void *)addr, len);
}
/*
* For range that intersects with the found mapping
* write to (Device DAX) deep_flush file.
* Call msync for the non-intersecting part.
*/
if (mt->base_addr > addr) {
size_t curr_len = mt->base_addr - addr;
if (curr_len > len)
curr_len = len;
if (pmem_msync((void *)addr, curr_len) != 0)
return -1;
len -= curr_len;
if (len == 0)
return 0;
addr = mt->base_addr;
}
size_t mt_in_len = mt->end_addr - addr;
size_t persist_len = MIN(len, mt_in_len);
if (os_deep_type(mt, (void *)addr, persist_len))
return -1;
if (mt->end_addr >= addr + len)
return 0;
len -= mt_in_len;
addr = mt->end_addr;
}
return 0;
}
/*
* os_part_deep_common -- common function to handle both
* deep_persist and deep_drain part flush cases.
*/
int
os_part_deep_common(struct pool_replica *rep, unsigned partidx, void *addr,
size_t len, int flush)
{
LOG(3, "part %p part %d addr %p len %lu flush %d",
rep, partidx, addr, len, flush);
if (!rep->is_pmem) {
/*
* In case of part on non-pmem call msync on the range
* to deep flush the data. Deep drain is empty as all
* data is msynced to persistence.
*/
if (!flush)
return 0;
if (pmem_msync(addr, len)) {
LOG(1, "pmem_msync(%p, %lu)", addr, len);
return -1;
}
return 0;
}
struct pool_set_part part = rep->part[partidx];
/* Call deep flush if it was requested */
if (flush) {
LOG(15, "pmem_deep_flush addr %p, len %lu", addr, len);
pmem_deep_flush(addr, len);
}
/*
* Before deep drain call normal drain to ensure that data
* is at least in WPQ.
*/
pmem_drain();
if (part.is_dev_dax) {
/*
* During deep_drain for part on device DAX search for
* device region id, and perform WPQ flush on found
* device DAX region.
*/
unsigned region_id;
int ret = util_ddax_region_find(part.path, ®ion_id);
if (ret < 0) {
if (errno == ENOENT) {
errno = ENOTSUP;
LOG(1, "!deep_flush not supported");
} else {
LOG(1, "invalid dax_region id %u", region_id);
}
return -1;
}
if (pmem2_deep_flush_write(region_id)) {
LOG(1, "pmem2_deep_flush_write(%u)",
region_id);
return -1;
}
} else {
/*
* For deep_drain on normal pmem it is enough to
* call msync on one page.
*/
if (pmem_msync(addr, MIN(Pagesize, len))) {
LOG(1, "pmem_msync(%p, %lu)", addr, len);
return -1;
}
}
return 0;
}
| 3,932 | 21.095506 | 75 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/file_windows.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2015-2020, Intel Corporation */
/*
* file_windows.c -- Windows emulation of Linux-specific system calls
*/
/*
* XXX - The initial approach to PMDK for Windows port was to minimize the
* amount of changes required in the core part of the library, and to avoid
* preprocessor conditionals, if possible. For that reason, some of the
* Linux system calls that have no equivalents on Windows have been emulated
* using Windows API.
* Note that it was not a goal to fully emulate POSIX-compliant behavior
* of mentioned functions. They are used only internally, so current
* implementation is just good enough to satisfy PMDK needs and to make it
* work on Windows.
*/
#include <windows.h>
#include <sys/stat.h>
#include <sys/file.h>
#include "alloc.h"
#include "file.h"
#include "out.h"
#include "os.h"
/*
* util_tmpfile -- create a temporary file
*/
int
util_tmpfile(const char *dir, const char *templ, int flags)
{
LOG(3, "dir \"%s\" template \"%s\" flags %x", dir, templ, flags);
/* only O_EXCL is allowed here */
ASSERT(flags == 0 || flags == O_EXCL);
int oerrno;
int fd = -1;
size_t len = strlen(dir) + strlen(templ) + 1;
char *fullname = Malloc(sizeof(*fullname) * len);
if (fullname == NULL) {
ERR("!Malloc");
return -1;
}
int ret = _snprintf(fullname, len, "%s%s", dir, templ);
if (ret < 0 || ret >= len) {
ERR("snprintf: %d", ret);
goto err;
}
LOG(4, "fullname \"%s\"", fullname);
/*
* XXX - block signals and modify file creation mask for the time
* of mkstmep() execution. Restore previous settings once the file
* is created.
*/
fd = os_mkstemp(fullname);
if (fd < 0) {
ERR("!os_mkstemp");
goto err;
}
/*
* There is no point to use unlink() here. First, because it does not
* work on open files. Second, because the file is created with
* O_TEMPORARY flag, and it looks like such temp files cannot be open
* from another process, even though they are visible on
* the filesystem.
*/
Free(fullname);
return fd;
err:
Free(fullname);
oerrno = errno;
if (fd != -1)
(void) os_close(fd);
errno = oerrno;
return -1;
}
/*
* util_is_absolute_path -- check if the path is absolute
*/
int
util_is_absolute_path(const char *path)
{
LOG(3, "path \"%s\"", path);
if (path == NULL || path[0] == '\0')
return 0;
if (path[0] == '\\' || path[1] == ':')
return 1;
return 0;
}
/*
* util_file_mkdir -- creates new dir
*/
int
util_file_mkdir(const char *path, mode_t mode)
{
/*
* On windows we cannot create read only dir so mode
* parameter is useless.
*/
UNREFERENCED_PARAMETER(mode);
LOG(3, "path: %s mode: %d", path, mode);
return _mkdir(path);
}
/*
* util_file_dir_open -- open a directory
*/
int
util_file_dir_open(struct dir_handle *handle, const char *path)
{
/* init handle */
handle->handle = NULL;
handle->path = path;
return 0;
}
/*
* util_file_dir_next - read next file in directory
*/
int
util_file_dir_next(struct dir_handle *handle, struct file_info *info)
{
WIN32_FIND_DATAA data;
if (handle->handle == NULL) {
handle->handle = FindFirstFileA(handle->path, &data);
if (handle->handle == NULL)
return 1;
} else {
if (FindNextFileA(handle->handle, &data) == 0)
return 1;
}
info->filename[NAME_MAX] = '\0';
strncpy(info->filename, data.cFileName, NAME_MAX + 1);
if (info->filename[NAME_MAX] != '\0')
return -1; /* filename truncated */
info->is_dir = data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY;
return 0;
}
/*
* util_file_dir_close -- close a directory
*/
int
util_file_dir_close(struct dir_handle *handle)
{
return FindClose(handle->handle);
}
/*
* util_file_dir_remove -- remove directory
*/
int
util_file_dir_remove(const char *path)
{
return RemoveDirectoryA(path) == 0 ? -1 : 0;
}
/*
* util_file_device_dax_alignment -- returns internal Device DAX alignment
*/
size_t
util_file_device_dax_alignment(const char *path)
{
LOG(3, "path \"%s\"", path);
return 0;
}
/*
* util_ddax_region_find -- returns DEV dax region id that contains file
*/
int
util_ddax_region_find(const char *path, unsigned *region_id)
{
LOG(3, "path \"%s\"", path);
return -1;
}
| 4,186 | 20.253807 | 76 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/mmap.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2020, Intel Corporation */
/*
* mmap.c -- mmap utilities
*/
#include <errno.h>
#include <inttypes.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "file.h"
#include "queue.h"
#include "mmap.h"
#include "sys_util.h"
#include "os.h"
#include "alloc.h"
#include "libpmem2.h"
int Mmap_no_random;
void *Mmap_hint;
static os_rwlock_t Mmap_list_lock;
static PMDK_SORTEDQ_HEAD(map_list_head, map_tracker) Mmap_list =
PMDK_SORTEDQ_HEAD_INITIALIZER(Mmap_list);
/*
* util_mmap_init -- initialize the mmap utils
*
* This is called from the library initialization code.
*/
void
util_mmap_init(void)
{
LOG(3, NULL);
util_rwlock_init(&Mmap_list_lock);
/*
* For testing, allow overriding the default mmap() hint address.
* If hint address is defined, it also disables address randomization.
*/
char *e = os_getenv("PMEM_MMAP_HINT");
if (e) {
char *endp;
errno = 0;
unsigned long long val = strtoull(e, &endp, 16);
if (errno || endp == e) {
LOG(2, "Invalid PMEM_MMAP_HINT");
} else if (os_access(OS_MAPFILE, R_OK)) {
LOG(2, "No /proc, PMEM_MMAP_HINT ignored");
} else {
Mmap_hint = (void *)val;
Mmap_no_random = 1;
LOG(3, "PMEM_MMAP_HINT set to %p", Mmap_hint);
}
}
}
/*
* util_mmap_fini -- clean up the mmap utils
*
* This is called before process stop.
*/
void
util_mmap_fini(void)
{
LOG(3, NULL);
util_rwlock_destroy(&Mmap_list_lock);
}
/*
* util_map -- memory map a file
*
* This is just a convenience function that calls mmap() with the
* appropriate arguments and includes our trace points.
*/
void *
util_map(int fd, os_off_t off, size_t len, int flags, int rdonly,
size_t req_align, int *map_sync)
{
LOG(3, "fd %d len %zu flags %d rdonly %d req_align %zu map_sync %p",
fd, len, flags, rdonly, req_align, map_sync);
void *base;
void *addr = util_map_hint(len, req_align);
if (addr == MAP_FAILED) {
LOG(1, "cannot find a contiguous region of given size");
return NULL;
}
if (req_align)
ASSERTeq((uintptr_t)addr % req_align, 0);
int proto = rdonly ? PROT_READ : PROT_READ|PROT_WRITE;
base = util_map_sync(addr, len, proto, flags, fd, off, map_sync);
if (base == MAP_FAILED) {
ERR("!mmap %zu bytes", len);
return NULL;
}
LOG(3, "mapped at %p", base);
return base;
}
/*
* util_unmap -- unmap a file
*
* This is just a convenience function that calls munmap() with the
* appropriate arguments and includes our trace points.
*/
int
util_unmap(void *addr, size_t len)
{
LOG(3, "addr %p len %zu", addr, len);
/*
* XXX Workaround for https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=169608
*/
#ifdef __FreeBSD__
if (!IS_PAGE_ALIGNED((uintptr_t)addr)) {
errno = EINVAL;
ERR("!munmap");
return -1;
}
#endif
int retval = munmap(addr, len);
if (retval < 0)
ERR("!munmap");
return retval;
}
/*
* util_range_ro -- set a memory range read-only
*/
int
util_range_ro(void *addr, size_t len)
{
LOG(3, "addr %p len %zu", addr, len);
uintptr_t uptr;
int retval;
/*
* mprotect requires addr to be a multiple of pagesize, so
* adjust addr and len to represent the full 4k chunks
* covering the given range.
*/
/* increase len by the amount we gain when we round addr down */
len += (uintptr_t)addr & (Pagesize - 1);
/* round addr down to page boundary */
uptr = (uintptr_t)addr & ~(Pagesize - 1);
if ((retval = mprotect((void *)uptr, len, PROT_READ)) < 0)
ERR("!mprotect: PROT_READ");
return retval;
}
/*
* util_range_rw -- set a memory range read-write
*/
int
util_range_rw(void *addr, size_t len)
{
LOG(3, "addr %p len %zu", addr, len);
uintptr_t uptr;
int retval;
/*
* mprotect requires addr to be a multiple of pagesize, so
* adjust addr and len to represent the full 4k chunks
* covering the given range.
*/
/* increase len by the amount we gain when we round addr down */
len += (uintptr_t)addr & (Pagesize - 1);
/* round addr down to page boundary */
uptr = (uintptr_t)addr & ~(Pagesize - 1);
if ((retval = mprotect((void *)uptr, len, PROT_READ|PROT_WRITE)) < 0)
ERR("!mprotect: PROT_READ|PROT_WRITE");
return retval;
}
/*
* util_range_none -- set a memory range for no access allowed
*/
int
util_range_none(void *addr, size_t len)
{
LOG(3, "addr %p len %zu", addr, len);
uintptr_t uptr;
int retval;
/*
* mprotect requires addr to be a multiple of pagesize, so
* adjust addr and len to represent the full 4k chunks
* covering the given range.
*/
/* increase len by the amount we gain when we round addr down */
len += (uintptr_t)addr & (Pagesize - 1);
/* round addr down to page boundary */
uptr = (uintptr_t)addr & ~(Pagesize - 1);
if ((retval = mprotect((void *)uptr, len, PROT_NONE)) < 0)
ERR("!mprotect: PROT_NONE");
return retval;
}
/*
* util_range_comparer -- (internal) compares the two mapping trackers
*/
static intptr_t
util_range_comparer(struct map_tracker *a, struct map_tracker *b)
{
return ((intptr_t)a->base_addr - (intptr_t)b->base_addr);
}
/*
* util_range_find_unlocked -- (internal) find the map tracker
* for given address range
*
* Returns the first entry at least partially overlapping given range.
* It's up to the caller to check whether the entry exactly matches the range,
* or if the range spans multiple entries.
*/
static struct map_tracker *
util_range_find_unlocked(uintptr_t addr, size_t len)
{
LOG(10, "addr 0x%016" PRIxPTR " len %zu", addr, len);
uintptr_t end = addr + len;
struct map_tracker *mt;
PMDK_SORTEDQ_FOREACH(mt, &Mmap_list, entry) {
if (addr < mt->end_addr &&
(addr >= mt->base_addr || end > mt->base_addr))
goto out;
/* break if there is no chance to find matching entry */
if (addr < mt->base_addr)
break;
}
mt = NULL;
out:
return mt;
}
/*
* util_range_find -- find the map tracker for given address range
* the same as util_range_find_unlocked but locked
*/
struct map_tracker *
util_range_find(uintptr_t addr, size_t len)
{
LOG(10, "addr 0x%016" PRIxPTR " len %zu", addr, len);
util_rwlock_rdlock(&Mmap_list_lock);
struct map_tracker *mt = util_range_find_unlocked(addr, len);
util_rwlock_unlock(&Mmap_list_lock);
return mt;
}
/*
* util_range_register -- add a memory range into a map tracking list
*/
int
util_range_register(const void *addr, size_t len, const char *path,
enum pmem_map_type type)
{
LOG(3, "addr %p len %zu path %s type %d", addr, len, path, type);
/* check if not tracked already */
if (util_range_find((uintptr_t)addr, len) != NULL) {
ERR(
"duplicated persistent memory range; presumably unmapped with munmap() instead of pmem_unmap(): addr %p len %zu",
addr, len);
errno = ENOMEM;
return -1;
}
struct map_tracker *mt;
mt = Malloc(sizeof(struct map_tracker));
if (mt == NULL) {
ERR("!Malloc");
return -1;
}
mt->base_addr = (uintptr_t)addr;
mt->end_addr = mt->base_addr + len;
mt->type = type;
if (type == PMEM_DEV_DAX) {
unsigned region_id;
int ret = util_ddax_region_find(path, ®ion_id);
if (ret < 0) {
ERR("Cannot find DAX device region id");
return -1;
}
mt->region_id = region_id;
}
util_rwlock_wrlock(&Mmap_list_lock);
PMDK_SORTEDQ_INSERT(&Mmap_list, mt, entry, struct map_tracker,
util_range_comparer);
util_rwlock_unlock(&Mmap_list_lock);
return 0;
}
/*
* util_range_split -- (internal) remove or split a map tracking entry
*/
static int
util_range_split(struct map_tracker *mt, const void *addrp, const void *endp)
{
LOG(3, "begin %p end %p", addrp, endp);
uintptr_t addr = (uintptr_t)addrp;
uintptr_t end = (uintptr_t)endp;
ASSERTne(mt, NULL);
if (addr == end || addr % Mmap_align != 0 || end % Mmap_align != 0) {
ERR(
"invalid munmap length, must be non-zero and page aligned");
return -1;
}
struct map_tracker *mtb = NULL;
struct map_tracker *mte = NULL;
/*
* 1) b e b e
* xxxxxxxxxxxxx => xxx.......xxxx - mtb+mte
* 2) b e b e
* xxxxxxxxxxxxx => xxxxxxx....... - mtb
* 3) b e b e
* xxxxxxxxxxxxx => ........xxxxxx - mte
* 4) b e b e
* xxxxxxxxxxxxx => .............. - <none>
*/
if (addr > mt->base_addr) {
/* case #1/2 */
/* new mapping at the beginning */
mtb = Malloc(sizeof(struct map_tracker));
if (mtb == NULL) {
ERR("!Malloc");
goto err;
}
mtb->base_addr = mt->base_addr;
mtb->end_addr = addr;
mtb->region_id = mt->region_id;
mtb->type = mt->type;
}
if (end < mt->end_addr) {
/* case #1/3 */
/* new mapping at the end */
mte = Malloc(sizeof(struct map_tracker));
if (mte == NULL) {
ERR("!Malloc");
goto err;
}
mte->base_addr = end;
mte->end_addr = mt->end_addr;
mte->region_id = mt->region_id;
mte->type = mt->type;
}
PMDK_SORTEDQ_REMOVE(&Mmap_list, mt, entry);
if (mtb) {
PMDK_SORTEDQ_INSERT(&Mmap_list, mtb, entry,
struct map_tracker, util_range_comparer);
}
if (mte) {
PMDK_SORTEDQ_INSERT(&Mmap_list, mte, entry,
struct map_tracker, util_range_comparer);
}
/* free entry for the original mapping */
Free(mt);
return 0;
err:
Free(mtb);
Free(mte);
return -1;
}
/*
* util_range_unregister -- remove a memory range
* from map tracking list
*
* Remove the region between [begin,end]. If it's in a middle of the existing
* mapping, it results in two new map trackers.
*/
int
util_range_unregister(const void *addr, size_t len)
{
LOG(3, "addr %p len %zu", addr, len);
int ret = 0;
util_rwlock_wrlock(&Mmap_list_lock);
/*
* Changes in the map tracker list must match the underlying behavior.
*
* $ man 2 mmap:
* The address addr must be a multiple of the page size (but length
* need not be). All pages containing a part of the indicated range
* are unmapped.
*
* This means that we must align the length to the page size.
*/
len = PAGE_ALIGNED_UP_SIZE(len);
void *end = (char *)addr + len;
/* XXX optimize the loop */
struct map_tracker *mt;
while ((mt = util_range_find_unlocked((uintptr_t)addr, len)) != NULL) {
if (util_range_split(mt, addr, end) != 0) {
ret = -1;
break;
}
}
util_rwlock_unlock(&Mmap_list_lock);
return ret;
}
/*
* util_range_is_pmem -- return true if entire range
* is persistent memory
*/
int
util_range_is_pmem(const void *addrp, size_t len)
{
LOG(10, "addr %p len %zu", addrp, len);
uintptr_t addr = (uintptr_t)addrp;
int retval = 1;
util_rwlock_rdlock(&Mmap_list_lock);
do {
struct map_tracker *mt = util_range_find(addr, len);
if (mt == NULL) {
LOG(4, "address not found 0x%016" PRIxPTR, addr);
retval = 0;
break;
}
LOG(10, "range found - begin 0x%016" PRIxPTR
" end 0x%016" PRIxPTR,
mt->base_addr, mt->end_addr);
if (mt->base_addr > addr) {
LOG(10, "base address doesn't match: "
"0x%" PRIxPTR " > 0x%" PRIxPTR,
mt->base_addr, addr);
retval = 0;
break;
}
uintptr_t map_len = mt->end_addr - addr;
if (map_len > len)
map_len = len;
len -= map_len;
addr += map_len;
} while (len > 0);
util_rwlock_unlock(&Mmap_list_lock);
return retval;
}
| 11,141 | 21.063366 | 115 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/mmap_posix.c
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2014-2018, Intel Corporation */
/*
* mmap_posix.c -- memory-mapped files for Posix
*/
#include <stdio.h>
#include <sys/mman.h>
#include <sys/param.h>
#include "mmap.h"
#include "out.h"
#include "os.h"
#define PROCMAXLEN 2048 /* maximum expected line length in /proc files */
char *Mmap_mapfile = OS_MAPFILE; /* Should be modified only for testing */
#ifdef __FreeBSD__
static const char * const sscanf_os = "%p %p";
#else
static const char * const sscanf_os = "%p-%p";
#endif
/*
* util_map_hint_unused -- use /proc to determine a hint address for mmap()
*
* This is a helper function for util_map_hint().
* It opens up /proc/self/maps and looks for the first unused address
* in the process address space that is:
* - greater or equal 'minaddr' argument,
* - large enough to hold range of given length,
* - aligned to the specified unit.
*
* Asking for aligned address like this will allow the DAX code to use large
* mappings. It is not an error if mmap() ignores the hint and chooses
* different address.
*/
char *
util_map_hint_unused(void *minaddr, size_t len, size_t align)
{
LOG(3, "minaddr %p len %zu align %zu", minaddr, len, align);
ASSERT(align > 0);
FILE *fp;
if ((fp = os_fopen(Mmap_mapfile, "r")) == NULL) {
ERR("!%s", Mmap_mapfile);
return MAP_FAILED;
}
char line[PROCMAXLEN]; /* for fgets() */
char *lo = NULL; /* beginning of current range in maps file */
char *hi = NULL; /* end of current range in maps file */
char *raddr = minaddr; /* ignore regions below 'minaddr' */
if (raddr == NULL)
raddr += Pagesize;
raddr = (char *)roundup((uintptr_t)raddr, align);
while (fgets(line, PROCMAXLEN, fp) != NULL) {
/* check for range line */
if (sscanf(line, sscanf_os, &lo, &hi) == 2) {
LOG(4, "%p-%p", lo, hi);
if (lo > raddr) {
if ((uintptr_t)(lo - raddr) >= len) {
LOG(4, "unused region of size %zu "
"found at %p",
lo - raddr, raddr);
break;
} else {
LOG(4, "region is too small: %zu < %zu",
lo - raddr, len);
}
}
if (hi > raddr) {
raddr = (char *)roundup((uintptr_t)hi, align);
LOG(4, "nearest aligned addr %p", raddr);
}
if (raddr == NULL) {
LOG(4, "end of address space reached");
break;
}
}
}
/*
* Check for a case when this is the last unused range in the address
* space, but is not large enough. (very unlikely)
*/
if ((raddr != NULL) && (UINTPTR_MAX - (uintptr_t)raddr < len)) {
ERR("end of address space reached");
raddr = MAP_FAILED;
}
fclose(fp);
LOG(3, "returning %p", raddr);
return raddr;
}
/*
* util_map_hint -- determine hint address for mmap()
*
* If PMEM_MMAP_HINT environment variable is not set, we let the system to pick
* the randomized mapping address. Otherwise, a user-defined hint address
* is used.
*
* ALSR in 64-bit Linux kernel uses 28-bit of randomness for mmap
* (bit positions 12-39), which means the base mapping address is randomized
* within [0..1024GB] range, with 4KB granularity. Assuming additional
* 1GB alignment, it results in 1024 possible locations.
*
* Configuring the hint address via PMEM_MMAP_HINT environment variable
* disables address randomization. In such case, the function will search for
* the first unused, properly aligned region of given size, above the specified
* address.
*/
char *
util_map_hint(size_t len, size_t req_align)
{
LOG(3, "len %zu req_align %zu", len, req_align);
char *hint_addr = MAP_FAILED;
/* choose the desired alignment based on the requested length */
size_t align = util_map_hint_align(len, req_align);
if (Mmap_no_random) {
LOG(4, "user-defined hint %p", Mmap_hint);
hint_addr = util_map_hint_unused(Mmap_hint, len, align);
} else {
/*
* Create dummy mapping to find an unused region of given size.
* Request for increased size for later address alignment.
* Use MAP_PRIVATE with read-only access to simulate
* zero cost for overcommit accounting. Note: MAP_NORESERVE
* flag is ignored if overcommit is disabled (mode 2).
*/
char *addr = mmap(NULL, len + align, PROT_READ,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
ERR("!mmap MAP_ANONYMOUS");
} else {
LOG(4, "system choice %p", addr);
hint_addr = (char *)roundup((uintptr_t)addr, align);
munmap(addr, len + align);
}
}
LOG(4, "hint %p", hint_addr);
return hint_addr;
}
/*
* util_map_sync -- memory map given file into memory, if MAP_SHARED flag is
* provided it attempts to use MAP_SYNC flag. Otherwise it fallbacks to
* mmap(2).
*/
void *
util_map_sync(void *addr, size_t len, int proto, int flags, int fd,
os_off_t offset, int *map_sync)
{
LOG(15, "addr %p len %zu proto %x flags %x fd %d offset %ld "
"map_sync %p", addr, len, proto, flags, fd, offset, map_sync);
if (map_sync)
*map_sync = 0;
/* if map_sync is NULL do not even try to mmap with MAP_SYNC flag */
if (!map_sync || flags & MAP_PRIVATE)
return mmap(addr, len, proto, flags, fd, offset);
/* MAP_SHARED */
void *ret = mmap(addr, len, proto,
flags | MAP_SHARED_VALIDATE | MAP_SYNC,
fd, offset);
if (ret != MAP_FAILED) {
LOG(4, "mmap with MAP_SYNC succeeded");
*map_sync = 1;
return ret;
}
if (errno == EINVAL || errno == ENOTSUP) {
LOG(4, "mmap with MAP_SYNC not supported");
return mmap(addr, len, proto, flags, fd, offset);
}
/* other error */
return MAP_FAILED;
}
| 5,438 | 27.036082 | 79 |
c
|
null |
NearPMSW-main/nearpm/logging/pmdk/src/common/ravl.h
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2019, Intel Corporation */
/*
* ravl.h -- internal definitions for ravl tree
*/
#ifndef LIBPMEMOBJ_RAVL_H
#define LIBPMEMOBJ_RAVL_H 1
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
struct ravl;
struct ravl_node;
enum ravl_predicate {
RAVL_PREDICATE_EQUAL = 1 << 0,
RAVL_PREDICATE_GREATER = 1 << 1,
RAVL_PREDICATE_LESS = 1 << 2,
RAVL_PREDICATE_LESS_EQUAL =
RAVL_PREDICATE_EQUAL | RAVL_PREDICATE_LESS,
RAVL_PREDICATE_GREATER_EQUAL =
RAVL_PREDICATE_EQUAL | RAVL_PREDICATE_GREATER,
};
typedef int ravl_compare(const void *lhs, const void *rhs);
typedef void ravl_cb(void *data, void *arg);
typedef void ravl_constr(void *data, size_t data_size, const void *arg);
struct ravl *ravl_new(ravl_compare *compare);
struct ravl *ravl_new_sized(ravl_compare *compare, size_t data_size);
void ravl_delete(struct ravl *ravl);
void ravl_delete_cb(struct ravl *ravl, ravl_cb cb, void *arg);
void ravl_foreach(struct ravl *ravl, ravl_cb cb, void *arg);
int ravl_empty(struct ravl *ravl);
void ravl_clear(struct ravl *ravl);
int ravl_insert(struct ravl *ravl, const void *data);
int ravl_emplace(struct ravl *ravl, ravl_constr constr, const void *arg);
int ravl_emplace_copy(struct ravl *ravl, const void *data);
struct ravl_node *ravl_find(struct ravl *ravl, const void *data,
enum ravl_predicate predicate_flags);
void *ravl_data(struct ravl_node *node);
void ravl_remove(struct ravl *ravl, struct ravl_node *node);
#ifdef __cplusplus
}
#endif
#endif /* LIBPMEMOBJ_RAVL_H */
| 1,556 | 27.309091 | 73 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.