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/checkpointing/redis-NDP-chekpoint/src/memtest.c
|
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#if defined(__sun)
#include <stropts.h>
#endif
#include "config.h"
#if (ULONG_MAX == 4294967295UL)
#define MEMTEST_32BIT
#elif (ULONG_MAX == 18446744073709551615ULL)
#define MEMTEST_64BIT
#else
#error "ULONG_MAX value not supported."
#endif
#ifdef MEMTEST_32BIT
#define ULONG_ONEZERO 0xaaaaaaaaUL
#define ULONG_ZEROONE 0x55555555UL
#else
#define ULONG_ONEZERO 0xaaaaaaaaaaaaaaaaUL
#define ULONG_ZEROONE 0x5555555555555555UL
#endif
static struct winsize ws;
size_t progress_printed; /* Printed chars in screen-wide progress bar. */
size_t progress_full; /* How many chars to write to fill the progress bar. */
void memtest_progress_start(char *title, int pass) {
int j;
printf("\x1b[H\x1b[2J"); /* Cursor home, clear screen. */
/* Fill with dots. */
for (j = 0; j < ws.ws_col*(ws.ws_row-2); j++) printf(".");
printf("Please keep the test running several minutes per GB of memory.\n");
printf("Also check http://www.memtest86.com/ and http://pyropus.ca/software/memtester/");
printf("\x1b[H\x1b[2K"); /* Cursor home, clear current line. */
printf("%s [%d]\n", title, pass); /* Print title. */
progress_printed = 0;
progress_full = ws.ws_col*(ws.ws_row-3);
fflush(stdout);
}
void memtest_progress_end(void) {
printf("\x1b[H\x1b[2J"); /* Cursor home, clear screen. */
}
void memtest_progress_step(size_t curr, size_t size, char c) {
size_t chars = ((unsigned long long)curr*progress_full)/size, j;
for (j = 0; j < chars-progress_printed; j++) printf("%c",c);
progress_printed = chars;
fflush(stdout);
}
/* Test that addressing is fine. Every location is populated with its own
* address, and finally verified. This test is very fast but may detect
* ASAP big issues with the memory subsystem. */
int memtest_addressing(unsigned long *l, size_t bytes, int interactive) {
unsigned long words = bytes/sizeof(unsigned long);
unsigned long j, *p;
/* Fill */
p = l;
for (j = 0; j < words; j++) {
*p = (unsigned long)p;
p++;
if ((j & 0xffff) == 0 && interactive)
memtest_progress_step(j,words*2,'A');
}
/* Test */
p = l;
for (j = 0; j < words; j++) {
if (*p != (unsigned long)p) {
if (interactive) {
printf("\n*** MEMORY ADDRESSING ERROR: %p contains %lu\n",
(void*) p, *p);
exit(1);
}
return 1;
}
p++;
if ((j & 0xffff) == 0 && interactive)
memtest_progress_step(j+words,words*2,'A');
}
return 0;
}
/* Fill words stepping a single page at every write, so we continue to
* touch all the pages in the smallest amount of time reducing the
* effectiveness of caches, and making it hard for the OS to transfer
* pages on the swap.
*
* In this test we can't call rand() since the system may be completely
* unable to handle library calls, so we have to resort to our own
* PRNG that only uses local state. We use an xorshift* PRNG. */
#define xorshift64star_next() do { \
rseed ^= rseed >> 12; \
rseed ^= rseed << 25; \
rseed ^= rseed >> 27; \
rout = rseed * UINT64_C(2685821657736338717); \
} while(0)
void memtest_fill_random(unsigned long *l, size_t bytes, int interactive) {
unsigned long step = 4096/sizeof(unsigned long);
unsigned long words = bytes/sizeof(unsigned long)/2;
unsigned long iwords = words/step; /* words per iteration */
unsigned long off, w, *l1, *l2;
uint64_t rseed = UINT64_C(0xd13133de9afdb566); /* Just a random seed. */
uint64_t rout = 0;
assert((bytes & 4095) == 0);
for (off = 0; off < step; off++) {
l1 = l+off;
l2 = l1+words;
for (w = 0; w < iwords; w++) {
xorshift64star_next();
*l1 = *l2 = (unsigned long) rout;
l1 += step;
l2 += step;
if ((w & 0xffff) == 0 && interactive)
memtest_progress_step(w+iwords*off,words,'R');
}
}
}
/* Like memtest_fill_random() but uses the two specified values to fill
* memory, in an alternated way (v1|v2|v1|v2|...) */
void memtest_fill_value(unsigned long *l, size_t bytes, unsigned long v1,
unsigned long v2, char sym, int interactive)
{
unsigned long step = 4096/sizeof(unsigned long);
unsigned long words = bytes/sizeof(unsigned long)/2;
unsigned long iwords = words/step; /* words per iteration */
unsigned long off, w, *l1, *l2, v;
assert((bytes & 4095) == 0);
for (off = 0; off < step; off++) {
l1 = l+off;
l2 = l1+words;
v = (off & 1) ? v2 : v1;
for (w = 0; w < iwords; w++) {
#ifdef MEMTEST_32BIT
*l1 = *l2 = ((unsigned long) v) |
(((unsigned long) v) << 16);
#else
*l1 = *l2 = ((unsigned long) v) |
(((unsigned long) v) << 16) |
(((unsigned long) v) << 32) |
(((unsigned long) v) << 48);
#endif
l1 += step;
l2 += step;
if ((w & 0xffff) == 0 && interactive)
memtest_progress_step(w+iwords*off,words,sym);
}
}
}
int memtest_compare(unsigned long *l, size_t bytes, int interactive) {
unsigned long words = bytes/sizeof(unsigned long)/2;
unsigned long w, *l1, *l2;
assert((bytes & 4095) == 0);
l1 = l;
l2 = l1+words;
for (w = 0; w < words; w++) {
if (*l1 != *l2) {
if (interactive) {
printf("\n*** MEMORY ERROR DETECTED: %p != %p (%lu vs %lu)\n",
(void*)l1, (void*)l2, *l1, *l2);
exit(1);
}
return 1;
}
l1 ++;
l2 ++;
if ((w & 0xffff) == 0 && interactive)
memtest_progress_step(w,words,'=');
}
return 0;
}
int memtest_compare_times(unsigned long *m, size_t bytes, int pass, int times,
int interactive)
{
int j;
int errors = 0;
for (j = 0; j < times; j++) {
if (interactive) memtest_progress_start("Compare",pass);
errors += memtest_compare(m,bytes,interactive);
if (interactive) memtest_progress_end();
}
return errors;
}
/* Test the specified memory. The number of bytes must be multiple of 4096.
* If interactive is true the program exists with an error and prints
* ASCII arts to show progresses. Instead when interactive is 0, it can
* be used as an API call, and returns 1 if memory errors were found or
* 0 if there were no errors detected. */
int memtest_test(unsigned long *m, size_t bytes, int passes, int interactive) {
int pass = 0;
int errors = 0;
while (pass != passes) {
pass++;
if (interactive) memtest_progress_start("Addressing test",pass);
errors += memtest_addressing(m,bytes,interactive);
if (interactive) memtest_progress_end();
if (interactive) memtest_progress_start("Random fill",pass);
memtest_fill_random(m,bytes,interactive);
if (interactive) memtest_progress_end();
errors += memtest_compare_times(m,bytes,pass,4,interactive);
if (interactive) memtest_progress_start("Solid fill",pass);
memtest_fill_value(m,bytes,0,(unsigned long)-1,'S',interactive);
if (interactive) memtest_progress_end();
errors += memtest_compare_times(m,bytes,pass,4,interactive);
if (interactive) memtest_progress_start("Checkerboard fill",pass);
memtest_fill_value(m,bytes,ULONG_ONEZERO,ULONG_ZEROONE,'C',interactive);
if (interactive) memtest_progress_end();
errors += memtest_compare_times(m,bytes,pass,4,interactive);
}
return errors;
}
/* A version of memtest_test() that tests memory in small pieces
* in order to restore the memory content at exit.
*
* One problem we have with this approach, is that the cache can avoid
* real memory accesses, and we can't test big chunks of memory at the
* same time, because we need to backup them on the stack (the allocator
* may not be usable or we may be already in an out of memory condition).
* So what we do is to try to trash the cache with useless memory accesses
* between the fill and compare cycles. */
#define MEMTEST_BACKUP_WORDS (1024*(1024/sizeof(long)))
/* Random accesses of MEMTEST_DECACHE_SIZE are performed at the start and
* end of the region between fill and compare cycles in order to trash
* the cache. */
#define MEMTEST_DECACHE_SIZE (1024*8)
int memtest_preserving_test(unsigned long *m, size_t bytes, int passes) {
unsigned long backup[MEMTEST_BACKUP_WORDS];
unsigned long *p = m;
unsigned long *end = (unsigned long*) (((unsigned char*)m)+(bytes-MEMTEST_DECACHE_SIZE));
size_t left = bytes;
int errors = 0;
if (bytes & 4095) return 0; /* Can't test across 4k page boundaries. */
if (bytes < 4096*2) return 0; /* Can't test a single page. */
while(left) {
/* If we have to test a single final page, go back a single page
* so that we can test two pages, since the code can't test a single
* page but at least two. */
if (left == 4096) {
left += 4096;
p -= 4096/sizeof(unsigned long);
}
int pass = 0;
size_t len = (left > sizeof(backup)) ? sizeof(backup) : left;
/* Always test an even number of pages. */
if (len/4096 % 2) len -= 4096;
memcpy(backup,p,len); /* Backup. */
while(pass != passes) {
pass++;
errors += memtest_addressing(p,len,0);
memtest_fill_random(p,len,0);
if (bytes >= MEMTEST_DECACHE_SIZE) {
memtest_compare_times(m,MEMTEST_DECACHE_SIZE,pass,1,0);
memtest_compare_times(end,MEMTEST_DECACHE_SIZE,pass,1,0);
}
errors += memtest_compare_times(p,len,pass,4,0);
memtest_fill_value(p,len,0,(unsigned long)-1,'S',0);
if (bytes >= MEMTEST_DECACHE_SIZE) {
memtest_compare_times(m,MEMTEST_DECACHE_SIZE,pass,1,0);
memtest_compare_times(end,MEMTEST_DECACHE_SIZE,pass,1,0);
}
errors += memtest_compare_times(p,len,pass,4,0);
memtest_fill_value(p,len,ULONG_ONEZERO,ULONG_ZEROONE,'C',0);
if (bytes >= MEMTEST_DECACHE_SIZE) {
memtest_compare_times(m,MEMTEST_DECACHE_SIZE,pass,1,0);
memtest_compare_times(end,MEMTEST_DECACHE_SIZE,pass,1,0);
}
errors += memtest_compare_times(p,len,pass,4,0);
}
memcpy(p,backup,len); /* Restore. */
left -= len;
p += len/sizeof(unsigned long);
}
return errors;
}
/* Perform an interactive test allocating the specified number of megabytes. */
void memtest_alloc_and_test(size_t megabytes, int passes) {
size_t bytes = megabytes*1024*1024;
unsigned long *m = malloc(bytes);
if (m == NULL) {
fprintf(stderr,"Unable to allocate %zu megabytes: %s",
megabytes, strerror(errno));
exit(1);
}
memtest_test(m,bytes,passes,1);
free(m);
}
void memtest(size_t megabytes, int passes) {
if (ioctl(1, TIOCGWINSZ, &ws) == -1) {
ws.ws_col = 80;
ws.ws_row = 20;
}
memtest_alloc_and_test(megabytes,passes);
printf("\nYour memory passed this test.\n");
printf("Please if you are still in doubt use the following two tools:\n");
printf("1) memtest86: http://www.memtest86.com/\n");
printf("2) memtester: http://pyropus.ca/software/memtester/\n");
exit(0);
}
| 13,441 | 36.235457 | 93 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/pmem.c
|
/*
* Copyright (c) 2017, Andreas Bluemle <andreas dot bluemle at itxperts dot de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef USE_PMDK
#include "server.h"
#include "obj.h"
#include "libpmemobj.h"
#include "util.h"
/////////////////Page fault handling/////////////////
#include <bits/types/sig_atomic_t.h>
#include <bits/types/sigset_t.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <libpmem.h>
#define SIGSTKSZ 8192
#define SA_SIGINFO 4
#define SA_ONSTACK 0x08000000 /* Use signal stack by using `sa_restorer'. */
#define SA_RESTART 0x10000000 /* Restart syscall on signal return. */
#define SA_NODEFER 0x40000000 /* Don't automatically block the signal when*/
stack_t _sigstk;
int updated_page_count1 = 0;
int all_updates1 = 0;
void * checkpoint_start = NULL;
bool init = true;
void * page[50];
PMEMobjpool *pop;
void * device;
static void* open_device1(const char* pathname)
{
//int fd = os_open("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0",O_RDWR|O_SYNC);
int fd = open(pathname,O_RDWR|O_SYNC);
if(fd == -1)
{
printf("Couldnt opene file!!\n");
exit(0);
}
void * ptr = mmap(0,4096,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);
if(ptr == (void *)-1)
{
printf("Could not map memory!!\n");
exit(0);
}
printf("opened device without error!!\n");
return ptr;
}
#define CPTIME
void cmd_issue( uint32_t opcode,
uint32_t TXID,
uint32_t TID,
uint32_t OID,
uint64_t data_addr,
uint32_t data_size,
void * ptr){
//command with thread id encoded as first 8 bits of each word
uint32_t issue_cmd[7];
issue_cmd[0] = (TID<<24)|(opcode<<16)|(TXID<<8)|TID;
issue_cmd[1] = (TID<<24)|(OID<<16)|(data_addr>>48);
issue_cmd[2] = (TID<<24)|((data_addr & 0x0000FFFFFFFFFFFF)>>24);
issue_cmd[3] = (TID<<24)|(data_addr & 0x0000000000FFFFFF);
issue_cmd[4] = (TID<<24)|(data_size<<8);
issue_cmd[5] = (TID<<24)|(0X00FFFFFF>>16);
issue_cmd[6] = (TID<<24)|((0X00FFFFFF & 0x0000FFFF)<<8);
for(int i=0;i<7;i++){
//printf("%d %08x\n",TID, issue_cmd[i]);
*((u_int32_t *) ptr) = issue_cmd[i];
}
}
#define CPTIME
#ifdef CPTIME
static inline uint64_t getCycle(){
uint32_t cycles_high, cycles_low, pid;
asm volatile ("RDTSCP\n\t" // rdtscp into eax and edx
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"mov %%ecx, %2\n\t"
:"=r" (cycles_high), "=r" (cycles_low), "=r" (pid) //store in vars
:// no input
:"%eax", "%edx", "%ecx" // clobbered by rdtscp
);
return((uint64_t)cycles_high << 32) | cycles_low;
}
#endif
static void makecheckpoint( void * ptr) {
#ifdef CPTIME
uint64_t endCycles, startCycles,totalCycles;
startCycles = getCycle();
#endif
if(init){
size_t mapped_len1;
int is_pmem1;
if ((checkpoint_start = pmem_map_file("/mnt/mem/checkpoint", 4096*50,
PMEM_FILE_CREATE, 0666, &mapped_len1, &is_pmem1)) == NULL) {
fprintf(stderr, "pmem_map_file failed\n");
exit(0);
}
device = open_device1("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0");
init = false;
}
uint64_t pageNo = ((uint64_t)ptr)/4096;
unsigned long * pageStart = (unsigned long *)(pageNo*4096);
uint64_t cp_count = 0;
// memcpy(checkpoint_start , pageStart,4096);
// pmem_persist( checkpoint_start ,4096);
if(all_updates1 > 5 || updated_page_count1 == 40){
for(int i=0;i<updated_page_count1;i++){
cp_count++;
//memcpy(checkpoint_start + i*4096, page[i],4096);
//pmem_persist( checkpoint_start + i*4096,4096);
cmd_issue(2,0,0,0, (uint64_t)(checkpoint_start + i*4096),4096,device);
page[updated_page_count1] = 0;
}
printf("pagecnt %ld\n",cp_count);
updated_page_count1 = 0;
all_updates1 = 0;
}
all_updates1++;
for(int i=0; i<updated_page_count1; i++){
if(page[i] == pageStart){
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
printf("cycles = %ld\n", totalCycles);
#endif
return;
}
}
page[updated_page_count1] = pageStart;
updated_page_count1++;
#ifdef CPTIME
endCycles = getCycle();
totalCycles = endCycles - startCycles;
double totTime = ((double)totalCycles)/2000000000;
printf("cp %f\n", totTime);
printf("cycles = %ld\n", totalCycles);
#endif
}
///////////////////////////////////////////////////////////////
int
pmemReconstruct(void)
{
TOID(struct redis_pmem_root) root;
TOID(struct key_val_pair_PM) kv_PM_oid;
struct key_val_pair_PM *kv_PM;
dict *d;
void *key;
void *val;
void *pmem_base_addr;
root = server.pm_rootoid;
pmem_base_addr = (void *)server.pm_pool->addr;
d = server.db[0].dict;
dictExpand(d, D_RO(root)->num_dict_entries);
for (kv_PM_oid = D_RO(root)->pe_first; TOID_IS_NULL(kv_PM_oid) == 0; kv_PM_oid = D_RO(kv_PM_oid)->pmem_list_next){
kv_PM = (key_val_pair_PM *)(kv_PM_oid.oid.off + (uint64_t)pmem_base_addr);
key = (void *)(kv_PM->key_oid.off + (uint64_t)pmem_base_addr);
val = (void *)(kv_PM->val_oid.off + (uint64_t)pmem_base_addr);
(void)dictAddReconstructedPM(d, key, val);
}
return C_OK;
}
void pmemKVpairSet(void *key, void *val)
{
PMEMoid *kv_PM_oid;
PMEMoid val_oid;
struct key_val_pair_PM *kv_PM_p;
kv_PM_oid = sdsPMEMoidBackReference((sds)key);
kv_PM_p = (struct key_val_pair_PM *)pmemobj_direct(*kv_PM_oid);
val_oid.pool_uuid_lo = server.pool_uuid_lo;
val_oid.off = (uint64_t)val - (uint64_t)server.pm_pool->addr;
//setpage(&(kv_PM_p->val_oid));
//printf("B");
struct key_val_pair_PM a;
kv_PM_p = &a;
kv_PM_p->val_oid = val_oid;
makecheckpoint(&(kv_PM_p));
TX_ADD_FIELD_DIRECT(kv_PM_p, val_oid);
// printf("A");
return;
}
PMEMoid
pmemAddToPmemList(void *key, void *val)
{
PMEMoid key_oid;
PMEMoid val_oid;
PMEMoid kv_PM;
struct key_val_pair_PM *kv_PM_p;
TOID(struct key_val_pair_PM) typed_kv_PM;
struct redis_pmem_root *root;
key_oid.pool_uuid_lo = server.pool_uuid_lo;
key_oid.off = (uint64_t)key - (uint64_t)server.pm_pool->addr;
val_oid.pool_uuid_lo = server.pool_uuid_lo;
val_oid.off = (uint64_t)val - (uint64_t)server.pm_pool->addr;
kv_PM = pmemobj_tx_zalloc(sizeof(struct key_val_pair_PM), pm_type_key_val_pair_PM);
kv_PM_p = (struct key_val_pair_PM *)pmemobj_direct(kv_PM);
kv_PM_p->key_oid = key_oid;
kv_PM_p->val_oid = val_oid;
typed_kv_PM.oid = kv_PM;
root = pmemobj_direct(server.pm_rootoid.oid);
kv_PM_p->pmem_list_next = root->pe_first;
if(!TOID_IS_NULL(root->pe_first)) {
struct key_val_pair_PM *head = D_RW(root->pe_first);
TX_ADD_FIELD_DIRECT(head,pmem_list_prev);
makecheckpoint(&(head->pmem_list_prev));
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
head->pmem_list_prev = typed_kv_PM;
}
TX_ADD_DIRECT(root);
makecheckpoint(root);
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
root->pe_first = typed_kv_PM;
root->num_dict_entries++;
return kv_PM;
}
void
pmemRemoveFromPmemList(PMEMoid kv_PM_oid)
{
TOID(struct key_val_pair_PM) typed_kv_PM;
struct redis_pmem_root *root;
root = pmemobj_direct(server.pm_rootoid.oid);
typed_kv_PM.oid = kv_PM_oid;
if(TOID_EQUALS(root->pe_first, typed_kv_PM)) {
TOID(struct key_val_pair_PM) typed_kv_PM_next = D_RO(typed_kv_PM)->pmem_list_next;
if(!TOID_IS_NULL(typed_kv_PM_next)){
struct key_val_pair_PM *next = D_RW(typed_kv_PM_next);
TX_ADD_FIELD_DIRECT(next,pmem_list_prev);
makecheckpoint(&(next->pmem_list_prev));
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
next->pmem_list_prev.oid = OID_NULL;
}
TX_FREE(root->pe_first);
TX_ADD_DIRECT(root);
makecheckpoint(root);
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
root->pe_first = typed_kv_PM_next;
root->num_dict_entries--;
return;
}
else {
TOID(struct key_val_pair_PM) typed_kv_PM_prev = D_RO(typed_kv_PM)->pmem_list_prev;
TOID(struct key_val_pair_PM) typed_kv_PM_next = D_RO(typed_kv_PM)->pmem_list_next;
if(!TOID_IS_NULL(typed_kv_PM_prev)){
struct key_val_pair_PM *prev = D_RW(typed_kv_PM_prev);
TX_ADD_FIELD_DIRECT(prev,pmem_list_next);
makecheckpoint(&(prev->pmem_list_next));
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
prev->pmem_list_next = typed_kv_PM_next;
}
if(!TOID_IS_NULL(typed_kv_PM_next)){
struct key_val_pair_PM *next = D_RW(typed_kv_PM_next);
TX_ADD_FIELD_DIRECT(next,pmem_list_prev);
makecheckpoint(&(next->pmem_list_prev));
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
next->pmem_list_prev = typed_kv_PM_prev;
}
TX_FREE(typed_kv_PM);
TX_ADD_FIELD_DIRECT(root,num_dict_entries);
makecheckpoint(&(root->num_dict_entries));
//serverLog(LL_NOTICE,"ulog\n");
//printf("ulog\n");
root->num_dict_entries--;
return;
}
}
#endif
| 11,010 | 30.016901 | 118 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/solarisfixes.h
|
/* Solaris specific fixes.
*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(__sun)
#if defined(__GNUC__)
#include <math.h>
#undef isnan
#define isnan(x) \
__extension__({ __typeof (x) __x_a = (x); \
__builtin_expect(__x_a != __x_a, 0); })
#undef isfinite
#define isfinite(x) \
__extension__ ({ __typeof (x) __x_f = (x); \
__builtin_expect(!isnan(__x_f - __x_f), 1); })
#undef isinf
#define isinf(x) \
__extension__ ({ __typeof (x) __x_i = (x); \
__builtin_expect(!isnan(__x_i) && !isfinite(__x_i), 0); })
#define u_int uint
#define u_int32_t uint32_t
#endif /* __GNUC__ */
#endif /* __sun */
| 2,201 | 39.036364 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/quicklist.h
|
/* quicklist.h - A generic doubly linked quicklist implementation
*
* Copyright (c) 2014, Matt Stancliff <matt@genges.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this quicklist of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this quicklist of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __QUICKLIST_H__
#define __QUICKLIST_H__
/* Node, quicklist, and Iterator are the only data structures used currently. */
/* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
* We use bit fields keep the quicklistNode at 32 bytes.
* count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually < 32k).
* encoding: 2 bits, RAW=1, LZF=2.
* container: 2 bits, NONE=1, ZIPLIST=2.
* recompress: 1 bit, bool, true if node is temporarry decompressed for usage.
* attempted_compress: 1 bit, boolean, used for verifying during testing.
* extra: 12 bits, free for future use; pads out the remainder of 32 bits */
typedef struct quicklistNode {
struct quicklistNode *prev;
struct quicklistNode *next;
unsigned char *zl;
unsigned int sz; /* ziplist size in bytes */
unsigned int count : 16; /* count of items in ziplist */
unsigned int encoding : 2; /* RAW==1 or LZF==2 */
unsigned int container : 2; /* NONE==1 or ZIPLIST==2 */
unsigned int recompress : 1; /* was this node previous compressed? */
unsigned int attempted_compress : 1; /* node can't compress; too small */
unsigned int extra : 10; /* more bits to steal for future usage */
} quicklistNode;
/* quicklistLZF is a 4+N byte struct holding 'sz' followed by 'compressed'.
* 'sz' is byte length of 'compressed' field.
* 'compressed' is LZF data with total (compressed) length 'sz'
* NOTE: uncompressed length is stored in quicklistNode->sz.
* When quicklistNode->zl is compressed, node->zl points to a quicklistLZF */
typedef struct quicklistLZF {
unsigned int sz; /* LZF size in bytes*/
char compressed[];
} quicklistLZF;
/* quicklist is a 32 byte struct (on 64-bit systems) describing a quicklist.
* 'count' is the number of total entries.
* 'len' is the number of quicklist nodes.
* 'compress' is: -1 if compression disabled, otherwise it's the number
* of quicklistNodes to leave uncompressed at ends of quicklist.
* 'fill' is the user-requested (or default) fill factor. */
typedef struct quicklist {
quicklistNode *head;
quicklistNode *tail;
unsigned long count; /* total count of all entries in all ziplists */
unsigned int len; /* number of quicklistNodes */
int fill : 16; /* fill factor for individual nodes */
unsigned int compress : 16; /* depth of end nodes not to compress;0=off */
} quicklist;
typedef struct quicklistIter {
const quicklist *quicklist;
quicklistNode *current;
unsigned char *zi;
long offset; /* offset in current ziplist */
int direction;
} quicklistIter;
typedef struct quicklistEntry {
const quicklist *quicklist;
quicklistNode *node;
unsigned char *zi;
unsigned char *value;
long long longval;
unsigned int sz;
int offset;
} quicklistEntry;
#define QUICKLIST_HEAD 0
#define QUICKLIST_TAIL -1
/* quicklist node encodings */
#define QUICKLIST_NODE_ENCODING_RAW 1
#define QUICKLIST_NODE_ENCODING_LZF 2
/* quicklist compression disable */
#define QUICKLIST_NOCOMPRESS 0
/* quicklist container formats */
#define QUICKLIST_NODE_CONTAINER_NONE 1
#define QUICKLIST_NODE_CONTAINER_ZIPLIST 2
#define quicklistNodeIsCompressed(node) \
((node)->encoding == QUICKLIST_NODE_ENCODING_LZF)
/* Prototypes */
quicklist *quicklistCreate(void);
quicklist *quicklistNew(int fill, int compress);
void quicklistSetCompressDepth(quicklist *quicklist, int depth);
void quicklistSetFill(quicklist *quicklist, int fill);
void quicklistSetOptions(quicklist *quicklist, int fill, int depth);
void quicklistRelease(quicklist *quicklist);
int quicklistPushHead(quicklist *quicklist, void *value, const size_t sz);
int quicklistPushTail(quicklist *quicklist, void *value, const size_t sz);
void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
int where);
void quicklistAppendZiplist(quicklist *quicklist, unsigned char *zl);
quicklist *quicklistAppendValuesFromZiplist(quicklist *quicklist,
unsigned char *zl);
quicklist *quicklistCreateFromZiplist(int fill, int compress,
unsigned char *zl);
void quicklistInsertAfter(quicklist *quicklist, quicklistEntry *node,
void *value, const size_t sz);
void quicklistInsertBefore(quicklist *quicklist, quicklistEntry *node,
void *value, const size_t sz);
void quicklistDelEntry(quicklistIter *iter, quicklistEntry *entry);
int quicklistReplaceAtIndex(quicklist *quicklist, long index, void *data,
int sz);
int quicklistDelRange(quicklist *quicklist, const long start, const long stop);
quicklistIter *quicklistGetIterator(const quicklist *quicklist, int direction);
quicklistIter *quicklistGetIteratorAtIdx(const quicklist *quicklist,
int direction, const long long idx);
int quicklistNext(quicklistIter *iter, quicklistEntry *node);
void quicklistReleaseIterator(quicklistIter *iter);
quicklist *quicklistDup(quicklist *orig);
int quicklistIndex(const quicklist *quicklist, const long long index,
quicklistEntry *entry);
void quicklistRewind(quicklist *quicklist, quicklistIter *li);
void quicklistRewindTail(quicklist *quicklist, quicklistIter *li);
void quicklistRotate(quicklist *quicklist);
int quicklistPopCustom(quicklist *quicklist, int where, unsigned char **data,
unsigned int *sz, long long *sval,
void *(*saver)(unsigned char *data, unsigned int sz));
int quicklistPop(quicklist *quicklist, int where, unsigned char **data,
unsigned int *sz, long long *slong);
unsigned int quicklistCount(quicklist *ql);
int quicklistCompare(unsigned char *p1, unsigned char *p2, int p2_len);
size_t quicklistGetLzf(const quicklistNode *node, void **data);
#ifdef REDIS_TEST
int quicklistTest(int argc, char *argv[]);
#endif
/* Directions for iterators */
#define AL_START_HEAD 0
#define AL_START_TAIL 1
#endif /* __QUICKLIST_H__ */
| 7,808 | 44.935294 | 80 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/redis-check-rdb.c
|
/*
* Copyright (c) 2016, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include "rdb.h"
#include <stdarg.h>
void createSharedObjects(void);
void rdbLoadProgressCallback(rio *r, const void *buf, size_t len);
long long rdbLoadMillisecondTime(rio *rdb);
int rdbCheckMode = 0;
struct {
rio *rio;
robj *key; /* Current key we are reading. */
int key_type; /* Current key type if != -1. */
unsigned long keys; /* Number of keys processed. */
unsigned long expires; /* Number of keys with an expire. */
unsigned long already_expired; /* Number of keys already expired. */
int doing; /* The state while reading the RDB. */
int error_set; /* True if error is populated. */
char error[1024];
} rdbstate;
/* At every loading step try to remember what we were about to do, so that
* we can log this information when an error is encountered. */
#define RDB_CHECK_DOING_START 0
#define RDB_CHECK_DOING_READ_TYPE 1
#define RDB_CHECK_DOING_READ_EXPIRE 2
#define RDB_CHECK_DOING_READ_KEY 3
#define RDB_CHECK_DOING_READ_OBJECT_VALUE 4
#define RDB_CHECK_DOING_CHECK_SUM 5
#define RDB_CHECK_DOING_READ_LEN 6
#define RDB_CHECK_DOING_READ_AUX 7
char *rdb_check_doing_string[] = {
"start",
"read-type",
"read-expire",
"read-key",
"read-object-value",
"check-sum",
"read-len",
"read-aux"
};
char *rdb_type_string[] = {
"string",
"list-linked",
"set-hashtable",
"zset-v1",
"hash-hashtable",
"zset-v2",
"module-value",
"","",
"hash-zipmap",
"list-ziplist",
"set-intset",
"zset-ziplist",
"hash-ziplist",
"quicklist"
};
/* Show a few stats collected into 'rdbstate' */
void rdbShowGenericInfo(void) {
printf("[info] %lu keys read\n", rdbstate.keys);
printf("[info] %lu expires\n", rdbstate.expires);
printf("[info] %lu already expired\n", rdbstate.already_expired);
}
/* Called on RDB errors. Provides details about the RDB and the offset
* we were when the error was detected. */
void rdbCheckError(const char *fmt, ...) {
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
printf("--- RDB ERROR DETECTED ---\n");
printf("[offset %llu] %s\n",
(unsigned long long) (rdbstate.rio ?
rdbstate.rio->processed_bytes : 0), msg);
printf("[additional info] While doing: %s\n",
rdb_check_doing_string[rdbstate.doing]);
if (rdbstate.key)
printf("[additional info] Reading key '%s'\n",
(char*)rdbstate.key->ptr);
if (rdbstate.key_type != -1)
printf("[additional info] Reading type %d (%s)\n",
rdbstate.key_type,
((unsigned)rdbstate.key_type <
sizeof(rdb_type_string)/sizeof(char*)) ?
rdb_type_string[rdbstate.key_type] : "unknown");
rdbShowGenericInfo();
}
/* Print informations during RDB checking. */
void rdbCheckInfo(const char *fmt, ...) {
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
printf("[offset %llu] %s\n",
(unsigned long long) (rdbstate.rio ?
rdbstate.rio->processed_bytes : 0), msg);
}
/* Used inside rdb.c in order to log specific errors happening inside
* the RDB loading internals. */
void rdbCheckSetError(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(rdbstate.error, sizeof(rdbstate.error), fmt, ap);
va_end(ap);
rdbstate.error_set = 1;
}
/* During RDB check we setup a special signal handler for memory violations
* and similar conditions, so that we can log the offending part of the RDB
* if the crash is due to broken content. */
void rdbCheckHandleCrash(int sig, siginfo_t *info, void *secret) {
UNUSED(sig);
UNUSED(info);
UNUSED(secret);
rdbCheckError("Server crash checking the specified RDB file!");
exit(1);
}
void rdbCheckSetupSignals(void) {
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
act.sa_sigaction = rdbCheckHandleCrash;
sigaction(SIGSEGV, &act, NULL);
sigaction(SIGBUS, &act, NULL);
sigaction(SIGFPE, &act, NULL);
sigaction(SIGILL, &act, NULL);
}
/* Check the specified RDB file. */
int redis_check_rdb(char *rdbfilename) {
uint64_t dbid;
int type, rdbver;
char buf[1024];
long long expiretime, now = mstime();
FILE *fp;
rio rdb;
if ((fp = fopen(rdbfilename,"r")) == NULL) return C_ERR;
rioInitWithFile(&rdb,fp);
rdbstate.rio = &rdb;
rdb.update_cksum = rdbLoadProgressCallback;
if (rioRead(&rdb,buf,9) == 0) goto eoferr;
buf[9] = '\0';
if (memcmp(buf,"REDIS",5) != 0) {
rdbCheckError("Wrong signature trying to load DB from file");
return 1;
}
rdbver = atoi(buf+5);
if (rdbver < 1 || rdbver > RDB_VERSION) {
rdbCheckError("Can't handle RDB format version %d",rdbver);
return 1;
}
startLoading(fp);
while(1) {
robj *key, *val;
expiretime = -1;
/* Read type. */
rdbstate.doing = RDB_CHECK_DOING_READ_TYPE;
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
/* Handle special types. */
if (type == RDB_OPCODE_EXPIRETIME) {
rdbstate.doing = RDB_CHECK_DOING_READ_EXPIRE;
/* EXPIRETIME: load an expire associated with the next key
* to load. Note that after loading an expire we need to
* load the actual type, and continue. */
if ((expiretime = rdbLoadTime(&rdb)) == -1) goto eoferr;
/* We read the time so we need to read the object type again. */
rdbstate.doing = RDB_CHECK_DOING_READ_TYPE;
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
/* the EXPIRETIME opcode specifies time in seconds, so convert
* into milliseconds. */
expiretime *= 1000;
} else if (type == RDB_OPCODE_EXPIRETIME_MS) {
/* EXPIRETIME_MS: milliseconds precision expire times introduced
* with RDB v3. Like EXPIRETIME but no with more precision. */
rdbstate.doing = RDB_CHECK_DOING_READ_EXPIRE;
if ((expiretime = rdbLoadMillisecondTime(&rdb)) == -1) goto eoferr;
/* We read the time so we need to read the object type again. */
rdbstate.doing = RDB_CHECK_DOING_READ_TYPE;
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
} else if (type == RDB_OPCODE_EOF) {
/* EOF: End of file, exit the main loop. */
break;
} else if (type == RDB_OPCODE_SELECTDB) {
/* SELECTDB: Select the specified database. */
rdbstate.doing = RDB_CHECK_DOING_READ_LEN;
if ((dbid = rdbLoadLen(&rdb,NULL)) == RDB_LENERR)
goto eoferr;
rdbCheckInfo("Selecting DB ID %d", dbid);
continue; /* Read type again. */
} else if (type == RDB_OPCODE_RESIZEDB) {
/* RESIZEDB: Hint about the size of the keys in the currently
* selected data base, in order to avoid useless rehashing. */
uint64_t db_size, expires_size;
rdbstate.doing = RDB_CHECK_DOING_READ_LEN;
if ((db_size = rdbLoadLen(&rdb,NULL)) == RDB_LENERR)
goto eoferr;
if ((expires_size = rdbLoadLen(&rdb,NULL)) == RDB_LENERR)
goto eoferr;
continue; /* Read type again. */
} else if (type == RDB_OPCODE_AUX) {
/* AUX: generic string-string fields. Use to add state to RDB
* which is backward compatible. Implementations of RDB loading
* are requierd to skip AUX fields they don't understand.
*
* An AUX field is composed of two strings: key and value. */
robj *auxkey, *auxval;
rdbstate.doing = RDB_CHECK_DOING_READ_AUX;
if ((auxkey = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
if ((auxval = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
rdbCheckInfo("AUX FIELD %s = '%s'",
(char*)auxkey->ptr, (char*)auxval->ptr);
decrRefCount(auxkey);
decrRefCount(auxval);
continue; /* Read type again. */
} else {
if (!rdbIsObjectType(type)) {
rdbCheckError("Invalid object type: %d", type);
return 1;
}
rdbstate.key_type = type;
}
/* Read key */
rdbstate.doing = RDB_CHECK_DOING_READ_KEY;
if ((key = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
rdbstate.key = key;
rdbstate.keys++;
/* Read value */
rdbstate.doing = RDB_CHECK_DOING_READ_OBJECT_VALUE;
if ((val = rdbLoadObject(type,&rdb)) == NULL) goto eoferr;
/* Check if the key already expired. This function is used when loading
* an RDB file from disk, either at startup, or when an RDB was
* received from the master. In the latter case, the master is
* responsible for key expiry. If we would expire keys here, the
* snapshot taken by the master may not be reflected on the slave. */
if (server.masterhost == NULL && expiretime != -1 && expiretime < now)
rdbstate.already_expired++;
if (expiretime != -1) rdbstate.expires++;
rdbstate.key = NULL;
decrRefCount(key);
decrRefCount(val);
rdbstate.key_type = -1;
}
/* Verify the checksum if RDB version is >= 5 */
if (rdbver >= 5 && server.rdb_checksum) {
uint64_t cksum, expected = rdb.cksum;
rdbstate.doing = RDB_CHECK_DOING_CHECK_SUM;
if (rioRead(&rdb,&cksum,8) == 0) goto eoferr;
memrev64ifbe(&cksum);
if (cksum == 0) {
rdbCheckInfo("RDB file was saved with checksum disabled: no check performed.");
} else if (cksum != expected) {
rdbCheckError("RDB CRC error");
} else {
rdbCheckInfo("Checksum OK");
}
}
fclose(fp);
return 0;
eoferr: /* unexpected end of file is handled here with a fatal exit */
if (rdbstate.error_set) {
rdbCheckError(rdbstate.error);
} else {
rdbCheckError("Unexpected EOF reading RDB file");
}
return 1;
}
/* RDB check main: called form redis.c when Redis is executed with the
* redis-check-rdb alias.
*
* The function never returns, but exits with the status code according
* to success (RDB is sane) or error (RDB is corrupted). */
int redis_check_rdb_main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <rdb-file-name>\n", argv[0]);
exit(1);
}
createSharedObjects(); /* Needed for loading. */
server.loading_process_events_interval_bytes = 0;
rdbCheckMode = 1;
rdbCheckInfo("Checking RDB file %s", argv[1]);
rdbCheckSetupSignals();
int retval = redis_check_rdb(argv[1]);
if (retval == 0) {
rdbCheckInfo("\\o/ RDB looks OK! \\o/");
rdbShowGenericInfo();
}
exit(retval);
}
| 12,789 | 35.965318 | 91 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/asciilogo.h
|
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
char *ascii_logo =
" _._ \n"
" _.-``__ ''-._ \n"
" _.-`` `. `_. ''-._ Redis %s (%s/%d) %s bit\n"
" .-`` .-```. ```\\/ _.,_ ''-._ \n"
" ( ' , .-` | `, ) Running in %s mode\n"
" |`-._`-...-` __...-.``-._|'` _.-'| Port: %d\n"
" | `-._ `._ / _.-' | PID: %ld\n"
" `-._ `-._ `-./ _.-' _.-' \n"
" |`-._`-._ `-.__.-' _.-'_.-'| \n"
" | `-._`-._ _.-'_.-' | http://redis.io \n"
" `-._ `-._`-.__.-'_.-' _.-' \n"
" |`-._`-._ `-.__.-' _.-'_.-'| \n"
" | `-._`-._ _.-'_.-' | \n"
" `-._ `-._`-.__.-'_.-' _.-' \n"
" `-._ `-.__.-' _.-' \n"
" `-._ _.-' \n"
" `-.__.-' \n\n";
| 2,833 | 58.041667 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/syncio.c
|
/* Synchronous socket and file I/O operations useful across the core.
*
* Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
/* ----------------- Blocking sockets I/O with timeouts --------------------- */
/* Redis performs most of the I/O in a nonblocking way, with the exception
* of the SYNC command where the slave does it in a blocking way, and
* the MIGRATE command that must be blocking in order to be atomic from the
* point of view of the two instances (one migrating the key and one receiving
* the key). This is why need the following blocking I/O functions.
*
* All the functions take the timeout in milliseconds. */
#define SYNCIO__RESOLUTION 10 /* Resolution in milliseconds */
/* Write the specified payload to 'fd'. If writing the whole payload will be
* done within 'timeout' milliseconds the operation succeeds and 'size' is
* returned. Otherwise the operation fails, -1 is returned, and an unspecified
* partial write could be performed against the file descriptor. */
ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nwritten, ret = size;
long long start = mstime();
long long remaining = timeout;
while(1) {
long long wait = (remaining > SYNCIO__RESOLUTION) ?
remaining : SYNCIO__RESOLUTION;
long long elapsed;
/* Optimistically try to write before checking if the file descriptor
* is actually writable. At worst we get EAGAIN. */
nwritten = write(fd,ptr,size);
if (nwritten == -1) {
if (errno != EAGAIN) return -1;
} else {
ptr += nwritten;
size -= nwritten;
}
if (size == 0) return ret;
/* Wait */
aeWait(fd,AE_WRITABLE,wait);
elapsed = mstime() - start;
if (elapsed >= timeout) {
errno = ETIMEDOUT;
return -1;
}
remaining = timeout - elapsed;
}
}
/* Read the specified amount of bytes from 'fd'. If all the bytes are read
* within 'timeout' milliseconds the operation succeed and 'size' is returned.
* Otherwise the operation fails, -1 is returned, and an unspecified amount of
* data could be read from the file descriptor. */
ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nread, totread = 0;
long long start = mstime();
long long remaining = timeout;
if (size == 0) return 0;
while(1) {
long long wait = (remaining > SYNCIO__RESOLUTION) ?
remaining : SYNCIO__RESOLUTION;
long long elapsed;
/* Optimistically try to read before checking if the file descriptor
* is actually readable. At worst we get EAGAIN. */
nread = read(fd,ptr,size);
if (nread == 0) return -1; /* short read. */
if (nread == -1) {
if (errno != EAGAIN) return -1;
} else {
ptr += nread;
size -= nread;
totread += nread;
}
if (size == 0) return totread;
/* Wait */
aeWait(fd,AE_READABLE,wait);
elapsed = mstime() - start;
if (elapsed >= timeout) {
errno = ETIMEDOUT;
return -1;
}
remaining = timeout - elapsed;
}
}
/* Read a line making sure that every char will not require more than 'timeout'
* milliseconds to be read.
*
* On success the number of bytes read is returned, otherwise -1.
* On success the string is always correctly terminated with a 0 byte. */
ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nread = 0;
size--;
while(size) {
char c;
if (syncRead(fd,&c,1,timeout) == -1) return -1;
if (c == '\n') {
*ptr = '\0';
if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
return nread;
} else {
*ptr++ = c;
*ptr = '\0';
nread++;
}
size--;
}
return nread;
}
| 5,580 | 37.226027 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/lzf_c.c
|
/*
* Copyright (c) 2000-2010 Marc Alexander Lehmann <schmorp@schmorp.de>
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
* CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
* CIAL, 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 OTH-
* ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License ("GPL") version 2 or any later version,
* in which case the provisions of the GPL are applicable instead of
* the above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use your
* version of this file under the BSD license, indicate your decision
* by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under
* either the BSD or the GPL.
*/
#include "lzfP.h"
#define HSIZE (1 << (HLOG))
/*
* don't play with this unless you benchmark!
* the data format is not dependent on the hash function.
* the hash function might seem strange, just believe me,
* it works ;)
*/
#ifndef FRST
# define FRST(p) (((p[0]) << 8) | p[1])
# define NEXT(v,p) (((v) << 8) | p[2])
# if ULTRA_FAST
# define IDX(h) ((( h >> (3*8 - HLOG)) - h ) & (HSIZE - 1))
# elif VERY_FAST
# define IDX(h) ((( h >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
# else
# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
# endif
#endif
/*
* IDX works because it is very similar to a multiplicative hash, e.g.
* ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1))
* the latter is also quite fast on newer CPUs, and compresses similarly.
*
* the next one is also quite good, albeit slow ;)
* (int)(cos(h & 0xffffff) * 1e6)
*/
#if 0
/* original lzv-like hash function, much worse and thus slower */
# define FRST(p) (p[0] << 5) ^ p[1]
# define NEXT(v,p) ((v) << 5) ^ p[2]
# define IDX(h) ((h) & (HSIZE - 1))
#endif
#define MAX_LIT (1 << 5)
#define MAX_OFF (1 << 13)
#define MAX_REF ((1 << 8) + (1 << 3))
#if __GNUC__ >= 3
# define expect(expr,value) __builtin_expect ((expr),(value))
# define inline inline
#else
# define expect(expr,value) (expr)
# define inline static
#endif
#define expect_false(expr) expect ((expr) != 0, 0)
#define expect_true(expr) expect ((expr) != 0, 1)
/*
* compressed format
*
* 000LLLLL <L+1> ; literal, L+1=1..33 octets
* LLLooooo oooooooo ; backref L+1=1..7 octets, o+1=1..4096 offset
* 111ooooo LLLLLLLL oooooooo ; backref L+8 octets, o+1=1..4096 offset
*
*/
unsigned int
lzf_compress (const void *const in_data, unsigned int in_len,
void *out_data, unsigned int out_len
#if LZF_STATE_ARG
, LZF_STATE htab
#endif
)
{
#if !LZF_STATE_ARG
LZF_STATE htab;
#endif
const u8 *ip = (const u8 *)in_data;
u8 *op = (u8 *)out_data;
const u8 *in_end = ip + in_len;
u8 *out_end = op + out_len;
const u8 *ref;
/* off requires a type wide enough to hold a general pointer difference.
* ISO C doesn't have that (size_t might not be enough and ptrdiff_t only
* works for differences within a single object). We also assume that no
* no bit pattern traps. Since the only platform that is both non-POSIX
* and fails to support both assumptions is windows 64 bit, we make a
* special workaround for it.
*/
#if defined (WIN32) && defined (_M_X64)
unsigned _int64 off; /* workaround for missing POSIX compliance */
#else
unsigned long off;
#endif
unsigned int hval;
int lit;
if (!in_len || !out_len)
return 0;
#if INIT_HTAB
memset (htab, 0, sizeof (htab));
#endif
lit = 0; op++; /* start run */
hval = FRST (ip);
while (ip < in_end - 2)
{
LZF_HSLOT *hslot;
hval = NEXT (hval, ip);
hslot = htab + IDX (hval);
ref = *hslot + LZF_HSLOT_BIAS; *hslot = ip - LZF_HSLOT_BIAS;
if (1
#if INIT_HTAB
&& ref < ip /* the next test will actually take care of this, but this is faster */
#endif
&& (off = ip - ref - 1) < MAX_OFF
&& ref > (u8 *)in_data
&& ref[2] == ip[2]
#if STRICT_ALIGN
&& ((ref[1] << 8) | ref[0]) == ((ip[1] << 8) | ip[0])
#else
&& *(u16 *)ref == *(u16 *)ip
#endif
)
{
/* match found at *ref++ */
unsigned int len = 2;
unsigned int maxlen = in_end - ip - len;
maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */
if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */
return 0;
op [- lit - 1] = lit - 1; /* stop run */
op -= !lit; /* undo run if length is zero */
for (;;)
{
if (expect_true (maxlen > 16))
{
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
len++; if (ref [len] != ip [len]) break;
}
do
len++;
while (len < maxlen && ref[len] == ip[len]);
break;
}
len -= 2; /* len is now #octets - 1 */
ip++;
if (len < 7)
{
*op++ = (off >> 8) + (len << 5);
}
else
{
*op++ = (off >> 8) + ( 7 << 5);
*op++ = len - 7;
}
*op++ = off;
lit = 0; op++; /* start run */
ip += len + 1;
if (expect_false (ip >= in_end - 2))
break;
#if ULTRA_FAST || VERY_FAST
--ip;
# if VERY_FAST && !ULTRA_FAST
--ip;
# endif
hval = FRST (ip);
hval = NEXT (hval, ip);
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
ip++;
# if VERY_FAST && !ULTRA_FAST
hval = NEXT (hval, ip);
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
ip++;
# endif
#else
ip -= len + 1;
do
{
hval = NEXT (hval, ip);
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
ip++;
}
while (len--);
#endif
}
else
{
/* one more literal byte we must copy */
if (expect_false (op >= out_end))
return 0;
lit++; *op++ = *ip++;
if (expect_false (lit == MAX_LIT))
{
op [- lit - 1] = lit - 1; /* stop run */
lit = 0; op++; /* start run */
}
}
}
if (op + 3 > out_end) /* at most 3 bytes can be missing here */
return 0;
while (ip < in_end)
{
lit++; *op++ = *ip++;
if (expect_false (lit == MAX_LIT))
{
op [- lit - 1] = lit - 1; /* stop run */
lit = 0; op++; /* start run */
}
}
op [- lit - 1] = lit - 1; /* end run */
op -= !lit; /* undo run if length is zero */
return op - (u8 *)out_data;
}
| 9,012 | 29.866438 | 93 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/endianconv.c
|
/* endinconv.c -- Endian conversions utilities.
*
* This functions are never called directly, but always using the macros
* defined into endianconv.h, this way we define everything is a non-operation
* if the arch is already little endian.
*
* Redis tries to encode everything as little endian (but a few things that need
* to be backward compatible are still in big endian) because most of the
* production environments are little endian, and we have a lot of conversions
* in a few places because ziplists, intsets, zipmaps, need to be endian-neutral
* even in memory, since they are serialied on RDB files directly with a single
* write(2) without other additional steps.
*
* ----------------------------------------------------------------------------
*
* Copyright (c) 2011-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
/* Toggle the 16 bit unsigned integer pointed by *p from little endian to
* big endian */
void memrev16(void *p) {
unsigned char *x = p, t;
t = x[0];
x[0] = x[1];
x[1] = t;
}
/* Toggle the 32 bit unsigned integer pointed by *p from little endian to
* big endian */
void memrev32(void *p) {
unsigned char *x = p, t;
t = x[0];
x[0] = x[3];
x[3] = t;
t = x[1];
x[1] = x[2];
x[2] = t;
}
/* Toggle the 64 bit unsigned integer pointed by *p from little endian to
* big endian */
void memrev64(void *p) {
unsigned char *x = p, t;
t = x[0];
x[0] = x[7];
x[7] = t;
t = x[1];
x[1] = x[6];
x[6] = t;
t = x[2];
x[2] = x[5];
x[5] = t;
t = x[3];
x[3] = x[4];
x[4] = t;
}
uint16_t intrev16(uint16_t v) {
memrev16(&v);
return v;
}
uint32_t intrev32(uint32_t v) {
memrev32(&v);
return v;
}
uint64_t intrev64(uint64_t v) {
memrev64(&v);
return v;
}
#ifdef REDIS_TEST
#include <stdio.h>
#define UNUSED(x) (void)(x)
int endianconvTest(int argc, char *argv[]) {
char buf[32];
UNUSED(argc);
UNUSED(argv);
sprintf(buf,"ciaoroma");
memrev16(buf);
printf("%s\n", buf);
sprintf(buf,"ciaoroma");
memrev32(buf);
printf("%s\n", buf);
sprintf(buf,"ciaoroma");
memrev64(buf);
printf("%s\n", buf);
return 0;
}
#endif
| 3,777 | 28.286822 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/crc16.c
|
#include "server.h"
/*
* Copyright 2001-2010 Georges Menie (www.menie.org)
* Copyright 2010-2012 Salvatore Sanfilippo (adapted to Redis coding style)
* 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 University of California, Berkeley 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 AND 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.
*/
/* CRC16 implementation according to CCITT standards.
*
* Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the
* following parameters:
*
* Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN"
* Width : 16 bit
* Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1)
* Initialization : 0000
* Reflect Input byte : False
* Reflect Output CRC : False
* Xor constant to output CRC : 0000
* Output for "123456789" : 31C3
*/
static const uint16_t crc16tab[256]= {
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
};
uint16_t crc16(const char *buf, int len) {
int counter;
uint16_t crc = 0;
for (counter = 0; counter < len; counter++)
crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *buf++)&0x00FF];
return crc;
}
| 4,477 | 49.314607 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/adlist.h
|
/* adlist.h - A generic doubly linked list implementation
*
* Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ADLIST_H__
#define __ADLIST_H__
/* Node, List, and Iterator are the only data structures used currently. */
typedef struct listNode {
struct listNode *prev;
struct listNode *next;
void *value;
} listNode;
typedef struct listIter {
listNode *next;
int direction;
} listIter;
typedef struct list {
listNode *head;
listNode *tail;
void *(*dup)(void *ptr);
void (*free)(void *ptr);
int (*match)(void *ptr, void *key);
unsigned long len;
} list;
/* Functions implemented as macros */
#define listLength(l) ((l)->len)
#define listFirst(l) ((l)->head)
#define listLast(l) ((l)->tail)
#define listPrevNode(n) ((n)->prev)
#define listNextNode(n) ((n)->next)
#define listNodeValue(n) ((n)->value)
#define listSetDupMethod(l,m) ((l)->dup = (m))
#define listSetFreeMethod(l,m) ((l)->free = (m))
#define listSetMatchMethod(l,m) ((l)->match = (m))
#define listGetDupMethod(l) ((l)->dup)
#define listGetFree(l) ((l)->free)
#define listGetMatchMethod(l) ((l)->match)
/* Prototypes */
list *listCreate(void);
void listRelease(list *list);
list *listAddNodeHead(list *list, void *value);
list *listAddNodeTail(list *list, void *value);
list *listInsertNode(list *list, listNode *old_node, void *value, int after);
void listDelNode(list *list, listNode *node);
listIter *listGetIterator(list *list, int direction);
listNode *listNext(listIter *iter);
void listReleaseIterator(listIter *iter);
list *listDup(list *orig);
listNode *listSearchKey(list *list, void *key);
listNode *listIndex(list *list, long index);
void listRewind(list *list, listIter *li);
void listRewindTail(list *list, listIter *li);
void listRotate(list *list);
/* Directions for iterators */
#define AL_START_HEAD 0
#define AL_START_TAIL 1
#endif /* __ADLIST_H__ */
| 3,451 | 35.723404 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/sparkline.h
|
/* sparkline.h -- ASCII Sparklines header file
*
* ---------------------------------------------------------------------------
*
* Copyright(C) 2011-2014 Salvatore Sanfilippo <antirez@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SPARKLINE_H
#define __SPARKLINE_H
/* A sequence is represented of many "samples" */
struct sample {
double value;
char *label;
};
struct sequence {
int length;
int labels;
struct sample *samples;
double min, max;
};
#define SPARKLINE_NO_FLAGS 0
#define SPARKLINE_FILL 1 /* Fill the area under the curve. */
#define SPARKLINE_LOG_SCALE 2 /* Use logarithmic scale. */
struct sequence *createSparklineSequence(void);
void sparklineSequenceAddSample(struct sequence *seq, double value, char *label);
void freeSparklineSequence(struct sequence *seq);
sds sparklineRenderRange(sds output, struct sequence *seq, int rows, int offset, int len, int flags);
sds sparklineRender(sds output, struct sequence *seq, int columns, int rows, int flags);
#endif /* __SPARKLINE_H */
| 2,345 | 40.157895 | 101 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/pmem.h
|
/*
* Copyright (c) 2017, Andreas Bluemle <andreas dot bluemle at itxperts dot de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __PMEM_H
#define __PMEM_H
#ifdef USE_PMDK
typedef struct key_val_pair_PM {
PMEMoid key_oid;
PMEMoid val_oid;
TOID(struct key_val_pair_PM) pmem_list_next;
TOID(struct key_val_pair_PM) pmem_list_prev;
} key_val_pair_PM;
int pmemReconstruct(void);
void pmemKVpairSet(void *key, void *val);
PMEMoid pmemAddToPmemList(void *key, void *val);
void pmemRemoveFromPmemList(PMEMoid kv_PM_oid);
#endif
#endif
| 2,040 | 41.520833 | 79 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/t_string.c
|
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include <math.h> /* isnan(), isinf() */
#include <time.h>
/*-----------------------------------------------------------------------------
* String Commands
*----------------------------------------------------------------------------*/
static int checkStringLength(client *c, long long size) {
if (size > 512*1024*1024) {
addReplyError(c,"string exceeds maximum allowed size (512MB)");
return C_ERR;
}
return C_OK;
}
/* The setGenericCommand() function implements the SET operation with different
* options and variants. This function is called in order to implement the
* following commands: SET, SETEX, PSETEX, SETNX.
*
* 'flags' changes the behavior of the command (NX or XX, see belove).
*
* 'expire' represents an expire to set in form of a Redis object as passed
* by the user. It is interpreted according to the specified 'unit'.
*
* 'ok_reply' and 'abort_reply' is what the function will reply to the client
* if the operation is performed, or when it is not because of NX or
* XX flags.
*
* If ok_reply is NULL "+OK" is used.
* If abort_reply is NULL, "$-1" is used. */
#define OBJ_SET_NO_FLAGS 0
#define OBJ_SET_NX (1<<0) /* Set if key not exists. */
#define OBJ_SET_XX (1<<1) /* Set if key exists. */
#define OBJ_SET_EX (1<<2) /* Set if time in seconds is given */
#define OBJ_SET_PX (1<<3) /* Set if time in ms in given */
void setGenericCommand(client *c, int flags, robj *key, robj *val, robj *expire, int unit, robj *ok_reply, robj *abort_reply) {
long long milliseconds = 0; /* initialized to avoid any harmness warning */
#ifdef USE_PMDK
robj* newVal = 0;
#endif
if (expire) {
if (getLongLongFromObjectOrReply(c, expire, &milliseconds, NULL) != C_OK)
return;
if (milliseconds <= 0) {
addReplyErrorFormat(c,"invalid expire time in %s",c->cmd->name);
return;
}
if (unit == UNIT_SECONDS) milliseconds *= 1000;
}
if ((flags & OBJ_SET_NX && lookupKeyWrite(c->db,key) != NULL) ||
(flags & OBJ_SET_XX && lookupKeyWrite(c->db,key) == NULL))
{
addReply(c, abort_reply ? abort_reply : shared.nullbulk);
return;
}
printf("called1");
#ifdef USE_PMDK
if (server.persistent) {
int error = 0;
printf("called2");
// clock_t t;
// t = clock();
/* Copy value from RAM to PM - create RedisObject and sds(value) */
TX_BEGIN(server.pm_pool) {
newVal = dupStringObjectPM(val);
/* Set key in PM - create DictEntry and sds(key) linked to RedisObject with value
* Don't increment value "ref counter" as in normal process. */
setKeyPM(c->db,key,newVal);
} TX_ONABORT {
error = 1;
} TX_END
// t = clock() - t;
// double time_taken = ((double)t); // in seconds
// printf("tx3 %f\n", time_taken);
if (error) {
addReplyError(c, "setting key in PM failed!");
return;
}
} else {
setKey(c->db,key,val);
}
#else
setKey(c->db,key,val);
#endif
server.dirty++;
if (expire) setExpire(c->db,key,mstime()+milliseconds);
notifyKeyspaceEvent(NOTIFY_STRING,"set",key,c->db->id);
if (expire) notifyKeyspaceEvent(NOTIFY_GENERIC,
"expire",key,c->db->id);
addReply(c, ok_reply ? ok_reply : shared.ok);
}
/* SET key value [NX] [XX] [EX <seconds>] [PX <milliseconds>] */
void setCommand(client *c) {
//printf("setcmd\n");
int j;
robj *expire = NULL;
int unit = UNIT_SECONDS;
int flags = OBJ_SET_NO_FLAGS;
for (j = 3; j < c->argc; j++) {
char *a = c->argv[j]->ptr;
robj *next = (j == c->argc-1) ? NULL : c->argv[j+1];
if ((a[0] == 'n' || a[0] == 'N') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_XX))
{
flags |= OBJ_SET_NX;
} else if ((a[0] == 'x' || a[0] == 'X') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_NX))
{
flags |= OBJ_SET_XX;
} else if ((a[0] == 'e' || a[0] == 'E') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_PX) && next)
{
flags |= OBJ_SET_EX;
unit = UNIT_SECONDS;
expire = next;
j++;
} else if ((a[0] == 'p' || a[0] == 'P') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_EX) && next)
{
flags |= OBJ_SET_PX;
unit = UNIT_MILLISECONDS;
expire = next;
j++;
} else {
addReply(c,shared.syntaxerr);
return;
}
}
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,flags,c->argv[1],c->argv[2],expire,unit,NULL,NULL);
}
void setnxCommand(client *c) {
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,OBJ_SET_NX,c->argv[1],c->argv[2],NULL,0,shared.cone,shared.czero);
}
void setexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_SET_NO_FLAGS,c->argv[1],c->argv[3],c->argv[2],UNIT_SECONDS,NULL,NULL);
}
void psetexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_SET_NO_FLAGS,c->argv[1],c->argv[3],c->argv[2],UNIT_MILLISECONDS,NULL,NULL);
}
int getGenericCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
return C_OK;
if (o->type != OBJ_STRING) {
addReply(c,shared.wrongtypeerr);
return C_ERR;
} else {
addReplyBulk(c,o);
return C_OK;
}
}
void getCommand(client *c) {
getGenericCommand(c);
}
void getsetCommand(client *c) {
if (getGenericCommand(c) == C_ERR) return;
c->argv[2] = tryObjectEncoding(c->argv[2]);
setKey(c->db,c->argv[1],c->argv[2]);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[1],c->db->id);
server.dirty++;
}
void setrangeCommand(client *c) {
robj *o;
long offset;
sds value = c->argv[3]->ptr;
if (getLongFromObjectOrReply(c,c->argv[2],&offset,NULL) != C_OK)
return;
if (offset < 0) {
addReplyError(c,"offset is out of range");
return;
}
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Return 0 when setting nothing on a non-existing string */
if (sdslen(value) == 0) {
addReply(c,shared.czero);
return;
}
/* Return when the resulting string exceeds allowed size */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
o = createObject(OBJ_STRING,sdsnewlen(NULL, offset+sdslen(value)));
dbAdd(c->db,c->argv[1],o);
} else {
size_t olen;
/* Key exists, check type */
if (checkType(c,o,OBJ_STRING))
return;
/* Return existing string length when setting nothing */
olen = stringObjectLen(o);
if (sdslen(value) == 0) {
addReplyLongLong(c,olen);
return;
}
/* Return when the resulting string exceeds allowed size */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
/* Create a copy when the object is shared or encoded. */
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
if (sdslen(value) > 0) {
o->ptr = sdsgrowzero(o->ptr,offset+sdslen(value));
memcpy((char*)o->ptr+offset,value,sdslen(value));
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,
"setrange",c->argv[1],c->db->id);
server.dirty++;
}
addReplyLongLong(c,sdslen(o->ptr));
}
void getrangeCommand(client *c) {
robj *o;
long long start, end;
char *str, llbuf[32];
size_t strlen;
if (getLongLongFromObjectOrReply(c,c->argv[2],&start,NULL) != C_OK)
return;
if (getLongLongFromObjectOrReply(c,c->argv[3],&end,NULL) != C_OK)
return;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptybulk)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
if (o->encoding == OBJ_ENCODING_INT) {
str = llbuf;
strlen = ll2string(llbuf,sizeof(llbuf),(long)o->ptr);
} else {
str = o->ptr;
strlen = sdslen(str);
}
/* Convert negative indexes */
if (start < 0 && end < 0 && start > end) {
addReply(c,shared.emptybulk);
return;
}
if (start < 0) start = strlen+start;
if (end < 0) end = strlen+end;
if (start < 0) start = 0;
if (end < 0) end = 0;
if ((unsigned long long)end >= strlen) end = strlen-1;
/* Precondition: end >= 0 && end < strlen, so the only condition where
* nothing can be returned is: start > end. */
if (start > end || strlen == 0) {
addReply(c,shared.emptybulk);
} else {
addReplyBulkCBuffer(c,(char*)str+start,end-start+1);
}
}
void mgetCommand(client *c) {
int j;
addReplyMultiBulkLen(c,c->argc-1);
for (j = 1; j < c->argc; j++) {
robj *o = lookupKeyRead(c->db,c->argv[j]);
if (o == NULL) {
addReply(c,shared.nullbulk);
} else {
if (o->type != OBJ_STRING) {
addReply(c,shared.nullbulk);
} else {
addReplyBulk(c,o);
}
}
}
}
void msetGenericCommand(client *c, int nx) {
int j, busykeys = 0;
if ((c->argc % 2) == 0) {
addReplyError(c,"wrong number of arguments for MSET");
return;
}
/* Handle the NX flag. The MSETNX semantic is to return zero and don't
* set nothing at all if at least one already key exists. */
if (nx) {
for (j = 1; j < c->argc; j += 2) {
if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
busykeys++;
}
}
if (busykeys) {
addReply(c, shared.czero);
return;
}
}
for (j = 1; j < c->argc; j += 2) {
c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
setKey(c->db,c->argv[j],c->argv[j+1]);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[j],c->db->id);
}
server.dirty += (c->argc-1)/2;
addReply(c, nx ? shared.cone : shared.ok);
}
void msetCommand(client *c) {
msetGenericCommand(c,0);
}
void msetnxCommand(client *c) {
msetGenericCommand(c,1);
}
void incrDecrCommand(client *c, long long incr) {
long long value, oldvalue;
robj *o, *new;
o = lookupKeyWrite(c->db,c->argv[1]);
if (o != NULL && checkType(c,o,OBJ_STRING)) return;
if (getLongLongFromObjectOrReply(c,o,&value,NULL) != C_OK) return;
oldvalue = value;
if ((incr < 0 && oldvalue < 0 && incr < (LLONG_MIN-oldvalue)) ||
(incr > 0 && oldvalue > 0 && incr > (LLONG_MAX-oldvalue))) {
addReplyError(c,"increment or decrement would overflow");
return;
}
value += incr;
if (o && o->refcount == 1 && o->encoding == OBJ_ENCODING_INT &&
(value < 0 || value >= OBJ_SHARED_INTEGERS) &&
value >= LONG_MIN && value <= LONG_MAX)
{
new = o;
o->ptr = (void*)((long)value);
} else {
new = createStringObjectFromLongLong(value);
if (o) {
dbOverwrite(c->db,c->argv[1],new);
} else {
dbAdd(c->db,c->argv[1],new);
}
}
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrby",c->argv[1],c->db->id);
server.dirty++;
addReply(c,shared.colon);
addReply(c,new);
addReply(c,shared.crlf);
}
void incrCommand(client *c) {
incrDecrCommand(c,1);
}
void decrCommand(client *c) {
incrDecrCommand(c,-1);
}
void incrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
incrDecrCommand(c,incr);
}
void decrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
incrDecrCommand(c,-incr);
}
void incrbyfloatCommand(client *c) {
long double incr, value;
robj *o, *new, *aux;
o = lookupKeyWrite(c->db,c->argv[1]);
if (o != NULL && checkType(c,o,OBJ_STRING)) return;
if (getLongDoubleFromObjectOrReply(c,o,&value,NULL) != C_OK ||
getLongDoubleFromObjectOrReply(c,c->argv[2],&incr,NULL) != C_OK)
return;
value += incr;
if (isnan(value) || isinf(value)) {
addReplyError(c,"increment would produce NaN or Infinity");
return;
}
new = createStringObjectFromLongDouble(value,1);
if (o)
dbOverwrite(c->db,c->argv[1],new);
else
dbAdd(c->db,c->argv[1],new);
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrbyfloat",c->argv[1],c->db->id);
server.dirty++;
addReplyBulk(c,new);
/* Always replicate INCRBYFLOAT as a SET command with the final value
* in order to make sure that differences in float precision or formatting
* will not create differences in replicas or after an AOF restart. */
aux = createStringObject("SET",3);
rewriteClientCommandArgument(c,0,aux);
decrRefCount(aux);
rewriteClientCommandArgument(c,2,new);
}
void appendCommand(client *c) {
size_t totlen;
robj *o, *append;
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Create the key */
c->argv[2] = tryObjectEncoding(c->argv[2]);
dbAdd(c->db,c->argv[1],c->argv[2]);
incrRefCount(c->argv[2]);
totlen = stringObjectLen(c->argv[2]);
} else {
/* Key exists, check type */
if (checkType(c,o,OBJ_STRING))
return;
/* "append" is an argument, so always an sds */
append = c->argv[2];
totlen = stringObjectLen(o)+sdslen(append->ptr);
if (checkStringLength(c,totlen) != C_OK)
return;
/* Append the value */
o = dbUnshareStringValue(c->db,c->argv[1],o);
o->ptr = sdscatlen(o->ptr,append->ptr,sdslen(append->ptr));
totlen = sdslen(o->ptr);
}
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"append",c->argv[1],c->db->id);
server.dirty++;
addReplyLongLong(c,totlen);
}
void strlenCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
addReplyLongLong(c,stringObjectLen(o));
}
| 16,238 | 30.903733 | 127 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/dict.h
|
/* Hash Tables Implementation.
*
* This file implements in-memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto-resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*
* Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#ifndef __DICT_H
#define __DICT_H
#define DICT_OK 0
#define DICT_ERR 1
/* Unused arguments generate annoying warnings... */
#define DICT_NOTUSED(V) ((void) V)
typedef struct dictEntry {
void *key;
union {
void *val;
uint64_t u64;
int64_t s64;
double d;
} v;
struct dictEntry *next;
} dictEntry;
typedef struct dictType {
unsigned int (*hashFunction)(const void *key);
void *(*keyDup)(void *privdata, const void *key);
void *(*valDup)(void *privdata, const void *obj);
int (*keyCompare)(void *privdata, const void *key1, const void *key2);
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
/* This is our hash table structure. Every dictionary has two of this as we
* implement incremental rehashing, for the old to the new table. */
typedef struct dictht {
dictEntry **table;
unsigned long size;
unsigned long sizemask;
unsigned long used;
} dictht;
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2];
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
int iterators; /* number of iterators currently running */
} dict;
/* If safe is set to 1 this is a safe iterator, that means, you can call
* dictAdd, dictFind, and other functions against the dictionary even while
* iterating. Otherwise it is a non safe iterator, and only dictNext()
* should be called while iterating. */
typedef struct dictIterator {
dict *d;
long index;
int table, safe;
dictEntry *entry, *nextEntry;
/* unsafe iterator fingerprint for misuse detection. */
long long fingerprint;
} dictIterator;
typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
/* This is the initial size of every hash table */
#define DICT_HT_INITIAL_SIZE 4
/* ------------------------------- Macros ------------------------------------*/
#define dictFreeVal(d, entry) \
if ((d)->type->valDestructor) \
(d)->type->valDestructor((d)->privdata, (entry)->v.val)
#define dictSetVal(d, entry, _val_) do { \
if ((d)->type->valDup) \
entry->v.val = (d)->type->valDup((d)->privdata, _val_); \
else \
entry->v.val = (_val_); \
} while(0)
#define dictSetSignedIntegerVal(entry, _val_) \
do { entry->v.s64 = _val_; } while(0)
#define dictSetUnsignedIntegerVal(entry, _val_) \
do { entry->v.u64 = _val_; } while(0)
#define dictSetDoubleVal(entry, _val_) \
do { entry->v.d = _val_; } while(0)
#define dictFreeKey(d, entry) \
if ((d)->type->keyDestructor) \
(d)->type->keyDestructor((d)->privdata, (entry)->key)
#define dictSetKey(d, entry, _key_) do { \
if ((d)->type->keyDup) \
entry->key = (d)->type->keyDup((d)->privdata, _key_); \
else \
entry->key = (_key_); \
} while(0)
#define dictCompareKeys(d, key1, key2) \
(((d)->type->keyCompare) ? \
(d)->type->keyCompare((d)->privdata, key1, key2) : \
(key1) == (key2))
#define dictHashKey(d, key) (d)->type->hashFunction(key)
#define dictGetKey(he) ((he)->key)
#define dictGetVal(he) ((he)->v.val)
#define dictGetSignedIntegerVal(he) ((he)->v.s64)
#define dictGetUnsignedIntegerVal(he) ((he)->v.u64)
#define dictGetDoubleVal(he) ((he)->v.d)
#define dictSlots(d) ((d)->ht[0].size+(d)->ht[1].size)
#define dictSize(d) ((d)->ht[0].used+(d)->ht[1].used)
#define dictIsRehashing(d) ((d)->rehashidx != -1)
/* API */
dict *dictCreate(dictType *type, void *privDataPtr);
int dictExpand(dict *d, unsigned long size);
int dictAdd(dict *d, void *key, void *val);
dictEntry *dictAddRaw(dict *d, void *key);
int dictReplace(dict *d, void *key, void *val);
dictEntry *dictReplaceRaw(dict *d, void *key);
int dictDelete(dict *d, const void *key);
int dictDeleteNoFree(dict *d, const void *key);
void dictRelease(dict *d);
dictEntry * dictFind(dict *d, const void *key);
void *dictFetchValue(dict *d, const void *key);
int dictResize(dict *d);
dictIterator *dictGetIterator(dict *d);
dictIterator *dictGetSafeIterator(dict *d);
dictEntry *dictNext(dictIterator *iter);
void dictReleaseIterator(dictIterator *iter);
dictEntry *dictGetRandomKey(dict *d);
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count);
void dictGetStats(char *buf, size_t bufsize, dict *d);
unsigned int dictGenHashFunction(const void *key, int len);
unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len);
void dictEmpty(dict *d, void(callback)(void*));
void dictEnableResize(void);
void dictDisableResize(void);
int dictRehash(dict *d, int n);
int dictRehashMilliseconds(dict *d, int ms);
void dictSetHashFunctionSeed(unsigned int initval);
unsigned int dictGetHashFunctionSeed(void);
unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, void *privdata);
#ifdef USE_PMDK
/* PMEM-specific API */
int dictAddPM(dict *d, void *key, void *val);
dictEntry *dictAddRawPM(dict *d, void *key);
dictEntry *dictAddReconstructedPM(dict *d, void *key, void *val);
int dictReplacePM(dict *d, void *key, void *val);
#endif
/* Hash table types */
extern dictType dictTypeHeapStringCopyKey;
extern dictType dictTypeHeapStrings;
extern dictType dictTypeHeapStringCopyKeyValue;
#endif /* __DICT_H */
| 7,201 | 36.123711 | 87 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/zmalloc.c
|
/* zmalloc - total amount of allocated memory aware version of malloc()
*
* Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
/* This function provide us access to the original libc free(). This is useful
* for instance to free results obtained by backtrace_symbols(). We need
* to define this function before including zmalloc.h that may shadow the
* free implementation if we use jemalloc or another non standard allocator. */
void zlibc_free(void *ptr) {
free(ptr);
}
#include <string.h>
#include <pthread.h>
#include "config.h"
#include "zmalloc.h"
#ifdef HAVE_MALLOC_SIZE
#define PREFIX_SIZE (0)
#else
#if defined(__sun) || defined(__sparc) || defined(__sparc__)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t))
#endif
#endif
/* Explicitly override malloc/free etc when using tcmalloc. */
#if defined(USE_TCMALLOC)
#define malloc(size) tc_malloc(size)
#define calloc(count,size) tc_calloc(count,size)
#define realloc(ptr,size) tc_realloc(ptr,size)
#define free(ptr) tc_free(ptr)
#elif defined(USE_JEMALLOC)
#define malloc(size) je_malloc(size)
#define calloc(count,size) je_calloc(count,size)
#define realloc(ptr,size) je_realloc(ptr,size)
#define free(ptr) je_free(ptr)
#endif
#if defined(__ATOMIC_RELAXED)
#define update_zmalloc_stat_add(__n) __atomic_add_fetch(&used_memory, (__n), __ATOMIC_RELAXED)
#define update_zmalloc_stat_sub(__n) __atomic_sub_fetch(&used_memory, (__n), __ATOMIC_RELAXED)
#elif defined(HAVE_ATOMIC)
#define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n))
#define update_zmalloc_stat_sub(__n) __sync_sub_and_fetch(&used_memory, (__n))
#else
#define update_zmalloc_stat_add(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory += (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#define update_zmalloc_stat_sub(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory -= (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#endif
#define update_zmalloc_stat_alloc(__n) do { \
size_t _n = (__n); \
if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \
if (zmalloc_thread_safe) { \
update_zmalloc_stat_add(_n); \
} else { \
used_memory += _n; \
} \
} while(0)
#define update_zmalloc_stat_free(__n) do { \
size_t _n = (__n); \
if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \
if (zmalloc_thread_safe) { \
update_zmalloc_stat_sub(_n); \
} else { \
used_memory -= _n; \
} \
} while(0)
static size_t used_memory = 0;
static int zmalloc_thread_safe = 0;
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
static void zmalloc_default_oom(size_t size) {
fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n",
size);
fflush(stderr);
abort();
}
static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom;
void *zmalloc(size_t size) {
void *ptr = malloc(size+PREFIX_SIZE);
if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr));
return ptr;
#else
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size+PREFIX_SIZE);
return (char*)ptr+PREFIX_SIZE;
#endif
}
void *zcalloc(size_t size) {
void *ptr = calloc(1, size+PREFIX_SIZE);
if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr));
return ptr;
#else
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size+PREFIX_SIZE);
return (char*)ptr+PREFIX_SIZE;
#endif
}
void *zrealloc(void *ptr, size_t size) {
#ifndef HAVE_MALLOC_SIZE
void *realptr;
#endif
size_t oldsize;
void *newptr;
if (ptr == NULL) return zmalloc(size);
#ifdef HAVE_MALLOC_SIZE
oldsize = zmalloc_size(ptr);
newptr = realloc(ptr,size);
if (!newptr) zmalloc_oom_handler(size);
update_zmalloc_stat_free(oldsize);
update_zmalloc_stat_alloc(zmalloc_size(newptr));
return newptr;
#else
realptr = (char*)ptr-PREFIX_SIZE;
oldsize = *((size_t*)realptr);
newptr = realloc(realptr,size+PREFIX_SIZE);
if (!newptr) zmalloc_oom_handler(size);
*((size_t*)newptr) = size;
update_zmalloc_stat_free(oldsize);
update_zmalloc_stat_alloc(size);
return (char*)newptr+PREFIX_SIZE;
#endif
}
/* Provide zmalloc_size() for systems where this function is not provided by
* malloc itself, given that in that case we store a header with this
* information as the first bytes of every allocation. */
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr) {
void *realptr = (char*)ptr-PREFIX_SIZE;
size_t size = *((size_t*)realptr);
/* Assume at least that all the allocations are padded at sizeof(long) by
* the underlying allocator. */
if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
return size+PREFIX_SIZE;
}
#endif
void zfree(void *ptr) {
#ifndef HAVE_MALLOC_SIZE
void *realptr;
size_t oldsize;
#endif
if (ptr == NULL) return;
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_free(zmalloc_size(ptr));
free(ptr);
#else
realptr = (char*)ptr-PREFIX_SIZE;
oldsize = *((size_t*)realptr);
update_zmalloc_stat_free(oldsize+PREFIX_SIZE);
free(realptr);
#endif
}
char *zstrdup(const char *s) {
size_t l = strlen(s)+1;
char *p = zmalloc(l);
memcpy(p,s,l);
return p;
}
size_t zmalloc_used_memory(void) {
size_t um;
if (zmalloc_thread_safe) {
#if defined(__ATOMIC_RELAXED) || defined(HAVE_ATOMIC)
um = update_zmalloc_stat_add(0);
#else
pthread_mutex_lock(&used_memory_mutex);
um = used_memory;
pthread_mutex_unlock(&used_memory_mutex);
#endif
}
else {
um = used_memory;
}
return um;
}
void zmalloc_enable_thread_safeness(void) {
zmalloc_thread_safe = 1;
}
void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) {
zmalloc_oom_handler = oom_handler;
}
/* Get the RSS information in an OS-specific way.
*
* WARNING: the function zmalloc_get_rss() is not designed to be fast
* and may not be called in the busy loops where Redis tries to release
* memory expiring or swapping out objects.
*
* For this kind of "fast RSS reporting" usages use instead the
* function RedisEstimateRSS() that is a much faster (and less precise)
* version of the function. */
#if defined(HAVE_PROC_STAT)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
size_t zmalloc_get_rss(void) {
int page = sysconf(_SC_PAGESIZE);
size_t rss;
char buf[4096];
char filename[256];
int fd, count;
char *p, *x;
snprintf(filename,256,"/proc/%d/stat",getpid());
if ((fd = open(filename,O_RDONLY)) == -1) return 0;
if (read(fd,buf,4096) <= 0) {
close(fd);
return 0;
}
close(fd);
p = buf;
count = 23; /* RSS is the 24th field in /proc/<pid>/stat */
while(p && count--) {
p = strchr(p,' ');
if (p) p++;
}
if (!p) return 0;
x = strchr(p,' ');
if (!x) return 0;
*x = '\0';
rss = strtoll(p,NULL,10);
rss *= page;
return rss;
}
#elif defined(HAVE_TASKINFO)
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/task.h>
#include <mach/mach_init.h>
size_t zmalloc_get_rss(void) {
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS)
return 0;
task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
return t_info.resident_size;
}
#else
size_t zmalloc_get_rss(void) {
/* If we can't get the RSS in an OS-specific way for this system just
* return the memory usage we estimated in zmalloc()..
*
* Fragmentation will appear to be always 1 (no fragmentation)
* of course... */
return zmalloc_used_memory();
}
#endif
/* Fragmentation = RSS / allocated-bytes */
float zmalloc_get_fragmentation_ratio(size_t rss) {
return (float)rss/zmalloc_used_memory();
}
/* Get the sum of the specified field (converted form kb to bytes) in
* /proc/self/smaps. The field must be specified with trailing ":" as it
* apperas in the smaps output.
*
* Example: zmalloc_get_smap_bytes_by_field("Rss:");
*/
#if defined(HAVE_PROC_SMAPS)
size_t zmalloc_get_smap_bytes_by_field(char *field) {
char line[1024];
size_t bytes = 0;
FILE *fp = fopen("/proc/self/smaps","r");
int flen = strlen(field);
if (!fp) return 0;
while(fgets(line,sizeof(line),fp) != NULL) {
if (strncmp(line,field,flen) == 0) {
char *p = strchr(line,'k');
if (p) {
*p = '\0';
bytes += strtol(line+flen,NULL,10) * 1024;
}
}
}
fclose(fp);
return bytes;
}
#else
size_t zmalloc_get_smap_bytes_by_field(char *field) {
((void) field);
return 0;
}
#endif
size_t zmalloc_get_private_dirty(void) {
return zmalloc_get_smap_bytes_by_field("Private_Dirty:");
}
/* Returns the size of physical memory (RAM) in bytes.
* It looks ugly, but this is the cleanest way to achive cross platform results.
* Cleaned up from:
*
* http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system
*
* Note that this function:
* 1) Was released under the following CC attribution license:
* http://creativecommons.org/licenses/by/3.0/deed.en_US.
* 2) Was originally implemented by David Robert Nadeau.
* 3) Was modified for Redis by Matt Stancliff.
* 4) This note exists in order to comply with the original license.
*/
size_t zmalloc_get_memory_size(void) {
#if defined(__unix__) || defined(__unix) || defined(unix) || \
(defined(__APPLE__) && defined(__MACH__))
#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
int mib[2];
mib[0] = CTL_HW;
#if defined(HW_MEMSIZE)
mib[1] = HW_MEMSIZE; /* OSX. --------------------- */
#elif defined(HW_PHYSMEM64)
mib[1] = HW_PHYSMEM64; /* NetBSD, OpenBSD. --------- */
#endif
int64_t size = 0; /* 64-bit */
size_t len = sizeof(size);
if (sysctl( mib, 2, &size, &len, NULL, 0) == 0)
return (size_t)size;
return 0L; /* Failed? */
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */
return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE);
#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))
/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */
int mib[2];
mib[0] = CTL_HW;
#if defined(HW_REALMEM)
mib[1] = HW_REALMEM; /* FreeBSD. ----------------- */
#elif defined(HW_PYSMEM)
mib[1] = HW_PHYSMEM; /* Others. ------------------ */
#endif
unsigned int size = 0; /* 32-bit */
size_t len = sizeof(size);
if (sysctl(mib, 2, &size, &len, NULL, 0) == 0)
return (size_t)size;
return 0L; /* Failed? */
#endif /* sysctl and sysconf variants */
#else
return 0L; /* Unknown OS. */
#endif
}
| 12,846 | 29.299528 | 94 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/sort.c
|
/* SORT command and helper functions.
*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include "pqsort.h" /* Partial qsort for SORT+LIMIT */
#include <math.h> /* isnan() */
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank);
redisSortOperation *createSortOperation(int type, robj *pattern) {
redisSortOperation *so = zmalloc(sizeof(*so));
so->type = type;
so->pattern = pattern;
return so;
}
/* Return the value associated to the key with a name obtained using
* the following rules:
*
* 1) The first occurrence of '*' in 'pattern' is substituted with 'subst'.
*
* 2) If 'pattern' matches the "->" string, everything on the left of
* the arrow is treated as the name of a hash field, and the part on the
* left as the key name containing a hash. The value of the specified
* field is returned.
*
* 3) If 'pattern' equals "#", the function simply returns 'subst' itself so
* that the SORT command can be used like: SORT key GET # to retrieve
* the Set/List elements directly.
*
* The returned object will always have its refcount increased by 1
* when it is non-NULL. */
robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
char *p, *f, *k;
sds spat, ssub;
robj *keyobj, *fieldobj = NULL, *o;
int prefixlen, sublen, postfixlen, fieldlen;
/* If the pattern is "#" return the substitution object itself in order
* to implement the "SORT ... GET #" feature. */
spat = pattern->ptr;
if (spat[0] == '#' && spat[1] == '\0') {
incrRefCount(subst);
return subst;
}
/* The substitution object may be specially encoded. If so we create
* a decoded object on the fly. Otherwise getDecodedObject will just
* increment the ref count, that we'll decrement later. */
subst = getDecodedObject(subst);
ssub = subst->ptr;
/* If we can't find '*' in the pattern we return NULL as to GET a
* fixed key does not make sense. */
p = strchr(spat,'*');
if (!p) {
decrRefCount(subst);
return NULL;
}
/* Find out if we're dealing with a hash dereference. */
if ((f = strstr(p+1, "->")) != NULL && *(f+2) != '\0') {
fieldlen = sdslen(spat)-(f-spat)-2;
fieldobj = createStringObject(f+2,fieldlen);
} else {
fieldlen = 0;
}
/* Perform the '*' substitution. */
prefixlen = p-spat;
sublen = sdslen(ssub);
postfixlen = sdslen(spat)-(prefixlen+1)-(fieldlen ? fieldlen+2 : 0);
keyobj = createStringObject(NULL,prefixlen+sublen+postfixlen);
k = keyobj->ptr;
memcpy(k,spat,prefixlen);
memcpy(k+prefixlen,ssub,sublen);
memcpy(k+prefixlen+sublen,p+1,postfixlen);
decrRefCount(subst); /* Incremented by decodeObject() */
/* Lookup substituted key */
o = lookupKeyRead(db,keyobj);
if (o == NULL) goto noobj;
if (fieldobj) {
if (o->type != OBJ_HASH) goto noobj;
/* Retrieve value from hash by the field name. This operation
* already increases the refcount of the returned object. */
o = hashTypeGetObject(o, fieldobj);
} else {
if (o->type != OBJ_STRING) goto noobj;
/* Every object that this function returns needs to have its refcount
* increased. sortCommand decreases it again. */
incrRefCount(o);
}
decrRefCount(keyobj);
if (fieldobj) decrRefCount(fieldobj);
return o;
noobj:
decrRefCount(keyobj);
if (fieldlen) decrRefCount(fieldobj);
return NULL;
}
/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
* the additional parameter is not standard but a BSD-specific we have to
* pass sorting parameters via the global 'server' structure */
int sortCompare(const void *s1, const void *s2) {
const redisSortObject *so1 = s1, *so2 = s2;
int cmp;
if (!server.sort_alpha) {
/* Numeric sorting. Here it's trivial as we precomputed scores */
if (so1->u.score > so2->u.score) {
cmp = 1;
} else if (so1->u.score < so2->u.score) {
cmp = -1;
} else {
/* Objects have the same score, but we don't want the comparison
* to be undefined, so we compare objects lexicographically.
* This way the result of SORT is deterministic. */
cmp = compareStringObjects(so1->obj,so2->obj);
}
} else {
/* Alphanumeric sorting */
if (server.sort_bypattern) {
if (!so1->u.cmpobj || !so2->u.cmpobj) {
/* At least one compare object is NULL */
if (so1->u.cmpobj == so2->u.cmpobj)
cmp = 0;
else if (so1->u.cmpobj == NULL)
cmp = -1;
else
cmp = 1;
} else {
/* We have both the objects, compare them. */
if (server.sort_store) {
cmp = compareStringObjects(so1->u.cmpobj,so2->u.cmpobj);
} else {
/* Here we can use strcoll() directly as we are sure that
* the objects are decoded string objects. */
cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
}
}
} else {
/* Compare elements directly. */
if (server.sort_store) {
cmp = compareStringObjects(so1->obj,so2->obj);
} else {
cmp = collateStringObjects(so1->obj,so2->obj);
}
}
}
return server.sort_desc ? -cmp : cmp;
}
/* The SORT command is the most complex command in Redis. Warning: this code
* is optimized for speed and a bit less for readability */
void sortCommand(client *c) {
list *operations;
unsigned int outputlen = 0;
int desc = 0, alpha = 0;
long limit_start = 0, limit_count = -1, start, end;
int j, dontsort = 0, vectorlen;
int getop = 0; /* GET operation counter */
int int_convertion_error = 0;
int syntax_error = 0;
robj *sortval, *sortby = NULL, *storekey = NULL;
redisSortObject *vector; /* Resulting vector to sort */
/* Lookup the key to sort. It must be of the right types */
sortval = lookupKeyRead(c->db,c->argv[1]);
if (sortval && sortval->type != OBJ_SET &&
sortval->type != OBJ_LIST &&
sortval->type != OBJ_ZSET)
{
addReply(c,shared.wrongtypeerr);
return;
}
/* Create a list of operations to perform for every sorted element.
* Operations can be GET */
operations = listCreate();
listSetFreeMethod(operations,zfree);
j = 2; /* options start at argv[2] */
/* Now we need to protect sortval incrementing its count, in the future
* SORT may have options able to overwrite/delete keys during the sorting
* and the sorted key itself may get destroyed */
if (sortval)
incrRefCount(sortval);
else
sortval = createQuicklistObject();
/* The SORT command has an SQL-alike syntax, parse it */
while(j < c->argc) {
int leftargs = c->argc-j-1;
if (!strcasecmp(c->argv[j]->ptr,"asc")) {
desc = 0;
} else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
desc = 1;
} else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
alpha = 1;
} else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
if ((getLongFromObjectOrReply(c, c->argv[j+1], &limit_start, NULL)
!= C_OK) ||
(getLongFromObjectOrReply(c, c->argv[j+2], &limit_count, NULL)
!= C_OK))
{
syntax_error++;
break;
}
j+=2;
} else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
storekey = c->argv[j+1];
j++;
} else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
sortby = c->argv[j+1];
/* If the BY pattern does not contain '*', i.e. it is constant,
* we don't need to sort nor to lookup the weight keys. */
if (strchr(c->argv[j+1]->ptr,'*') == NULL) {
dontsort = 1;
} else {
/* If BY is specified with a real patter, we can't accept
* it in cluster mode. */
if (server.cluster_enabled) {
addReplyError(c,"BY option of SORT denied in Cluster mode.");
syntax_error++;
break;
}
}
j++;
} else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
if (server.cluster_enabled) {
addReplyError(c,"GET option of SORT denied in Cluster mode.");
syntax_error++;
break;
}
listAddNodeTail(operations,createSortOperation(
SORT_OP_GET,c->argv[j+1]));
getop++;
j++;
} else {
addReply(c,shared.syntaxerr);
syntax_error++;
break;
}
j++;
}
/* Handle syntax errors set during options parsing. */
if (syntax_error) {
decrRefCount(sortval);
listRelease(operations);
return;
}
/* When sorting a set with no sort specified, we must sort the output
* so the result is consistent across scripting and replication.
*
* The other types (list, sorted set) will retain their native order
* even if no sort order is requested, so they remain stable across
* scripting and replication. */
if (dontsort &&
sortval->type == OBJ_SET &&
(storekey || c->flags & CLIENT_LUA))
{
/* Force ALPHA sorting */
dontsort = 0;
alpha = 1;
sortby = NULL;
}
/* Destructively convert encoded sorted sets for SORT. */
if (sortval->type == OBJ_ZSET)
zsetConvert(sortval, OBJ_ENCODING_SKIPLIST);
/* Objtain the length of the object to sort. */
switch(sortval->type) {
case OBJ_LIST: vectorlen = listTypeLength(sortval); break;
case OBJ_SET: vectorlen = setTypeSize(sortval); break;
case OBJ_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
default: vectorlen = 0; serverPanic("Bad SORT type"); /* Avoid GCC warning */
}
/* Perform LIMIT start,count sanity checking. */
start = (limit_start < 0) ? 0 : limit_start;
end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
if (start >= vectorlen) {
start = vectorlen-1;
end = vectorlen-2;
}
if (end >= vectorlen) end = vectorlen-1;
/* Whenever possible, we load elements into the output array in a more
* direct way. This is possible if:
*
* 1) The object to sort is a sorted set or a list (internally sorted).
* 2) There is nothing to sort as dontsort is true (BY <constant string>).
*
* In this special case, if we have a LIMIT option that actually reduces
* the number of elements to fetch, we also optimize to just load the
* range we are interested in and allocating a vector that is big enough
* for the selected range length. */
if ((sortval->type == OBJ_ZSET || sortval->type == OBJ_LIST) &&
dontsort &&
(start != 0 || end != vectorlen-1))
{
vectorlen = end-start+1;
}
/* Load the sorting vector with all the objects to sort */
vector = zmalloc(sizeof(redisSortObject)*vectorlen);
j = 0;
if (sortval->type == OBJ_LIST && dontsort) {
/* Special handling for a list, if 'dontsort' is true.
* This makes sure we return elements in the list original
* ordering, accordingly to DESC / ASC options.
*
* Note that in this case we also handle LIMIT here in a direct
* way, just getting the required range, as an optimization. */
if (end >= start) {
listTypeIterator *li;
listTypeEntry entry;
li = listTypeInitIterator(sortval,
desc ? (long)(listTypeLength(sortval) - start - 1) : start,
desc ? REDIS_LIST_HEAD : REDIS_LIST_TAIL);
while(j < vectorlen && listTypeNext(li,&entry)) {
vector[j].obj = listTypeGet(&entry);
vector[j].u.score = 0;
vector[j].u.cmpobj = NULL;
j++;
}
listTypeReleaseIterator(li);
/* Fix start/end: output code is not aware of this optimization. */
end -= start;
start = 0;
}
} else if (sortval->type == OBJ_LIST) {
listTypeIterator *li = listTypeInitIterator(sortval,0,REDIS_LIST_TAIL);
listTypeEntry entry;
while(listTypeNext(li,&entry)) {
vector[j].obj = listTypeGet(&entry);
vector[j].u.score = 0;
vector[j].u.cmpobj = NULL;
j++;
}
listTypeReleaseIterator(li);
} else if (sortval->type == OBJ_SET) {
setTypeIterator *si = setTypeInitIterator(sortval);
robj *ele;
while((ele = setTypeNextObject(si)) != NULL) {
vector[j].obj = ele;
vector[j].u.score = 0;
vector[j].u.cmpobj = NULL;
j++;
}
setTypeReleaseIterator(si);
} else if (sortval->type == OBJ_ZSET && dontsort) {
/* Special handling for a sorted set, if 'dontsort' is true.
* This makes sure we return elements in the sorted set original
* ordering, accordingly to DESC / ASC options.
*
* Note that in this case we also handle LIMIT here in a direct
* way, just getting the required range, as an optimization. */
zset *zs = sortval->ptr;
zskiplist *zsl = zs->zsl;
zskiplistNode *ln;
robj *ele;
int rangelen = vectorlen;
/* Check if starting point is trivial, before doing log(N) lookup. */
if (desc) {
long zsetlen = dictSize(((zset*)sortval->ptr)->dict);
ln = zsl->tail;
if (start > 0)
ln = zslGetElementByRank(zsl,zsetlen-start);
} else {
ln = zsl->header->level[0].forward;
if (start > 0)
ln = zslGetElementByRank(zsl,start+1);
}
while(rangelen--) {
serverAssertWithInfo(c,sortval,ln != NULL);
ele = ln->obj;
vector[j].obj = ele;
vector[j].u.score = 0;
vector[j].u.cmpobj = NULL;
j++;
ln = desc ? ln->backward : ln->level[0].forward;
}
/* Fix start/end: output code is not aware of this optimization. */
end -= start;
start = 0;
} else if (sortval->type == OBJ_ZSET) {
dict *set = ((zset*)sortval->ptr)->dict;
dictIterator *di;
dictEntry *setele;
di = dictGetIterator(set);
while((setele = dictNext(di)) != NULL) {
vector[j].obj = dictGetKey(setele);
vector[j].u.score = 0;
vector[j].u.cmpobj = NULL;
j++;
}
dictReleaseIterator(di);
} else {
serverPanic("Unknown type");
}
serverAssertWithInfo(c,sortval,j == vectorlen);
/* Now it's time to load the right scores in the sorting vector */
if (dontsort == 0) {
for (j = 0; j < vectorlen; j++) {
robj *byval;
if (sortby) {
/* lookup value to sort by */
byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
if (!byval) continue;
} else {
/* use object itself to sort by */
byval = vector[j].obj;
}
if (alpha) {
if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
} else {
if (sdsEncodedObject(byval)) {
char *eptr;
vector[j].u.score = strtod(byval->ptr,&eptr);
if (eptr[0] != '\0' || errno == ERANGE ||
isnan(vector[j].u.score))
{
int_convertion_error = 1;
}
} else if (byval->encoding == OBJ_ENCODING_INT) {
/* Don't need to decode the object if it's
* integer-encoded (the only encoding supported) so
* far. We can just cast it */
vector[j].u.score = (long)byval->ptr;
} else {
serverAssertWithInfo(c,sortval,1 != 1);
}
}
/* when the object was retrieved using lookupKeyByPattern,
* its refcount needs to be decreased. */
if (sortby) {
decrRefCount(byval);
}
}
}
if (dontsort == 0) {
server.sort_desc = desc;
server.sort_alpha = alpha;
server.sort_bypattern = sortby ? 1 : 0;
server.sort_store = storekey ? 1 : 0;
if (sortby && (start != 0 || end != vectorlen-1))
pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
else
qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
}
/* Send command output to the output buffer, performing the specified
* GET/DEL/INCR/DECR operations if any. */
outputlen = getop ? getop*(end-start+1) : end-start+1;
if (int_convertion_error) {
addReplyError(c,"One or more scores can't be converted into double");
} else if (storekey == NULL) {
/* STORE option not specified, sent the sorting result to client */
addReplyMultiBulkLen(c,outputlen);
for (j = start; j <= end; j++) {
listNode *ln;
listIter li;
if (!getop) addReplyBulk(c,vector[j].obj);
listRewind(operations,&li);
while((ln = listNext(&li))) {
redisSortOperation *sop = ln->value;
robj *val = lookupKeyByPattern(c->db,sop->pattern,
vector[j].obj);
if (sop->type == SORT_OP_GET) {
if (!val) {
addReply(c,shared.nullbulk);
} else {
addReplyBulk(c,val);
decrRefCount(val);
}
} else {
/* Always fails */
serverAssertWithInfo(c,sortval,sop->type == SORT_OP_GET);
}
}
}
} else {
robj *sobj = createQuicklistObject();
/* STORE option specified, set the sorting result as a List object */
for (j = start; j <= end; j++) {
listNode *ln;
listIter li;
if (!getop) {
listTypePush(sobj,vector[j].obj,REDIS_LIST_TAIL);
} else {
listRewind(operations,&li);
while((ln = listNext(&li))) {
redisSortOperation *sop = ln->value;
robj *val = lookupKeyByPattern(c->db,sop->pattern,
vector[j].obj);
if (sop->type == SORT_OP_GET) {
if (!val) val = createStringObject("",0);
/* listTypePush does an incrRefCount, so we should take care
* care of the incremented refcount caused by either
* lookupKeyByPattern or createStringObject("",0) */
listTypePush(sobj,val,REDIS_LIST_TAIL);
decrRefCount(val);
} else {
/* Always fails */
serverAssertWithInfo(c,sortval,sop->type == SORT_OP_GET);
}
}
}
}
if (outputlen) {
setKey(c->db,storekey,sobj);
notifyKeyspaceEvent(NOTIFY_LIST,"sortstore",storekey,
c->db->id);
server.dirty += outputlen;
} else if (dbDelete(c->db,storekey)) {
signalModifiedKey(c->db,storekey);
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",storekey,c->db->id);
server.dirty++;
}
decrRefCount(sobj);
addReplyLongLong(c,outputlen);
}
/* Cleanup */
if (sortval->type == OBJ_LIST || sortval->type == OBJ_SET)
for (j = 0; j < vectorlen; j++)
decrRefCount(vector[j].obj);
decrRefCount(sortval);
listRelease(operations);
for (j = 0; j < vectorlen; j++) {
if (alpha && vector[j].u.cmpobj)
decrRefCount(vector[j].u.cmpobj);
}
zfree(vector);
}
| 22,327 | 36.780034 | 84 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/release.c
|
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Every time the Redis Git SHA1 or Dirty status changes only this small
* file is recompiled, as we access this information in all the other
* files using this functions. */
#include <string.h>
#include "release.h"
#include "version.h"
#include "crc64.h"
char *redisGitSHA1(void) {
return REDIS_GIT_SHA1;
}
char *redisGitDirty(void) {
return REDIS_GIT_DIRTY;
}
uint64_t redisBuildId(void) {
char *buildid = REDIS_VERSION REDIS_BUILD_ID REDIS_GIT_DIRTY REDIS_GIT_SHA1;
return crc64(0,(unsigned char*)buildid,strlen(buildid));
}
| 2,163 | 39.830189 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/crc64.c
|
/* Redis uses the CRC64 variant with "Jones" coefficients and init value of 0.
*
* Specification of this CRC64 variant follows:
* Name: crc-64-jones
* Width: 64 bites
* Poly: 0xad93d23594c935a9
* Reflected In: True
* Xor_In: 0xffffffffffffffff
* Reflected_Out: True
* Xor_Out: 0x0
* Check("123456789"): 0xe9c6d914c4b8d9ca
*
* Copyright (c) 2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. */
#include <stdint.h>
static const uint64_t crc64_tab[256] = {
UINT64_C(0x0000000000000000), UINT64_C(0x7ad870c830358979),
UINT64_C(0xf5b0e190606b12f2), UINT64_C(0x8f689158505e9b8b),
UINT64_C(0xc038e5739841b68f), UINT64_C(0xbae095bba8743ff6),
UINT64_C(0x358804e3f82aa47d), UINT64_C(0x4f50742bc81f2d04),
UINT64_C(0xab28ecb46814fe75), UINT64_C(0xd1f09c7c5821770c),
UINT64_C(0x5e980d24087fec87), UINT64_C(0x24407dec384a65fe),
UINT64_C(0x6b1009c7f05548fa), UINT64_C(0x11c8790fc060c183),
UINT64_C(0x9ea0e857903e5a08), UINT64_C(0xe478989fa00bd371),
UINT64_C(0x7d08ff3b88be6f81), UINT64_C(0x07d08ff3b88be6f8),
UINT64_C(0x88b81eabe8d57d73), UINT64_C(0xf2606e63d8e0f40a),
UINT64_C(0xbd301a4810ffd90e), UINT64_C(0xc7e86a8020ca5077),
UINT64_C(0x4880fbd87094cbfc), UINT64_C(0x32588b1040a14285),
UINT64_C(0xd620138fe0aa91f4), UINT64_C(0xacf86347d09f188d),
UINT64_C(0x2390f21f80c18306), UINT64_C(0x594882d7b0f40a7f),
UINT64_C(0x1618f6fc78eb277b), UINT64_C(0x6cc0863448deae02),
UINT64_C(0xe3a8176c18803589), UINT64_C(0x997067a428b5bcf0),
UINT64_C(0xfa11fe77117cdf02), UINT64_C(0x80c98ebf2149567b),
UINT64_C(0x0fa11fe77117cdf0), UINT64_C(0x75796f2f41224489),
UINT64_C(0x3a291b04893d698d), UINT64_C(0x40f16bccb908e0f4),
UINT64_C(0xcf99fa94e9567b7f), UINT64_C(0xb5418a5cd963f206),
UINT64_C(0x513912c379682177), UINT64_C(0x2be1620b495da80e),
UINT64_C(0xa489f35319033385), UINT64_C(0xde51839b2936bafc),
UINT64_C(0x9101f7b0e12997f8), UINT64_C(0xebd98778d11c1e81),
UINT64_C(0x64b116208142850a), UINT64_C(0x1e6966e8b1770c73),
UINT64_C(0x8719014c99c2b083), UINT64_C(0xfdc17184a9f739fa),
UINT64_C(0x72a9e0dcf9a9a271), UINT64_C(0x08719014c99c2b08),
UINT64_C(0x4721e43f0183060c), UINT64_C(0x3df994f731b68f75),
UINT64_C(0xb29105af61e814fe), UINT64_C(0xc849756751dd9d87),
UINT64_C(0x2c31edf8f1d64ef6), UINT64_C(0x56e99d30c1e3c78f),
UINT64_C(0xd9810c6891bd5c04), UINT64_C(0xa3597ca0a188d57d),
UINT64_C(0xec09088b6997f879), UINT64_C(0x96d1784359a27100),
UINT64_C(0x19b9e91b09fcea8b), UINT64_C(0x636199d339c963f2),
UINT64_C(0xdf7adabd7a6e2d6f), UINT64_C(0xa5a2aa754a5ba416),
UINT64_C(0x2aca3b2d1a053f9d), UINT64_C(0x50124be52a30b6e4),
UINT64_C(0x1f423fcee22f9be0), UINT64_C(0x659a4f06d21a1299),
UINT64_C(0xeaf2de5e82448912), UINT64_C(0x902aae96b271006b),
UINT64_C(0x74523609127ad31a), UINT64_C(0x0e8a46c1224f5a63),
UINT64_C(0x81e2d7997211c1e8), UINT64_C(0xfb3aa75142244891),
UINT64_C(0xb46ad37a8a3b6595), UINT64_C(0xceb2a3b2ba0eecec),
UINT64_C(0x41da32eaea507767), UINT64_C(0x3b024222da65fe1e),
UINT64_C(0xa2722586f2d042ee), UINT64_C(0xd8aa554ec2e5cb97),
UINT64_C(0x57c2c41692bb501c), UINT64_C(0x2d1ab4dea28ed965),
UINT64_C(0x624ac0f56a91f461), UINT64_C(0x1892b03d5aa47d18),
UINT64_C(0x97fa21650afae693), UINT64_C(0xed2251ad3acf6fea),
UINT64_C(0x095ac9329ac4bc9b), UINT64_C(0x7382b9faaaf135e2),
UINT64_C(0xfcea28a2faafae69), UINT64_C(0x8632586aca9a2710),
UINT64_C(0xc9622c4102850a14), UINT64_C(0xb3ba5c8932b0836d),
UINT64_C(0x3cd2cdd162ee18e6), UINT64_C(0x460abd1952db919f),
UINT64_C(0x256b24ca6b12f26d), UINT64_C(0x5fb354025b277b14),
UINT64_C(0xd0dbc55a0b79e09f), UINT64_C(0xaa03b5923b4c69e6),
UINT64_C(0xe553c1b9f35344e2), UINT64_C(0x9f8bb171c366cd9b),
UINT64_C(0x10e3202993385610), UINT64_C(0x6a3b50e1a30ddf69),
UINT64_C(0x8e43c87e03060c18), UINT64_C(0xf49bb8b633338561),
UINT64_C(0x7bf329ee636d1eea), UINT64_C(0x012b592653589793),
UINT64_C(0x4e7b2d0d9b47ba97), UINT64_C(0x34a35dc5ab7233ee),
UINT64_C(0xbbcbcc9dfb2ca865), UINT64_C(0xc113bc55cb19211c),
UINT64_C(0x5863dbf1e3ac9dec), UINT64_C(0x22bbab39d3991495),
UINT64_C(0xadd33a6183c78f1e), UINT64_C(0xd70b4aa9b3f20667),
UINT64_C(0x985b3e827bed2b63), UINT64_C(0xe2834e4a4bd8a21a),
UINT64_C(0x6debdf121b863991), UINT64_C(0x1733afda2bb3b0e8),
UINT64_C(0xf34b37458bb86399), UINT64_C(0x8993478dbb8deae0),
UINT64_C(0x06fbd6d5ebd3716b), UINT64_C(0x7c23a61ddbe6f812),
UINT64_C(0x3373d23613f9d516), UINT64_C(0x49aba2fe23cc5c6f),
UINT64_C(0xc6c333a67392c7e4), UINT64_C(0xbc1b436e43a74e9d),
UINT64_C(0x95ac9329ac4bc9b5), UINT64_C(0xef74e3e19c7e40cc),
UINT64_C(0x601c72b9cc20db47), UINT64_C(0x1ac40271fc15523e),
UINT64_C(0x5594765a340a7f3a), UINT64_C(0x2f4c0692043ff643),
UINT64_C(0xa02497ca54616dc8), UINT64_C(0xdafce7026454e4b1),
UINT64_C(0x3e847f9dc45f37c0), UINT64_C(0x445c0f55f46abeb9),
UINT64_C(0xcb349e0da4342532), UINT64_C(0xb1eceec59401ac4b),
UINT64_C(0xfebc9aee5c1e814f), UINT64_C(0x8464ea266c2b0836),
UINT64_C(0x0b0c7b7e3c7593bd), UINT64_C(0x71d40bb60c401ac4),
UINT64_C(0xe8a46c1224f5a634), UINT64_C(0x927c1cda14c02f4d),
UINT64_C(0x1d148d82449eb4c6), UINT64_C(0x67ccfd4a74ab3dbf),
UINT64_C(0x289c8961bcb410bb), UINT64_C(0x5244f9a98c8199c2),
UINT64_C(0xdd2c68f1dcdf0249), UINT64_C(0xa7f41839ecea8b30),
UINT64_C(0x438c80a64ce15841), UINT64_C(0x3954f06e7cd4d138),
UINT64_C(0xb63c61362c8a4ab3), UINT64_C(0xcce411fe1cbfc3ca),
UINT64_C(0x83b465d5d4a0eece), UINT64_C(0xf96c151de49567b7),
UINT64_C(0x76048445b4cbfc3c), UINT64_C(0x0cdcf48d84fe7545),
UINT64_C(0x6fbd6d5ebd3716b7), UINT64_C(0x15651d968d029fce),
UINT64_C(0x9a0d8ccedd5c0445), UINT64_C(0xe0d5fc06ed698d3c),
UINT64_C(0xaf85882d2576a038), UINT64_C(0xd55df8e515432941),
UINT64_C(0x5a3569bd451db2ca), UINT64_C(0x20ed197575283bb3),
UINT64_C(0xc49581ead523e8c2), UINT64_C(0xbe4df122e51661bb),
UINT64_C(0x3125607ab548fa30), UINT64_C(0x4bfd10b2857d7349),
UINT64_C(0x04ad64994d625e4d), UINT64_C(0x7e7514517d57d734),
UINT64_C(0xf11d85092d094cbf), UINT64_C(0x8bc5f5c11d3cc5c6),
UINT64_C(0x12b5926535897936), UINT64_C(0x686de2ad05bcf04f),
UINT64_C(0xe70573f555e26bc4), UINT64_C(0x9ddd033d65d7e2bd),
UINT64_C(0xd28d7716adc8cfb9), UINT64_C(0xa85507de9dfd46c0),
UINT64_C(0x273d9686cda3dd4b), UINT64_C(0x5de5e64efd965432),
UINT64_C(0xb99d7ed15d9d8743), UINT64_C(0xc3450e196da80e3a),
UINT64_C(0x4c2d9f413df695b1), UINT64_C(0x36f5ef890dc31cc8),
UINT64_C(0x79a59ba2c5dc31cc), UINT64_C(0x037deb6af5e9b8b5),
UINT64_C(0x8c157a32a5b7233e), UINT64_C(0xf6cd0afa9582aa47),
UINT64_C(0x4ad64994d625e4da), UINT64_C(0x300e395ce6106da3),
UINT64_C(0xbf66a804b64ef628), UINT64_C(0xc5bed8cc867b7f51),
UINT64_C(0x8aeeace74e645255), UINT64_C(0xf036dc2f7e51db2c),
UINT64_C(0x7f5e4d772e0f40a7), UINT64_C(0x05863dbf1e3ac9de),
UINT64_C(0xe1fea520be311aaf), UINT64_C(0x9b26d5e88e0493d6),
UINT64_C(0x144e44b0de5a085d), UINT64_C(0x6e963478ee6f8124),
UINT64_C(0x21c640532670ac20), UINT64_C(0x5b1e309b16452559),
UINT64_C(0xd476a1c3461bbed2), UINT64_C(0xaeaed10b762e37ab),
UINT64_C(0x37deb6af5e9b8b5b), UINT64_C(0x4d06c6676eae0222),
UINT64_C(0xc26e573f3ef099a9), UINT64_C(0xb8b627f70ec510d0),
UINT64_C(0xf7e653dcc6da3dd4), UINT64_C(0x8d3e2314f6efb4ad),
UINT64_C(0x0256b24ca6b12f26), UINT64_C(0x788ec2849684a65f),
UINT64_C(0x9cf65a1b368f752e), UINT64_C(0xe62e2ad306bafc57),
UINT64_C(0x6946bb8b56e467dc), UINT64_C(0x139ecb4366d1eea5),
UINT64_C(0x5ccebf68aecec3a1), UINT64_C(0x2616cfa09efb4ad8),
UINT64_C(0xa97e5ef8cea5d153), UINT64_C(0xd3a62e30fe90582a),
UINT64_C(0xb0c7b7e3c7593bd8), UINT64_C(0xca1fc72bf76cb2a1),
UINT64_C(0x45775673a732292a), UINT64_C(0x3faf26bb9707a053),
UINT64_C(0x70ff52905f188d57), UINT64_C(0x0a2722586f2d042e),
UINT64_C(0x854fb3003f739fa5), UINT64_C(0xff97c3c80f4616dc),
UINT64_C(0x1bef5b57af4dc5ad), UINT64_C(0x61372b9f9f784cd4),
UINT64_C(0xee5fbac7cf26d75f), UINT64_C(0x9487ca0fff135e26),
UINT64_C(0xdbd7be24370c7322), UINT64_C(0xa10fceec0739fa5b),
UINT64_C(0x2e675fb4576761d0), UINT64_C(0x54bf2f7c6752e8a9),
UINT64_C(0xcdcf48d84fe75459), UINT64_C(0xb71738107fd2dd20),
UINT64_C(0x387fa9482f8c46ab), UINT64_C(0x42a7d9801fb9cfd2),
UINT64_C(0x0df7adabd7a6e2d6), UINT64_C(0x772fdd63e7936baf),
UINT64_C(0xf8474c3bb7cdf024), UINT64_C(0x829f3cf387f8795d),
UINT64_C(0x66e7a46c27f3aa2c), UINT64_C(0x1c3fd4a417c62355),
UINT64_C(0x935745fc4798b8de), UINT64_C(0xe98f353477ad31a7),
UINT64_C(0xa6df411fbfb21ca3), UINT64_C(0xdc0731d78f8795da),
UINT64_C(0x536fa08fdfd90e51), UINT64_C(0x29b7d047efec8728),
};
uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l) {
uint64_t j;
for (j = 0; j < l; j++) {
uint8_t byte = s[j];
crc = crc64_tab[(uint8_t)crc ^ byte] ^ (crc >> 8);
}
return crc;
}
/* Test main */
#ifdef REDIS_TEST
#include <stdio.h>
#define UNUSED(x) (void)(x)
int crc64Test(int argc, char *argv[]) {
UNUSED(argc);
UNUSED(argv);
printf("e9c6d914c4b8d9ca == %016llx\n",
(unsigned long long) crc64(0,(unsigned char*)"123456789",9));
return 0;
}
#endif
| 10,717 | 53.683673 | 78 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/adlist.c
|
/* adlist.c - A generic doubly linked list implementation
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"
/* Create a new list. The created list can be freed with
* AlFreeList(), but private value of every node need to be freed
* by the user before to call AlFreeList().
*
* On error, NULL is returned. Otherwise the pointer to the new list. */
list *listCreate(void)
{
struct list *list;
if ((list = zmalloc(sizeof(*list))) == NULL)
return NULL;
list->head = list->tail = NULL;
list->len = 0;
list->dup = NULL;
list->free = NULL;
list->match = NULL;
return list;
}
/* Free the whole list.
*
* This function can't fail. */
void listRelease(list *list)
{
unsigned long len;
listNode *current, *next;
current = list->head;
len = list->len;
while(len--) {
next = current->next;
if (list->free) list->free(current->value);
zfree(current);
current = next;
}
zfree(list);
}
/* Add a new node to the list, to head, containing the specified 'value'
* pointer as value.
*
* On error, NULL is returned and no operation is performed (i.e. the
* list remains unaltered).
* On success the 'list' pointer you pass to the function is returned. */
list *listAddNodeHead(list *list, void *value)
{
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (list->len == 0) {
list->head = list->tail = node;
node->prev = node->next = NULL;
} else {
node->prev = NULL;
node->next = list->head;
list->head->prev = node;
list->head = node;
}
list->len++;
return list;
}
/* Add a new node to the list, to tail, containing the specified 'value'
* pointer as value.
*
* On error, NULL is returned and no operation is performed (i.e. the
* list remains unaltered).
* On success the 'list' pointer you pass to the function is returned. */
list *listAddNodeTail(list *list, void *value)
{
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (list->len == 0) {
list->head = list->tail = node;
node->prev = node->next = NULL;
} else {
node->prev = list->tail;
node->next = NULL;
list->tail->next = node;
list->tail = node;
}
list->len++;
return list;
}
list *listInsertNode(list *list, listNode *old_node, void *value, int after) {
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (after) {
node->prev = old_node;
node->next = old_node->next;
if (list->tail == old_node) {
list->tail = node;
}
} else {
node->next = old_node;
node->prev = old_node->prev;
if (list->head == old_node) {
list->head = node;
}
}
if (node->prev != NULL) {
node->prev->next = node;
}
if (node->next != NULL) {
node->next->prev = node;
}
list->len++;
return list;
}
/* Remove the specified node from the specified list.
* It's up to the caller to free the private value of the node.
*
* This function can't fail. */
void listDelNode(list *list, listNode *node)
{
if (node->prev)
node->prev->next = node->next;
else
list->head = node->next;
if (node->next)
node->next->prev = node->prev;
else
list->tail = node->prev;
if (list->free) list->free(node->value);
zfree(node);
list->len--;
}
/* Returns a list iterator 'iter'. After the initialization every
* call to listNext() will return the next element of the list.
*
* This function can't fail. */
listIter *listGetIterator(list *list, int direction)
{
listIter *iter;
if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;
if (direction == AL_START_HEAD)
iter->next = list->head;
else
iter->next = list->tail;
iter->direction = direction;
return iter;
}
/* Release the iterator memory */
void listReleaseIterator(listIter *iter) {
zfree(iter);
}
/* Create an iterator in the list private iterator structure */
void listRewind(list *list, listIter *li) {
li->next = list->head;
li->direction = AL_START_HEAD;
}
void listRewindTail(list *list, listIter *li) {
li->next = list->tail;
li->direction = AL_START_TAIL;
}
/* Return the next element of an iterator.
* It's valid to remove the currently returned element using
* listDelNode(), but not to remove other elements.
*
* The function returns a pointer to the next element of the list,
* or NULL if there are no more elements, so the classical usage patter
* is:
*
* iter = listGetIterator(list,<direction>);
* while ((node = listNext(iter)) != NULL) {
* doSomethingWith(listNodeValue(node));
* }
*
* */
listNode *listNext(listIter *iter)
{
listNode *current = iter->next;
if (current != NULL) {
if (iter->direction == AL_START_HEAD)
iter->next = current->next;
else
iter->next = current->prev;
}
return current;
}
/* Duplicate the whole list. On out of memory NULL is returned.
* On success a copy of the original list is returned.
*
* The 'Dup' method set with listSetDupMethod() function is used
* to copy the node value. Otherwise the same pointer value of
* the original node is used as value of the copied node.
*
* The original list both on success or error is never modified. */
list *listDup(list *orig)
{
list *copy;
listIter iter;
listNode *node;
if ((copy = listCreate()) == NULL)
return NULL;
copy->dup = orig->dup;
copy->free = orig->free;
copy->match = orig->match;
listRewind(orig, &iter);
while((node = listNext(&iter)) != NULL) {
void *value;
if (copy->dup) {
value = copy->dup(node->value);
if (value == NULL) {
listRelease(copy);
return NULL;
}
} else
value = node->value;
if (listAddNodeTail(copy, value) == NULL) {
listRelease(copy);
return NULL;
}
}
return copy;
}
/* Search the list for a node matching a given key.
* The match is performed using the 'match' method
* set with listSetMatchMethod(). If no 'match' method
* is set, the 'value' pointer of every node is directly
* compared with the 'key' pointer.
*
* On success the first matching node pointer is returned
* (search starts from head). If no matching node exists
* NULL is returned. */
listNode *listSearchKey(list *list, void *key)
{
listIter iter;
listNode *node;
listRewind(list, &iter);
while((node = listNext(&iter)) != NULL) {
if (list->match) {
if (list->match(node->value, key)) {
return node;
}
} else {
if (key == node->value) {
return node;
}
}
}
return NULL;
}
/* Return the element at the specified zero-based index
* where 0 is the head, 1 is the element next to head
* and so on. Negative integers are used in order to count
* from the tail, -1 is the last element, -2 the penultimate
* and so on. If the index is out of range NULL is returned. */
listNode *listIndex(list *list, long index) {
listNode *n;
if (index < 0) {
index = (-index)-1;
n = list->tail;
while(index-- && n) n = n->prev;
} else {
n = list->head;
while(index-- && n) n = n->next;
}
return n;
}
/* Rotate the list removing the tail node and inserting it to the head. */
void listRotate(list *list) {
listNode *tail = list->tail;
if (listLength(list) <= 1) return;
/* Detach current tail */
list->tail = tail->prev;
list->tail->next = NULL;
/* Move it as head */
list->head->prev = tail;
tail->prev = NULL;
tail->next = list->head;
list->head = tail;
}
| 9,657 | 27.744048 | 78 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/rio.h
|
/*
* Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com>
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __REDIS_RIO_H
#define __REDIS_RIO_H
#include <stdio.h>
#include <stdint.h>
#include "sds.h"
struct _rio {
/* Backend functions.
* Since this functions do not tolerate short writes or reads the return
* value is simplified to: zero on error, non zero on complete success. */
size_t (*read)(struct _rio *, void *buf, size_t len);
size_t (*write)(struct _rio *, const void *buf, size_t len);
off_t (*tell)(struct _rio *);
int (*flush)(struct _rio *);
/* The update_cksum method if not NULL is used to compute the checksum of
* all the data that was read or written so far. The method should be
* designed so that can be called with the current checksum, and the buf
* and len fields pointing to the new block of data to add to the checksum
* computation. */
void (*update_cksum)(struct _rio *, const void *buf, size_t len);
/* The current checksum */
uint64_t cksum;
/* number of bytes read or written */
size_t processed_bytes;
/* maximum single read or write chunk size */
size_t max_processing_chunk;
/* Backend-specific vars. */
union {
/* In-memory buffer target. */
struct {
sds ptr;
off_t pos;
} buffer;
/* Stdio file pointer target. */
struct {
FILE *fp;
off_t buffered; /* Bytes written since last fsync. */
off_t autosync; /* fsync after 'autosync' bytes written. */
} file;
/* Multiple FDs target (used to write to N sockets). */
struct {
int *fds; /* File descriptors. */
int *state; /* Error state of each fd. 0 (if ok) or errno. */
int numfds;
off_t pos;
sds buf;
} fdset;
} io;
};
typedef struct _rio rio;
/* The following functions are our interface with the stream. They'll call the
* actual implementation of read / write / tell, and will update the checksum
* if needed. */
static inline size_t rioWrite(rio *r, const void *buf, size_t len) {
while (len) {
size_t bytes_to_write = (r->max_processing_chunk && r->max_processing_chunk < len) ? r->max_processing_chunk : len;
if (r->update_cksum) r->update_cksum(r,buf,bytes_to_write);
if (r->write(r,buf,bytes_to_write) == 0)
return 0;
buf = (char*)buf + bytes_to_write;
len -= bytes_to_write;
r->processed_bytes += bytes_to_write;
}
return 1;
}
static inline size_t rioRead(rio *r, void *buf, size_t len) {
while (len) {
size_t bytes_to_read = (r->max_processing_chunk && r->max_processing_chunk < len) ? r->max_processing_chunk : len;
if (r->read(r,buf,bytes_to_read) == 0)
return 0;
if (r->update_cksum) r->update_cksum(r,buf,bytes_to_read);
buf = (char*)buf + bytes_to_read;
len -= bytes_to_read;
r->processed_bytes += bytes_to_read;
}
return 1;
}
static inline off_t rioTell(rio *r) {
return r->tell(r);
}
static inline int rioFlush(rio *r) {
return r->flush(r);
}
void rioInitWithFile(rio *r, FILE *fp);
void rioInitWithBuffer(rio *r, sds s);
void rioInitWithFdset(rio *r, int *fds, int numfds);
void rioFreeFdset(rio *r);
size_t rioWriteBulkCount(rio *r, char prefix, int count);
size_t rioWriteBulkString(rio *r, const char *buf, size_t len);
size_t rioWriteBulkLongLong(rio *r, long long l);
size_t rioWriteBulkDouble(rio *r, double d);
void rioGenericUpdateChecksum(rio *r, const void *buf, size_t len);
void rioSetAutoSync(rio *r, off_t bytes);
#endif
| 5,290 | 36.260563 | 123 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/src/endianconv.h
|
/* See endianconv.c top comments for more information
*
* ----------------------------------------------------------------------------
*
* Copyright (c) 2011-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ENDIANCONV_H
#define __ENDIANCONV_H
#include "config.h"
#include <stdint.h>
void memrev16(void *p);
void memrev32(void *p);
void memrev64(void *p);
uint16_t intrev16(uint16_t v);
uint32_t intrev32(uint32_t v);
uint64_t intrev64(uint64_t v);
/* variants of the function doing the actual convertion only if the target
* host is big endian */
#if (BYTE_ORDER == LITTLE_ENDIAN)
#define memrev16ifbe(p)
#define memrev32ifbe(p)
#define memrev64ifbe(p)
#define intrev16ifbe(v) (v)
#define intrev32ifbe(v) (v)
#define intrev64ifbe(v) (v)
#else
#define memrev16ifbe(p) memrev16(p)
#define memrev32ifbe(p) memrev32(p)
#define memrev64ifbe(p) memrev64(p)
#define intrev16ifbe(v) intrev16(v)
#define intrev32ifbe(v) intrev32(v)
#define intrev64ifbe(v) intrev64(v)
#endif
/* The functions htonu64() and ntohu64() convert the specified value to
* network byte ordering and back. In big endian systems they are no-ops. */
#if (BYTE_ORDER == BIG_ENDIAN)
#define htonu64(v) (v)
#define ntohu64(v) (v)
#else
#define htonu64(v) intrev64(v)
#define ntohu64(v) intrev64(v)
#endif
#ifdef REDIS_TEST
int endianconvTest(int argc, char *argv[]);
#endif
#endif
| 2,901 | 35.734177 | 79 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/linenoise/linenoise.h
|
/* linenoise.h -- VERSION 1.0
*
* Guerrilla line editing library against the idea that a line editing lib
* needs to be 20,000 lines of C code.
*
* See linenoise.c for more information.
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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.
*
* 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
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __LINENOISE_H
#define __LINENOISE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct linenoiseCompletions {
size_t len;
char **cvec;
} linenoiseCompletions;
typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *);
typedef char*(linenoiseHintsCallback)(const char *, int *color, int *bold);
typedef void(linenoiseFreeHintsCallback)(void *);
void linenoiseSetCompletionCallback(linenoiseCompletionCallback *);
void linenoiseSetHintsCallback(linenoiseHintsCallback *);
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *);
void linenoiseAddCompletion(linenoiseCompletions *, const char *);
char *linenoise(const char *prompt);
void linenoiseFree(void *ptr);
int linenoiseHistoryAdd(const char *line);
int linenoiseHistorySetMaxLen(int len);
int linenoiseHistorySave(const char *filename);
int linenoiseHistoryLoad(const char *filename);
void linenoiseClearScreen(void);
void linenoiseSetMultiLine(int ml);
void linenoisePrintKeyCodes(void);
#ifdef __cplusplus
}
#endif
#endif /* __LINENOISE_H */
| 2,825 | 37.189189 | 80 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/linenoise/example.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linenoise.h"
void completion(const char *buf, linenoiseCompletions *lc) {
if (buf[0] == 'h') {
linenoiseAddCompletion(lc,"hello");
linenoiseAddCompletion(lc,"hello there");
}
}
char *hints(const char *buf, int *color, int *bold) {
if (!strcasecmp(buf,"hello")) {
*color = 35;
*bold = 0;
return " World";
}
return NULL;
}
int main(int argc, char **argv) {
char *line;
char *prgname = argv[0];
/* Parse options, with --multiline we enable multi line editing. */
while(argc > 1) {
argc--;
argv++;
if (!strcmp(*argv,"--multiline")) {
linenoiseSetMultiLine(1);
printf("Multi-line mode enabled.\n");
} else if (!strcmp(*argv,"--keycodes")) {
linenoisePrintKeyCodes();
exit(0);
} else {
fprintf(stderr, "Usage: %s [--multiline] [--keycodes]\n", prgname);
exit(1);
}
}
/* Set the completion callback. This will be called every time the
* user uses the <tab> key. */
linenoiseSetCompletionCallback(completion);
linenoiseSetHintsCallback(hints);
/* Load history from file. The history file is just a plain text file
* where entries are separated by newlines. */
linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
/* Now this is the main loop of the typical linenoise-based application.
* The call to linenoise() will block as long as the user types something
* and presses enter.
*
* The typed string is returned as a malloc() allocated string by
* linenoise, so the user needs to free() it. */
while((line = linenoise("hello> ")) != NULL) {
/* Do something with the string. */
if (line[0] != '\0' && line[0] != '/') {
printf("echo: '%s'\n", line);
linenoiseHistoryAdd(line); /* Add to the history. */
linenoiseHistorySave("history.txt"); /* Save the history on disk. */
} else if (!strncmp(line,"/historylen",11)) {
/* The "/historylen" command will change the history len. */
int len = atoi(line+11);
linenoiseHistorySetMaxLen(len);
} else if (line[0] == '/') {
printf("Unreconized command: %s\n", line);
}
free(line);
}
return 0;
}
| 2,425 | 31.346667 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/dict.c
|
/* Hash table implementation.
*
* This file implements in memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "fmacros.h"
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include "dict.h"
/* -------------------------- private prototypes ---------------------------- */
static int _dictExpandIfNeeded(dict *ht);
static unsigned long _dictNextPower(unsigned long size);
static int _dictKeyIndex(dict *ht, const void *key);
static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
/* -------------------------- hash functions -------------------------------- */
/* Generic hash function (a popular one from Bernstein).
* I tested a few and this was the best. */
static unsigned int dictGenHashFunction(const unsigned char *buf, int len) {
unsigned int hash = 5381;
while (len--)
hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
return hash;
}
/* ----------------------------- API implementation ------------------------- */
/* Reset an hashtable already initialized with ht_init().
* NOTE: This function should only called by ht_destroy(). */
static void _dictReset(dict *ht) {
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
}
/* Create a new hash table */
static dict *dictCreate(dictType *type, void *privDataPtr) {
dict *ht = malloc(sizeof(*ht));
_dictInit(ht,type,privDataPtr);
return ht;
}
/* Initialize the hash table */
static int _dictInit(dict *ht, dictType *type, void *privDataPtr) {
_dictReset(ht);
ht->type = type;
ht->privdata = privDataPtr;
return DICT_OK;
}
/* Expand or create the hashtable */
static int dictExpand(dict *ht, unsigned long size) {
dict n; /* the new hashtable */
unsigned long realsize = _dictNextPower(size), i;
/* the size is invalid if it is smaller than the number of
* elements already inside the hashtable */
if (ht->used > size)
return DICT_ERR;
_dictInit(&n, ht->type, ht->privdata);
n.size = realsize;
n.sizemask = realsize-1;
n.table = calloc(realsize,sizeof(dictEntry*));
/* Copy all the elements from the old to the new table:
* note that if the old hash table is empty ht->size is zero,
* so dictExpand just creates an hash table. */
n.used = ht->used;
for (i = 0; i < ht->size && ht->used > 0; i++) {
dictEntry *he, *nextHe;
if (ht->table[i] == NULL) continue;
/* For each hash entry on this slot... */
he = ht->table[i];
while(he) {
unsigned int h;
nextHe = he->next;
/* Get the new element index */
h = dictHashKey(ht, he->key) & n.sizemask;
he->next = n.table[h];
n.table[h] = he;
ht->used--;
/* Pass to the next element */
he = nextHe;
}
}
assert(ht->used == 0);
free(ht->table);
/* Remap the new hashtable in the old */
*ht = n;
return DICT_OK;
}
/* Add an element to the target hash table */
static int dictAdd(dict *ht, void *key, void *val) {
int index;
dictEntry *entry;
/* Get the index of the new element, or -1 if
* the element already exists. */
if ((index = _dictKeyIndex(ht, key)) == -1)
return DICT_ERR;
/* Allocates the memory and stores key */
entry = malloc(sizeof(*entry));
entry->next = ht->table[index];
ht->table[index] = entry;
/* Set the hash entry fields. */
dictSetHashKey(ht, entry, key);
dictSetHashVal(ht, entry, val);
ht->used++;
return DICT_OK;
}
/* Add an element, discarding the old if the key already exists.
* Return 1 if the key was added from scratch, 0 if there was already an
* element with such key and dictReplace() just performed a value update
* operation. */
static int dictReplace(dict *ht, void *key, void *val) {
dictEntry *entry, auxentry;
/* Try to add the element. If the key
* does not exists dictAdd will suceed. */
if (dictAdd(ht, key, val) == DICT_OK)
return 1;
/* It already exists, get the entry */
entry = dictFind(ht, key);
/* Free the old value and set the new one */
/* Set the new value and free the old one. Note that it is important
* to do that in this order, as the value may just be exactly the same
* as the previous one. In this context, think to reference counting,
* you want to increment (set), and then decrement (free), and not the
* reverse. */
auxentry = *entry;
dictSetHashVal(ht, entry, val);
dictFreeEntryVal(ht, &auxentry);
return 0;
}
/* Search and remove an element */
static int dictDelete(dict *ht, const void *key) {
unsigned int h;
dictEntry *de, *prevde;
if (ht->size == 0)
return DICT_ERR;
h = dictHashKey(ht, key) & ht->sizemask;
de = ht->table[h];
prevde = NULL;
while(de) {
if (dictCompareHashKeys(ht,key,de->key)) {
/* Unlink the element from the list */
if (prevde)
prevde->next = de->next;
else
ht->table[h] = de->next;
dictFreeEntryKey(ht,de);
dictFreeEntryVal(ht,de);
free(de);
ht->used--;
return DICT_OK;
}
prevde = de;
de = de->next;
}
return DICT_ERR; /* not found */
}
/* Destroy an entire hash table */
static int _dictClear(dict *ht) {
unsigned long i;
/* Free all the elements */
for (i = 0; i < ht->size && ht->used > 0; i++) {
dictEntry *he, *nextHe;
if ((he = ht->table[i]) == NULL) continue;
while(he) {
nextHe = he->next;
dictFreeEntryKey(ht, he);
dictFreeEntryVal(ht, he);
free(he);
ht->used--;
he = nextHe;
}
}
/* Free the table and the allocated cache structure */
free(ht->table);
/* Re-initialize the table */
_dictReset(ht);
return DICT_OK; /* never fails */
}
/* Clear & Release the hash table */
static void dictRelease(dict *ht) {
_dictClear(ht);
free(ht);
}
static dictEntry *dictFind(dict *ht, const void *key) {
dictEntry *he;
unsigned int h;
if (ht->size == 0) return NULL;
h = dictHashKey(ht, key) & ht->sizemask;
he = ht->table[h];
while(he) {
if (dictCompareHashKeys(ht, key, he->key))
return he;
he = he->next;
}
return NULL;
}
static dictIterator *dictGetIterator(dict *ht) {
dictIterator *iter = malloc(sizeof(*iter));
iter->ht = ht;
iter->index = -1;
iter->entry = NULL;
iter->nextEntry = NULL;
return iter;
}
static dictEntry *dictNext(dictIterator *iter) {
while (1) {
if (iter->entry == NULL) {
iter->index++;
if (iter->index >=
(signed)iter->ht->size) break;
iter->entry = iter->ht->table[iter->index];
} else {
iter->entry = iter->nextEntry;
}
if (iter->entry) {
/* We need to save the 'next' here, the iterator user
* may delete the entry we are returning. */
iter->nextEntry = iter->entry->next;
return iter->entry;
}
}
return NULL;
}
static void dictReleaseIterator(dictIterator *iter) {
free(iter);
}
/* ------------------------- private functions ------------------------------ */
/* Expand the hash table if needed */
static int _dictExpandIfNeeded(dict *ht) {
/* If the hash table is empty expand it to the intial size,
* if the table is "full" dobule its size. */
if (ht->size == 0)
return dictExpand(ht, DICT_HT_INITIAL_SIZE);
if (ht->used == ht->size)
return dictExpand(ht, ht->size*2);
return DICT_OK;
}
/* Our hash table capability is a power of two */
static unsigned long _dictNextPower(unsigned long size) {
unsigned long i = DICT_HT_INITIAL_SIZE;
if (size >= LONG_MAX) return LONG_MAX;
while(1) {
if (i >= size)
return i;
i *= 2;
}
}
/* Returns the index of a free slot that can be populated with
* an hash entry for the given 'key'.
* If the key already exists, -1 is returned. */
static int _dictKeyIndex(dict *ht, const void *key) {
unsigned int h;
dictEntry *he;
/* Expand the hashtable if needed */
if (_dictExpandIfNeeded(ht) == DICT_ERR)
return -1;
/* Compute the key hash value */
h = dictHashKey(ht, key) & ht->sizemask;
/* Search if this slot does not already contain the given key */
he = ht->table[h];
while(he) {
if (dictCompareHashKeys(ht, key, he->key))
return -1;
he = he->next;
}
return h;
}
| 10,549 | 30.120944 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/net.c
|
/* Extracted from anet.c to work properly with Hiredis error reporting.
*
* Copyright (c) 2006-2011, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "fmacros.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <poll.h>
#include <limits.h>
#include "net.h"
#include "sds.h"
/* Defined in hiredis.c */
void __redisSetError(redisContext *c, int type, const char *str);
static void redisContextCloseFd(redisContext *c) {
if (c && c->fd >= 0) {
close(c->fd);
c->fd = -1;
}
}
static void __redisSetErrorFromErrno(redisContext *c, int type, const char *prefix) {
char buf[128] = { 0 };
size_t len = 0;
if (prefix != NULL)
len = snprintf(buf,sizeof(buf),"%s: ",prefix);
strerror_r(errno,buf+len,sizeof(buf)-len);
__redisSetError(c,type,buf);
}
static int redisSetReuseAddr(redisContext *c) {
int on = 1;
if (setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
return REDIS_OK;
}
static int redisCreateSocket(redisContext *c, int type) {
int s;
if ((s = socket(type, SOCK_STREAM, 0)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
return REDIS_ERR;
}
c->fd = s;
if (type == AF_INET) {
if (redisSetReuseAddr(c) == REDIS_ERR) {
return REDIS_ERR;
}
}
return REDIS_OK;
}
static int redisSetBlocking(redisContext *c, int blocking) {
int flags;
/* Set the socket nonblocking.
* Note that fcntl(2) for F_GETFL and F_SETFL can't be
* interrupted by a signal. */
if ((flags = fcntl(c->fd, F_GETFL)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_GETFL)");
redisContextCloseFd(c);
return REDIS_ERR;
}
if (blocking)
flags &= ~O_NONBLOCK;
else
flags |= O_NONBLOCK;
if (fcntl(c->fd, F_SETFL, flags) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_SETFL)");
redisContextCloseFd(c);
return REDIS_ERR;
}
return REDIS_OK;
}
int redisKeepAlive(redisContext *c, int interval) {
int val = 1;
int fd = c->fd;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1){
__redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
return REDIS_ERR;
}
val = interval;
#ifdef _OSX
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0) {
__redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
return REDIS_ERR;
}
#else
#ifndef __sun
val = interval;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
__redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
return REDIS_ERR;
}
val = interval/3;
if (val == 0) val = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
__redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
return REDIS_ERR;
}
val = 3;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
__redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
return REDIS_ERR;
}
#endif
#endif
return REDIS_OK;
}
static int redisSetTcpNoDelay(redisContext *c) {
int yes = 1;
if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(TCP_NODELAY)");
redisContextCloseFd(c);
return REDIS_ERR;
}
return REDIS_OK;
}
#define __MAX_MSEC (((LONG_MAX) - 999) / 1000)
static int redisContextWaitReady(redisContext *c, const struct timeval *timeout) {
struct pollfd wfd[1];
long msec;
msec = -1;
wfd[0].fd = c->fd;
wfd[0].events = POLLOUT;
/* Only use timeout when not NULL. */
if (timeout != NULL) {
if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
__redisSetErrorFromErrno(c, REDIS_ERR_IO, NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
msec = (timeout->tv_sec * 1000) + ((timeout->tv_usec + 999) / 1000);
if (msec < 0 || msec > INT_MAX) {
msec = INT_MAX;
}
}
if (errno == EINPROGRESS) {
int res;
if ((res = poll(wfd, 1, msec)) == -1) {
__redisSetErrorFromErrno(c, REDIS_ERR_IO, "poll(2)");
redisContextCloseFd(c);
return REDIS_ERR;
} else if (res == 0) {
errno = ETIMEDOUT;
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
if (redisCheckSocketError(c) != REDIS_OK)
return REDIS_ERR;
return REDIS_OK;
}
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
int redisCheckSocketError(redisContext *c) {
int err = 0;
socklen_t errlen = sizeof(err);
if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"getsockopt(SO_ERROR)");
return REDIS_ERR;
}
if (err) {
errno = err;
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
return REDIS_ERR;
}
return REDIS_OK;
}
int redisContextSetTimeout(redisContext *c, const struct timeval tv) {
if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_RCVTIMEO)");
return REDIS_ERR;
}
if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1) {
__redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_SNDTIMEO)");
return REDIS_ERR;
}
return REDIS_OK;
}
static int _redisContextConnectTcp(redisContext *c, const char *addr, int port,
const struct timeval *timeout,
const char *source_addr) {
int s, rv;
char _port[6]; /* strlen("65535"); */
struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
int blocking = (c->flags & REDIS_BLOCK);
snprintf(_port, 6, "%d", port);
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
/* Try with IPv6 if no IPv4 address was found. We do it in this order since
* in a Redis client you can't afford to test if you have IPv6 connectivity
* as this would add latency to every connect. Otherwise a more sensible
* route could be: Use IPv6 if both addresses are available and there is IPv6
* connectivity. */
if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
hints.ai_family = AF_INET6;
if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
__redisSetError(c,REDIS_ERR_OTHER,gai_strerror(rv));
return REDIS_ERR;
}
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
continue;
c->fd = s;
if (redisSetBlocking(c,0) != REDIS_OK)
goto error;
if (source_addr) {
int bound = 0;
/* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0) {
char buf[128];
snprintf(buf,sizeof(buf),"Can't get addr: %s",gai_strerror(rv));
__redisSetError(c,REDIS_ERR_OTHER,buf);
goto error;
}
for (b = bservinfo; b != NULL; b = b->ai_next) {
if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
bound = 1;
break;
}
}
freeaddrinfo(bservinfo);
if (!bound) {
char buf[128];
snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno));
__redisSetError(c,REDIS_ERR_OTHER,buf);
goto error;
}
}
if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
if (errno == EHOSTUNREACH) {
redisContextCloseFd(c);
continue;
} else if (errno == EINPROGRESS && !blocking) {
/* This is ok. */
} else {
if (redisContextWaitReady(c,timeout) != REDIS_OK)
goto error;
}
}
if (blocking && redisSetBlocking(c,1) != REDIS_OK)
goto error;
if (redisSetTcpNoDelay(c) != REDIS_OK)
goto error;
c->flags |= REDIS_CONNECTED;
rv = REDIS_OK;
goto end;
}
if (p == NULL) {
char buf[128];
snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno));
__redisSetError(c,REDIS_ERR_OTHER,buf);
goto error;
}
error:
rv = REDIS_ERR;
end:
freeaddrinfo(servinfo);
return rv; // Need to return REDIS_OK if alright
}
int redisContextConnectTcp(redisContext *c, const char *addr, int port,
const struct timeval *timeout) {
return _redisContextConnectTcp(c, addr, port, timeout, NULL);
}
int redisContextConnectBindTcp(redisContext *c, const char *addr, int port,
const struct timeval *timeout,
const char *source_addr) {
return _redisContextConnectTcp(c, addr, port, timeout, source_addr);
}
int redisContextConnectUnix(redisContext *c, const char *path, const struct timeval *timeout) {
int blocking = (c->flags & REDIS_BLOCK);
struct sockaddr_un sa;
if (redisCreateSocket(c,AF_LOCAL) < 0)
return REDIS_ERR;
if (redisSetBlocking(c,0) != REDIS_OK)
return REDIS_ERR;
sa.sun_family = AF_LOCAL;
strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
if (connect(c->fd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
if (errno == EINPROGRESS && !blocking) {
/* This is ok. */
} else {
if (redisContextWaitReady(c,timeout) != REDIS_OK)
return REDIS_ERR;
}
}
/* Reset socket to be blocking after connect(2). */
if (blocking && redisSetBlocking(c,1) != REDIS_OK)
return REDIS_ERR;
c->flags |= REDIS_CONNECTED;
return REDIS_OK;
}
| 12,238 | 30.955614 | 95 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/net.h
|
/* Extracted from anet.c to work properly with Hiredis error reporting.
*
* Copyright (c) 2006-2011, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __NET_H
#define __NET_H
#include "hiredis.h"
#if defined(__sun) || defined(_AIX)
#define AF_LOCAL AF_UNIX
#endif
int redisCheckSocketError(redisContext *c);
int redisContextSetTimeout(redisContext *c, const struct timeval tv);
int redisContextConnectTcp(redisContext *c, const char *addr, int port, const struct timeval *timeout);
int redisContextConnectBindTcp(redisContext *c, const char *addr, int port,
const struct timeval *timeout,
const char *source_addr);
int redisContextConnectUnix(redisContext *c, const char *path, const struct timeval *timeout);
int redisKeepAlive(redisContext *c, int interval);
#endif
| 2,453 | 46.192308 | 103 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/sds.h
|
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Oran Agra
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SDS_H
#define __SDS_H
#define SDS_MAX_PREALLOC (1024*1024)
#include <sys/types.h>
#include <stdarg.h>
#include <stdint.h>
typedef char *sds;
/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */
uint8_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr16 {
uint16_t len; /* used */
uint16_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr32 {
uint32_t len; /* used */
uint32_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr64 {
uint64_t len; /* used */
uint64_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
#define SDS_TYPE_5 0
#define SDS_TYPE_8 1
#define SDS_TYPE_16 2
#define SDS_TYPE_32 3
#define SDS_TYPE_64 4
#define SDS_TYPE_MASK 7
#define SDS_TYPE_BITS 3
#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T)));
#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))))
#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS)
static inline size_t sdslen(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->len;
case SDS_TYPE_16:
return SDS_HDR(16,s)->len;
case SDS_TYPE_32:
return SDS_HDR(32,s)->len;
case SDS_TYPE_64:
return SDS_HDR(64,s)->len;
}
return 0;
}
static inline size_t sdsavail(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: {
return 0;
}
case SDS_TYPE_8: {
SDS_HDR_VAR(8,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_16: {
SDS_HDR_VAR(16,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_32: {
SDS_HDR_VAR(32,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_64: {
SDS_HDR_VAR(64,s);
return sh->alloc - sh->len;
}
}
return 0;
}
static inline void sdssetlen(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
{
unsigned char *fp = ((unsigned char*)s)-1;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS);
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len = newlen;
break;
}
}
static inline void sdsinclen(sds s, size_t inc) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
{
unsigned char *fp = ((unsigned char*)s)-1;
unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS);
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len += inc;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len += inc;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len += inc;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len += inc;
break;
}
}
/* sdsalloc() = sdsavail() + sdslen() */
static inline size_t sdsalloc(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->alloc;
case SDS_TYPE_16:
return SDS_HDR(16,s)->alloc;
case SDS_TYPE_32:
return SDS_HDR(32,s)->alloc;
case SDS_TYPE_64:
return SDS_HDR(64,s)->alloc;
}
return 0;
}
static inline void sdssetalloc(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
/* Nothing to do, this type has no total allocation info. */
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->alloc = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->alloc = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->alloc = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->alloc = newlen;
break;
}
}
sds sdsnewlen(const void *init, size_t initlen);
sds sdsnew(const char *init);
sds sdsempty(void);
sds sdsdup(const sds s);
void sdsfree(sds s);
sds sdsgrowzero(sds s, size_t len);
sds sdscatlen(sds s, const void *t, size_t len);
sds sdscat(sds s, const char *t);
sds sdscatsds(sds s, const sds t);
sds sdscpylen(sds s, const char *t, size_t len);
sds sdscpy(sds s, const char *t);
sds sdscatvprintf(sds s, const char *fmt, va_list ap);
#ifdef __GNUC__
sds sdscatprintf(sds s, const char *fmt, ...)
__attribute__((format(printf, 2, 3)));
#else
sds sdscatprintf(sds s, const char *fmt, ...);
#endif
sds sdscatfmt(sds s, char const *fmt, ...);
sds sdstrim(sds s, const char *cset);
void sdsrange(sds s, int start, int end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count);
void sdsfreesplitres(sds *tokens, int count);
void sdstolower(sds s);
void sdstoupper(sds s);
sds sdsfromlonglong(long long value);
sds sdscatrepr(sds s, const char *p, size_t len);
sds *sdssplitargs(const char *line, int *argc);
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen);
sds sdsjoin(char **argv, int argc, char *sep);
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);
/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, int incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);
void *sdsAllocPtr(sds s);
/* Export the allocator used by SDS to the program using SDS.
* Sometimes the program SDS is linked to, may use a different set of
* allocators, but may want to allocate or free things that SDS will
* respectively free or allocate. */
void *sds_malloc(size_t size);
void *sds_realloc(void *ptr, size_t size);
void sds_free(void *ptr);
#ifdef REDIS_TEST
int sdsTest(int argc, char *argv[]);
#endif
#endif
| 8,934 | 31.609489 | 88 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/hiredis.h
|
/*
* Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __HIREDIS_H
#define __HIREDIS_H
#include <stdio.h> /* for size_t */
#include <stdarg.h> /* for va_list */
#include <sys/time.h> /* for struct timeval */
#define HIREDIS_MAJOR 0
#define HIREDIS_MINOR 11
#define HIREDIS_PATCH 0
#define REDIS_ERR -1
#define REDIS_OK 0
/* When an error occurs, the err flag in a context is set to hold the type of
* error that occured. REDIS_ERR_IO means there was an I/O error and you
* should use the "errno" variable to find out what is wrong.
* For other values, the "errstr" field will hold a description. */
#define REDIS_ERR_IO 1 /* Error in read or write */
#define REDIS_ERR_EOF 3 /* End of file */
#define REDIS_ERR_PROTOCOL 4 /* Protocol error */
#define REDIS_ERR_OOM 5 /* Out of memory */
#define REDIS_ERR_OTHER 2 /* Everything else... */
/* Connection type can be blocking or non-blocking and is set in the
* least significant bit of the flags field in redisContext. */
#define REDIS_BLOCK 0x1
/* Connection may be disconnected before being free'd. The second bit
* in the flags field is set when the context is connected. */
#define REDIS_CONNECTED 0x2
/* The async API might try to disconnect cleanly and flush the output
* buffer and read all subsequent replies before disconnecting.
* This flag means no new commands can come in and the connection
* should be terminated once all replies have been read. */
#define REDIS_DISCONNECTING 0x4
/* Flag specific to the async API which means that the context should be clean
* up as soon as possible. */
#define REDIS_FREEING 0x8
/* Flag that is set when an async callback is executed. */
#define REDIS_IN_CALLBACK 0x10
/* Flag that is set when the async context has one or more subscriptions. */
#define REDIS_SUBSCRIBED 0x20
/* Flag that is set when monitor mode is active */
#define REDIS_MONITORING 0x40
#define REDIS_REPLY_STRING 1
#define REDIS_REPLY_ARRAY 2
#define REDIS_REPLY_INTEGER 3
#define REDIS_REPLY_NIL 4
#define REDIS_REPLY_STATUS 5
#define REDIS_REPLY_ERROR 6
#define REDIS_READER_MAX_BUF (1024*16) /* Default max unused reader buffer. */
#define REDIS_KEEPALIVE_INTERVAL 15 /* seconds */
#ifdef __cplusplus
extern "C" {
#endif
/* This is the reply object returned by redisCommand() */
typedef struct redisReply {
int type; /* REDIS_REPLY_* */
long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
int len; /* Length of string */
char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;
typedef struct redisReadTask {
int type;
int elements; /* number of elements in multibulk container */
int idx; /* index in parent (array) object */
void *obj; /* holds user-generated value for a read task */
struct redisReadTask *parent; /* parent task */
void *privdata; /* user-settable arbitrary field */
} redisReadTask;
typedef struct redisReplyObjectFunctions {
void *(*createString)(const redisReadTask*, char*, size_t);
void *(*createArray)(const redisReadTask*, int);
void *(*createInteger)(const redisReadTask*, long long);
void *(*createNil)(const redisReadTask*);
void (*freeObject)(void*);
} redisReplyObjectFunctions;
/* State for the protocol parser */
typedef struct redisReader {
int err; /* Error flags, 0 when there is no error */
char errstr[128]; /* String representation of error when applicable */
char *buf; /* Read buffer */
size_t pos; /* Buffer cursor */
size_t len; /* Buffer length */
size_t maxbuf; /* Max length of unused buffer */
redisReadTask rstack[9];
int ridx; /* Index of current read task */
void *reply; /* Temporary reply pointer */
redisReplyObjectFunctions *fn;
void *privdata;
} redisReader;
/* Public API for the protocol parser. */
redisReader *redisReaderCreate(void);
void redisReaderFree(redisReader *r);
int redisReaderFeed(redisReader *r, const char *buf, size_t len);
int redisReaderGetReply(redisReader *r, void **reply);
/* Backwards compatibility, can be removed on big version bump. */
#define redisReplyReaderCreate redisReaderCreate
#define redisReplyReaderFree redisReaderFree
#define redisReplyReaderFeed redisReaderFeed
#define redisReplyReaderGetReply redisReaderGetReply
#define redisReplyReaderSetPrivdata(_r, _p) (int)(((redisReader*)(_r))->privdata = (_p))
#define redisReplyReaderGetObject(_r) (((redisReader*)(_r))->reply)
#define redisReplyReaderGetError(_r) (((redisReader*)(_r))->errstr)
/* Function to free the reply objects hiredis returns by default. */
void freeReplyObject(void *reply);
/* Functions to format a command according to the protocol. */
int redisvFormatCommand(char **target, const char *format, va_list ap);
int redisFormatCommand(char **target, const char *format, ...);
int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen);
/* Context for a connection to Redis */
typedef struct redisContext {
int err; /* Error flags, 0 when there is no error */
char errstr[128]; /* String representation of error when applicable */
int fd;
int flags;
char *obuf; /* Write buffer */
redisReader *reader; /* Protocol reader */
} redisContext;
redisContext *redisConnect(const char *ip, int port);
redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv);
redisContext *redisConnectNonBlock(const char *ip, int port);
redisContext *redisConnectBindNonBlock(const char *ip, int port, const char *source_addr);
redisContext *redisConnectUnix(const char *path);
redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv);
redisContext *redisConnectUnixNonBlock(const char *path);
redisContext *redisConnectFd(int fd);
int redisSetTimeout(redisContext *c, const struct timeval tv);
int redisEnableKeepAlive(redisContext *c);
void redisFree(redisContext *c);
int redisFreeKeepFd(redisContext *c);
int redisBufferRead(redisContext *c);
int redisBufferWrite(redisContext *c, int *done);
/* In a blocking context, this function first checks if there are unconsumed
* replies to return and returns one if so. Otherwise, it flushes the output
* buffer to the socket and reads until it has a reply. In a non-blocking
* context, it will return unconsumed replies until there are no more. */
int redisGetReply(redisContext *c, void **reply);
int redisGetReplyFromReader(redisContext *c, void **reply);
/* Write a formatted command to the output buffer. Use these functions in blocking mode
* to get a pipeline of commands. */
int redisAppendFormattedCommand(redisContext *c, const char *cmd, size_t len);
/* Write a command to the output buffer. Use these functions in blocking mode
* to get a pipeline of commands. */
int redisvAppendCommand(redisContext *c, const char *format, va_list ap);
int redisAppendCommand(redisContext *c, const char *format, ...);
int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
/* Issue a command to Redis. In a blocking context, it is identical to calling
* redisAppendCommand, followed by redisGetReply. The function will return
* NULL if there was an error in performing the request, otherwise it will
* return the reply. In a non-blocking context, it is identical to calling
* only redisAppendCommand and will always return NULL. */
void *redisvCommand(redisContext *c, const char *format, va_list ap);
void *redisCommand(redisContext *c, const char *format, ...);
void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
#ifdef __cplusplus
}
#endif
#endif
| 9,403 | 41.552036 | 96 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/sdsalloc.h
|
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* SDS allocator selection.
*
* This file is used in order to change the SDS allocator at compile time.
* Just define the following defines to what you want to use. Also add
* the include of your alternate allocator if needed (not needed in order
* to use the default libc allocator). */
#include "zmalloc.h"
#define s_malloc zmalloc
#define s_realloc zrealloc
#define s_free zfree
| 2,083 | 47.465116 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/dict.h
|
/* Hash table implementation.
*
* This file implements in memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DICT_H
#define __DICT_H
#define DICT_OK 0
#define DICT_ERR 1
/* Unused arguments generate annoying warnings... */
#define DICT_NOTUSED(V) ((void) V)
typedef struct dictEntry {
void *key;
void *val;
struct dictEntry *next;
} dictEntry;
typedef struct dictType {
unsigned int (*hashFunction)(const void *key);
void *(*keyDup)(void *privdata, const void *key);
void *(*valDup)(void *privdata, const void *obj);
int (*keyCompare)(void *privdata, const void *key1, const void *key2);
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
typedef struct dict {
dictEntry **table;
dictType *type;
unsigned long size;
unsigned long sizemask;
unsigned long used;
void *privdata;
} dict;
typedef struct dictIterator {
dict *ht;
int index;
dictEntry *entry, *nextEntry;
} dictIterator;
/* This is the initial size of every hash table */
#define DICT_HT_INITIAL_SIZE 4
/* ------------------------------- Macros ------------------------------------*/
#define dictFreeEntryVal(ht, entry) \
if ((ht)->type->valDestructor) \
(ht)->type->valDestructor((ht)->privdata, (entry)->val)
#define dictSetHashVal(ht, entry, _val_) do { \
if ((ht)->type->valDup) \
entry->val = (ht)->type->valDup((ht)->privdata, _val_); \
else \
entry->val = (_val_); \
} while(0)
#define dictFreeEntryKey(ht, entry) \
if ((ht)->type->keyDestructor) \
(ht)->type->keyDestructor((ht)->privdata, (entry)->key)
#define dictSetHashKey(ht, entry, _key_) do { \
if ((ht)->type->keyDup) \
entry->key = (ht)->type->keyDup((ht)->privdata, _key_); \
else \
entry->key = (_key_); \
} while(0)
#define dictCompareHashKeys(ht, key1, key2) \
(((ht)->type->keyCompare) ? \
(ht)->type->keyCompare((ht)->privdata, key1, key2) : \
(key1) == (key2))
#define dictHashKey(ht, key) (ht)->type->hashFunction(key)
#define dictGetEntryKey(he) ((he)->key)
#define dictGetEntryVal(he) ((he)->val)
#define dictSlots(ht) ((ht)->size)
#define dictSize(ht) ((ht)->used)
/* API */
static unsigned int dictGenHashFunction(const unsigned char *buf, int len);
static dict *dictCreate(dictType *type, void *privDataPtr);
static int dictExpand(dict *ht, unsigned long size);
static int dictAdd(dict *ht, void *key, void *val);
static int dictReplace(dict *ht, void *key, void *val);
static int dictDelete(dict *ht, const void *key);
static void dictRelease(dict *ht);
static dictEntry * dictFind(dict *ht, const void *key);
static dictIterator *dictGetIterator(dict *ht);
static dictEntry *dictNext(dictIterator *iter);
static void dictReleaseIterator(dictIterator *iter);
#endif /* __DICT_H */
| 4,691 | 35.944882 | 80 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/adapters/ae.h
|
/*
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __HIREDIS_AE_H__
#define __HIREDIS_AE_H__
#include <sys/types.h>
#include <ae.h>
#include "../hiredis.h"
#include "../async.h"
typedef struct redisAeEvents {
redisAsyncContext *context;
aeEventLoop *loop;
int fd;
int reading, writing;
} redisAeEvents;
static void redisAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) {
((void)el); ((void)fd); ((void)mask);
redisAeEvents *e = (redisAeEvents*)privdata;
redisAsyncHandleRead(e->context);
}
static void redisAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) {
((void)el); ((void)fd); ((void)mask);
redisAeEvents *e = (redisAeEvents*)privdata;
redisAsyncHandleWrite(e->context);
}
static void redisAeAddRead(void *privdata) {
redisAeEvents *e = (redisAeEvents*)privdata;
aeEventLoop *loop = e->loop;
if (!e->reading) {
e->reading = 1;
aeCreateFileEvent(loop,e->fd,AE_READABLE,redisAeReadEvent,e);
}
}
static void redisAeDelRead(void *privdata) {
redisAeEvents *e = (redisAeEvents*)privdata;
aeEventLoop *loop = e->loop;
if (e->reading) {
e->reading = 0;
aeDeleteFileEvent(loop,e->fd,AE_READABLE);
}
}
static void redisAeAddWrite(void *privdata) {
redisAeEvents *e = (redisAeEvents*)privdata;
aeEventLoop *loop = e->loop;
if (!e->writing) {
e->writing = 1;
aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e);
}
}
static void redisAeDelWrite(void *privdata) {
redisAeEvents *e = (redisAeEvents*)privdata;
aeEventLoop *loop = e->loop;
if (e->writing) {
e->writing = 0;
aeDeleteFileEvent(loop,e->fd,AE_WRITABLE);
}
}
static void redisAeCleanup(void *privdata) {
redisAeEvents *e = (redisAeEvents*)privdata;
redisAeDelRead(privdata);
redisAeDelWrite(privdata);
free(e);
}
static int redisAeAttach(aeEventLoop *loop, redisAsyncContext *ac) {
redisContext *c = &(ac->c);
redisAeEvents *e;
/* Nothing should be attached when something is already attached */
if (ac->ev.data != NULL)
return REDIS_ERR;
/* Create container for context and r/w events */
e = (redisAeEvents*)malloc(sizeof(*e));
e->context = ac;
e->loop = loop;
e->fd = c->fd;
e->reading = e->writing = 0;
/* Register functions to start/stop listening for events */
ac->ev.addRead = redisAeAddRead;
ac->ev.delRead = redisAeDelRead;
ac->ev.addWrite = redisAeAddWrite;
ac->ev.delWrite = redisAeDelWrite;
ac->ev.cleanup = redisAeCleanup;
ac->ev.data = e;
return REDIS_OK;
}
#endif
| 4,219 | 31.96875 | 82 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/adapters/libevent.h
|
/*
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __HIREDIS_LIBEVENT_H__
#define __HIREDIS_LIBEVENT_H__
#include <event.h>
#include "../hiredis.h"
#include "../async.h"
typedef struct redisLibeventEvents {
redisAsyncContext *context;
struct event rev, wev;
} redisLibeventEvents;
static void redisLibeventReadEvent(int fd, short event, void *arg) {
((void)fd); ((void)event);
redisLibeventEvents *e = (redisLibeventEvents*)arg;
redisAsyncHandleRead(e->context);
}
static void redisLibeventWriteEvent(int fd, short event, void *arg) {
((void)fd); ((void)event);
redisLibeventEvents *e = (redisLibeventEvents*)arg;
redisAsyncHandleWrite(e->context);
}
static void redisLibeventAddRead(void *privdata) {
redisLibeventEvents *e = (redisLibeventEvents*)privdata;
event_add(&e->rev,NULL);
}
static void redisLibeventDelRead(void *privdata) {
redisLibeventEvents *e = (redisLibeventEvents*)privdata;
event_del(&e->rev);
}
static void redisLibeventAddWrite(void *privdata) {
redisLibeventEvents *e = (redisLibeventEvents*)privdata;
event_add(&e->wev,NULL);
}
static void redisLibeventDelWrite(void *privdata) {
redisLibeventEvents *e = (redisLibeventEvents*)privdata;
event_del(&e->wev);
}
static void redisLibeventCleanup(void *privdata) {
redisLibeventEvents *e = (redisLibeventEvents*)privdata;
event_del(&e->rev);
event_del(&e->wev);
free(e);
}
static int redisLibeventAttach(redisAsyncContext *ac, struct event_base *base) {
redisContext *c = &(ac->c);
redisLibeventEvents *e;
/* Nothing should be attached when something is already attached */
if (ac->ev.data != NULL)
return REDIS_ERR;
/* Create container for context and r/w events */
e = (redisLibeventEvents*)malloc(sizeof(*e));
e->context = ac;
/* Register functions to start/stop listening for events */
ac->ev.addRead = redisLibeventAddRead;
ac->ev.delRead = redisLibeventDelRead;
ac->ev.addWrite = redisLibeventAddWrite;
ac->ev.delWrite = redisLibeventDelWrite;
ac->ev.cleanup = redisLibeventCleanup;
ac->ev.data = e;
/* Initialize and install read/write events */
event_set(&e->rev,c->fd,EV_READ,redisLibeventReadEvent,e);
event_set(&e->wev,c->fd,EV_WRITE,redisLibeventWriteEvent,e);
event_base_set(base,&e->rev);
event_base_set(base,&e->wev);
return REDIS_OK;
}
#endif
| 3,980 | 35.522936 | 80 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/adapters/libev.h
|
/*
* Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __HIREDIS_LIBEV_H__
#define __HIREDIS_LIBEV_H__
#include <stdlib.h>
#include <sys/types.h>
#include <ev.h>
#include "../hiredis.h"
#include "../async.h"
typedef struct redisLibevEvents {
redisAsyncContext *context;
struct ev_loop *loop;
int reading, writing;
ev_io rev, wev;
} redisLibevEvents;
static void redisLibevReadEvent(EV_P_ ev_io *watcher, int revents) {
#if EV_MULTIPLICITY
((void)loop);
#endif
((void)revents);
redisLibevEvents *e = (redisLibevEvents*)watcher->data;
redisAsyncHandleRead(e->context);
}
static void redisLibevWriteEvent(EV_P_ ev_io *watcher, int revents) {
#if EV_MULTIPLICITY
((void)loop);
#endif
((void)revents);
redisLibevEvents *e = (redisLibevEvents*)watcher->data;
redisAsyncHandleWrite(e->context);
}
static void redisLibevAddRead(void *privdata) {
redisLibevEvents *e = (redisLibevEvents*)privdata;
struct ev_loop *loop = e->loop;
((void)loop);
if (!e->reading) {
e->reading = 1;
ev_io_start(EV_A_ &e->rev);
}
}
static void redisLibevDelRead(void *privdata) {
redisLibevEvents *e = (redisLibevEvents*)privdata;
struct ev_loop *loop = e->loop;
((void)loop);
if (e->reading) {
e->reading = 0;
ev_io_stop(EV_A_ &e->rev);
}
}
static void redisLibevAddWrite(void *privdata) {
redisLibevEvents *e = (redisLibevEvents*)privdata;
struct ev_loop *loop = e->loop;
((void)loop);
if (!e->writing) {
e->writing = 1;
ev_io_start(EV_A_ &e->wev);
}
}
static void redisLibevDelWrite(void *privdata) {
redisLibevEvents *e = (redisLibevEvents*)privdata;
struct ev_loop *loop = e->loop;
((void)loop);
if (e->writing) {
e->writing = 0;
ev_io_stop(EV_A_ &e->wev);
}
}
static void redisLibevCleanup(void *privdata) {
redisLibevEvents *e = (redisLibevEvents*)privdata;
redisLibevDelRead(privdata);
redisLibevDelWrite(privdata);
free(e);
}
static int redisLibevAttach(EV_P_ redisAsyncContext *ac) {
redisContext *c = &(ac->c);
redisLibevEvents *e;
/* Nothing should be attached when something is already attached */
if (ac->ev.data != NULL)
return REDIS_ERR;
/* Create container for context and r/w events */
e = (redisLibevEvents*)malloc(sizeof(*e));
e->context = ac;
#if EV_MULTIPLICITY
e->loop = loop;
#else
e->loop = NULL;
#endif
e->reading = e->writing = 0;
e->rev.data = e;
e->wev.data = e;
/* Register functions to start/stop listening for events */
ac->ev.addRead = redisLibevAddRead;
ac->ev.delRead = redisLibevDelRead;
ac->ev.addWrite = redisLibevAddWrite;
ac->ev.delWrite = redisLibevDelWrite;
ac->ev.cleanup = redisLibevCleanup;
ac->ev.data = e;
/* Initialize read/write events */
ev_io_init(&e->rev,redisLibevReadEvent,c->fd,EV_READ);
ev_io_init(&e->wev,redisLibevWriteEvent,c->fd,EV_WRITE);
return REDIS_OK;
}
#endif
| 4,587 | 30 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/examples/example-libev.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <hiredis.h>
#include <async.h>
#include <adapters/libev.h>
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = r;
if (reply == NULL) return;
printf("argv[%s]: %s\n", (char*)privdata, reply->str);
/* Disconnect after receiving the reply to GET */
redisAsyncDisconnect(c);
}
void connectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Connected...\n");
}
void disconnectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Disconnected...\n");
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}
redisLibevAttach(EV_DEFAULT_ c);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
ev_loop(EV_DEFAULT_ 0);
return 0;
}
| 1,405 | 25.528302 | 87 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/examples/example.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
unsigned int j;
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
/* PING server */
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key */
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key using binary safe API */
reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
printf("SET (binary API): %s\n", reply->str);
freeReplyObject(reply);
/* Try a GET and two INCR */
reply = redisCommand(c,"GET foo");
printf("GET foo: %s\n", reply->str);
freeReplyObject(reply);
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* again ... */
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* Create a list of numbers, from 0 to 9 */
reply = redisCommand(c,"DEL mylist");
freeReplyObject(reply);
for (j = 0; j < 10; j++) {
char buf[64];
snprintf(buf,64,"%d",j);
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
freeReplyObject(reply);
}
/* Let's check what we have inside the list */
reply = redisCommand(c,"LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
}
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}
| 2,236 | 27.316456 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/examples/example-libuv.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <hiredis.h>
#include <async.h>
#include <adapters/libuv.h>
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = r;
if (reply == NULL) return;
printf("argv[%s]: %s\n", (char*)privdata, reply->str);
/* Disconnect after receiving the reply to GET */
redisAsyncDisconnect(c);
}
void connectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Connected...\n");
}
void disconnectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Disconnected...\n");
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
uv_loop_t* loop = uv_default_loop();
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}
redisLibuvAttach(c,loop);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}
| 1,445 | 25.777778 | 87 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/examples/example-ae.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <hiredis.h>
#include <async.h>
#include <adapters/ae.h>
/* Put event loop in the global scope, so it can be explicitly stopped */
static aeEventLoop *loop;
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = r;
if (reply == NULL) return;
printf("argv[%s]: %s\n", (char*)privdata, reply->str);
/* Disconnect after receiving the reply to GET */
redisAsyncDisconnect(c);
}
void connectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
aeStop(loop);
return;
}
printf("Connected...\n");
}
void disconnectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
aeStop(loop);
return;
}
printf("Disconnected...\n");
aeStop(loop);
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}
loop = aeCreateEventLoop(64);
redisAeAttach(loop, c);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
aeMain(loop);
return 0;
}
| 1,583 | 24.142857 | 87 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/hiredis/examples/example-libevent.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <hiredis.h>
#include <async.h>
#include <adapters/libevent.h>
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = r;
if (reply == NULL) return;
printf("argv[%s]: %s\n", (char*)privdata, reply->str);
/* Disconnect after receiving the reply to GET */
redisAsyncDisconnect(c);
}
void connectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Connected...\n");
}
void disconnectCallback(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
return;
}
printf("Disconnected...\n");
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
struct event_base *base = event_base_new();
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}
redisLibeventAttach(c,base);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
event_base_dispatch(base);
return 0;
}
| 1,455 | 25.962963 | 87 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_config.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 2,527 | 32.706667 | 77 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_log.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* rpmemd_log.c -- rpmemd logging functions definitions
*/
/* for GNU version of basename */
/* XXX Consider changing to Posix basename for consistency */
#ifdef __FreeBSD__
#include <libgen.h>
#else
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "rpmemd_log.h"
#include "os.h"
#include "valgrind_internal.h"
#define RPMEMD_SYSLOG_OPTS (LOG_NDELAY | LOG_PID)
#define RPMEMD_SYSLOG_FACILITY (LOG_USER)
#define RPMEMD_DEFAULT_FH stderr
#define RPMEMD_MAX_MSG ((size_t)8192)
#define RPMEMD_MAX_PREFIX ((size_t)256)
enum rpmemd_log_level rpmemd_log_level;
static char *rpmemd_ident;
static int rpmemd_use_syslog;
static FILE *rpmemd_log_file;
static char rpmemd_prefix_buff[RPMEMD_MAX_PREFIX];
static const char *rpmemd_log_level_str[MAX_RPD_LOG] = {
[RPD_LOG_ERR] = "err",
[RPD_LOG_WARN] = "warn",
[RPD_LOG_NOTICE] = "notice",
[RPD_LOG_INFO] = "info",
[_RPD_LOG_DBG] = "debug",
};
static int rpmemd_level2prio[MAX_RPD_LOG] = {
[RPD_LOG_ERR] = LOG_ERR,
[RPD_LOG_WARN] = LOG_WARNING,
[RPD_LOG_NOTICE] = LOG_NOTICE,
[RPD_LOG_INFO] = LOG_INFO,
[_RPD_LOG_DBG] = LOG_DEBUG,
};
/*
* rpmemd_log_level_from_str -- converts string to log level value
*/
enum rpmemd_log_level
rpmemd_log_level_from_str(const char *str)
{
if (!str)
return MAX_RPD_LOG;
for (enum rpmemd_log_level level = 0; level < MAX_RPD_LOG; level++) {
if (strcmp(rpmemd_log_level_str[level], str) == 0)
return level;
}
return MAX_RPD_LOG;
}
/*
* rpmemd_log_level_to_str -- converts log level enum to string
*/
const char *
rpmemd_log_level_to_str(enum rpmemd_log_level level)
{
if (level >= MAX_RPD_LOG)
return NULL;
return rpmemd_log_level_str[level];
}
/*
* rpmemd_log_init -- inititalize logging subsystem
*
* ident - string prepended to every message
* use_syslog - use syslog instead of standard output
*/
int
rpmemd_log_init(const char *ident, const char *fname, int use_syslog)
{
rpmemd_use_syslog = use_syslog;
if (rpmemd_use_syslog) {
openlog(rpmemd_ident, RPMEMD_SYSLOG_OPTS,
RPMEMD_SYSLOG_FACILITY);
} else {
rpmemd_ident = strdup(ident);
if (!rpmemd_ident) {
perror("strdup");
return -1;
}
if (fname) {
rpmemd_log_file = os_fopen(fname, "a");
if (!rpmemd_log_file) {
perror(fname);
return -1;
}
} else {
rpmemd_log_file = RPMEMD_DEFAULT_FH;
}
}
return 0;
}
/*
* rpmemd_log_close -- deinitialize logging subsystem
*/
void
rpmemd_log_close(void)
{
if (rpmemd_use_syslog) {
closelog();
} else {
if (rpmemd_log_file != RPMEMD_DEFAULT_FH)
fclose(rpmemd_log_file);
free(rpmemd_ident);
}
}
/*
* rpmemd_prefix -- set prefix for every message
*/
int
rpmemd_prefix(const char *fmt, ...)
{
if (!fmt) {
rpmemd_prefix_buff[0] = '\0';
return 0;
}
va_list ap;
va_start(ap, fmt);
int ret = vsnprintf(rpmemd_prefix_buff, RPMEMD_MAX_PREFIX,
fmt, ap);
va_end(ap);
if (ret < 0)
return -1;
return 0;
}
/*
* rpmemd_log -- main logging function
*/
void
rpmemd_log(enum rpmemd_log_level level, const char *fname, int lineno,
const char *fmt, ...)
{
if (!rpmemd_use_syslog && level > rpmemd_log_level)
return;
char buff[RPMEMD_MAX_MSG];
size_t cnt = 0;
int ret;
if (fname) {
ret = snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"[%s:%d] ", basename(fname), lineno);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", ret);
cnt += (size_t)ret;
}
if (rpmemd_prefix_buff[0]) {
ret = snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"%s ", rpmemd_prefix_buff);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", ret);
cnt += (size_t)ret;
}
const char *errorstr = "";
const char *prefix = "";
const char *suffix = "\n";
if (fmt) {
if (*fmt == '!') {
fmt++;
errorstr = strerror(errno);
prefix = ": ";
}
va_list ap;
va_start(ap, fmt);
ret = vsnprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt, fmt, ap);
va_end(ap);
if (ret < 0)
RPMEMD_FATAL("vsnprintf failed");
cnt += (size_t)ret;
ret = snprintf(&buff[cnt], RPMEMD_MAX_MSG - cnt,
"%s%s%s", prefix, errorstr, suffix);
if (ret < 0)
RPMEMD_FATAL("snprintf failed: %d", ret);
}
if (rpmemd_use_syslog) {
int prio = rpmemd_level2prio[level];
syslog(prio, "%s", buff);
} else {
/* 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
fprintf(rpmemd_log_file, "%s", buff);
fflush(rpmemd_log_file);
#ifdef SUPPRESS_FPUTS_DRD_ERROR
VALGRIND_ANNOTATE_IGNORE_READS_END();
VALGRIND_ANNOTATE_IGNORE_WRITES_END();
#endif
}
}
| 6,316 | 23.389961 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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 intitialization");
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;
}
| 20,013 | 23.026411 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_log.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 3,506 | 32.4 | 77 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_util.c
|
/*
* Copyright 2017-2018, Intel Corporation
*
* 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.
*/
/*
* 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;
}
| 4,354 | 28.228188 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_db.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 2,647 | 41.031746 | 76 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_obc.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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));
}
| 13,826 | 22.839655 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_config.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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 = snprintf(str, size, "%s", home);
if (r < 0)
RPMEMD_FATAL("snprintf: %d", r);
} else {
uid_t uid = getuid();
struct passwd *pw = getpwuid(uid);
if (pw == NULL)
RPMEMD_FATAL("!getpwuid");
int r = snprintf(str, size, "%s", pw->pw_dir);
if (r < 0)
RPMEMD_FATAL("snprintf: %d", r);
}
}
/*
* 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 = snprintf(path, size, "%s/%s", dir, file);
if (r < 0)
RPMEMD_FATAL("snprintf: %d", r);
}
/*
* 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 = snprintf(buf, haystack_len, "%s%s%s", haystack, home_dir,
after);
if (r < 0)
RPMEMD_FATAL("snprintf: %d", r);
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))
return 1;
} else {
if (parse_config_file(RPMEMD_GLOBAL_CONFIG_FILE, config,
cl_options, 0))
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))
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);
}
| 16,411 | 23.754148 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_util.h
|
/*
* Copyright 2017-2018, Intel Corporation
*
* 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.
*/
/*
* rpmemd_util.h -- rpmemd utility functions declarations
*/
int rpmemd_pmem_persist(const void *addr, size_t len);
int rpmemd_flush_fatal(const void *addr, size_t len);
int rpmemd_apply_pm_policy(enum rpmem_persist_method *persist_method,
int (**persist)(const void *addr, size_t len),
void *(**memcpy_persist)(void *pmemdest, const void *src, size_t len),
const int is_pmem);
| 1,988 | 45.255814 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_db.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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
*/
LIST_HEAD(list_head, rpmemd_db_entry);
/*
* struct rpmemd_db_entry -- entry in the pool set list
*/
struct rpmemd_db_entry {
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 = snprintf(new_str, new_len, "%s/%s", path1, path2);
if (ret < 0 || (size_t)ret != new_len - 1) {
RPMEMD_LOG(ERR, "snprintf error: %d", ret);
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(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;
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;
}
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;
LIST_INIT(&head);
int ret = rpmemd_db_check_dir_r(&head, db, db->root_dir, "");
while (!LIST_EMPTY(&head)) {
struct rpmemd_db_entry *edb = LIST_FIRST(&head);
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;
}
| 15,255 | 21.941353 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_fip.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 2,581 | 37.537313 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd.h
|
/*
* Copyright 2016, Intel Corporation
*
* 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.
*/
/*
* rpmemd.h -- rpmemd main header file
*/
#define DAEMON_NAME "rpmemd"
| 1,673 | 43.052632 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/rpmemd/rpmemd_obc.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 2,811 | 39.753623 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/dump.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* create.c -- pmempool create command source file
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <err.h>
#include "common.h"
#include "dump.h"
#include "output.h"
#include "os.h"
#include "libpmemblk.h"
#include "libpmemlog.h"
#define VERBOSE_DEFAULT 1
/*
* pmempool_dump -- context and arguments for dump command
*/
struct pmempool_dump {
char *fname;
char *ofname;
char *range;
FILE *ofh;
int hex;
uint64_t bsize;
struct ranges ranges;
size_t chunksize;
uint64_t chunkcnt;
};
/*
* pmempool_dump_default -- default arguments and context values
*/
static const struct pmempool_dump pmempool_dump_default = {
.fname = NULL,
.ofname = NULL,
.range = NULL,
.ofh = NULL,
.hex = 1,
.bsize = 0,
.chunksize = 0,
.chunkcnt = 0,
};
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"output", required_argument, NULL, 'o' | OPT_ALL},
{"binary", no_argument, NULL, 'b' | OPT_ALL},
{"range", required_argument, NULL, 'r' | OPT_ALL},
{"chunk", required_argument, NULL, 'c' | OPT_LOG},
{"help", no_argument, NULL, 'h' | OPT_ALL},
{NULL, 0, NULL, 0 },
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Dump user data from pool\n"
"\n"
"Available options:\n"
" -o, --output <file> output file name\n"
" -b, --binary dump data in binary format\n"
" -r, --range <range> range of bytes/blocks/data chunks\n"
" -c, --chunk <size> size of chunk for PMEMLOG pool\n"
" -h, --help display this help and exit\n"
"\n"
"For complete documentation see %s-dump(1) manual page.\n"
;
/*
* print_usage -- print application usage short description
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s dump [<args>] <file>\n", appname);
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_dump_help -- print help message for dump command
*/
void
pmempool_dump_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* pmempool_dump_log_process_chunk -- callback for pmemlog_walk
*/
static int
pmempool_dump_log_process_chunk(const void *buf, size_t len, void *arg)
{
struct pmempool_dump *pdp = (struct pmempool_dump *)arg;
if (len == 0)
return 0;
struct range *curp = NULL;
if (pdp->chunksize) {
LIST_FOREACH(curp, &pdp->ranges.head, next) {
if (pdp->chunkcnt >= curp->first &&
pdp->chunkcnt <= curp->last &&
pdp->chunksize <= len) {
if (pdp->hex) {
outv_hexdump(VERBOSE_DEFAULT,
buf, pdp->chunksize,
pdp->chunksize * pdp->chunkcnt,
0);
} else {
if (fwrite(buf, pdp->chunksize,
1, pdp->ofh) != 1)
err(1, "%s", pdp->ofname);
}
}
}
pdp->chunkcnt++;
} else {
LIST_FOREACH(curp, &pdp->ranges.head, next) {
if (curp->first >= len)
continue;
uint8_t *ptr = (uint8_t *)buf + curp->first;
if (curp->last >= len)
curp->last = len - 1;
uint64_t count = curp->last - curp->first + 1;
if (pdp->hex) {
outv_hexdump(VERBOSE_DEFAULT, ptr,
count, curp->first, 0);
} else {
if (fwrite(ptr, count, 1, pdp->ofh) != 1)
err(1, "%s", pdp->ofname);
}
}
}
return 1;
}
/*
* pmempool_dump_parse_range -- parse range passed by arguments
*/
static int
pmempool_dump_parse_range(struct pmempool_dump *pdp, size_t max)
{
struct range entire;
memset(&entire, 0, sizeof(entire));
entire.last = max;
if (util_parse_ranges(pdp->range, &pdp->ranges, entire)) {
outv_err("invalid range value specified"
" -- '%s'\n", pdp->range);
return -1;
}
if (LIST_EMPTY(&pdp->ranges.head))
util_ranges_add(&pdp->ranges, entire);
return 0;
}
/*
* pmempool_dump_log -- dump data from pmem log pool
*/
static int
pmempool_dump_log(struct pmempool_dump *pdp)
{
PMEMlogpool *plp = pmemlog_open(pdp->fname);
if (!plp) {
warn("%s", pdp->fname);
return -1;
}
os_off_t off = pmemlog_tell(plp);
if (off < 0) {
warn("%s", pdp->fname);
pmemlog_close(plp);
return -1;
}
if (off == 0)
goto end;
size_t max = (size_t)off - 1;
if (pdp->chunksize)
max /= pdp->chunksize;
if (pmempool_dump_parse_range(pdp, max))
return -1;
pdp->chunkcnt = 0;
pmemlog_walk(plp, pdp->chunksize, pmempool_dump_log_process_chunk, pdp);
end:
pmemlog_close(plp);
return 0;
}
/*
* pmempool_dump_blk -- dump data from pmem blk pool
*/
static int
pmempool_dump_blk(struct pmempool_dump *pdp)
{
PMEMblkpool *pbp = pmemblk_open(pdp->fname, pdp->bsize);
if (!pbp) {
warn("%s", pdp->fname);
return -1;
}
if (pmempool_dump_parse_range(pdp, pmemblk_nblock(pbp) - 1))
return -1;
uint8_t *buff = malloc(pdp->bsize);
if (!buff)
err(1, "Cannot allocate memory for pmemblk block buffer");
int ret = 0;
uint64_t i;
struct range *curp = NULL;
LIST_FOREACH(curp, &pdp->ranges.head, next) {
assert((os_off_t)curp->last >= 0);
for (i = curp->first; i <= curp->last; i++) {
if (pmemblk_read(pbp, buff, (os_off_t)i)) {
ret = -1;
outv_err("reading block number %lu "
"failed\n", i);
break;
}
if (pdp->hex) {
uint64_t offset = i * pdp->bsize;
outv_hexdump(VERBOSE_DEFAULT, buff,
pdp->bsize, offset, 0);
} else {
if (fwrite(buff, pdp->bsize, 1,
pdp->ofh) != 1) {
warn("write");
ret = -1;
break;
}
}
}
}
free(buff);
pmemblk_close(pbp);
return ret;
}
static const struct option_requirement option_requirements[] = {
{ 0, 0, 0}
};
/*
* pmempool_dump_func -- dump command main function
*/
int
pmempool_dump_func(const char *appname, int argc, char *argv[])
{
struct pmempool_dump pd = pmempool_dump_default;
LIST_INIT(&pd.ranges.head);
out_set_vlevel(VERBOSE_DEFAULT);
struct options *opts = util_options_alloc(long_options,
sizeof(long_options) / sizeof(long_options[0]),
option_requirements);
int ret = 0;
long long chunksize;
int opt;
while ((opt = util_options_getopt(argc, argv,
"ho:br:c:", opts)) != -1) {
switch (opt) {
case 'o':
pd.ofname = optarg;
break;
case 'b':
pd.hex = 0;
break;
case 'r':
pd.range = optarg;
break;
case 'c':
chunksize = atoll(optarg);
if (chunksize <= 0) {
outv_err("invalid chunk size specified '%s'\n",
optarg);
exit(EXIT_FAILURE);
}
pd.chunksize = (size_t)chunksize;
break;
case 'h':
pmempool_dump_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
pd.fname = argv[optind];
} else {
print_usage(appname);
exit(EXIT_FAILURE);
}
if (pd.ofname == NULL) {
/* use standard output by default */
pd.ofh = stdout;
} else {
pd.ofh = os_fopen(pd.ofname, "wb");
if (!pd.ofh) {
warn("%s", pd.ofname);
exit(EXIT_FAILURE);
}
}
/* set output stream - stdout or file passed by -o option */
out_set_stream(pd.ofh);
struct pmem_pool_params params;
/* parse pool type and block size for pmem blk pool */
pmem_pool_parse_params(pd.fname, ¶ms, 1);
ret = util_options_verify(opts, params.type);
if (ret)
goto out;
switch (params.type) {
case PMEM_POOL_TYPE_LOG:
ret = pmempool_dump_log(&pd);
break;
case PMEM_POOL_TYPE_BLK:
pd.bsize = params.blk.bsize;
ret = pmempool_dump_blk(&pd);
break;
case PMEM_POOL_TYPE_OBJ:
outv_err("%s: PMEMOBJ pool not supported\n", pd.fname);
ret = -1;
goto out;
case PMEM_POOL_TYPE_CTO:
outv_err("%s: PMEMCTO pool not supported\n", pd.fname);
ret = -1;
goto out;
case PMEM_POOL_TYPE_UNKNOWN:
outv_err("%s: unknown pool type -- '%s'\n", pd.fname,
params.signature);
ret = -1;
goto out;
default:
outv_err("%s: cannot determine type of pool\n", pd.fname);
ret = -1;
goto out;
}
if (ret)
outv_err("%s: dumping pool file failed\n", pd.fname);
out:
if (pd.ofh != stdout)
fclose(pd.ofh);
util_ranges_clear(&pd.ranges);
util_options_free(opts);
return ret;
}
| 9,679 | 21.776471 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/check.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* check.h -- pmempool check command header file
*/
int pmempool_check_func(const char *appname, int argc, char *argv[]);
void pmempool_check_help(const char *appname);
| 1,776 | 44.564103 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/info_cto.c
|
/*
* Copyright 2014-2017, Intel Corporation
*
* 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_cto.c -- pmempool info command source file for cto 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 "common.h"
#include "output.h"
#include "info.h"
/*
* info_cto_descriptor -- print pmemcto descriptor
*/
static void
info_cto_descriptor(struct pmem_info *pip)
{
int v = VERBOSE_DEFAULT;
if (!outv_check(v))
return;
outv(v, "\nPMEM CTO Header:\n");
struct pmemcto *pcp = pip->cto.pcp;
uint8_t *hdrptr = (uint8_t *)pcp + sizeof(pcp->hdr);
size_t hdrsize = sizeof(*pcp) - sizeof(pcp->hdr);
size_t hdroff = sizeof(pcp->hdr);
outv_hexdump(pip->args.vhdrdump, hdrptr, hdrsize, hdroff, 1);
/* check if layout is zeroed */
char *layout = util_check_memory((uint8_t *)pcp->layout,
sizeof(pcp->layout), 0) ?
pcp->layout : "(null)";
outv_field(v, "Layout", "%s", layout);
outv_field(v, "Base address", "%p", (void *)pcp->addr);
outv_field(v, "Size", "0x%zx", (size_t)pcp->size);
outv_field(v, "Consistent", "%d", pcp->consistent);
outv_field(v, "Root pointer", "%p", (void *)pcp->root);
}
/*
* pmempool_info_cto -- print information about cto pool type
*/
int
pmempool_info_cto(struct pmem_info *pip)
{
pip->cto.pcp = pool_set_file_map(pip->pfile, 0);
if (pip->cto.pcp == NULL)
return -1;
pip->cto.size = pip->pfile->size;
info_cto_descriptor(pip);
return 0;
}
| 3,043 | 30.708333 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/create.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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 "libpmemcto.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, --clearbadblocks 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 and PMEMCTO:\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 |
OPT_CTO},
{"force", no_argument, NULL, 'f' | OPT_ALL},
{"clearbadblocks", 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|cto> [<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_cto -- create pmem cto pool
*/
static int
pmempool_create_cto(struct pmempool_create *pcp)
{
PMEMctopool *ptp = pmemcto_create(pcp->fname, pcp->layout,
pcp->params.size, pcp->params.mode);
if (!ptp) {
outv_err("'%s' -- %s\n", pcp->fname, pmemcto_errormsg());
return -1;
}
pmemcto_close(ptp);
return 0;
}
/*
* pmempool_create_blk -- create pmem blk pool
*/
static int
pmempool_create_blk(struct pmempool_create *pcp)
{
int ret = 0;
if (pcp->params.blk.bsize == 0) {
outv(1, "No block size option passed"
" - picking minimum block size.\n");
pcp->params.blk.bsize = PMEMBLK_MIN_BLK;
}
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;
case PMEM_POOL_TYPE_CTO:
outv(1, "\tlayout: '%s'\n", params->cto.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;
}
/*
* 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;
}
}
} 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;
}
size_t max_layout = pc.params.type == PMEM_POOL_TYPE_OBJ ?
PMEMOBJ_MAX_LAYOUT : PMEMCTO_MAX_LAYOUT;
if (pc.layout && strlen(pc.layout) >= max_layout) {
outv_err("Layout name is to long, maximum number of characters"
" (including the terminating null byte) is %zu\n",
max_layout);
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;
case PMEM_POOL_TYPE_CTO:
if (!pc.layout) {
memcpy(pc.params.cto.layout,
pc.inherit_params.cto.layout,
sizeof(pc.params.cto.layout));
} else {
size_t len = sizeof(pc.params.cto.layout);
strncpy(pc.params.cto.layout, pc.layout,
len - 1);
pc.params.cto.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));
} 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;
case PMEM_POOL_TYPE_CTO:
ret = pmempool_create_cto(&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;
}
| 16,310 | 22.60492 | 76 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/transform.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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;
}
}
| 5,204 | 26.394737 | 77 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/info_blk.c
|
/*
* 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,521 | 24.611993 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/create.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* create.h -- pmempool create command header file
*/
int pmempool_create_func(const char *appname, int argc, char *argv[]);
void pmempool_create_help(const char *appname);
| 1,780 | 44.666667 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/pmempool.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* pmempool.c -- pmempool main source file
*/
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include "common.h"
#include "output.h"
#include "info.h"
#include "create.h"
#include "dump.h"
#include "check.h"
#include "rm.h"
#include "convert.h"
#include "synchronize.h"
#include "transform.h"
#include "feature.h"
#include "set.h"
#ifndef _WIN32
#include "rpmem_common.h"
#include "rpmem_util.h"
#endif
#define APPNAME "pmempool"
/*
* command -- struct for pmempool commands definition
*/
struct command {
const char *name;
const char *brief;
int (*func)(const char *, int, char *[]);
void (*help)(const char *);
};
static const struct command *get_command(const char *cmd_str);
static void print_help(const char *appname);
/*
* long_options -- pmempool command line arguments
*/
static const struct option long_options[] = {
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 },
};
/*
* help_help -- prints help message for help command
*/
static void
help_help(const char *appname)
{
printf("Usage: %s help <command>\n", appname);
}
/*
* help_func -- prints help message for specified command
*/
static int
help_func(const char *appname, int argc, char *argv[])
{
if (argc > 1) {
char *cmd_str = argv[1];
const struct command *cmdp = get_command(cmd_str);
if (cmdp && cmdp->help) {
cmdp->help(appname);
return 0;
} else {
outv_err("No help text for '%s' command\n", cmd_str);
return -1;
}
} else {
print_help(appname);
return -1;
}
}
/*
* commands -- definition of all pmempool commands
*/
static const struct command commands[] = {
{
.name = "info",
.brief = "print information and statistics about a pool",
.func = pmempool_info_func,
.help = pmempool_info_help,
},
{
.name = "create",
.brief = "create a pool",
.func = pmempool_create_func,
.help = pmempool_create_help,
},
{
.name = "dump",
.brief = "dump user data from a pool",
.func = pmempool_dump_func,
.help = pmempool_dump_help,
},
{
.name = "check",
.brief = "check consistency of a pool",
.func = pmempool_check_func,
.help = pmempool_check_help,
},
{
.name = "rm",
.brief = "remove pool or poolset",
.func = pmempool_rm_func,
.help = pmempool_rm_help,
},
{
.name = "convert",
.brief = "perform pool layout conversion",
.func = pmempool_convert_func,
.help = pmempool_convert_help,
},
{
.name = "sync",
.brief = "synchronize data between replicas",
.func = pmempool_sync_func,
.help = pmempool_sync_help,
},
{
.name = "transform",
.brief = "modify internal structure of a poolset",
.func = pmempool_transform_func,
.help = pmempool_transform_help,
},
{
.name = "feature",
.brief = "toggle / query pool features",
.func = pmempool_feature_func,
.help = pmempool_feature_help,
},
{
.name = "help",
.brief = "print help text about a command",
.func = help_func,
.help = help_help,
},
};
/*
* number of pmempool commands
*/
#define COMMANDS_NUMBER (sizeof(commands) / sizeof(commands[0]))
/*
* print_version -- prints pmempool version message
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* print_usage -- prints pmempool usage message
*/
static void
print_usage(const char *appname)
{
printf("usage: %s [--version] [--help] <command> [<args>]\n", appname);
}
/*
* print_help -- prints pmempool help message
*/
static void
print_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf("\n");
printf("Options:\n");
printf(" -V, --version display version\n");
printf(" -h, --help display this help and exit\n");
printf("\n");
printf("The available commands are:\n");
unsigned i;
for (i = 0; i < COMMANDS_NUMBER; i++) {
const char *format = (strlen(commands[i].name) / 8)
? "%s\t- %s\n" : "%s\t\t- %s\n";
printf(format, commands[i].name, commands[i].brief);
}
printf("\n");
printf("For complete documentation see %s(1) manual page.\n", appname);
}
/*
* get_command -- returns command for specified command name
*/
static const struct command *
get_command(const char *cmd_str)
{
unsigned i;
for (i = 0; i < COMMANDS_NUMBER; i++) {
if (strcmp(cmd_str, commands[i].name) == 0)
return &commands[i];
}
return NULL;
}
int
main(int argc, char *argv[])
{
int opt;
int option_index;
int ret = 0;
#ifdef _WIN32
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (int i = 0; i < argc; i++) {
argv[i] = util_toUTF8(wargv[i]);
if (argv[i] == NULL) {
for (i--; i >= 0; i--)
free(argv[i]);
outv_err("Error during arguments conversion\n");
return 1;
}
}
#endif
util_init();
#ifndef _WIN32
util_remote_init();
rpmem_util_cmds_init();
#endif
if (argc < 2) {
print_usage(APPNAME);
goto end;
}
while ((opt = getopt_long(2, argv, "Vh",
long_options, &option_index)) != -1) {
switch (opt) {
case 'V':
print_version(APPNAME);
goto end;
case 'h':
print_help(APPNAME);
goto end;
default:
print_usage(APPNAME);
ret = 1;
goto end;
}
}
char *cmd_str = argv[optind];
const struct command *cmdp = get_command(cmd_str);
if (cmdp) {
ret = cmdp->func(APPNAME, argc - 1, argv + 1);
} else {
outv_err("'%s' -- unknown command\n", cmd_str);
ret = 1;
}
#ifndef _WIN32
util_remote_fini();
rpmem_util_cmds_fini();
#endif
end:
#ifdef _WIN32
for (int i = argc; i > 0; i--)
free(argv[i - 1]);
#endif
if (ret)
return 1;
return 0;
}
| 7,204 | 21.728707 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/output.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* output.c -- definitions of output printing related functions
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <err.h>
#include <endian.h>
#include <inttypes.h>
#include <float.h>
#include "feature.h"
#include "common.h"
#include "output.h"
#define _STR(s) #s
#define STR(s) _STR(s)
#define TIME_STR_FMT "%a %b %d %Y %H:%M:%S"
#define UUID_STR_MAX 37
#define HEXDUMP_ROW_WIDTH 16
/*
* 2 chars + space per byte +
* space after 8 bytes and terminating NULL
*/
#define HEXDUMP_ROW_HEX_LEN (HEXDUMP_ROW_WIDTH * 3 + 1 + 1)
/* 1 printable char per byte + terminating NULL */
#define HEXDUMP_ROW_ASCII_LEN (HEXDUMP_ROW_WIDTH + 1)
#define SEPARATOR_CHAR '-'
#define MAX_INDENT 32
#define INDENT_CHAR ' '
static char out_indent_str[MAX_INDENT + 1];
static int out_indent_level;
static int out_vlevel;
static unsigned out_column_width = 20;
static FILE *out_fh;
static const char *out_prefix;
#define STR_MAX 256
/*
* outv_check -- verify verbosity level
*/
int
outv_check(int vlevel)
{
return vlevel && (out_vlevel >= vlevel);
}
/*
* out_set_col_width -- set column width
*
* See: outv_field() function
*/
void
out_set_col_width(unsigned col_width)
{
out_column_width = col_width;
}
/*
* out_set_vlevel -- set verbosity level
*/
void
out_set_vlevel(int vlevel)
{
out_vlevel = vlevel;
if (out_fh == NULL)
out_fh = stdout;
}
/*
* out_set_prefix -- set prefix to output format
*/
void
out_set_prefix(const char *prefix)
{
out_prefix = prefix;
}
/*
* out_set_stream -- set output stream
*/
void
out_set_stream(FILE *stream)
{
out_fh = stream;
memset(out_indent_str, INDENT_CHAR, MAX_INDENT);
}
/*
* outv_err -- print error message
*/
void
outv_err(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
outv_err_vargs(fmt, ap);
va_end(ap);
}
/*
* outv_err_vargs -- print error message
*/
void
outv_err_vargs(const char *fmt, va_list ap)
{
char *_str = strdup(fmt);
if (!_str)
err(1, "strdup");
char *str = _str;
fprintf(stderr, "error: ");
int errstr = str[0] == '!';
if (errstr)
str++;
char *nl = strchr(str, '\n');
if (nl)
*nl = '\0';
vfprintf(stderr, str, ap);
if (errstr)
fprintf(stderr, ": %s", strerror(errno));
fprintf(stderr, "\n");
free(_str);
}
/*
* outv_indent -- change indentation level by factor
*/
void
outv_indent(int vlevel, int i)
{
if (!outv_check(vlevel))
return;
out_indent_str[out_indent_level] = INDENT_CHAR;
out_indent_level += i;
if (out_indent_level < 0)
out_indent_level = 0;
if (out_indent_level > MAX_INDENT)
out_indent_level = MAX_INDENT;
out_indent_str[out_indent_level] = '\0';
}
/*
* _out_prefix -- print prefix if defined
*/
static void
_out_prefix(void)
{
if (out_prefix)
fprintf(out_fh, "%s: ", out_prefix);
}
/*
* _out_indent -- print indent
*/
static void
_out_indent(void)
{
fprintf(out_fh, "%s", out_indent_str);
}
/*
* outv -- print message taking into account verbosity level
*/
void
outv(int vlevel, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
_out_prefix();
_out_indent();
va_start(ap, fmt);
vfprintf(out_fh, fmt, ap);
va_end(ap);
}
/*
* outv_nl -- print new line without indentation
*/
void
outv_nl(int vlevel)
{
if (!outv_check(vlevel))
return;
_out_prefix();
fprintf(out_fh, "\n");
}
void
outv_title(int vlevel, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
fprintf(out_fh, "\n");
_out_prefix();
_out_indent();
va_start(ap, fmt);
vfprintf(out_fh, fmt, ap);
va_end(ap);
fprintf(out_fh, ":\n");
}
/*
* outv_field -- print field name and value in specified format
*
* Field name will have fixed width which can be changed by
* out_set_column_width() function.
* vlevel - verbosity level
* field - field name
* fmt - format form value
*/
void
outv_field(int vlevel, const char *field, const char *fmt, ...)
{
va_list ap;
if (!outv_check(vlevel))
return;
_out_prefix();
_out_indent();
va_start(ap, fmt);
fprintf(out_fh, "%-*s : ", out_column_width, field);
vfprintf(out_fh, fmt, ap);
fprintf(out_fh, "\n");
va_end(ap);
}
/*
* out_get_percentage -- return percentage string
*/
const char *
out_get_percentage(double perc)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
if (perc > 0.0 && perc < 0.0001) {
ret = snprintf(str_buff, STR_MAX, "%e %%", perc);
if (ret < 0)
return "";
} else {
int decimal = 0;
if (perc >= 100.0 || perc < DBL_EPSILON)
decimal = 0;
else
decimal = 6;
ret = snprintf(str_buff, STR_MAX, "%.*f %%", decimal, perc);
if (ret < 0 || ret >= STR_MAX)
return "";
}
return str_buff;
}
/*
* out_get_size_str -- return size string
*
* human - if 1 return size in human-readable format
* if 2 return size in bytes and human-readable format
* otherwise return size in bytes.
*/
const char *
out_get_size_str(uint64_t size, int human)
{
static char str_buff[STR_MAX] = {0, };
char units[] = {
'K', 'M', 'G', 'T', '\0'
};
const int nunits = sizeof(units) / sizeof(units[0]);
int ret = 0;
if (!human) {
ret = snprintf(str_buff, STR_MAX, "%"PRIu64, size);
} else {
int i = -1;
double dsize = (double)size;
uint64_t csize = size;
while (csize >= 1024 && i < nunits) {
csize /= 1024;
dsize /= 1024.0;
i++;
}
if (i >= 0 && i < nunits)
if (human == 1)
ret = snprintf(str_buff, STR_MAX, "%.1f%c",
dsize, units[i]);
else
ret = snprintf(str_buff, STR_MAX, "%.1f%c [%"
PRIu64"]", dsize, units[i], size);
else
ret = snprintf(str_buff, STR_MAX, "%"PRIu64,
size);
}
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
/*
* out_get_uuid_str -- returns uuid in human readable format
*/
const char *
out_get_uuid_str(uuid_t uuid)
{
static char uuid_str[UUID_STR_MAX] = {0, };
int ret = util_uuid_to_string(uuid, uuid_str);
if (ret != 0) {
outv(2, "failed to covert uuid to string");
return NULL;
}
return uuid_str;
}
/*
* out_get_time_str -- returns time in human readable format
*/
const char *
out_get_time_str(time_t time)
{
static char str_buff[STR_MAX] = {0, };
struct tm *tm = util_localtime(&time);
if (tm) {
strftime(str_buff, STR_MAX, TIME_STR_FMT, tm);
} else {
int ret = snprintf(str_buff, STR_MAX, "unknown");
if (ret < 0 || ret >= STR_MAX)
return "";
}
return str_buff;
}
/*
* out_get_ascii_str -- get string with printable ASCII dump buffer
*
* Convert non-printable ASCII characters to dot '.'
* See: util_get_printable_ascii() function.
*/
static int
out_get_ascii_str(char *str, size_t str_len, const uint8_t *datap, size_t len)
{
int c = 0;
size_t i;
char pch;
if (str_len < len)
return -1;
for (i = 0; i < len; i++) {
pch = util_get_printable_ascii((char)datap[i]);
int t = snprintf(str + c, str_len - (size_t)c, "%c", pch);
if (t < 0)
return -1;
c += t;
}
return c;
}
/*
* out_get_hex_str -- get string with hexadecimal dump of buffer
*
* Hexadecimal bytes in format %02x, each one followed by space,
* additional space after every 8th byte.
*/
static int
out_get_hex_str(char *str, size_t str_len, const uint8_t *datap, size_t len)
{
int c = 0;
size_t i;
int t;
if (str_len < (3 * len + 1))
return -1;
for (i = 0; i < len; i++) {
/* add space after n*8 byte */
if (i && (i % 8) == 0) {
t = snprintf(str + c, str_len - (size_t)c, " ");
if (t < 0)
return -1;
c += t;
}
t = snprintf(str + c, str_len - (size_t)c, "%02x ", datap[i]);
if (t < 0)
return -1;
c += t;
}
return c;
}
/*
* outv_hexdump -- print buffer in canonical hex+ASCII format
*
* Print offset in hexadecimal,
* sixteen space-separated, two column, hexadecimal bytes,
* followed by the same sixteen bytes converted to printable ASCII characters
* enclosed in '|' characters.
*/
void
outv_hexdump(int vlevel, const void *addr, size_t len, size_t offset, int sep)
{
if (!outv_check(vlevel) || len <= 0)
return;
const uint8_t *datap = (uint8_t *)addr;
uint8_t row_hex_str[HEXDUMP_ROW_HEX_LEN] = {0, };
uint8_t row_ascii_str[HEXDUMP_ROW_ASCII_LEN] = {0, };
size_t curr = 0;
size_t prev = 0;
int repeated = 0;
int n = 0;
while (len) {
size_t curr_len = min(len, HEXDUMP_ROW_WIDTH);
/*
* Check if current row is the same as the previous one
* don't check it for first and last rows.
*/
if (len != curr_len && curr &&
!memcmp(datap + prev, datap + curr, curr_len)) {
if (!repeated) {
/* print star only for the first repeated */
fprintf(out_fh, "*\n");
repeated = 1;
}
} else {
repeated = 0;
/* row with hexadecimal bytes */
int rh = out_get_hex_str((char *)row_hex_str,
HEXDUMP_ROW_HEX_LEN, datap + curr, curr_len);
/* row with printable ascii chars */
int ra = out_get_ascii_str((char *)row_ascii_str,
HEXDUMP_ROW_ASCII_LEN, datap + curr, curr_len);
if (ra && rh)
n = fprintf(out_fh, "%08zx %-*s|%-*s|\n",
curr + offset,
HEXDUMP_ROW_HEX_LEN, row_hex_str,
HEXDUMP_ROW_WIDTH, row_ascii_str);
prev = curr;
}
len -= curr_len;
curr += curr_len;
}
if (sep && n) {
while (--n)
fprintf(out_fh, "%c", SEPARATOR_CHAR);
fprintf(out_fh, "\n");
}
}
/*
* out_get_checksum -- return checksum string with result
*/
const char *
out_get_checksum(void *addr, size_t len, uint64_t *csump, size_t skip_off)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
/*
* The memory range can be mapped with PROT_READ, so allocate a new
* buffer for the checksum and calculate there.
*/
void *buf = Malloc(len);
if (buf == NULL) {
ret = snprintf(str_buff, STR_MAX, "failed");
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
memcpy(buf, addr, len);
uint64_t *ncsump = (uint64_t *)
((char *)buf + ((char *)csump - (char *)addr));
uint64_t csum = *csump;
/* validate checksum and get correct one */
int valid = util_validate_checksum(buf, len, ncsump, skip_off);
if (valid)
ret = snprintf(str_buff, STR_MAX, "0x%" PRIx64" [OK]",
le64toh(csum));
else
ret = snprintf(str_buff, STR_MAX,
"0x%" PRIx64 " [wrong! should be: 0x%" PRIx64 "]",
le64toh(csum), le64toh(*ncsump));
Free(buf);
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
/*
* out_get_btt_map_entry -- return BTT map entry with flags strings
*/
const char *
out_get_btt_map_entry(uint32_t map)
{
static char str_buff[STR_MAX] = {0, };
int is_init = (map & ~BTT_MAP_ENTRY_LBA_MASK) == 0;
int is_zero = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ZERO;
int is_error = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_ERROR;
int is_normal = (map & ~BTT_MAP_ENTRY_LBA_MASK) ==
BTT_MAP_ENTRY_NORMAL;
uint32_t lba = map & BTT_MAP_ENTRY_LBA_MASK;
int ret = snprintf(str_buff, STR_MAX, "0x%08x state: %s", lba,
is_init ? "init" :
is_zero ? "zero" :
is_error ? "error" :
is_normal ? "normal" : "unknown");
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
/*
* out_get_pool_type_str -- get pool type string
*/
const char *
out_get_pool_type_str(pmem_pool_type_t type)
{
switch (type) {
case PMEM_POOL_TYPE_LOG:
return "log";
case PMEM_POOL_TYPE_BLK:
return "blk";
case PMEM_POOL_TYPE_OBJ:
return "obj";
case PMEM_POOL_TYPE_BTT:
return "btt";
case PMEM_POOL_TYPE_CTO:
return "cto";
default:
return "unknown";
}
}
/*
* out_get_pool_signature -- return signature of specified pool type
*/
const char *
out_get_pool_signature(pmem_pool_type_t type)
{
switch (type) {
case PMEM_POOL_TYPE_LOG:
return LOG_HDR_SIG;
case PMEM_POOL_TYPE_BLK:
return BLK_HDR_SIG;
case PMEM_POOL_TYPE_OBJ:
return OBJ_HDR_SIG;
case PMEM_POOL_TYPE_CTO:
return CTO_HDR_SIG;
default:
return NULL;
}
}
/*
* out_get_chunk_type_str -- get chunk type string
*/
const char *
out_get_chunk_type_str(enum chunk_type type)
{
switch (type) {
case CHUNK_TYPE_FOOTER:
return "footer";
case CHUNK_TYPE_FREE:
return "free";
case CHUNK_TYPE_USED:
return "used";
case CHUNK_TYPE_RUN:
return "run";
case CHUNK_TYPE_UNKNOWN:
default:
return "unknown";
}
}
/*
* out_get_chunk_flags -- get names of set flags for chunk header
*/
const char *
out_get_chunk_flags(uint16_t flags)
{
if (flags & CHUNK_FLAG_COMPACT_HEADER)
return "compact header";
else if (flags & CHUNK_FLAG_HEADER_NONE)
return "header none";
return "";
}
/*
* out_get_zone_magic_str -- get zone magic string with additional
* information about correctness of the magic value
*/
const char *
out_get_zone_magic_str(uint32_t magic)
{
static char str_buff[STR_MAX] = {0, };
const char *correct = NULL;
switch (magic) {
case 0:
correct = "uninitialized";
break;
case ZONE_HEADER_MAGIC:
correct = "OK";
break;
default:
correct = "wrong! should be " STR(ZONE_HEADER_MAGIC);
break;
}
int ret = snprintf(str_buff, STR_MAX, "0x%08x [%s]", magic, correct);
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
/*
* out_get_pmemoid_str -- get PMEMoid string
*/
const char *
out_get_pmemoid_str(PMEMoid oid, uint64_t uuid_lo)
{
static char str_buff[STR_MAX] = {0, };
int free_cor = 0;
int ret = 0;
char *correct = "OK";
if (oid.pool_uuid_lo && oid.pool_uuid_lo != uuid_lo) {
ret = snprintf(str_buff, STR_MAX,
"wrong! should be 0x%016"PRIx64, uuid_lo);
if (ret < 0 || ret >= STR_MAX)
err(1, "snprintf: %d", ret);
correct = strdup(str_buff);
if (!correct)
err(1, "Cannot allocate memory for PMEMoid string\n");
free_cor = 1;
}
ret = snprintf(str_buff, STR_MAX,
"off: 0x%016"PRIx64" pool_uuid_lo: 0x%016"
PRIx64" [%s]", oid.off, oid.pool_uuid_lo, correct);
if (free_cor)
free(correct);
if (ret < 0 || ret >= STR_MAX)
err(1, "snprintf: %d", ret);
return str_buff;
}
/*
* out_get_arch_machine_class_str -- get a string representation of the machine
* class
*/
const char *
out_get_arch_machine_class_str(uint8_t machine_class)
{
switch (machine_class) {
case PMDK_MACHINE_CLASS_64:
return "64";
default:
return "unknown";
}
}
/*
* out_get_arch_data_str -- get a string representation of the data endianness
*/
const char *
out_get_arch_data_str(uint8_t data)
{
switch (data) {
case PMDK_DATA_LE:
return "2's complement, little endian";
case PMDK_DATA_BE:
return "2's complement, big endian";
default:
return "unknown";
}
}
/*
* out_get_arch_machine_str -- get a string representation of the machine type
*/
const char *
out_get_arch_machine_str(uint16_t machine)
{
static char str_buff[STR_MAX] = {0, };
switch (machine) {
case PMDK_MACHINE_X86_64:
return "AMD X86-64";
case PMDK_MACHINE_AARCH64:
return "Aarch64";
default:
break;
}
int ret = snprintf(str_buff, STR_MAX, "unknown %u", machine);
if (ret < 0 || ret >= STR_MAX)
return "unknown";
return str_buff;
}
/*
* out_get_last_shutdown_str -- get a string representation of the finish state
*/
const char *
out_get_last_shutdown_str(uint8_t dirty)
{
if (dirty)
return "dirty";
else
return "clean";
}
/*
* out_get_alignment_descr_str -- get alignment descriptor string
*/
const char *
out_get_alignment_desc_str(uint64_t ad, uint64_t valid_ad)
{
static char str_buff[STR_MAX] = {0, };
int ret = 0;
if (ad == valid_ad)
ret = snprintf(str_buff, STR_MAX, "0x%016"PRIx64"[OK]", ad);
else
ret = snprintf(str_buff, STR_MAX, "0x%016"PRIx64" "
"[wrong! should be 0x%016"PRIx64"]", ad, valid_ad);
if (ret < 0 || ret >= STR_MAX)
return "";
return str_buff;
}
/*
* out_concat -- concatenate the new element to the list of strings
*
* If concatenation is successful it increments current position in the output
* string and number of elements in the list. Elements are separated with ", ".
*/
static int
out_concat(char *str_buff, int *curr, int *count, const char *str)
{
ASSERTne(str_buff, NULL);
ASSERTne(curr, NULL);
ASSERTne(str, NULL);
const char *separator = (count != NULL && *count > 0) ? ", " : "";
int ret = snprintf(str_buff + *curr,
(size_t)(STR_MAX - *curr), "%s%s", separator, str);
if (ret < 0 || *curr + ret >= STR_MAX)
return -1;
*curr += ret;
if (count)
++(*count);
return 0;
}
/*
* out_get_incompat_features_str -- (internal) get a string with names of
* incompatibility flags
*/
const char *
out_get_incompat_features_str(uint32_t incompat)
{
static char str_buff[STR_MAX] = {0};
features_t features = {POOL_FEAT_ZERO, incompat, POOL_FEAT_ZERO};
int ret = 0;
if (incompat == 0) {
/* print the value only */
return "0x0";
} else {
/* print the value and the left square bracket */
ret = snprintf(str_buff, STR_MAX, "0x%x [", incompat);
if (ret < 0 || ret >= STR_MAX) {
ERR("snprintf for incompat features: %d", ret);
return "<error>";
}
/* print names of known options */
int count = 0;
int curr = ret;
features_t found;
const char *feat;
while (((feat = util_feature2str(features, &found))) != NULL) {
util_feature_disable(&features, found);
ret = out_concat(str_buff, &curr, &count, feat);
if (ret < 0)
return "";
}
/* check if any unknown flags are set */
if (!util_feature_is_zero(features)) {
if (out_concat(str_buff, &curr, &count,
"?UNKNOWN_FLAG?"))
return "";
}
/* print the right square bracket */
if (out_concat(str_buff, &curr, NULL, "]"))
return "";
}
return str_buff;
}
| 18,971 | 20.292929 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/dump.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* dump.h -- pmempool dump command header file
*/
int pmempool_dump_func(const char *appname, int argc, char *argv[]);
void pmempool_dump_help(const char *appname);
| 1,772 | 44.461538 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/rm.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* rm.h -- pmempool rm command header file
*/
void pmempool_rm_help(const char *appname);
int pmempool_rm_func(const char *appname, int argc, char *argv[]);
| 1,764 | 44.25641 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/feature.h
|
/*
* Copyright 2018, Intel Corporation
*
* 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.
*/
/*
* feature.h -- pmempool feature command header file
*/
int pmempool_feature_func(const char *appname, int argc, char *argv[]);
void pmempool_feature_help(const char *appname);
| 1,779 | 44.641026 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/feature.c
|
/*
* Copyright 2018, Intel Corporation
*
* 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.
*/
/*
* feature.c -- pmempool feature command source file
*/
#include <getopt.h>
#include <stdlib.h>
#include "common.h"
#include "feature.h"
#include "output.h"
#include "libpmempool.h"
/* operations over features */
enum feature_op {
undefined,
enable,
disable,
query
};
/*
* feature_ctx -- context and arguments for feature command
*/
struct feature_ctx {
int verbose;
const char *fname;
enum feature_op op;
enum pmempool_feature feature;
unsigned flags;
};
/*
* pmempool_feature_default -- default arguments for feature command
*/
static const struct feature_ctx pmempool_feature_default = {
.verbose = 0,
.fname = NULL,
.op = undefined,
.feature = UINT32_MAX,
.flags = 0
};
/*
* help_str -- string for help message
*/
static const char * const help_str =
"Toggle or query a pool feature\n"
"\n"
"For complete documentation see %s-feature(1) manual page.\n"
;
/*
* long_options -- command line options
*/
static const struct option long_options[] = {
{"enable", required_argument, NULL, 'e'},
{"disable", required_argument, NULL, 'd'},
{"query", required_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 feature [<args>] <file>\n", appname);
printf(
"feature: SINGLEHDR, CKSUM_2K, SHUTDOWN_STATE, CHECK_BAD_BLOCKS\n");
}
/*
* print_version -- print version string
*/
static void
print_version(const char *appname)
{
printf("%s %s\n", appname, SRCVERSION);
}
/*
* pmempool_feature_help -- print help message for feature command
*/
void
pmempool_feature_help(const char *appname)
{
print_usage(appname);
print_version(appname);
printf(help_str, appname);
}
/*
* feature_perform -- perform operation over function
*/
static int
feature_perform(struct feature_ctx *pfp)
{
int ret;
switch (pfp->op) {
case enable:
return pmempool_feature_enable(pfp->fname, pfp->feature,
pfp->flags);
case disable:
return pmempool_feature_disable(pfp->fname, pfp->feature,
pfp->flags);
case query:
ret = pmempool_feature_query(pfp->fname, pfp->feature,
pfp->flags);
if (ret < 0)
return 1;
printf("%d", ret);
return 0;
default:
ERR("Invalid option.");
return -1;
}
}
/*
* set_op -- set operation
*/
static void
set_op(const char *appname, struct feature_ctx *pfp, enum feature_op op,
const char *feature)
{
/* only one operation allowed */
if (pfp->op != undefined)
goto misuse;
pfp->op = op;
/* parse feature name */
uint32_t fval = util_str2pmempool_feature(feature);
if (fval == UINT32_MAX)
goto misuse;
pfp->feature = (enum pmempool_feature)fval;
return;
misuse:
print_usage(appname);
exit(EXIT_FAILURE);
}
/*
* parse_args -- parse command line arguments
*/
static int
parse_args(struct feature_ctx *pfp, const char *appname,
int argc, char *argv[])
{
int opt;
while ((opt = getopt_long(argc, argv, "vhe:d:q:h",
long_options, NULL)) != -1) {
switch (opt) {
case 'e':
set_op(appname, pfp, enable, optarg);
break;
case 'd':
set_op(appname, pfp, disable, optarg);
break;
case 'q':
set_op(appname, pfp, query, optarg);
break;
case 'v':
pfp->verbose = 2;
break;
case 'h':
pmempool_feature_help(appname);
exit(EXIT_SUCCESS);
default:
print_usage(appname);
exit(EXIT_FAILURE);
}
}
if (optind >= argc) {
print_usage(appname);
exit(EXIT_FAILURE);
}
pfp->fname = argv[optind];
return 0;
}
/*
* pmempool_feature_func -- main function for feature command
*/
int
pmempool_feature_func(const char *appname, int argc, char *argv[])
{
struct feature_ctx pf = pmempool_feature_default;
int ret = 0;
/* parse command line arguments */
ret = parse_args(&pf, appname, argc, argv);
if (ret)
return ret;
/* set verbosity level */
out_set_vlevel(pf.verbose);
return feature_perform(&pf);
}
| 5,562 | 22.472574 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/check.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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"
" -N, --no-exec 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'},
{"no-exec", no_argument, NULL, 'N'},
{"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, "ahvrNb:qy",
long_options, NULL)) != -1) {
switch (opt) {
case 'r':
pcp->repair = true;
break;
case 'y':
pcp->ans = 'y';
break;
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;
}
| 8,609 | 24.102041 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/convert.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* convert.h -- pmempool convert command header file
*/
#include <sys/types.h>
int pmempool_convert_func(const char *appname, int argc, char *argv[]);
void pmempool_convert_help(const char *appname);
| 1,808 | 43.121951 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/rm.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* rm.c -- pmempool rm command main source file
*/
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <err.h>
#include <stdio.h>
#include <fcntl.h>
#include "os.h"
#include "out.h"
#include "common.h"
#include "output.h"
#include "file.h"
#include "rm.h"
#include "set.h"
#ifdef USE_RPMEM
#include "librpmem.h"
#endif
enum ask_type {
ASK_SOMETIMES, /* ask before removing write-protected files */
ASK_ALWAYS, /* always ask */
ASK_NEVER, /* never ask */
};
/* verbosity level */
static int vlevel;
/* force remove and ignore errors */
static int force;
/* poolset files options */
#define RM_POOLSET_NONE (0)
#define RM_POOLSET_LOCAL (1 << 0)
#define RM_POOLSET_REMOTE (1 << 1)
#define RM_POOLSET_ALL (RM_POOLSET_LOCAL | RM_POOLSET_REMOTE)
static int rm_poolset_mode;
/* mode of interaction */
static enum ask_type ask_mode;
/* indicates whether librpmem is available */
static int rpmem_avail;
/* help message */
static const char * const help_str =
"Remove pool file or all files from poolset\n"
"\n"
"Available options:\n"
" -h, --help Print this help message.\n"
" -v, --verbose Be verbose.\n"
" -s, --only-pools Remove only pool files (default).\n"
" -a, --all Remove all poolset files - local and remote.\n"
" -l, --local Remove local poolset files\n"
" -r, --remote Remove remote poolset files\n"
" -f, --force Ignore nonexisting files.\n"
" -i, --interactive Prompt before every single removal.\n"
"\n"
"For complete documentation see %s-rm(1) manual page.\n";
/* short options string */
static const char *optstr = "hvsfialr";
/* long options */
static const struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{"only-pools", no_argument, NULL, 's'},
{"all", no_argument, NULL, 'a'},
{"local", no_argument, NULL, 'l'},
{"remote", no_argument, NULL, 'r'},
{"force", no_argument, NULL, 'f'},
{"interactive", no_argument, NULL, 'i'},
{NULL, 0, NULL, 0 },
};
/*
* print_usage -- print usage message
*/
static void
print_usage(const char *appname)
{
printf("Usage: %s rm [<args>] <files>\n", appname);
}
/*
* pmempool_rm_help -- print help message
*/
void
pmempool_rm_help(const char *appname)
{
print_usage(appname);
printf(help_str, appname);
}
/*
* rm_file -- remove single file
*/
static int
rm_file(const char *file)
{
int write_protected = os_access(file, W_OK) != 0;
char cask = 'y';
switch (ask_mode) {
case ASK_ALWAYS:
cask = '?';
break;
case ASK_NEVER:
cask = 'y';
break;
case ASK_SOMETIMES:
cask = write_protected ? '?' : 'y';
break;
default:
outv_err("unknown state");
return 1;
}
const char *pre_msg = write_protected ? "write-protected " : "";
char ans = ask_Yn(cask, "remove %sfile '%s' ?", pre_msg, file);
if (ans == INV_ANS)
outv(1, "invalid answer\n");
if (ans == 'y') {
if (util_unlink(file)) {
outv_err("cannot remove file '%s'", file);
return 1;
}
outv(1, "removed '%s'\n", file);
}
return 0;
}
/*
* remove_remote -- (internal) remove remote pool
*/
static int
remove_remote(const char *target, const char *pool_set)
{
#ifdef USE_RPMEM
char cask = 'y';
switch (ask_mode) {
case ASK_ALWAYS:
cask = '?';
break;
case ASK_NEVER:
case ASK_SOMETIMES:
cask = 'y';
break;
default:
outv_err("unknown state");
return 1;
}
char ans = ask_Yn(cask, "remove remote pool '%s' on '%s'?",
pool_set, target);
if (ans == INV_ANS)
outv(1, "invalid answer\n");
if (ans != 'y')
return 0;
if (!rpmem_avail) {
if (force) {
outv(1, "cannot remove '%s' on '%s' -- "
"librpmem not available", pool_set, target);
return 0;
}
outv_err("!cannot remove '%s' on '%s' -- "
"librpmem not available", pool_set, target);
return 1;
}
int flags = 0;
if (rm_poolset_mode & RM_POOLSET_REMOTE)
flags |= RPMEM_REMOVE_POOL_SET;
if (force)
flags |= RPMEM_REMOVE_FORCE;
int ret = Rpmem_remove(target, pool_set, flags);
if (ret) {
if (force) {
ret = 0;
outv(1, "cannot remove '%s' on '%s'",
pool_set, target);
} else {
/*
* Callback cannot return < 0 value because it
* is interpretted as error in parsing poolset file.
*/
ret = 1;
outv_err("!cannot remove '%s' on '%s'",
pool_set, target);
}
} else {
outv(1, "removed '%s' on '%s'\n",
pool_set, target);
}
return ret;
#else
outv_err("remote replication not supported");
return 1;
#endif
}
/*
* rm_poolset_cb -- (internal) callback for removing replicas
*/
static int
rm_poolset_cb(struct part_file *pf, void *arg)
{
int *error = (int *)arg;
int ret;
if (pf->is_remote) {
ret = remove_remote(pf->remote->node_addr,
pf->remote->pool_desc);
} else {
const char *part_file = pf->part->path;
outv(2, "part file : %s\n", part_file);
int exists = util_file_exists(part_file);
if (exists < 0)
ret = 1;
else if (!exists) {
/*
* Ignore not accessible file if force
* flag is set.
*/
if (force)
return 0;
ret = 1;
outv_err("!cannot remove file '%s'", part_file);
} else {
ret = rm_file(part_file);
}
}
if (ret)
*error = ret;
return 0;
}
/*
* rm_poolset -- remove files parsed from poolset file
*/
static int
rm_poolset(const char *file)
{
int error = 0;
int ret = util_poolset_foreach_part(file, rm_poolset_cb, &error);
if (ret == -1) {
outv_err("parsing poolset failed: %s\n",
out_get_errormsg());
return ret;
}
if (error && !force) {
outv_err("!removing '%s' failed\n", file);
return error;
}
return 0;
}
/*
* pmempool_rm_func -- main function for rm command
*/
int
pmempool_rm_func(const char *appname, int argc, char *argv[])
{
/* by default do not remove any poolset files */
rm_poolset_mode = RM_POOLSET_NONE;
int opt;
while ((opt = getopt_long(argc, argv, optstr,
long_options, NULL)) != -1) {
switch (opt) {
case 'h':
pmempool_rm_help(appname);
return 0;
case 'v':
vlevel++;
break;
case 's':
rm_poolset_mode = RM_POOLSET_NONE;
break;
case 'a':
rm_poolset_mode |= RM_POOLSET_ALL;
break;
case 'l':
rm_poolset_mode |= RM_POOLSET_LOCAL;
break;
case 'r':
rm_poolset_mode |= RM_POOLSET_REMOTE;
break;
case 'f':
force = 1;
ask_mode = ASK_NEVER;
break;
case 'i':
ask_mode = ASK_ALWAYS;
break;
default:
print_usage(appname);
return 1;
}
}
out_set_vlevel(vlevel);
if (optind == argc) {
print_usage(appname);
return 1;
}
#ifdef USE_RPMEM
/*
* Try to load librpmem, if loading failed -
* assume it is not available.
*/
util_remote_init();
rpmem_avail = !util_remote_load();
#endif
int lret = 0;
for (int i = optind; i < argc; i++) {
char *file = argv[i];
/* check if file exists and we can read it */
int exists = os_access(file, F_OK | R_OK) == 0;
if (!exists) {
/* ignore not accessible file if force flag is set */
if (force)
continue;
outv_err("!cannot remove '%s'", file);
lret = 1;
continue;
}
int is_poolset = util_is_poolset_file(file);
if (is_poolset < 0) {
outv(1, "%s: cannot determine type of file", file);
if (force)
continue;
}
if (is_poolset)
outv(2, "poolset file: %s\n", file);
else
outv(2, "pool file : %s\n", file);
int ret;
if (is_poolset) {
ret = rm_poolset(file);
if (!ret && (rm_poolset_mode & RM_POOLSET_LOCAL))
ret = rm_file(file);
} else {
ret = rm_file(file);
}
if (ret)
lret = ret;
}
return lret;
}
| 9,106 | 21.48642 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/synchronize.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* synchronize.h -- pmempool sync command header file
*/
int pmempool_sync_func(const char *appname, int argc, char *argv[]);
void pmempool_sync_help(const char *appname);
| 1,779 | 44.641026 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/common.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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 "libpmemcto.h"
#include "cto.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"
/* 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_CTO (1 << (PMEM_POOL_TYPE_CTO + OPT_SHIFT))
#define OPT_ALL (OPT_LOG | OPT_BLK | OPT_OBJ | OPT_BTT | OPT_CTO)
#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)\
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 4096UL /* 4 KB */
#define DEFAULT_DESC_SIZE 4096UL /* 4 KB */
#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_CTO = 0x10,
PMEM_POOL_TYPE_ALL = 0x1f,
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 {
char layout[PMEMCTO_MAX_LAYOUT];
} cto;
};
};
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 {
LIST_ENTRY(range) next;
uint64_t first;
uint64_t last;
};
struct ranges {
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);
int util_validate_checksum(void *addr, size_t len, uint64_t *csum,
uint64_t skip_off);
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, 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 */
};
| 7,787 | 31.181818 | 79 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/info_log.c
|
/*
* Copyright 2014-2017, Intel Corporation
*
* 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_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;
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;
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;
}
| 5,477 | 27.831579 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/transform.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* transform.h -- pmempool transform command header file
*/
int pmempool_transform_func(const char *appname, int argc, char *argv[]);
void pmempool_transform_help(const char *appname);
| 1,792 | 44.974359 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/info.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.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
/*
* 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 */
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 */
int vbadblocks; /* verbosity level for bad blocks */
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 {
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;
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;
struct {
struct pmemcto *pcp;
size_t size;
} cto;
};
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);
int pmempool_info_cto(struct pmem_info *pip);
| 5,934 | 30.236842 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/output.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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);
| 3,585 | 44.974359 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/synchronize.c
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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;
}
}
| 5,014 | 25.818182 | 98 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/pmempool/convert.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* convert.c -- pmempool convert command source file
*/
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "convert.h"
#include "os.h"
#ifdef _WIN32
static const char *delimeter = ";";
static const char *convert_bin = "\\pmdk-convert.exe";
#else
static const char *delimeter = ":";
static const char *convert_bin = "/pmdk-convert";
#endif // _WIN32
static int
pmempool_convert_get_path(char *p, size_t max_len)
{
char *path = strdup(os_getenv("PATH"));
if (!path) {
perror("strdup");
return -1;
}
char *dir = strtok(path, delimeter);
while (dir) {
size_t length = strlen(dir) + strlen(convert_bin) + 1;
if (length > max_len) {
fprintf(stderr, "very long dir in PATH, ignoring\n");
continue;
}
strcpy(p, dir);
strcat(p, convert_bin);
if (os_access(p, F_OK) == 0) {
free(path);
return 0;
}
dir = strtok(NULL, delimeter);
}
free(path);
return -1;
}
/*
* pmempool_convert_help -- print help message for convert command. This is
* help message from pmdk-convert tool.
*/
void
pmempool_convert_help(const char *appname)
{
char path[4096];
if (pmempool_convert_get_path(path, sizeof(path))) {
fprintf(stderr,
"pmdk-convert is not installed. Please install it.\n");
exit(1);
}
char *args[] = { path, "-h", NULL };
os_execv(path, args);
perror("execv");
exit(1);
}
/*
* pmempool_convert_func -- main function for convert command.
* It invokes pmdk-convert tool.
*/
int
pmempool_convert_func(const char *appname, int argc, char *argv[])
{
char path[4096];
if (pmempool_convert_get_path(path, sizeof(path))) {
fprintf(stderr,
"pmdk-convert is not installed. Please install it.\n");
exit(1);
}
char **args = malloc(((size_t)argc + 1) * sizeof(*args));
if (!args) {
perror("malloc");
exit(1);
}
args[0] = path;
for (int i = 1; i < argc; ++i)
args[i] = argv[i];
args[argc] = NULL;
os_execv(args[0], args);
perror("execv");
free(args);
exit(1);
}
| 3,619 | 24.673759 | 75 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/tools/daxio/daxio.c
|
/*
* Copyright 2018, Intel Corporation
*
* 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.
*/
/*
* 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_dimm.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)
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;
struct daxio_device src;
struct daxio_device dst;
};
/*
* default context
*/
static struct daxio_context Ctx = {
SIZE_MAX, /* len */
0, /* zero */
{ 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)
{
printf("Usage: daxio [option] ...\n");
printf("Valid options:\n");
printf("-i, --input=FILE - input device/file (default stdin)\n");
printf("-o, --output=FILE - output device/file (default stdout)\n");
printf("-k, --skip=BYTES - skip offset for input (default 0)\n");
printf("-s, --seek=BYTES - seek offset for output (default 0)\n");
printf("-l, --len=BYTES - total length to perform the I/O\n");
printf("-z, --zero - zeroing the device\n");
printf("-h. --help - print this help\n");
printf("-V, --version - display version of daxio\n");
}
/*
* 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'},
{"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: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 '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;
struct ndctl_region *region;
struct ndctl_dax *dax;
struct daxctl_region *dax_region;
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 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 = 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 = 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) {
flags = O_RDWR|O_TRUNC;
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) {
/* XXX - clear only badblocks in range bound by offset/len */
if (os_dimm_devdax_clear_badblocks_all(dev->path)) {
ERR("failed to clear badblocks on \"%s\"\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))
return -1;
return setup_device(ndctl_ctx, &ctx->dst, 1);
}
/*
* 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 mmaped 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,464 | 22.713115 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/libpmemlog/log.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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"
#ifdef __cplusplus
extern "C" {
#endif
#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 \
{0x0000, POOL_FEAT_INCOMPAT_DEFAULT, 0x0000}
#define LOG_FORMAT_FEAT_CHECK \
{0x0000, 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)4096)
/*
* 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);
}
#ifdef __cplusplus
}
#endif
#endif
| 3,867 | 31.504202 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/libpmemlog/log.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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;
}
if ((errno = os_rwlock_init(plp->rwlockp))) {
ERR("!os_rwlock_init");
Free((void *)plp->rwlockp);
return -1;
}
/*
* 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;
if (util_pool_create(&set, path, poolsize, PMEMLOG_MIN_POOL,
PMEMLOG_MIN_PART, &Log_create_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, 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);
if ((errno = os_rwlock_destroy(plp->rwlockp)))
ERR("!os_rwlock_destroy");
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);
if ((errno = os_rwlock_rdlock(plp->rwlockp))) {
ERR("!os_rwlock_rdlock");
return (size_t)-1;
}
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;
}
if ((errno = os_rwlock_wrlock(plp->rwlockp))) {
ERR("!os_rwlock_wrlock");
return -1;
}
/* 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;
}
if ((errno = os_rwlock_wrlock(plp->rwlockp))) {
ERR("!os_rwlock_wrlock");
return -1;
}
/* 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);
if ((errno = os_rwlock_rdlock(plp->rwlockp))) {
ERR("!os_rwlock_rdlock");
return (os_off_t)-1;
}
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;
}
if ((errno = os_rwlock_wrlock(plp->rwlockp))) {
ERR("!os_rwlock_wrlock");
return;
}
/* 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.
*/
if ((errno = os_rwlock_rdlock(plp->rwlockp))) {
ERR("!os_rwlock_rdlock");
return;
}
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
| 21,207 | 21.902808 | 75 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/libpmemlog/libpmemlog_main.c
|
/*
* Copyright 2016-2017, Intel Corporation
*
* 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.
*/
/*
* libpmemlog_main.c -- entry point for libpmemlog.dll
*
* XXX - This is a placeholder. All the library initialization/cleanup
* that is done in library ctors/dtors, as well as TLS initialization
* should be moved here.
*/
void libpmemlog_init(void);
void libpmemlog_fini(void);
int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason) {
case DLL_PROCESS_ATTACH:
libpmemlog_init();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
libpmemlog_fini();
break;
}
return TRUE;
}
| 2,184 | 34.241935 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/libpmemlog/libpmemlog.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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
| 5,816 | 24.181818 | 78 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/freebsd/include/endian.h
|
/*
* Copyright 2017, Intel Corporation
*
* 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.
*/
/*
* endian.h -- redirect for FreeBSD <sys/endian.h>
*/
#include <sys/endian.h>
| 1,680 | 43.236842 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/freebsd/include/features.h
|
/*
* Copyright 2017, Intel Corporation
*
* 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.
*/
/*
* features.h -- Empty file redirect
*/
| 1,641 | 44.611111 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/freebsd/include/sys/sysmacros.h
|
/*
* Copyright 2017, Intel Corporation
*
* 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/sysmacros.h -- Empty file redirect
*/
| 1,646 | 44.75 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/freebsd/include/linux/kdev_t.h
|
/*
* Copyright 2017, Intel Corporation
*
* 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.
*/
/*
* linux/kdev_t.h -- Empty file redirect
*/
| 1,645 | 44.722222 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/freebsd/include/linux/limits.h
|
/*
* Copyright 2017, Intel Corporation
*
* 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.
*/
/*
* linux/limits.h -- Empty file redirect
*/
| 1,645 | 44.722222 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_dimm_none.c
|
/*
* Copyright 2018, Intel Corporation
*
* 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_dimm_none.c -- fake dimm functions
*/
#include "out.h"
#include "os.h"
#include "os_dimm.h"
/*
* os_dimm_uid -- returns empty uid
*/
int
os_dimm_uid(const char *path, char *uid, size_t *len)
{
LOG(3, "path %s, uid %p, len %lu", path, uid, *len);
if (uid == NULL) {
*len = 1;
} else {
*uid = '\0';
}
return 0;
}
/*
* os_dimm_usc -- returns fake unsafe shutdown count
*/
int
os_dimm_usc(const char *path, uint64_t *usc)
{
LOG(3, "path %s, usc %p", path, usc);
*usc = 0;
return 0;
}
/*
* os_dimm_files_namespace_badblocks -- fake os_dimm_files_namespace_badblocks()
*/
int
os_dimm_files_namespace_badblocks(const char *path, struct badblocks *bbs)
{
LOG(3, "path %s", path);
os_stat_t st;
if (os_stat(path, &st)) {
ERR("!stat %s", path);
return -1;
}
return 0;
}
/*
* os_dimm_devdax_clear_badblocks -- fake bad block clearing routine
*/
int
os_dimm_devdax_clear_badblocks(const char *path, struct badblocks *bbs)
{
LOG(3, "path %s badblocks %p", path, bbs);
return 0;
}
/*
* os_dimm_devdax_clear_badblocks_all -- fake bad block clearing routine
*/
int
os_dimm_devdax_clear_badblocks_all(const char *path)
{
LOG(3, "path %s", path);
return 0;
}
| 2,793 | 25.609524 | 80 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/ctl.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* 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;
SLIST_ENTRY(ctl_index) entry;
};
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 necessery 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];
struct ctl_argument *arg;
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_##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)}
/* 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)}
#define CTL_READ_HANDLER(name)\
ctl_##name##_read
#define CTL_WRITE_HANDLER(name)\
ctl_##name##_write
#define CTL_RUNNABLE_HANDLER(name)\
ctl_##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), 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), 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)},\
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
| 6,437 | 27.113537 | 80 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_windows.c
|
/*
* Copyright 2017-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.
*/
/*
* os_windows.c -- windows abstraction layer
*/
#include <io.h>
#include <sys/locking.h>
#include <errno.h>
#include <pmemcompat.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;
/*
* 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;
return _chsize_s(fd, requested_size);
}
/*
* os_ftruncate -- truncate a file to a specified length
*/
int
os_ftruncate(int fd, os_off_t length)
{
return _chsize_s(fd, length);
}
/*
* 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;
}
| 14,725 | 20.655882 | 79 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_deep.h
|
/*
* Copyright 2017-2018, Intel Corporation
*
* 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_deep.h -- abstraction layer for common usage of deep_* functions
*/
#ifndef PMDK_OS_DEEP_PERSIST_H
#define PMDK_OS_DEEP_PERSIST_H 1
#include <stdint.h>
#include <stddef.h>
#include "set.h"
#ifdef __cplusplus
extern "C" {
#endif
int os_range_deep_common(uintptr_t addr, size_t len);
int os_part_deep_common(struct pool_replica *rep, unsigned partidx, void *addr,
size_t len, int flush);
#ifdef __cplusplus
}
#endif
#endif
| 2,042 | 34.842105 | 79 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_thread_posix.c
|
/*
* Copyright 2017-2018, Intel Corporation
*
* 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_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);
}
| 10,705 | 21.974249 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/ctl_global.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* ctl_global.h -- definitions for the global CTL namespace
*/
#ifndef PMDK_CTL_GLOBAL_H
#define PMDK_CTL_GLOBAL_H 1
#ifdef __cplusplus
extern "C" {
#endif
void ctl_global_register(void);
#ifdef __cplusplus
}
#endif
#endif
| 1,834 | 34.980392 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/file.h
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* 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_fd_get_type(int fd);
enum file_type util_file_get_type(const char *path);
int util_ddax_region_find(const char *path);
ssize_t util_file_get_size(const char *path);
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
/* XXX - consider adding an assertion on (count <= UINT_MAX) */
#define util_read(fd, buf, count) read(fd, buf, (unsigned)(count))
#define util_write(fd, buf, count) 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,839 | 31.268908 | 78 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/uuid_freebsd.c
|
/*
* Copyright 2015-2017, Intel Corporation
*
* 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.
*/
/*
* uuid_freebsd.c -- FreeBSD-specific implementation for UUID generation
*/
#include "uuid.h"
/* XXX Can't include <uuid/uuid.h> because it also defines uuid_t */
void uuid_generate(uuid_t);
/*
* util_uuid_generate -- generate a uuid
*
* Uses the available FreeBSD uuid_generate library function.
*/
int
util_uuid_generate(uuid_t uuid)
{
uuid_generate(uuid);
return 0;
}
| 1,987 | 35.814815 | 74 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/file_posix.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.
*/
/*
* file_posix.c -- Posix versions of file APIs
*/
/* for O_TMPFILE */
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include "os.h"
#include "file.h"
#include "out.h"
#define MAX_SIZE_LENGTH 64
#define DAX_REGION_ID_LEN 6 /* 5 digits + \0 */
/*
* util_tmpfile_mkstemp -- (internal) create temporary file
* if O_TMPFILE not supported
*/
static int
util_tmpfile_mkstemp(const char *dir, const char *templ)
{
/* the templ must start with a path separator */
ASSERTeq(templ[0], '/');
int oerrno;
int fd = -1;
char *fullname = alloca(strlen(dir) + strlen(templ) + 1);
(void) strcpy(fullname, dir);
(void) strcat(fullname, templ);
sigset_t set, oldset;
sigfillset(&set);
(void) sigprocmask(SIG_BLOCK, &set, &oldset);
mode_t prev_umask = umask(S_IRWXG | S_IRWXO);
fd = os_mkstemp(fullname);
umask(prev_umask);
if (fd < 0) {
ERR("!mkstemp");
goto err;
}
(void) os_unlink(fullname);
(void) sigprocmask(SIG_SETMASK, &oldset, NULL);
LOG(3, "unlinked file is \"%s\"", fullname);
return fd;
err:
oerrno = errno;
(void) sigprocmask(SIG_SETMASK, &oldset, NULL);
if (fd != -1)
(void) os_close(fd);
errno = oerrno;
return -1;
}
/*
* util_tmpfile -- create 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);
#ifdef O_TMPFILE
int fd = open(dir, O_TMPFILE | O_RDWR | flags, S_IRUSR | S_IWUSR);
/*
* Open can fail if underlying file system does not support O_TMPFILE
* flag.
*/
if (fd >= 0)
return fd;
if (errno != EOPNOTSUPP) {
ERR("!open");
return -1;
}
#endif
return util_tmpfile_mkstemp(dir, templ);
}
/*
* util_is_absolute_path -- check if the path is an absolute one
*/
int
util_is_absolute_path(const char *path)
{
LOG(3, "path: %s", path);
if (path[0] == OS_DIR_SEPARATOR)
return 1;
else
return 0;
}
/*
* util_create_mkdir -- creates new dir
*/
int
util_file_mkdir(const char *path, mode_t mode)
{
LOG(3, "path: %s mode: %o", path, mode);
return mkdir(path, mode);
}
/*
* util_file_dir_open -- open a directory
*/
int
util_file_dir_open(struct dir_handle *handle, const char *path)
{
LOG(3, "handle: %p path: %s", handle, path);
handle->dirp = opendir(path);
return handle->dirp == NULL;
}
/*
* util_file_dir_next -- read next file in directory
*/
int
util_file_dir_next(struct dir_handle *handle, struct file_info *info)
{
LOG(3, "handle: %p info: %p", handle, info);
struct dirent *d = readdir(handle->dirp);
if (d == NULL)
return 1; /* break */
info->filename[NAME_MAX] = '\0';
strncpy(info->filename, d->d_name, NAME_MAX + 1);
if (info->filename[NAME_MAX] != '\0')
return -1; /* filename truncated */
info->is_dir = d->d_type == DT_DIR;
return 0; /* continue */
}
/*
* util_file_dir_close -- close a directory
*/
int
util_file_dir_close(struct dir_handle *handle)
{
LOG(3, "path: %p", handle);
return closedir(handle->dirp);
}
/*
* util_file_dir_remove -- remove directory
*/
int
util_file_dir_remove(const char *path)
{
LOG(3, "path: %s", path);
return rmdir(path);
}
/*
* device_dax_alignment -- (internal) checks the alignment of given Device DAX
*/
static size_t
device_dax_alignment(const char *path)
{
LOG(3, "path \"%s\"", path);
os_stat_t st;
int olderrno;
if (os_stat(path, &st) < 0) {
ERR("!stat \"%s\"", path);
return 0;
}
char spath[PATH_MAX];
snprintf(spath, PATH_MAX, "/sys/dev/char/%u:%u/device/align",
os_major(st.st_rdev), os_minor(st.st_rdev));
LOG(4, "device align path \"%s\"", spath);
int fd = os_open(spath, O_RDONLY);
if (fd < 0) {
ERR("!open \"%s\"", spath);
return 0;
}
size_t size = 0;
char sizebuf[MAX_SIZE_LENGTH + 1];
ssize_t nread;
if ((nread = read(fd, sizebuf, MAX_SIZE_LENGTH)) < 0) {
ERR("!read");
goto out;
}
sizebuf[nread] = 0; /* null termination */
char *endptr;
olderrno = errno;
errno = 0;
/* 'align' is in decimal format */
size = strtoull(sizebuf, &endptr, 10);
if (endptr == sizebuf || *endptr != '\n' ||
(size == ULLONG_MAX && errno == ERANGE)) {
ERR("invalid device alignment %s", sizebuf);
size = 0;
goto out;
}
/*
* If the alignment value is not a power of two, try with
* hex format, as this is how it was printed in older kernels.
* Just in case someone is using kernel <4.9.
*/
if ((size & (size - 1)) != 0) {
size = strtoull(sizebuf, &endptr, 16);
if (endptr == sizebuf || *endptr != '\n' ||
(size == ULLONG_MAX && errno == ERANGE)) {
ERR("invalid device alignment %s", sizebuf);
size = 0;
goto out;
}
}
errno = olderrno;
out:
olderrno = errno;
(void) os_close(fd);
errno = olderrno;
LOG(4, "device alignment %zu", size);
return size;
}
/*
* 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 device_dax_alignment(path);
}
/*
* util_ddax_region_find -- returns Device DAX region id
*/
int
util_ddax_region_find(const char *path)
{
LOG(3, "path \"%s\"", path);
int dax_reg_id_fd;
char dax_region_path[PATH_MAX];
char reg_id[DAX_REGION_ID_LEN];
char *end_addr;
os_stat_t st;
ASSERTne(path, NULL);
if (os_stat(path, &st) < 0) {
ERR("!stat \"%s\"", path);
return -1;
}
dev_t dev_id = st.st_rdev;
unsigned major = os_major(dev_id);
unsigned minor = os_minor(dev_id);
int ret = snprintf(dax_region_path, PATH_MAX,
"/sys/dev/char/%u:%u/device/dax_region/id",
major, minor);
if (ret < 0) {
ERR("snprintf(%p, %d, /sys/dev/char/%u:%u/device/"
"dax_region/id, %u, %u): %d",
dax_region_path, PATH_MAX, major, minor, major, minor,
ret);
return -1;
}
if ((dax_reg_id_fd = os_open(dax_region_path, O_RDONLY)) < 0) {
LOG(1, "!open(\"%s\", O_RDONLY)", dax_region_path);
return -1;
}
ssize_t len = read(dax_reg_id_fd, reg_id, DAX_REGION_ID_LEN);
if (len == -1) {
ERR("!read(%d, %p, %d)", dax_reg_id_fd,
reg_id, DAX_REGION_ID_LEN);
goto err;
} else if (len < 2 || reg_id[len - 1] != '\n') {
errno = EINVAL;
ERR("!read(%d, %p, %d) invalid format", dax_reg_id_fd,
reg_id, DAX_REGION_ID_LEN);
goto err;
}
int olderrno = errno;
errno = 0;
long reg_num = strtol(reg_id, &end_addr, 10);
if ((errno == ERANGE && (reg_num == LONG_MAX || reg_num == LONG_MIN)) ||
(errno != 0 && reg_num == 0)) {
ERR("!strtol(%p, %p, 10)", reg_id, end_addr);
goto err;
}
errno = olderrno;
if (end_addr == reg_id) {
ERR("!strtol(%p, %p, 10) no digits were found",
reg_id, end_addr);
goto err;
}
if (*end_addr != '\n') {
ERR("!strtol(%s, %s, 10) invalid format",
reg_id, end_addr);
goto err;
}
os_close(dax_reg_id_fd);
return (int)reg_num;
err:
os_close(dax_reg_id_fd);
return -1;
}
| 8,608 | 21.835544 | 78 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/util_pmem.h
|
/*
* Copyright 2017-2018, Intel Corporation
*
* 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_pmem.h -- internal definitions for pmem utils
*/
#ifndef PMDK_UTIL_PMEM_H
#define PMDK_UTIL_PMEM_H 1
#include "libpmem.h"
#include "out.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* util_persist -- flush to persistence
*/
static inline void
util_persist(int is_pmem, const void *addr, size_t len)
{
LOG(3, "is_pmem %d, addr %p, len %zu", is_pmem, addr, len);
if (is_pmem)
pmem_persist(addr, len);
else if (pmem_msync(addr, len))
FATAL("!pmem_msync");
}
/*
* util_persist_auto -- flush to persistence
*/
static inline void
util_persist_auto(int is_pmem, const void *addr, size_t len)
{
LOG(3, "is_pmem %d, addr %p, len %zu", is_pmem, addr, len);
util_persist(is_pmem || pmem_is_pmem(addr, len), addr, len);
}
#ifdef __cplusplus
}
#endif
#endif /* util_pmem.h */
| 2,398 | 30.155844 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/util_posix.c
|
/*
* Copyright 2015-2018, Intel Corporation
*
* 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_posix.c -- Abstraction layer for misc utilities (Posix implementation)
*/
#include <string.h>
#include <util.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include "os.h"
#include "out.h"
/* pass through for Posix */
void
util_strerror(int errnum, char *buff, size_t bufflen)
{
strerror_r(errnum, buff, bufflen);
}
/*
* util_part_realpath -- get canonicalized absolute pathname
*
* As paths used in a poolset file have to be absolute (checked when parsing
* a poolset file), here we only have to resolve symlinks.
*/
char *
util_part_realpath(const char *path)
{
return realpath(path, NULL);
}
/*
* util_compare_file_inodes -- compare device and inodes of two files;
* this resolves hard links
*/
int
util_compare_file_inodes(const char *path1, const char *path2)
{
struct stat sb1, sb2;
if (os_stat(path1, &sb1)) {
if (errno != ENOENT) {
ERR("!stat failed for %s", path1);
return -1;
}
LOG(1, "stat failed for %s", path1);
errno = 0;
return strcmp(path1, path2) != 0;
}
if (os_stat(path2, &sb2)) {
if (errno != ENOENT) {
ERR("!stat failed for %s", path2);
return -1;
}
LOG(1, "stat failed for %s", path2);
errno = 0;
return strcmp(path1, path2) != 0;
}
return sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino;
}
/*
* util_aligned_malloc -- allocate aligned memory
*/
void *
util_aligned_malloc(size_t alignment, size_t size)
{
void *retval = NULL;
errno = posix_memalign(&retval, alignment, size);
return retval;
}
/*
* util_aligned_free -- free allocated memory in util_aligned_malloc
*/
void
util_aligned_free(void *ptr)
{
free(ptr);
}
/*
* util_getexecname -- return name of current executable
*/
char *
util_getexecname(char *path, size_t pathlen)
{
ssize_t cc;
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
cc = (sysctl(mib, 4, path, &pathlen, NULL, 0) == -1) ?
-1 : (ssize_t)pathlen;
#else
cc = readlink("/proc/self/exe", path, pathlen);
#endif
if (cc == -1)
strcpy(path, "unknown");
else
path[cc] = '\0';
return path;
}
| 3,778 | 25.243056 | 78 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/pmemcommon.h
|
/*
* Copyright 2016-2018, Intel Corporation
*
* 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.
*/
/*
* pmemcommon.h -- definitions for "common" module
*/
#ifndef PMEMCOMMON_H
#define PMEMCOMMON_H 1
#include "util.h"
#include "out.h"
#include "mmap.h"
#ifdef __cplusplus
extern "C" {
#endif
static inline void
common_init(const char *log_prefix, const char *log_level_var,
const char *log_file_var, int major_version,
int minor_version)
{
util_init();
out_init(log_prefix, log_level_var, log_file_var, major_version,
minor_version);
util_mmap_init();
}
static inline void
common_fini(void)
{
util_mmap_fini();
out_fini();
}
#ifdef __cplusplus
}
#endif
#endif
| 2,182 | 29.746479 | 74 |
h
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/badblock_linux.c
|
/*
* Copyright 2018, Intel Corporation
*
* 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.
*/
/*
* badblock_linux.c - implementation of the linux bad block API
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/falloc.h>
#include "file.h"
#include "os.h"
#include "out.h"
#include "extent.h"
#include "os_dimm.h"
#include "os_badblock.h"
#include "badblock.h"
#include "vec.h"
/*
* os_badblocks_get -- returns 0 and bad blocks in the 'bbs' array
* (that has to be pre-allocated)
* or -1 in case of an error
*/
int
os_badblocks_get(const char *file, struct badblocks *bbs)
{
LOG(3, "file %s badblocks %p", file, bbs);
ASSERTne(bbs, NULL);
VEC(bbsvec, struct bad_block) bbv = VEC_INITIALIZER;
struct extents *exts = NULL;
long extents = 0;
unsigned long long bb_beg;
unsigned long long bb_end;
unsigned long long bb_len;
unsigned long long bb_off;
unsigned long long ext_beg;
unsigned long long ext_end;
unsigned long long not_block_aligned;
int bb_found = -1; /* -1 means an error */
memset(bbs, 0, sizeof(*bbs));
if (os_dimm_files_namespace_badblocks(file, bbs)) {
LOG(1, "checking the file for bad blocks failed -- '%s'", file);
goto error_free_all;
}
if (bbs->bb_cnt == 0) {
bb_found = 0;
goto exit_free_all;
}
exts = Zalloc(sizeof(struct extents));
if (exts == NULL) {
ERR("!Zalloc");
goto error_free_all;
}
extents = os_extents_count(file, exts);
if (extents < 0) {
LOG(1, "counting file's extents failed -- '%s'", file);
goto error_free_all;
}
if (extents == 0) {
/* dax device has no extents */
bb_found = (int)bbs->bb_cnt;
for (unsigned b = 0; b < bbs->bb_cnt; b++) {
LOG(4, "bad block found: offset: %llu, length: %u",
bbs->bbv[b].offset,
bbs->bbv[b].length);
}
goto exit_free_all;
}
exts->extents = Zalloc(exts->extents_count * sizeof(struct extent));
if (exts->extents == NULL) {
ERR("!Zalloc");
goto error_free_all;
}
if (os_extents_get(file, exts)) {
LOG(1, "getting file's extents failed -- '%s'", file);
goto error_free_all;
}
bb_found = 0;
for (unsigned b = 0; b < bbs->bb_cnt; b++) {
bb_beg = bbs->bbv[b].offset;
bb_end = bb_beg + bbs->bbv[b].length - 1;
for (unsigned e = 0; e < exts->extents_count; e++) {
ext_beg = exts->extents[e].offset_physical;
ext_end = ext_beg + exts->extents[e].length - 1;
/* check if the bad block overlaps with file's extent */
if (bb_beg > ext_end || ext_beg > bb_end)
continue;
bb_found++;
bb_beg = (bb_beg > ext_beg) ? bb_beg : ext_beg;
bb_end = (bb_end < ext_end) ? bb_end : ext_end;
bb_len = bb_end - bb_beg + 1;
bb_off = bb_beg + exts->extents[e].offset_logical
- exts->extents[e].offset_physical;
/* check if offset is block-aligned */
not_block_aligned = bb_off & (exts->blksize - 1);
if (not_block_aligned) {
bb_off -= not_block_aligned;
bb_len += not_block_aligned;
}
/* check if length is block-aligned */
bb_len = ALIGN_UP(bb_len, exts->blksize);
LOG(4, "bad block found: offset: %llu, length: %llu",
bb_off, bb_len);
/*
* Form a new bad block structure with offset and length
* expressed in bytes and offset relative
* to the beginning of the file.
*/
struct bad_block bb;
bb.offset = bb_off;
bb.length = (unsigned)(bb_len);
/* unknown healthy replica */
bb.nhealthy = NO_HEALTHY_REPLICA;
/* add the new bad block to the vector */
if (VEC_PUSH_BACK(&bbv, bb)) {
VEC_DELETE(&bbv);
bb_found = -1;
goto error_free_all;
}
}
}
error_free_all:
Free(bbs->bbv);
bbs->bbv = NULL;
bbs->bb_cnt = 0;
exit_free_all:
if (exts) {
Free(exts->extents);
Free(exts);
}
if (extents > 0 && bb_found > 0) {
bbs->bbv = VEC_ARR(&bbv);
bbs->bb_cnt = (unsigned)VEC_SIZE(&bbv);
LOG(10, "number of bad blocks detected: %u", bbs->bb_cnt);
/* sanity check */
ASSERTeq((unsigned)bb_found, bbs->bb_cnt);
}
return (bb_found >= 0) ? 0 : -1;
}
/*
* os_badblocks_count -- returns number of bad blocks in the file
* or -1 in case of an error
*/
long
os_badblocks_count(const char *file)
{
LOG(3, "file %s", file);
struct badblocks *bbs = badblocks_new();
if (bbs == NULL)
return -1;
int ret = os_badblocks_get(file, bbs);
long count = (ret == 0) ? (long)bbs->bb_cnt : -1;
badblocks_delete(bbs);
return count;
}
/*
* os_badblocks_check_file -- check if the file contains bad blocks
*
* Return value:
* -1 : an error
* 0 : no bad blocks
* 1 : bad blocks detected
*/
int
os_badblocks_check_file(const char *file)
{
LOG(3, "file %s", file);
long bbsc = os_badblocks_count(file);
if (bbsc < 0) {
LOG(1, "counting bad blocks failed -- '%s'", file);
return -1;
}
if (bbsc > 0) {
LOG(1, "pool file '%s' contains %li bad block(s)", file, bbsc);
return 1;
}
return 0;
}
/*
* os_badblocks_clear_file -- clear the given bad blocks in the regular file
* (not in a dax device)
*/
static int
os_badblocks_clear_file(const char *file, struct badblocks *bbs)
{
LOG(3, "file %s badblocks %p", file, bbs);
ASSERTne(bbs, NULL);
int ret = 0;
int fd;
if ((fd = open(file, O_RDWR)) < 0) {
ERR("!open: %s", file);
return -1;
}
for (unsigned b = 0; b < bbs->bb_cnt; b++) {
off_t offset = (off_t)bbs->bbv[b].offset;
off_t length = (off_t)bbs->bbv[b].length;
LOG(10,
"clearing bad block: logical offset %li length %li (in 512B sectors)",
B2SEC(offset), B2SEC(length));
/* deallocate bad blocks */
if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, length)) {
ERR("!fallocate");
ret = -1;
break;
}
/* allocate new blocks */
if (fallocate(fd, FALLOC_FL_KEEP_SIZE, offset, length)) {
ERR("!fallocate");
ret = -1;
break;
}
}
close(fd);
return ret;
}
/*
* os_badblocks_clear -- clears the given bad blocks in a file
* (regular file or dax device)
*/
int
os_badblocks_clear(const char *file, struct badblocks *bbs)
{
LOG(3, "file %s badblocks %p", file, bbs);
ASSERTne(bbs, NULL);
enum file_type type = util_file_get_type(file);
if (type < 0)
return -1;
if (type == TYPE_DEVDAX)
return os_dimm_devdax_clear_badblocks(file, bbs);
return os_badblocks_clear_file(file, bbs);
}
/*
* os_badblocks_clear_all -- clears all bad blocks in a file
* (regular file or dax device)
*/
int
os_badblocks_clear_all(const char *file)
{
LOG(3, "file %s", file);
enum file_type type = util_file_get_type(file);
if (type < 0)
return -1;
if (type == TYPE_DEVDAX)
return os_dimm_devdax_clear_badblocks_all(file);
struct badblocks *bbs = badblocks_new();
if (bbs == NULL)
return -1;
int ret = os_badblocks_get(file, bbs);
if (ret) {
LOG(1, "checking bad blocks in the file failed -- '%s'", file);
goto error_free_all;
}
if (bbs->bb_cnt > 0) {
ret = os_badblocks_clear_file(file, bbs);
if (ret < 0) {
LOG(1, "clearing bad blocks in the file failed -- '%s'",
file);
goto error_free_all;
}
}
error_free_all:
badblocks_delete(bbs);
return ret;
}
| 8,635 | 22.790634 | 76 |
c
|
null |
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/util.c
|
/*
* Copyright 2014-2018, Intel Corporation
*
* 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.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 "util.h"
#include "valgrind_internal.h"
/* library-wide page size */
unsigned long long Pagesize;
/* allocation/mmap granularity */
unsigned long long Mmap_align;
/*
* our versions of malloc & friends start off pointing to the libc versions
*/
Malloc_func Malloc = malloc;
Free_func Free = free;
Realloc_func Realloc = realloc;
Strdup_func Strdup = strdup;
/*
* Zalloc -- allocate zeroed memory
*/
void *
Zalloc(size_t sz)
{
void *ret = Malloc(sz);
if (!ret)
return NULL;
return memset(ret, 0, sz);
}
#if ANY_VG_TOOL_ENABLED
/* initialized to true if the process is running inside Valgrind */
unsigned _On_valgrind;
#endif
#if VG_PMEMCHECK_ENABLED
#define LIB_LOG_LEN 20
#define FUNC_LOG_LEN 50
#define SUFFIX_LEN 7
/* true if pmreorder instrumentization 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 Fletcher64 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.
* 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)
{
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;
uint64_t csum;
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;
}
csum = (uint64_t)hi32 << 32 | lo32;
if (insert) {
*csump = htole64(csum);
return 1;
}
return *csump == htole64(csum);
}
/*
* util_checksum_seq -- compute sequential Fletcher64 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_set_alloc_funcs -- allow one to override malloc, etc.
*/
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))
{
Malloc = (malloc_func == NULL) ? malloc : malloc_func;
Free = (free_func == NULL) ? free : free_func;
Realloc = (realloc_func == NULL) ? realloc : realloc_func;
Strdup = (strdup_func == NULL) ? strdup : strdup_func;
}
/*
* 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_PMEMCHECK_ENABLED
if (On_valgrind) {
char *pmreorder_env = getenv("PMREORDER_EMIT_LOG");
if (pmreorder_env)
_Pmreorder_emit = atoi(pmreorder_env);
} else {
_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
| 9,626 | 22.19759 | 79 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.