Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/common/os_deep_windows.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2017-2018, Intel Corporation */ /* * os_deep_windows.c -- Windows abstraction layer for deep_* functions */ #include <windows.h> #include "out.h" #include "os.h" #include "set.h" #include "libpmem.h" /* * os_range_deep_common -- call msnyc for non DEV dax */ int os_range_deep_common(uintptr_t addr, size_t len) { LOG(3, "os_range_deep_common addr %p len %lu", addr, len); if (len == 0) return 0; return pmem_msync((void *)addr, len); } /* * os_part_deep_common -- common function to handle both * deep_persist and deep_drain part flush cases. */ int os_part_deep_common(struct pool_replica *rep, unsigned partidx, void *addr, size_t len, int flush) { LOG(3, "part %p part %d addr %p len %lu flush %d", rep, partidx, addr, len, flush); if (!rep->is_pmem) { /* * In case of part on non-pmem call msync on the range * to deep flush the data. Deep drain is empty as all * data is msynced to persistence. */ if (!flush) return 0; if (pmem_msync(addr, len)) { LOG(1, "pmem_msync(%p, %lu)", addr, len); return -1; } return 0; } /* Call deep flush if it was requested */ if (flush) { LOG(15, "pmem_deep_flush addr %p, len %lu", addr, len); pmem_deep_flush(addr, len); } /* * Before deep drain call normal drain to ensure that data * is at least in WPQ. */ pmem_drain(); /* * For deep_drain on normal pmem it is enough to * call msync on one page. */ if (pmem_msync(addr, MIN(Pagesize, len))) { LOG(1, "pmem_msync(%p, %lu)", addr, len); return -1; } return 0; }
1,598
20.039474
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/common/mmap_windows.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * Copyright (c) 2015-2017, 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. */ /* * mmap_windows.c -- memory-mapped files for Windows */ #include <sys/mman.h> #include "mmap.h" #include "out.h" /* * util_map_hint_unused -- use VirtualQuery to determine hint address * * This is a helper function for util_map_hint(). * It iterates through memory regions and looks for the first unused address * in the process address space that is: * - greater or equal 'minaddr' argument, * - large enough to hold range of given length, * - aligned to the specified unit. */ char * util_map_hint_unused(void *minaddr, size_t len, size_t align) { LOG(3, "minaddr %p len %zu align %zu", minaddr, len, align); ASSERT(align > 0); MEMORY_BASIC_INFORMATION mi; char *lo = NULL; /* beginning of current range in maps file */ char *hi = NULL; /* end of current range in maps file */ char *raddr = minaddr; /* ignore regions below 'minaddr' */ if (raddr == NULL) raddr += Pagesize; raddr = (char *)roundup((uintptr_t)raddr, align); while ((uintptr_t)raddr < UINTPTR_MAX - len) { size_t ret = VirtualQuery(raddr, &mi, sizeof(mi)); if (ret == 0) { ERR("VirtualQuery %p", raddr); return MAP_FAILED; } LOG(4, "addr %p len %zu state %d", mi.BaseAddress, mi.RegionSize, mi.State); if ((mi.State != MEM_FREE) || (mi.RegionSize < len)) { raddr = (char *)mi.BaseAddress + mi.RegionSize; raddr = (char *)roundup((uintptr_t)raddr, align); LOG(4, "nearest aligned addr %p", raddr); } else { LOG(4, "unused region of size %zu found at %p", mi.RegionSize, mi.BaseAddress); return mi.BaseAddress; } } LOG(4, "end of address space reached"); return MAP_FAILED; } /* * util_map_hint -- determine hint address for mmap() * * XXX - Windows doesn't support large DAX pages yet, so there is * no point in aligning for the same. */ char * util_map_hint(size_t len, size_t req_align) { LOG(3, "len %zu req_align %zu", len, req_align); char *hint_addr = MAP_FAILED; /* choose the desired alignment based on the requested length */ size_t align = util_map_hint_align(len, req_align); if (Mmap_no_random) { LOG(4, "user-defined hint %p", Mmap_hint); hint_addr = util_map_hint_unused(Mmap_hint, len, align); } else { /* * Create dummy mapping to find an unused region of given size. * Request for increased size for later address alignment. * * Use MAP_NORESERVE flag to only reserve the range of pages * rather than commit. We don't want the pages to be actually * backed by the operating system paging file, as the swap * file is usually too small to handle terabyte pools. */ char *addr = mmap(NULL, len + align, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0); if (addr != MAP_FAILED) { LOG(4, "system choice %p", addr); hint_addr = (char *)roundup((uintptr_t)addr, align); munmap(addr, len + align); } } LOG(4, "hint %p", hint_addr); return hint_addr; } /* * util_map_sync -- memory map given file into memory */ void * util_map_sync(void *addr, size_t len, int proto, int flags, int fd, os_off_t offset, int *map_sync) { LOG(15, "addr %p len %zu proto %x flags %x fd %d offset %ld", addr, len, proto, flags, fd, offset); if (map_sync) *map_sync = 0; return mmap(addr, len, proto, flags, fd, offset); }
4,965
31.887417
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/ex_common.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * ex_common.h -- examples utilities */ #ifndef EX_COMMON_H #define EX_COMMON_H #include <stdint.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #ifdef __cplusplus extern "C" { #endif #ifndef _WIN32 #include <unistd.h> #define CREATE_MODE_RW (S_IWUSR | S_IRUSR) /* * file_exists -- checks if file exists */ static inline int file_exists(char const *file) { return access(file, F_OK); } /* * find_last_set_64 -- returns last set bit position or -1 if set bit not found */ static inline int find_last_set_64(uint64_t val) { return 64 - __builtin_clzll(val) - 1; } #else #include <windows.h> #include <corecrt_io.h> #include <process.h> #define CREATE_MODE_RW (S_IWRITE | S_IREAD) /* * file_exists -- checks if file exists */ static inline int file_exists(char const *file) { return _access(file, 0); } /* * find_last_set_64 -- returns last set bit position or -1 if set bit not found */ static inline int find_last_set_64(uint64_t val) { DWORD lz = 0; if (BitScanReverse64(&lz, val)) return (int)lz; else return -1; } #endif #ifdef __cplusplus } #endif #endif /* ex_common.h */
1,199
14.584416
79
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemlog/manpage.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * manpage.c -- simple example for the libpmemlog man page */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #endif #include <string.h> #include <libpmemlog.h> /* size of the pmemlog pool -- 1 GB */ #define POOL_SIZE ((size_t)(1 << 30)) /* * printit -- log processing callback for use with pmemlog_walk() */ static int printit(const void *buf, size_t len, void *arg) { fwrite(buf, len, 1, stdout); return 0; } int main(int argc, char *argv[]) { const char path[] = "/pmem-fs/myfile"; PMEMlogpool *plp; size_t nbyte; char *str; /* create the pmemlog pool or open it if it already exists */ plp = pmemlog_create(path, POOL_SIZE, 0666); if (plp == NULL) plp = pmemlog_open(path); if (plp == NULL) { perror(path); exit(1); } /* how many bytes does the log hold? */ nbyte = pmemlog_nbyte(plp); printf("log holds %zu bytes\n", nbyte); /* append to the log... */ str = "This is the first string appended\n"; if (pmemlog_append(plp, str, strlen(str)) < 0) { perror("pmemlog_append"); exit(1); } str = "This is the second string appended\n"; if (pmemlog_append(plp, str, strlen(str)) < 0) { perror("pmemlog_append"); exit(1); } /* print the log contents */ printf("log contains:\n"); pmemlog_walk(plp, 0, printit, NULL); pmemlog_close(plp); return 0; }
1,456
18.958904
65
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemlog/logfile/addlog.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * addlog -- given a log file, append a log entry * * Usage: * fallocate -l 1G /path/to/pm-aware/file * addlog /path/to/pm-aware/file "first line of entry" "second line" */ #include <ex_common.h> #include <sys/stat.h> #include <stdio.h> #include <fcntl.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <libpmemlog.h> #include "logentry.h" int main(int argc, char *argv[]) { PMEMlogpool *plp; struct logentry header; struct iovec *iovp; struct iovec *next_iovp; int iovcnt; if (argc < 3) { fprintf(stderr, "usage: %s filename lines...\n", argv[0]); exit(1); } const char *path = argv[1]; /* create the log in the given file, or open it if already created */ plp = pmemlog_create(path, 0, CREATE_MODE_RW); if (plp == NULL && (plp = pmemlog_open(path)) == NULL) { perror(path); exit(1); } /* fill in the header */ time(&header.timestamp); header.pid = getpid(); /* * Create an iov for pmemlog_appendv(). For each argument given, * allocate two entries (one for the string, one for the newline * appended to the string). Allocate 1 additional entry for the * header that gets prepended to the entry. */ iovcnt = (argc - 2) * 2 + 2; if ((iovp = malloc(sizeof(*iovp) * iovcnt)) == NULL) { perror("malloc"); exit(1); } next_iovp = iovp; /* put the header into iov first */ next_iovp->iov_base = &header; next_iovp->iov_len = sizeof(header); next_iovp++; /* * Now put each arg in, following it with the string "\n". * Calculate a total character count in header.len along the way. */ header.len = 0; for (int arg = 2; arg < argc; arg++) { /* add the string given */ next_iovp->iov_base = argv[arg]; next_iovp->iov_len = strlen(argv[arg]); header.len += next_iovp->iov_len; next_iovp++; /* add the newline */ next_iovp->iov_base = "\n"; next_iovp->iov_len = 1; header.len += 1; next_iovp++; } /* * pad with NULs (at least one) to align next entry to sizeof(long long) * bytes */ int a = sizeof(long long); int len_to_round = 1 + (a - (header.len + 1) % a) % a; char *buf[sizeof(long long)] = {0}; next_iovp->iov_base = buf; next_iovp->iov_len = len_to_round; header.len += len_to_round; next_iovp++; /* atomically add it all to the log */ if (pmemlog_appendv(plp, iovp, iovcnt) < 0) { perror("pmemlog_appendv"); free(iovp); exit(1); } free(iovp); pmemlog_close(plp); return 0; }
2,511
21.230088
73
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemlog/logfile/logentry.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2017, Intel Corporation */ /* * info prepended to each log entry... */ struct logentry { size_t len; /* length of the rest of the log entry */ time_t timestamp; #ifndef _WIN32 pid_t pid; #else int pid; #endif };
280
15.529412
55
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemlog/logfile/printlog.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * printlog -- given a log file, print the entries * * Usage: * printlog [-t] /path/to/pm-aware/file * * -t option means truncate the file after printing it. */ #include <ex_common.h> #include <stdio.h> #include <fcntl.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <libpmemlog.h> #include "logentry.h" /* * printlog -- callback function called when walking the log */ static int printlog(const void *buf, size_t len, void *arg) { /* first byte after log contents */ const void *endp = (char *)buf + len; /* for each entry in the log... */ while (buf < endp) { struct logentry *headerp = (struct logentry *)buf; buf = (char *)buf + sizeof(struct logentry); /* print the header */ printf("Entry from pid: %d\n", headerp->pid); printf(" Created: %s", ctime(&headerp->timestamp)); printf(" Contents:\n"); /* print the log data itself, it is NUL-terminated */ printf("%s", (char *)buf); buf = (char *)buf + headerp->len; } return 0; } int main(int argc, char *argv[]) { int ind = 1; int tflag = 0; PMEMlogpool *plp; if (argc > 2) { if (strcmp(argv[1], "-t") == 0) { tflag = 1; ind++; } else { fprintf(stderr, "usage: %s [-t] file\n", argv[0]); exit(1); } } const char *path = argv[ind]; if ((plp = pmemlog_open(path)) == NULL) { perror(path); exit(1); } /* the rest of the work happens in printlog() above */ pmemlog_walk(plp, 0, printlog, NULL); if (tflag) pmemlog_rewind(plp); pmemlog_close(plp); return 0; }
1,614
18.457831
60
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/librpmem/basic.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * basic.c -- basic example for the librpmem */ #include <assert.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <librpmem.h> #define POOL_SIZE (32 * 1024 * 1024) #define DATA_OFF 4096 /* pool header size */ #define DATA_SIZE (POOL_SIZE - DATA_OFF) #define NLANES 64 #define SET_POOLSET_UUID 1 #define SET_UUID 2 #define SET_NEXT 3 #define SET_PREV 4 #define SET_FLAGS 5 static void default_attr(struct rpmem_pool_attr *attr) { memset(attr, 0, sizeof(*attr)); attr->major = 1; strncpy(attr->signature, "EXAMPLE", RPMEM_POOL_HDR_SIG_LEN); memset(attr->poolset_uuid, SET_POOLSET_UUID, RPMEM_POOL_HDR_UUID_LEN); memset(attr->uuid, SET_UUID, RPMEM_POOL_HDR_UUID_LEN); memset(attr->next_uuid, SET_NEXT, RPMEM_POOL_HDR_UUID_LEN); memset(attr->prev_uuid, SET_PREV, RPMEM_POOL_HDR_UUID_LEN); memset(attr->user_flags, SET_FLAGS, RPMEM_POOL_USER_FLAGS_LEN); } static int do_create(const char *target, const char *poolset, void *pool) { unsigned nlanes = NLANES; int ret = 0; struct rpmem_pool_attr pool_attr; default_attr(&pool_attr); RPMEMpool *rpp = rpmem_create(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_create: %s\n", rpmem_errormsg()); return 1; } if (rpmem_persist(rpp, DATA_OFF, DATA_SIZE, 0, 0)) { fprintf(stderr, "rpmem_persist: %s\n", rpmem_errormsg()); ret = 1; } if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } return ret; } static int do_open(const char *target, const char *poolset, void *pool) { unsigned nlanes = NLANES; int ret = 0; struct rpmem_pool_attr def_attr; default_attr(&def_attr); struct rpmem_pool_attr pool_attr; RPMEMpool *rpp = rpmem_open(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_open: %s\n", rpmem_errormsg()); return 1; } if (memcmp(&def_attr, &pool_attr, sizeof(def_attr))) { fprintf(stderr, "remote pool not consistent\n"); ret = 1; goto end; } if (rpmem_persist(rpp, DATA_OFF, DATA_SIZE, 0, 0)) { fprintf(stderr, "rpmem_persist: %s\n", rpmem_errormsg()); ret = 1; } end: if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } return ret; } static int do_remove(const char *target, const char *poolset) { if (rpmem_remove(target, poolset, 0)) { fprintf(stderr, "removing pool failed: %s\n", rpmem_errormsg()); return 1; } return 0; } enum op_t {op_create, op_open, op_remove, op_max}; static const char *str2op[] = { [op_create] = "create", [op_open] = "open", [op_remove] = "remove" }; static void parse_args(int argc, char *argv[], enum op_t *op, const char **target, const char **poolset) { if (argc < 4) { fprintf(stderr, "usage:\t%s [create|open|remove] " "<target> <poolset>\n", argv[0]); exit(1); } /* convert string to op */ *op = op_max; const size_t str2op_size = sizeof(str2op) / sizeof(str2op[0]); for (size_t i = 0; i < str2op_size; ++i) { if (strcmp(str2op[i], argv[1]) == 0) { *op = (enum op_t)i; break; } } if (*op == op_max) { fprintf(stderr, "unsupported operation -- '%s'\n", argv[1]); exit(1); } *target = argv[2]; *poolset = argv[3]; } static void * alloc_memory() { long pagesize = sysconf(_SC_PAGESIZE); if (pagesize < 0) { perror("sysconf"); exit(1); } /* allocate a page size aligned local memory pool */ void *mem; int ret = posix_memalign(&mem, pagesize, POOL_SIZE); if (ret) { fprintf(stderr, "posix_memalign: %s\n", strerror(ret)); exit(1); } assert(mem != NULL); return mem; } int main(int argc, char *argv[]) { enum op_t op; const char *target, *poolset; parse_args(argc, argv, &op, &target, &poolset); void *pool = alloc_memory(); int ret = 0; switch (op) { case op_create: ret = do_create(target, poolset, pool); break; case op_open: ret = do_open(target, poolset, pool); break; case op_remove: ret = do_remove(target, poolset); break; default: assert(0); } free(pool); return ret; }
4,173
19.460784
71
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/librpmem/hello.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019, Intel Corporation */ /* * hello.c -- hello world for librpmem */ #include <assert.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <librpmem.h> #define POOL_SIGNATURE "HELLO" enum lang_t {en, es}; static const char *hello_str[] = { [en] = "Hello world!", [es] = "¡Hola Mundo!" }; #define LANG_NUM (sizeof(hello_str) / sizeof(hello_str[0])) #define STR_SIZE 100 struct hello_t { enum lang_t lang; char str[STR_SIZE]; }; #define POOL_SIZE (32 * 1024 * 1024) #define DATA_OFF 4096 /* rpmem header size */ #define NLANES 4 #define DATA_SIZE (sizeof(struct hello_t)) static inline void write_hello_str(struct hello_t *hello, enum lang_t lang) { hello->lang = lang; strncpy(hello->str, hello_str[hello->lang], STR_SIZE); } static void translate(struct hello_t *hello) { printf("translating...\n"); enum lang_t lang = (enum lang_t)((hello->lang + 1) % LANG_NUM); write_hello_str(hello, lang); } static int remote_write(RPMEMpool *rpp) { printf("write message to the target...\n"); if (rpmem_persist(rpp, DATA_OFF, DATA_SIZE, 0, 0)) { printf("upload failed: %s\n", rpmem_errormsg()); return 1; } return 0; } static int remote_read(RPMEMpool *rpp, void *buff) { printf("read message from the target...\n"); if (rpmem_read(rpp, buff, DATA_OFF, DATA_SIZE, 0)) { printf("download failed: %s\n", rpmem_errormsg()); return 1; } return 0; } static RPMEMpool * remote_open(const char *target, const char *poolset, void *pool, int *created) { struct rpmem_pool_attr pool_attr; unsigned nlanes = NLANES; RPMEMpool *rpp; /* fill pool_attributes */ memset(&pool_attr, 0, sizeof(pool_attr)); strncpy(pool_attr.signature, POOL_SIGNATURE, RPMEM_POOL_HDR_SIG_LEN); /* create a remote pool */ rpp = rpmem_create(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (rpp) { memset(pool, 0, POOL_SIZE); *created = 1; return rpp; } if (errno != EEXIST) { fprintf(stderr, "rpmem_create: %s\n", rpmem_errormsg()); return NULL; } /* open a remote pool */ rpp = rpmem_open(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_open: %s\n", rpmem_errormsg()); return NULL; } /* verify signature */ if (strcmp(pool_attr.signature, POOL_SIGNATURE) != 0) { fprintf(stderr, "invalid signature\n"); goto err; } *created = 0; return rpp; err: /* close the remote pool */ if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } return NULL; } static void parse_args(int argc, char *argv[], const char **target, const char **poolset) { if (argc < 3) { fprintf(stderr, "usage:\t%s <target> <poolset>\n" "\n" "e.g.:\t%s localhost pool.set\n", argv[0], argv[0]); exit(1); } *target = argv[1]; *poolset = argv[2]; } static void * alloc_memory() { long pagesize = sysconf(_SC_PAGESIZE); if (pagesize < 0) { perror("sysconf"); return NULL; } /* allocate a page size aligned local memory pool */ void *mem; int ret = posix_memalign(&mem, pagesize, POOL_SIZE); if (ret) { fprintf(stderr, "posix_memalign: %s\n", strerror(ret)); return NULL; } return mem; } int main(int argc, char *argv[]) { const char *target, *poolset; parse_args(argc, argv, &target, &poolset); void *pool = alloc_memory(); if (!pool) exit(1); struct hello_t *hello = (struct hello_t *)(pool + DATA_OFF); int created; int ret; RPMEMpool *rpp = remote_open(target, poolset, pool, &created); if (!rpp) { ret = 1; goto exit_free; } if (created) { write_hello_str(hello, en); } else { ret = remote_read(rpp, hello); if (ret) goto exit_close; printf("\n%s\n\n", hello->str); translate(hello); } ret = remote_write(rpp); if (ret) goto exit_close; printf("rerun application to read the translation.\n"); exit_close: /* close the remote pool */ if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } exit_free: free(pool); return ret; }
4,087
18.374408
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/librpmem/manpage.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * manpage.c -- example from librpmem manpage */ #include <assert.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <librpmem.h> #define POOL_SIGNATURE "MANPAGE" #define POOL_SIZE (32 * 1024 * 1024) #define NLANES 4 #define DATA_OFF 4096 #define DATA_SIZE (POOL_SIZE - DATA_OFF) static void parse_args(int argc, char *argv[], const char **target, const char **poolset) { if (argc < 3) { fprintf(stderr, "usage:\t%s <target> <poolset>\n", argv[0]); exit(1); } *target = argv[1]; *poolset = argv[2]; } static void * alloc_memory() { long pagesize = sysconf(_SC_PAGESIZE); if (pagesize < 0) { perror("sysconf"); exit(1); } /* allocate a page size aligned local memory pool */ void *mem; int ret = posix_memalign(&mem, pagesize, POOL_SIZE); if (ret) { fprintf(stderr, "posix_memalign: %s\n", strerror(ret)); exit(1); } assert(mem != NULL); return mem; } int main(int argc, char *argv[]) { const char *target, *poolset; parse_args(argc, argv, &target, &poolset); unsigned nlanes = NLANES; void *pool = alloc_memory(); int ret; /* fill pool_attributes */ struct rpmem_pool_attr pool_attr; memset(&pool_attr, 0, sizeof(pool_attr)); strncpy(pool_attr.signature, POOL_SIGNATURE, RPMEM_POOL_HDR_SIG_LEN); /* create a remote pool */ RPMEMpool *rpp = rpmem_create(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_create: %s\n", rpmem_errormsg()); return 1; } /* store data on local pool */ memset(pool, 0, POOL_SIZE); /* make local data persistent on remote node */ ret = rpmem_persist(rpp, DATA_OFF, DATA_SIZE, 0, 0); if (ret) { fprintf(stderr, "rpmem_persist: %s\n", rpmem_errormsg()); return 1; } /* close the remote pool */ ret = rpmem_close(rpp); if (ret) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); return 1; } free(pool); return 0; }
2,002
19.03
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/librpmem/fibonacci/fibonacci.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019, Intel Corporation */ /* * fibonacci.c -- fibonacci sequence generator for librpmem */ #include <assert.h> #include <errno.h> #include <time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libpmem.h> #include <librpmem.h> #define POOL_SIGNATURE "FIBO" #define FIBO_SIG_LEN RPMEM_POOL_HDR_SIG_LEN struct fibo_t { char signature[FIBO_SIG_LEN]; unsigned n; /* index */ uint64_t fn; /* F_{n} */ uint64_t fn1; /* F_{n + 1} */ int checksum; }; #define POOL_SIZE (size_t)(32 * 1024 * 1024) #define RPMEM_HDR_SIZE 4096 #define FIBO_OFF RPMEM_HDR_SIZE #define FIBO_SIZE (sizeof(struct fibo_t)) #define RESERVED_SIZE (POOL_SIZE - RPMEM_HDR_SIZE - FIBO_SIZE) struct pool_t { unsigned char pool_hdr[RPMEM_HDR_SIZE]; struct fibo_t fibo; unsigned char reserved[RESERVED_SIZE]; }; #define NLANES 4 #define BROKEN_LOCAL (1 << 0) #define BROKEN_REMOTE (1 << 1) static int fibo_checksum(struct fibo_t *fibo) { return fibo->signature[0] + fibo->fn + fibo->fn1; } static void fibo_init(struct fibo_t *fibo) { printf("initializing...\n"); memset(fibo, 0, FIBO_SIZE); strncpy(fibo->signature, POOL_SIGNATURE, FIBO_SIG_LEN); fibo->n = 0; fibo->fn = 0; fibo->fn1 = 1; fibo->checksum = fibo_checksum(fibo); pmem_persist(fibo, FIBO_SIZE); } static int fibo_is_valid(struct fibo_t *fibo) { if (strncmp(fibo->signature, POOL_SIGNATURE, FIBO_SIG_LEN) != 0) return 0; return fibo->checksum == fibo_checksum(fibo); } static int fibo_is_zeroed(struct fibo_t *fibo) { char *data = (char *)fibo; for (size_t i = 0; i < FIBO_SIZE; ++i) if (data[i] != 0) return 0; return 1; } /* * fibo_validate -- validate local and remote copies of the F sequence */ static struct fibo_t * fibo_validate(struct fibo_t *fibo, struct fibo_t *fibo_r, unsigned *state) { struct fibo_t *valid = NULL; if (fibo_is_valid(fibo)) valid = fibo; else if (!fibo_is_zeroed(fibo)) { fprintf(stderr, "broken local memory pool!\n"); *state |= BROKEN_LOCAL; } if (fibo_is_valid(fibo_r)) { if (!valid) valid = fibo_r; else if (fibo_r->n > valid->n) valid = fibo_r; } else if (!fibo_is_zeroed(fibo_r)) { fprintf(stderr, "broken remote memory pool!\n"); *state |= BROKEN_REMOTE; } if (!valid) fprintf(stderr, "no valid Fibonacci numbers found.\n"); return valid; } /* * fibo_recovery -- based on validation outcome cleanup copies and initialize * if required */ static int fibo_recovery(RPMEMpool *rpp, struct pool_t *pool, struct fibo_t *fibo_r, int *initialized) { struct fibo_t *fibo = &pool->fibo; unsigned state = 0; int ret; struct fibo_t *valid = fibo_validate(fibo, fibo_r, &state); /* store valid fibonacci data in local */ if (valid) { if (valid != fibo) pmem_memcpy_persist(fibo, valid, FIBO_SIZE); *initialized = 0; } else { /* init local */ fibo_init(fibo); *initialized = 1; } /* local cleanup */ if (state & BROKEN_LOCAL) { /* zero reserved parts */ memset(pool->pool_hdr, 0, RPMEM_HDR_SIZE); memset(pool->reserved, 0, RESERVED_SIZE); pmem_persist(pool, POOL_SIZE); } /* remote cleanup */ if (state & BROKEN_REMOTE) { /* replicate data + reserved */ ret = rpmem_persist(rpp, FIBO_OFF, POOL_SIZE - FIBO_OFF, 0, 0); if (ret) { fprintf(stderr, "remote recovery failed: %s\n", rpmem_errormsg()); return ret; } } return 0; } /* * fibo_generate -- generate next Fibonacci number */ static void fibo_generate(struct fibo_t *fibo) { uint64_t fn2 = fibo->fn1 + fibo->fn; if (fn2 < fibo->fn1) { printf("overflow detected!\n"); fibo_init(fibo); return; } fibo->fn = fibo->fn1; fibo->fn1 = fn2; ++fibo->n; fibo->checksum = fibo_checksum(fibo); pmem_persist(fibo, FIBO_SIZE); } static void fibo_print(struct fibo_t *fibo) { if (fibo->n == 0) printf("F[0] = %lu\n", fibo->fn); printf("F[%u] = %lu\n", fibo->n + 1, fibo->fn1); } /* * remote_create_or_open -- create or open the remote replica */ static RPMEMpool * remote_create_or_open(const char *target, const char *poolset, struct pool_t *pool, int *created) { struct rpmem_pool_attr pool_attr; unsigned nlanes = NLANES; *created = 1; RPMEMpool *rpp; /* fill pool_attributes */ memset(&pool_attr, 0, sizeof(pool_attr)); strncpy(pool_attr.signature, POOL_SIGNATURE, RPMEM_POOL_HDR_SIG_LEN); /* create a remote pool */ rpp = rpmem_create(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (rpp) goto verify; if (errno != EEXIST) { fprintf(stderr, "rpmem_create: %s\n", rpmem_errormsg()); return NULL; } /* the remote pool exists */ *created = 0; /* open a remote pool */ rpp = rpmem_open(target, poolset, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_open: %s\n", rpmem_errormsg()); return NULL; } verify: /* verify signature */ if (strcmp(pool_attr.signature, POOL_SIGNATURE) != 0) { fprintf(stderr, "invalid signature\n"); goto err; } return rpp; err: /* close the remote pool */ if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } return NULL; } static int remote_write(RPMEMpool *rpp) { printf("storing Fibonacci numbers on the target...\n"); if (rpmem_persist(rpp, FIBO_OFF, FIBO_SIZE, 0, 0)) { printf("store failed: %s\n", rpmem_errormsg()); return 1; } return 0; } static int remote_read(RPMEMpool *rpp, void *buff) { printf("restore Fibonacci numbers from the target...\n"); if (rpmem_read(rpp, buff, FIBO_OFF, FIBO_SIZE, 0)) { printf("restore failed: %s\n", rpmem_errormsg()); return 1; } return 0; } static void parse_args(int argc, char *argv[], const char **target, const char **poolset, const char **path) { if (argc < 4) { fprintf(stderr, "usage:\t%s <target> <poolset> <path>\n", argv[0]); exit(1); } *target = argv[1]; *poolset = argv[2]; *path = argv[3]; } static struct pool_t * map_pmem(const char *path, size_t *mapped_len) { int is_pmem; struct pool_t *pool = pmem_map_file(path, 0, 0, 0, mapped_len, &is_pmem); if (!pool) return NULL; if (!is_pmem) { fprintf(stderr, "is not persistent memory: %s\n", path); goto err; } if (*mapped_len < POOL_SIZE) { fprintf(stderr, "too small: %ld < %ld\n", *mapped_len, POOL_SIZE); goto err; } return pool; err: pmem_unmap(pool, *mapped_len); exit(1); } int main(int argc, char *argv[]) { const char *target, *poolset, *path; parse_args(argc, argv, &target, &poolset, &path); struct fibo_t fibo_r; /* copy from remote */ int created; /* remote: 1 == created, 0 == opened */ int initialized; /* sequence: 1 == initialized, 0 = con be continued */ int ret; /* map local pool */ size_t mapped_len; struct pool_t *pool = map_pmem(path, &mapped_len); /* open remote pool */ RPMEMpool *rpp = remote_create_or_open(target, poolset, pool, &created); if (!rpp) { ret = 1; goto unmap; } if (created) { /* zero remote copy */ memset(&fibo_r, 0, FIBO_SIZE); } else { /* restore from remote */ ret = remote_read(rpp, &fibo_r); if (ret) { /* invalidate remote copy */ memset(&fibo_r, 1, FIBO_SIZE); } } /* validate copies from local and remote */ ret = fibo_recovery(rpp, pool, &fibo_r, &initialized); if (ret) { fprintf(stderr, "recovery failed.\n"); goto err; } /* generate new number */ if (!initialized) fibo_generate(&pool->fibo); fibo_print(&pool->fibo); /* store to remote */ ret = remote_write(rpp); if (ret) goto err; printf("rerun application to generate next Fibonacci number.\n"); err: /* close the remote pool */ if (rpmem_close(rpp)) { fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); exit(1); } unmap: pmem_unmap(pool, mapped_len); return ret; }
7,755
19.682667
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/pmreorder/pmreorder_list.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018-2019, Intel Corporation */ /* * pmreorder_list.c -- explains how to use pmreorder tool with libpmem * * usage: pmreorder_list <g|b|c> <path> * g - good case - add element to the list in a consistent way * b - bad case - add element to the list in an inconsistent way * c - check persistent consistency of the list */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libpmem.h> #define MAX_NODES 10 #define NODE_PTR(root, node_id) \ (node_id == 0 ? NULL : &(root)->nodes[(node_id)]) typedef size_t node_id; struct list_node { int value; node_id next; }; struct list_root { node_id head; struct list_node nodes[MAX_NODES]; }; /* * check_consistency -- check if list meets the set requirements * * for consistent cases function returns 0 * for inconsistent cases function returns 1 */ static int check_consistency(struct list_root *root) { struct list_node *node = NODE_PTR(root, root->head); /* * If node is linked to the list then its * value should be set properly. */ if (node == NULL) return 0; do { if (node->value == 0) return 1; node = NODE_PTR(root, node->next); } while (node != NULL); return 0; } /* * list_print -- print all elements to the screen */ static void list_print(struct list_root *list) { FILE *fp; fp = fopen("pmreorder_list.log", "w+"); if (fp == NULL) { perror("fopen pmreorder_list.log"); exit(1); } fprintf(fp, "List:\n"); struct list_node *node = NODE_PTR(list, list->head); if (node == NULL) { fprintf(fp, "List is empty"); goto end; } do { fprintf(fp, "Value: %d\n", node->value); node = NODE_PTR(list, node->next); } while (node != NULL); end: fclose(fp); } /* * list_insert_consistent -- add new element to the list in a consistent way */ static void list_insert_consistent(struct list_root *root, node_id node, int value) { struct list_node *new = NODE_PTR(root, node); new->value = value; new->next = root->head; pmem_persist(new, sizeof(*new)); root->head = node; pmem_persist(&root->head, sizeof(root->head)); } /* * list_insert_inconsistent -- add new element to the list * in an inconsistent way */ static void list_insert_inconsistent(struct list_root *root, node_id node, int value) { struct list_node *new = NODE_PTR(root, node); new->next = root->head; pmem_persist(&new->next, sizeof(node)); root->head = node; pmem_persist(&root->head, sizeof(root->head)); new->value = value; pmem_persist(&new->value, sizeof(value)); } int main(int argc, char *argv[]) { void *pmemaddr; size_t mapped_len; int is_pmem; int check; if (argc != 3 || strchr("cgb", argv[1][0]) == NULL || argv[1][1] != '\0') { printf("Usage: pmreorder_list <c|g|b> <path>\n"); exit(1); } /* create a pmem file and memory map it */ pmemaddr = pmem_map_file(argv[2], 0, 0, 0, &mapped_len, &is_pmem); if (pmemaddr == NULL) { perror("pmem_map_file"); exit(1); } struct list_root *r = pmemaddr; char opt = argv[1][0]; if (strchr("gb", opt)) pmem_memset_persist(r, 0, sizeof(struct list_root) + sizeof(struct list_node) * MAX_NODES); switch (opt) { case 'g': list_insert_consistent(r, 5, 55); list_insert_consistent(r, 3, 33); list_insert_consistent(r, 6, 66); break; case 'b': list_insert_inconsistent(r, 5, 55); list_insert_inconsistent(r, 3, 33); list_insert_inconsistent(r, 6, 66); break; case 'c': check = check_consistency(r); return check; default: printf("Unrecognized option: %c\n", opt); abort(); } list_print(r); pmem_unmap(pmemaddr, mapped_len); return 0; }
3,638
19.559322
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/manpage.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * manpage.c -- simple example for the libpmemblk man page */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #endif #include <string.h> #include <libpmemblk.h> /* size of the pmemblk pool -- 1 GB */ #define POOL_SIZE ((size_t)(1 << 30)) /* size of each element in the pmem pool */ #define ELEMENT_SIZE 1024 int main(int argc, char *argv[]) { const char path[] = "/pmem-fs/myfile"; PMEMblkpool *pbp; size_t nelements; char buf[ELEMENT_SIZE]; /* create the pmemblk pool or open it if it already exists */ pbp = pmemblk_create(path, ELEMENT_SIZE, POOL_SIZE, 0666); if (pbp == NULL) pbp = pmemblk_open(path, ELEMENT_SIZE); if (pbp == NULL) { perror(path); exit(1); } /* how many elements fit into the file? */ nelements = pmemblk_nblock(pbp); printf("file holds %zu elements\n", nelements); /* store a block at index 5 */ strcpy(buf, "hello, world"); if (pmemblk_write(pbp, buf, 5) < 0) { perror("pmemblk_write"); exit(1); } /* read the block at index 10 (reads as zeros initially) */ if (pmemblk_read(pbp, buf, 10) < 0) { perror("pmemblk_read"); exit(1); } /* zero out the block at index 5 */ if (pmemblk_set_zero(pbp, 5) < 0) { perror("pmemblk_set_zero"); exit(1); } /* ... */ pmemblk_close(pbp); return 0; }
1,422
19.042254
62
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/assetdb/asset_checkout.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * asset_checkout -- mark an asset as checked out to someone * * Usage: * asset_checkin /path/to/pm-aware/file asset-ID name */ #include <ex_common.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <assert.h> #include <libpmemblk.h> #include "asset.h" int main(int argc, char *argv[]) { PMEMblkpool *pbp; struct asset asset; int assetid; if (argc < 4) { fprintf(stderr, "usage: %s assetdb asset-ID name\n", argv[0]); exit(1); } const char *path = argv[1]; assetid = atoi(argv[2]); assert(assetid > 0); /* open an array of atomically writable elements */ if ((pbp = pmemblk_open(path, sizeof(struct asset))) == NULL) { perror("pmemblk_open"); exit(1); } /* read a required element in */ if (pmemblk_read(pbp, &asset, assetid) < 0) { perror("pmemblk_read"); exit(1); } /* check if it contains any data */ if ((asset.state != ASSET_FREE) && (asset.state != ASSET_CHECKED_OUT)) { fprintf(stderr, "Asset ID %d not found", assetid); exit(1); } if (asset.state == ASSET_CHECKED_OUT) { fprintf(stderr, "Asset ID %d already checked out\n", assetid); exit(1); } /* update user name, set checked out state, and take timestamp */ strncpy(asset.user, argv[3], ASSET_USER_NAME_MAX - 1); asset.user[ASSET_USER_NAME_MAX - 1] = '\0'; asset.state = ASSET_CHECKED_OUT; time(&asset.time); /* put it back in the block */ if (pmemblk_write(pbp, &asset, assetid) < 0) { perror("pmemblk_write"); exit(1); } pmemblk_close(pbp); return 0; }
1,634
20.233766
66
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/assetdb/asset_list.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * asset_list -- list all assets in an assetdb file * * Usage: * asset_list /path/to/pm-aware/file */ #include <ex_common.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <libpmemblk.h> #include "asset.h" int main(int argc, char *argv[]) { PMEMblkpool *pbp; size_t nelements; struct asset asset; if (argc < 2) { fprintf(stderr, "usage: %s assetdb\n", argv[0]); exit(1); } const char *path = argv[1]; /* open an array of atomically writable elements */ if ((pbp = pmemblk_open(path, sizeof(struct asset))) == NULL) { perror(path); exit(1); } /* how many elements do we have? */ nelements = pmemblk_nblock(pbp); /* print out all the elements that contain assets data */ for (size_t assetid = 0; assetid < nelements; ++assetid) { if (pmemblk_read(pbp, &asset, assetid) < 0) { perror("pmemblk_read"); exit(1); } if ((asset.state != ASSET_FREE) && (asset.state != ASSET_CHECKED_OUT)) { break; } printf("Asset ID: %zu\n", assetid); if (asset.state == ASSET_FREE) printf(" State: Free\n"); else { printf(" State: Checked out\n"); printf(" User: %s\n", asset.user); printf(" Time: %s", ctime(&asset.time)); } printf(" Name: %s\n", asset.name); } pmemblk_close(pbp); return 0; }
1,413
19.2
64
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/assetdb/asset_checkin.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * asset_checkin -- mark an asset as no longer checked out * * Usage: * asset_checkin /path/to/pm-aware/file asset-ID */ #include <ex_common.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <assert.h> #include <libpmemblk.h> #include "asset.h" int main(int argc, char *argv[]) { PMEMblkpool *pbp; struct asset asset; int assetid; if (argc < 3) { fprintf(stderr, "usage: %s assetdb asset-ID\n", argv[0]); exit(1); } const char *path = argv[1]; assetid = atoi(argv[2]); assert(assetid > 0); /* open an array of atomically writable elements */ if ((pbp = pmemblk_open(path, sizeof(struct asset))) == NULL) { perror("pmemblk_open"); exit(1); } /* read a required element in */ if (pmemblk_read(pbp, &asset, assetid) < 0) { perror("pmemblk_read"); exit(1); } /* check if it contains any data */ if ((asset.state != ASSET_FREE) && (asset.state != ASSET_CHECKED_OUT)) { fprintf(stderr, "Asset ID %d not found\n", assetid); exit(1); } /* change state to free, clear user name and timestamp */ asset.state = ASSET_FREE; asset.user[0] = '\0'; asset.time = 0; if (pmemblk_write(pbp, &asset, assetid) < 0) { perror("pmemblk_write"); exit(1); } pmemblk_close(pbp); return 0; }
1,375
18.657143
64
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/assetdb/asset_load.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * asset_load -- given pre-allocated assetdb file, load it up with assets * * Usage: * fallocate -l 1G /path/to/pm-aware/file * asset_load /path/to/pm-aware/file asset-file * * The asset-file should contain the names of the assets, one per line. */ #include <ex_common.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <libpmemblk.h> #include "asset.h" int main(int argc, char *argv[]) { FILE *fp; int len = ASSET_NAME_MAX; PMEMblkpool *pbp; size_t assetid = 0; size_t nelements; char *line; if (argc < 3) { fprintf(stderr, "usage: %s assetdb assetlist\n", argv[0]); exit(1); } const char *path_pool = argv[1]; const char *path_list = argv[2]; /* create pmemblk pool in existing (but as yet unmodified) file */ pbp = pmemblk_create(path_pool, sizeof(struct asset), 0, CREATE_MODE_RW); if (pbp == NULL) { perror(path_pool); exit(1); } nelements = pmemblk_nblock(pbp); if ((fp = fopen(path_list, "r")) == NULL) { perror(path_list); exit(1); } /* * Read in all the assets from the assetfile and put them in the * array, if a name of the asset is longer than ASSET_NAME_SIZE_MAX, * truncate it. */ line = malloc(len); if (line == NULL) { perror("malloc"); exit(1); } while (fgets(line, len, fp) != NULL) { struct asset asset; if (assetid >= nelements) { fprintf(stderr, "%s: too many assets to fit in %s " "(only %zu assets loaded)\n", path_list, path_pool, assetid); exit(1); } memset(&asset, '\0', sizeof(asset)); asset.state = ASSET_FREE; strncpy(asset.name, line, ASSET_NAME_MAX - 1); asset.name[ASSET_NAME_MAX - 1] = '\0'; if (pmemblk_write(pbp, &asset, assetid) < 0) { perror("pmemblk_write"); exit(1); } assetid++; } free(line); fclose(fp); pmemblk_close(pbp); return 0; }
1,965
19.061224
73
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemblk/assetdb/asset.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2017, Intel Corporation */ #define ASSET_NAME_MAX 256 #define ASSET_USER_NAME_MAX 64 #define ASSET_CHECKED_OUT 2 #define ASSET_FREE 1 struct asset { char name[ASSET_NAME_MAX]; char user[ASSET_USER_NAME_MAX]; time_t time; int state; };
300
19.066667
44
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/buffons_needle_problem.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019, Intel Corporation */ /* * buffons_needle_problem.c <path> [<n>] -- example illustrating * usage of libpmemobj * * Calculates pi number by solving Buffon's needle problem. * Takes one/two arguments -- path of the file and integer amount of trials * or only path when continuing simulation after interruption. * The greater number of trials, the higher calculation precision. */ #include <ex_common.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include <math.h> #include <time.h> #include <libpmemobj.h> /* * Layout definition */ POBJ_LAYOUT_BEGIN(pi); POBJ_LAYOUT_ROOT(pi, struct my_root) POBJ_LAYOUT_END(pi) /* * Used for changing degrees into radians */ #define RADIAN_CALCULATE M_PI / 180.0 static PMEMobjpool *pop; struct my_root { double x; /* coordinate of the needle's center */ double angle; /* angle between vertical position and the needle */ double l; /* length of the needle */ double sin_angle_l; /* sin(angle) * l */ double pi; /* calculated pi number */ double d; /* distance between lines on the board */ uint64_t i; /* variable used in for loop */ uint64_t p; /* amount of the positive trials */ uint64_t n; /* amount of the trials */ }; static void print_usage(char *argv_main[]) { printf("usage: %s <path> [<n>]\n", argv_main[0]); } /* * random_number -- randomizes number in range [0,1] */ static double random_number(void) { return (double)rand() / (double)RAND_MAX; } int main(int argc, char *argv[]) { if (argc < 2 || argc > 3) { print_usage(argv); return 1; } const char *path = argv[1]; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(pi), PMEMOBJ_MIN_POOL, 0666)) == NULL) { perror("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(pi))) == NULL) { perror("failed to open pool\n"); return 1; } } srand((unsigned int)time(NULL)); TOID(struct my_root) root = POBJ_ROOT(pop, struct my_root); struct my_root *const rootp_rw = D_RW(root); if (argc == 3) { const char *n = argv[2]; char *endptr; errno = 0; uint64_t ull_n = strtoull(n, &endptr, 10); if (*endptr != '\0' || (ull_n == ULLONG_MAX && errno == ERANGE)) { perror("wrong n parameter\n"); print_usage(argv); pmemobj_close(pop); return 1; } TX_BEGIN(pop) { TX_ADD(root); rootp_rw->l = 0.9; rootp_rw->d = 1.0; rootp_rw->i = 0; rootp_rw->p = 0; rootp_rw->n = ull_n; } TX_END } for (; rootp_rw->i < rootp_rw->n; ) { TX_BEGIN(pop) { TX_ADD(root); rootp_rw->angle = random_number() * 90 * RADIAN_CALCULATE; rootp_rw->x = random_number() * rootp_rw->d / 2; rootp_rw->sin_angle_l = rootp_rw->l / 2 * sin(rootp_rw->angle); if (rootp_rw->x <= rootp_rw->sin_angle_l) { rootp_rw->p++; } rootp_rw->pi = (2 * rootp_rw->l * rootp_rw->n) / (rootp_rw->p * rootp_rw->d); rootp_rw->i++; } TX_END } printf("%f\n", D_RO(root)->pi); pmemobj_close(pop); return 0; }
3,119
20.22449
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/manpage.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2014-2019, Intel Corporation */ /* * manpage.c -- simple example for the libpmemobj man page */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #endif #include <stdint.h> #include <string.h> #include <libpmemobj.h> /* size of the pmemobj pool -- 1 GB */ #define POOL_SIZE ((size_t)(1 << 30)) /* name of our layout in the pool */ #define LAYOUT_NAME "example_layout" int main(int argc, char *argv[]) { const char path[] = "/pmem-fs/myfile"; PMEMobjpool *pop; /* create the pmemobj pool or open it if it already exists */ pop = pmemobj_create(path, LAYOUT_NAME, POOL_SIZE, 0666); if (pop == NULL) pop = pmemobj_open(path, LAYOUT_NAME); if (pop == NULL) { perror(path); exit(1); } /* ... */ pmemobj_close(pop); return 0; }
869
17.510638
62
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/btree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * btree.c -- implementation of persistent binary search tree */ #include <ex_common.h> #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <libpmemobj.h> POBJ_LAYOUT_BEGIN(btree); POBJ_LAYOUT_ROOT(btree, struct btree); POBJ_LAYOUT_TOID(btree, struct btree_node); POBJ_LAYOUT_END(btree); struct btree_node { int64_t key; TOID(struct btree_node) slots[2]; char value[]; }; struct btree { TOID(struct btree_node) root; }; struct btree_node_arg { size_t size; int64_t key; const char *value; }; /* * btree_node_construct -- constructor of btree node */ static int btree_node_construct(PMEMobjpool *pop, void *ptr, void *arg) { struct btree_node *node = (struct btree_node *)ptr; struct btree_node_arg *a = (struct btree_node_arg *)arg; node->key = a->key; strcpy(node->value, a->value); node->slots[0] = TOID_NULL(struct btree_node); node->slots[1] = TOID_NULL(struct btree_node); pmemobj_persist(pop, node, a->size); return 0; } /* * btree_insert -- inserts new element into the tree */ static void btree_insert(PMEMobjpool *pop, int64_t key, const char *value) { TOID(struct btree) btree = POBJ_ROOT(pop, struct btree); TOID(struct btree_node) *dst = &D_RW(btree)->root; while (!TOID_IS_NULL(*dst)) { dst = &D_RW(*dst)->slots[key > D_RO(*dst)->key]; } struct btree_node_arg args; args.size = sizeof(struct btree_node) + strlen(value) + 1; args.key = key; args.value = value; POBJ_ALLOC(pop, dst, struct btree_node, args.size, btree_node_construct, &args); } /* * btree_find -- searches for key in the tree */ static const char * btree_find(PMEMobjpool *pop, int64_t key) { TOID(struct btree) btree = POBJ_ROOT(pop, struct btree); TOID(struct btree_node) node = D_RO(btree)->root; while (!TOID_IS_NULL(node)) { if (D_RO(node)->key == key) return D_RO(node)->value; else node = D_RO(node)->slots[key > D_RO(node)->key]; } return NULL; } /* * btree_node_print -- prints content of the btree node */ static void btree_node_print(const TOID(struct btree_node) node) { printf("%" PRIu64 " %s\n", D_RO(node)->key, D_RO(node)->value); } /* * btree_foreach -- invoke callback for every node */ static void btree_foreach(PMEMobjpool *pop, const TOID(struct btree_node) node, void(*cb)(const TOID(struct btree_node) node)) { if (TOID_IS_NULL(node)) return; btree_foreach(pop, D_RO(node)->slots[0], cb); cb(node); btree_foreach(pop, D_RO(node)->slots[1], cb); } /* * btree_print -- initiates foreach node print */ static void btree_print(PMEMobjpool *pop) { TOID(struct btree) btree = POBJ_ROOT(pop, struct btree); btree_foreach(pop, D_RO(btree)->root, btree_node_print); } int main(int argc, char *argv[]) { if (argc < 3) { printf("usage: %s file-name [p|i|f] [key] [value] \n", argv[0]); return 1; } const char *path = argv[1]; PMEMobjpool *pop; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(btree), PMEMOBJ_MIN_POOL, 0666)) == NULL) { perror("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(btree))) == NULL) { perror("failed to open pool\n"); return 1; } } const char op = argv[2][0]; int64_t key; const char *value; switch (op) { case 'p': btree_print(pop); break; case 'i': key = atoll(argv[3]); value = argv[4]; btree_insert(pop, key, value); break; case 'f': key = atoll(argv[3]); if ((value = btree_find(pop, key)) != NULL) printf("%s\n", value); else printf("not found\n"); break; default: printf("invalid operation\n"); break; } pmemobj_close(pop); return 0; }
3,779
19
67
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pi.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * pi.c -- example usage of user lists * * Calculates pi number with multiple threads using Leibniz formula. */ #include <ex_common.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <assert.h> #include <inttypes.h> #include <libpmemobj.h> #ifndef _WIN32 #include <pthread.h> #endif /* * Layout definition */ POBJ_LAYOUT_BEGIN(pi); POBJ_LAYOUT_ROOT(pi, struct pi); POBJ_LAYOUT_TOID(pi, struct pi_task); POBJ_LAYOUT_END(pi); static PMEMobjpool *pop; struct pi_task_proto { uint64_t start; uint64_t stop; long double result; }; struct pi_task { struct pi_task_proto proto; POBJ_LIST_ENTRY(struct pi_task) todo; POBJ_LIST_ENTRY(struct pi_task) done; }; struct pi { POBJ_LIST_HEAD(todo, struct pi_task) todo; POBJ_LIST_HEAD(done, struct pi_task) done; }; /* * pi_task_construct -- task constructor */ static int pi_task_construct(PMEMobjpool *pop, void *ptr, void *arg) { struct pi_task *t = (struct pi_task *)ptr; struct pi_task_proto *p = (struct pi_task_proto *)arg; t->proto = *p; pmemobj_persist(pop, t, sizeof(*t)); return 0; } /* * calc_pi -- worker for pi calculation */ #ifndef _WIN32 static void * calc_pi(void *arg) #else static DWORD WINAPI calc_pi(LPVOID arg) #endif { TOID(struct pi) pi = POBJ_ROOT(pop, struct pi); TOID(struct pi_task) task = *((TOID(struct pi_task) *)arg); long double result = 0; for (uint64_t i = D_RO(task)->proto.start; i < D_RO(task)->proto.stop; ++i) { result += (pow(-1, (double)i) / (2 * i + 1)); } D_RW(task)->proto.result = result; pmemobj_persist(pop, &D_RW(task)->proto.result, sizeof(result)); POBJ_LIST_MOVE_ELEMENT_HEAD(pop, &D_RW(pi)->todo, &D_RW(pi)->done, task, todo, done); return NULL; } /* * calc_pi_mt -- calculate all the pending to-do tasks */ static void calc_pi_mt(void) { TOID(struct pi) pi = POBJ_ROOT(pop, struct pi); int pending = 0; TOID(struct pi_task) iter; POBJ_LIST_FOREACH(iter, &D_RO(pi)->todo, todo) pending++; if (pending == 0) return; int i = 0; TOID(struct pi_task) *tasks = (TOID(struct pi_task) *)malloc( sizeof(TOID(struct pi_task)) * pending); if (tasks == NULL) { fprintf(stderr, "failed to allocate tasks\n"); return; } POBJ_LIST_FOREACH(iter, &D_RO(pi)->todo, todo) tasks[i++] = iter; #ifndef _WIN32 pthread_t workers[pending]; for (i = 0; i < pending; ++i) if (pthread_create(&workers[i], NULL, calc_pi, &tasks[i]) != 0) break; for (i = i - 1; i >= 0; --i) pthread_join(workers[i], NULL); #else HANDLE *workers = (HANDLE *) malloc(sizeof(HANDLE) * pending); for (i = 0; i < pending; ++i) { workers[i] = CreateThread(NULL, 0, calc_pi, &tasks[i], 0, NULL); if (workers[i] == NULL) break; } WaitForMultipleObjects(i, workers, TRUE, INFINITE); for (i = i - 1; i >= 0; --i) CloseHandle(workers[i]); free(workers); #endif free(tasks); } /* * prep_todo_list -- create tasks to be done */ static int prep_todo_list(int threads, int ops) { TOID(struct pi) pi = POBJ_ROOT(pop, struct pi); if (!POBJ_LIST_EMPTY(&D_RO(pi)->todo)) return -1; int ops_per_thread = ops / threads; uint64_t last = 0; /* last calculated denominator */ TOID(struct pi_task) iter; POBJ_LIST_FOREACH(iter, &D_RO(pi)->done, done) { if (last < D_RO(iter)->proto.stop) last = D_RO(iter)->proto.stop; } int i; for (i = 0; i < threads; ++i) { uint64_t start = last + (i * ops_per_thread); struct pi_task_proto proto; proto.start = start; proto.stop = start + ops_per_thread; proto.result = 0; POBJ_LIST_INSERT_NEW_HEAD(pop, &D_RW(pi)->todo, todo, sizeof(struct pi_task), pi_task_construct, &proto); } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { printf("usage: %s file-name " "[print|done|todo|finish|calc <# of threads> <ops>]\n", argv[0]); return 1; } const char *path = argv[1]; pop = NULL; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(pi), PMEMOBJ_MIN_POOL, CREATE_MODE_RW)) == NULL) { printf("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(pi))) == NULL) { printf("failed to open pool\n"); return 1; } } TOID(struct pi) pi = POBJ_ROOT(pop, struct pi); char op = argv[2][0]; switch (op) { case 'p': { /* print pi */ long double pi_val = 0; TOID(struct pi_task) iter; POBJ_LIST_FOREACH(iter, &D_RO(pi)->done, done) { pi_val += D_RO(iter)->proto.result; } printf("pi: %Lf\n", pi_val * 4); } break; case 'd': { /* print done list */ TOID(struct pi_task) iter; POBJ_LIST_FOREACH(iter, &D_RO(pi)->done, done) { printf("(%" PRIu64 " - %" PRIu64 ") = %Lf\n", D_RO(iter)->proto.start, D_RO(iter)->proto.stop, D_RO(iter)->proto.result); } } break; case 't': { /* print to-do list */ TOID(struct pi_task) iter; POBJ_LIST_FOREACH(iter, &D_RO(pi)->todo, todo) { printf("(%" PRIu64 " - %" PRIu64 ") = %Lf\n", D_RO(iter)->proto.start, D_RO(iter)->proto.stop, D_RO(iter)->proto.result); } } break; case 'c': { /* calculate pi */ if (argc < 5) { printf("usage: %s file-name " "calc <# of threads> <ops>\n", argv[0]); return 1; } int threads = atoi(argv[3]); int ops = atoi(argv[4]); assert((threads > 0) && (ops > 0)); if (prep_todo_list(threads, ops) == -1) printf("pending todo tasks\n"); else calc_pi_mt(); } break; case 'f': { /* finish to-do tasks */ calc_pi_mt(); } break; } pmemobj_close(pop); return 0; }
5,620
20.786822
68
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/lists.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * lists.c -- example usage of atomic lists API */ #include <ex_common.h> #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libpmemobj.h> POBJ_LAYOUT_BEGIN(two_lists); POBJ_LAYOUT_ROOT(two_lists, struct my_root); POBJ_LAYOUT_TOID(two_lists, struct foo_el); POBJ_LAYOUT_TOID(two_lists, struct bar_el); POBJ_LAYOUT_END(two_lists); #define MAX_LISTS 10 struct foo_el { POBJ_LIST_ENTRY(struct foo_el) entries; int value; }; struct bar_el { POBJ_LIST_ENTRY(struct bar_el) entries; int value; }; struct listbase { POBJ_LIST_HEAD(foo, struct foo_el) foo_list; POBJ_LIST_HEAD(bar, struct bar_el) bar_list; }; struct my_root { struct listbase lists[MAX_LISTS]; }; enum list_type { LIST_INVALID, LIST_FOO, LIST_BAR, MAX_LIST_TYPES }; struct list_constr_args { enum list_type type; int value; }; /* * list_print -- prints the chosen list content to standard output */ static void list_print(PMEMobjpool *pop, struct listbase *base, enum list_type type) { switch (type) { case LIST_FOO: { TOID(struct foo_el) iter; POBJ_LIST_FOREACH(iter, &base->foo_list, entries) { printf("%d\n", D_RO(iter)->value); } } break; case LIST_BAR: { TOID(struct bar_el) iter; POBJ_LIST_FOREACH(iter, &base->bar_list, entries) { printf("%d\n", D_RO(iter)->value); } } break; default: assert(0); } } /* * list_element_constr -- constructor of the list element */ static int list_element_constr(PMEMobjpool *pop, void *ptr, void *arg) { struct list_constr_args *args = (struct list_constr_args *)arg; switch (args->type) { case LIST_FOO: { struct foo_el *e = (struct foo_el *)ptr; e->value = args->value; pmemobj_persist(pop, &e->value, sizeof(e->value)); } break; case LIST_BAR: { struct bar_el *e = (struct bar_el *)ptr; e->value = args->value; pmemobj_persist(pop, &e->value, sizeof(e->value)); } break; default: assert(0); } return 0; } /* * list_insert -- inserts a new element into the chosen list */ static void list_insert(PMEMobjpool *pop, struct listbase *base, enum list_type type, int value) { struct list_constr_args args = {type, value}; switch (type) { case LIST_FOO: POBJ_LIST_INSERT_NEW_HEAD(pop, &base->foo_list, entries, sizeof(struct foo_el), list_element_constr, &args); break; case LIST_BAR: POBJ_LIST_INSERT_NEW_HEAD(pop, &base->bar_list, entries, sizeof(struct bar_el), list_element_constr, &args); break; default: assert(0); } } int main(int argc, char *argv[]) { if (argc != 5) { printf("usage: %s file-name list_id foo|bar print|val\n", argv[0]); return 1; } const char *path = argv[1]; PMEMobjpool *pop; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(two_lists), PMEMOBJ_MIN_POOL, 0666)) == NULL) { perror("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(two_lists))) == NULL) { perror("failed to open pool\n"); return 1; } } int id = atoi(argv[2]); if (id < 0 || id >= MAX_LISTS) { fprintf(stderr, "list index out of scope\n"); return 1; } enum list_type type = LIST_INVALID; if (strcmp(argv[3], "foo") == 0) { type = LIST_FOO; } else if (strcmp(argv[3], "bar") == 0) { type = LIST_BAR; } if (type == LIST_INVALID) { fprintf(stderr, "invalid list type\n"); return 1; } TOID(struct my_root) r = POBJ_ROOT(pop, struct my_root); if (strcmp(argv[4], "print") == 0) { list_print(pop, &D_RW(r)->lists[id], type); } else { int val = atoi(argv[4]); list_insert(pop, &D_RW(r)->lists[id], type, val); } pmemobj_close(pop); return 0; }
3,743
19.02139
72
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/setjmp.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * setjmp.c -- example illustrating an issue with indeterminate value * of non-volatile automatic variables after transaction abort. * See libpmemobj(7) for details. * * NOTE: To observe the problem (likely segfault on a second call to free()), * the example program should be compiled with optimizations enabled (-O2). */ #include <stdlib.h> #include <stdio.h> #include <libpmemobj.h> /* name of our layout in the pool */ #define LAYOUT_NAME "setjmp_example" int main(int argc, const char *argv[]) { const char path[] = "/pmem-fs/myfile"; PMEMobjpool *pop; /* create the pmemobj pool */ pop = pmemobj_create(path, LAYOUT_NAME, PMEMOBJ_MIN_POOL, 0666); if (pop == NULL) { perror(path); exit(1); } /* initialize pointer variables with invalid addresses */ int *bad_example_1 = (int *)0xBAADF00D; int *bad_example_2 = (int *)0xBAADF00D; int *bad_example_3 = (int *)0xBAADF00D; int *volatile good_example = (int *)0xBAADF00D; TX_BEGIN(pop) { bad_example_1 = malloc(sizeof(int)); bad_example_2 = malloc(sizeof(int)); bad_example_3 = malloc(sizeof(int)); good_example = malloc(sizeof(int)); /* manual or library abort called here */ pmemobj_tx_abort(EINVAL); } TX_ONCOMMIT { /* * This section is longjmp-safe */ } TX_ONABORT { /* * This section is not longjmp-safe */ free(good_example); /* OK */ free(bad_example_1); /* undefined behavior */ } TX_FINALLY { /* * This section is not longjmp-safe on transaction abort only */ free(bad_example_2); /* undefined behavior */ } TX_END free(bad_example_3); /* undefined behavior */ pmemobj_close(pop); return 0; }
1,723
23.985507
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pminvaders/pminvaders.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * pminvaders.c -- example usage of non-tx allocations */ #include <stddef.h> #ifdef __FreeBSD__ #include <ncurses/ncurses.h> /* Need pkg, not system, version */ #else #include <ncurses.h> #endif #include <unistd.h> #include <time.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <libpmem.h> #include <libpmemobj.h> #define LAYOUT_NAME "pminvaders" #define PMINVADERS_POOL_SIZE (100 * 1024 * 1024) /* 100 megabytes */ #define GAME_WIDTH 30 #define GAME_HEIGHT 30 #define RRAND(min, max) (rand() % ((max) - (min) + 1) + (min)) #define STEP 50 #define PLAYER_Y (GAME_HEIGHT - 1) #define MAX_GSTATE_TIMER 10000 #define MIN_GSTATE_TIMER 5000 #define MAX_ALIEN_TIMER 1000 #define MAX_PLAYER_TIMER 1000 #define MAX_BULLET_TIMER 500 int use_ndp_redo = 0; enum colors { C_UNKNOWN, C_PLAYER, C_ALIEN, C_BULLET, MAX_C }; struct game_state { uint32_t timer; /* alien spawn timer */ uint16_t score; uint16_t high_score; }; struct alien { uint16_t x; uint16_t y; uint32_t timer; /* movement timer */ }; struct player { uint16_t x; uint16_t padding; /* to 8 bytes */ uint32_t timer; /* weapon cooldown */ }; struct bullet { uint16_t x; uint16_t y; uint32_t timer; /* movement timer */ }; /* * Layout definition */ POBJ_LAYOUT_BEGIN(pminvaders); POBJ_LAYOUT_ROOT(pminvaders, struct game_state); POBJ_LAYOUT_TOID(pminvaders, struct player); POBJ_LAYOUT_TOID(pminvaders, struct alien); POBJ_LAYOUT_TOID(pminvaders, struct bullet); POBJ_LAYOUT_END(pminvaders); static PMEMobjpool *pop; static struct game_state *gstate; /* * create_alien -- constructor for aliens, spawn at random position */ static int create_alien(PMEMobjpool *pop, void *ptr, void *arg) { struct alien *a = ptr; a->y = 1; a->x = RRAND(2, GAME_WIDTH - 2); a->timer = 1; pmemobj_persist(pop, a, sizeof(*a)); return 0; } /* * create_player -- constructor for the player, spawn in the middle of the map */ static int create_player(PMEMobjpool *pop, void *ptr, void *arg) { struct player *p = ptr; p->x = GAME_WIDTH / 2; p->timer = 1; pmemobj_persist(pop, p, sizeof(*p)); return 0; } /* * create_bullet -- constructor for bullets, spawn at the position of the player */ static int create_bullet(PMEMobjpool *pop, void *ptr, void *arg) { struct bullet *b = ptr; struct player *p = arg; b->x = p->x; b->y = PLAYER_Y - 1; b->timer = 1; pmemobj_persist(pop, b, sizeof(*b)); return 0; } static void draw_border(void) { for (int x = 0; x <= GAME_WIDTH; ++x) { mvaddch(0, x, ACS_HLINE); mvaddch(GAME_HEIGHT, x, ACS_HLINE); } for (int y = 0; y <= GAME_HEIGHT; ++y) { mvaddch(y, 0, ACS_VLINE); mvaddch(y, GAME_WIDTH, ACS_VLINE); } mvaddch(0, 0, ACS_ULCORNER); mvaddch(GAME_HEIGHT, 0, ACS_LLCORNER); mvaddch(0, GAME_WIDTH, ACS_URCORNER); mvaddch(GAME_HEIGHT, GAME_WIDTH, ACS_LRCORNER); } static void draw_alien(const TOID(struct alien) a) { mvaddch(D_RO(a)->y, D_RO(a)->x, ACS_DIAMOND|COLOR_PAIR(C_ALIEN)); } static void draw_player(const TOID(struct player) p) { mvaddch(PLAYER_Y, D_RO(p)->x, ACS_DIAMOND|COLOR_PAIR(C_PLAYER)); } static void draw_bullet(const TOID(struct bullet) b) { mvaddch(D_RO(b)->y, D_RO(b)->x, ACS_BULLET|COLOR_PAIR(C_BULLET)); } static void draw_score(void) { mvprintw(1, 1, "Score: %u | %u\n", gstate->score, gstate->high_score); } /* * timer_tick -- very simple persistent timer */ static int timer_tick(uint32_t *timer) { int ret = *timer == 0 || ((*timer)--) == 0; pmemobj_persist(pop, timer, sizeof(*timer)); return ret; } /* * update_score -- change player score and global high score */ static void update_score(int m) { if (m < 0 && gstate->score == 0) return; uint16_t score = gstate->score + m; uint16_t highscore = score > gstate->high_score ? score : gstate->high_score; struct game_state s = { .timer = gstate->timer, .score = score, .high_score = highscore }; *gstate = s; pmemobj_persist(pop, gstate, sizeof(*gstate)); } /* * process_aliens -- process spawn and movement of the aliens */ static void process_aliens(void) { /* alien spawn timer */ if (timer_tick(&gstate->timer)) { gstate->timer = RRAND(MIN_GSTATE_TIMER, MAX_GSTATE_TIMER); pmemobj_persist(pop, gstate, sizeof(*gstate)); POBJ_NEW(pop, NULL, struct alien, create_alien, NULL); } TOID(struct alien) iter, next; POBJ_FOREACH_SAFE_TYPE(pop, iter, next) { if (timer_tick(&D_RW(iter)->timer)) { D_RW(iter)->timer = MAX_ALIEN_TIMER; D_RW(iter)->y++; } pmemobj_persist(pop, D_RW(iter), sizeof(struct alien)); draw_alien(iter); /* decrease the score if the ship wasn't intercepted */ if (D_RO(iter)->y > GAME_HEIGHT - 1) { POBJ_FREE(&iter); update_score(-1); pmemobj_persist(pop, gstate, sizeof(*gstate)); } } } /* * process_collision -- search for any aliens on the position of the bullet */ static int process_collision(const TOID(struct bullet) b) { TOID(struct alien) iter; POBJ_FOREACH_TYPE(pop, iter) { if (D_RO(b)->x == D_RO(iter)->x && D_RO(b)->y == D_RO(iter)->y) { update_score(1); POBJ_FREE(&iter); return 1; } } return 0; } /* * process_bullets -- process bullets movement and collision */ static void process_bullets(void) { TOID(struct bullet) iter, next; POBJ_FOREACH_SAFE_TYPE(pop, iter, next) { /* bullet movement timer */ if (timer_tick(&D_RW(iter)->timer)) { D_RW(iter)->timer = MAX_BULLET_TIMER; D_RW(iter)->y--; } pmemobj_persist(pop, D_RW(iter), sizeof(struct bullet)); draw_bullet(iter); if (D_RO(iter)->y == 0 || process_collision(iter)) POBJ_FREE(&iter); } } /* * process_player -- handle player actions */ static void process_player(int input) { TOID(struct player) plr = POBJ_FIRST(pop, struct player); /* weapon cooldown tick */ timer_tick(&D_RW(plr)->timer); switch (input) { case KEY_LEFT: case 'o': { uint16_t dstx = D_RO(plr)->x - 1; if (dstx != 0) D_RW(plr)->x = dstx; } break; case KEY_RIGHT: case 'p': { uint16_t dstx = D_RO(plr)->x + 1; if (dstx != GAME_WIDTH - 1) D_RW(plr)->x = dstx; } break; case ' ': if (D_RO(plr)->timer == 0) { D_RW(plr)->timer = MAX_PLAYER_TIMER; POBJ_NEW(pop, NULL, struct bullet, create_bullet, D_RW(plr)); } break; default: break; } pmemobj_persist(pop, D_RW(plr), sizeof(struct player)); draw_player(plr); } /* * game_loop -- process drawing and logic of the game */ static void game_loop(int input) { erase(); draw_score(); draw_border(); process_aliens(); process_bullets(); process_player(input); usleep(STEP); refresh(); } int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } const char *path = argv[1]; pop = NULL; srand(time(NULL)); if (access(path, F_OK) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(pminvaders), PMINVADERS_POOL_SIZE, S_IWUSR | S_IRUSR)) == NULL) { printf("failed to create pool\n"); return 1; } /* create the player and initialize with a constructor */ POBJ_NEW(pop, NULL, struct player, create_player, NULL); } else { if ((pop = pmemobj_open(path, LAYOUT_NAME)) == NULL) { printf("failed to open pool\n"); return 1; } } /* global state of the game is kept in the root object */ TOID(struct game_state) game_state = POBJ_ROOT(pop, struct game_state); gstate = D_RW(game_state); initscr(); start_color(); init_pair(C_PLAYER, COLOR_GREEN, COLOR_BLACK); init_pair(C_ALIEN, COLOR_RED, COLOR_BLACK); init_pair(C_BULLET, COLOR_YELLOW, COLOR_BLACK); nodelay(stdscr, true); curs_set(0); keypad(stdscr, true); int in; while ((in = getch()) != 'q') { game_loop(in); } pmemobj_close(pop); endwin(); return 0; }
7,784
18.413965
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pminvaders/pminvaders2.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * pminvaders2.c -- PMEM-based clone of space invaders (version 2.0) * * RULES: * +1 point for each alien destroyed (72 per level) * -100 points and move to a lower level when killed */ #include <stddef.h> #ifdef __FreeBSD__ #include <ncurses/ncurses.h> /* Need pkg, not system, version */ #else #include <ncurses.h> #endif #include <unistd.h> #include <time.h> #include <stdlib.h> #include <sys/stat.h> #include <libpmem.h> #include <libpmemobj.h> /* * Layout definition */ POBJ_LAYOUT_BEGIN(pminvaders2); POBJ_LAYOUT_ROOT(pminvaders2, struct root); POBJ_LAYOUT_TOID(pminvaders2, struct state); POBJ_LAYOUT_TOID(pminvaders2, struct alien); POBJ_LAYOUT_TOID(pminvaders2, struct player); POBJ_LAYOUT_TOID(pminvaders2, struct bullet); POBJ_LAYOUT_TOID(pminvaders2, struct star); POBJ_LAYOUT_END(pminvaders2); #define POOL_SIZE (100 * 1024 * 1024) /* 100 megabytes */ #define GAME_WIDTH 50 #define GAME_HEIGHT 25 #define ALIENS_ROW 4 #define ALIENS_COL 18 #define RRAND(min, max) (rand() % ((max) - (min) + 1) + (min)) #define STEP 50 #define PLAYER_Y (GAME_HEIGHT - 1) #define MAX_GSTATE_TIMER 10000 #define MIN_GSTATE_TIMER 5000 #define MAX_ALIEN_TIMER 1000 #define MAX_PLAYER_TIMER 1000 #define MAX_BULLET_TIMER 500 #define MAX_STAR1_TIMER 200 #define MAX_STAR2_TIMER 100 int use_ndp_redo = 0; enum game_event { EVENT_NOP, EVENT_BOUNCE, EVENT_PLAYER_KILLED, EVENT_ALIENS_KILLED }; enum colors { C_UNKNOWN, C_PLAYER, C_ALIEN, C_BULLET, C_STAR, C_INTRO }; struct state { unsigned timer; int score; int high_score; int level; int new_level; int dx; int dy; }; struct player { unsigned x; unsigned timer; }; struct alien { unsigned x; unsigned y; TOID(struct alien) prev; TOID(struct alien) next; }; struct star { unsigned x; unsigned y; int c; unsigned timer; TOID(struct star) prev; TOID(struct star) next; }; struct bullet { unsigned x; unsigned y; unsigned timer; TOID(struct bullet) prev; TOID(struct bullet) next; }; struct root { TOID(struct state) state; TOID(struct player) player; TOID(struct alien) aliens; TOID(struct bullet) bullets; TOID(struct star) stars; }; /* * draw_star -- draw a star */ static void draw_star(const struct star *s) { mvaddch(s->y, s->x, s->c | COLOR_PAIR(C_STAR)); } /* * draw_alien -- draw an alien */ static void draw_alien(const struct alien *a) { mvaddch(a->y, a->x, ACS_DIAMOND | COLOR_PAIR(C_ALIEN)); } /* * draw_player -- draw a player */ static void draw_player(const struct player *p) { mvaddch(PLAYER_Y, p->x, ACS_DIAMOND | COLOR_PAIR(C_PLAYER)); } /* * draw_bullet -- draw a bullet */ static void draw_bullet(const struct bullet *b) { mvaddch(b->y, b->x, ACS_BULLET | COLOR_PAIR(C_BULLET)); } /* * draw_score -- draw the game score and the global highest score */ static void draw_score(const struct state *s) { mvprintw(1, 1, "Level: %u Score: %u | %u\n", s->level, s->score, s->high_score); } /* * draw_title -- draw the game title and menu */ static void draw_title(void) { int x = (GAME_WIDTH - 40) / 2; int y = GAME_HEIGHT / 2 - 2; attron(COLOR_PAIR(C_INTRO)); mvprintw(y + 0, x, "#### # # ### # # # # ### ###"); mvprintw(y + 1, x, "# # ## ## # ## # # # # # #"); mvprintw(y + 2, x, "#### # # # # # # # # # ### # #"); mvprintw(y + 3, x, "# # # # # # ## # # # # #"); mvprintw(y + 4, x, "# # # ### # # # ### # ###"); attroff(COLOR_PAIR(C_INTRO)); mvprintw(y + 6, x, " Press 'space' to resume "); mvprintw(y + 7, x, " Press 'q' to quit "); } /* * draw_border -- draw a frame around the map */ static void draw_border(void) { for (int x = 0; x <= GAME_WIDTH; ++x) { mvaddch(0, x, ACS_HLINE); mvaddch(GAME_HEIGHT, x, ACS_HLINE); } for (int y = 0; y <= GAME_HEIGHT; ++y) { mvaddch(y, 0, ACS_VLINE); mvaddch(y, GAME_WIDTH, ACS_VLINE); } mvaddch(0, 0, ACS_ULCORNER); mvaddch(GAME_HEIGHT, 0, ACS_LLCORNER); mvaddch(0, GAME_WIDTH, ACS_URCORNER); mvaddch(GAME_HEIGHT, GAME_WIDTH, ACS_LRCORNER); } /* * timer_tick -- very simple persistent timer */ static int timer_tick(unsigned *timer) { return *timer == 0 || ((*timer)--) == 0; } /* * create_star -- create a single star at random position */ static TOID(struct star) create_star(unsigned x, unsigned y, TOID(struct star) next) { TOID(struct star) s = TX_ZNEW(struct star); struct star *sp = D_RW(s); sp->x = x; sp->y = y; sp->c = rand() % 2 ? '*' : '.'; sp->timer = sp->c == '.' ? MAX_STAR1_TIMER : MAX_STAR2_TIMER; sp->prev = TOID_NULL(struct star); sp->next = next; if (!TOID_IS_NULL(next)) D_RW(next)->prev = s; return s; } /* * create_stars -- create a new set of stars at random positions */ static void create_stars(TOID(struct root) r) { for (int x = 1; x < GAME_WIDTH; x++) { if (rand() % 100 < 4) D_RW(r)->stars = create_star(x, 1, D_RW(r)->stars); } } /* * process_stars -- process creation and movement of the stars */ static void process_stars(PMEMobjpool *pop, TOID(struct root) r) { int new_line = 0; TX_BEGIN(pop) { TOID(struct star) s = D_RO(r)->stars; while (!TOID_IS_NULL(s)) { TX_ADD(s); struct star *sptr = D_RW(s); TOID(struct star) sp = sptr->prev; TOID(struct star) sn = sptr->next; if (timer_tick(&sptr->timer)) { sptr->timer = sptr->c == '.' ? MAX_STAR1_TIMER : MAX_STAR2_TIMER; sptr->y++; if (sptr->c == '.') new_line = 1; } draw_star(sptr); if (sptr->y >= GAME_HEIGHT) { if (!TOID_IS_NULL(sp)) { TX_ADD(sp); D_RW(sp)->next = sn; } else { TX_ADD(r); D_RW(r)->stars = sn; } if (!TOID_IS_NULL(sn)) { TX_ADD(sn); D_RW(sn)->prev = sp; } TX_FREE(s); } s = sn; } if (new_line) create_stars(r); } TX_END; } /* * create_alien -- create an alien at given position */ static TOID(struct alien) create_alien(unsigned x, unsigned y, TOID(struct alien) next) { TOID(struct alien) a = TX_ZNEW(struct alien); struct alien *ap = D_RW(a); ap->x = x; ap->y = y; ap->prev = TOID_NULL(struct alien); ap->next = next; if (!TOID_IS_NULL(next)) D_RW(next)->prev = a; return a; } /* * create_aliens -- create new set of aliens */ static void create_aliens(TOID(struct root) r) { for (int x = 0; x < ALIENS_COL; x++) { for (int y = 0; y < ALIENS_ROW; y++) { unsigned pos_x = (GAME_WIDTH / 2) - (ALIENS_COL) + (x * 2); unsigned pos_y = y + 3; D_RW(r)->aliens = create_alien(pos_x, pos_y, D_RW(r)->aliens); } } } /* * remove_aliens -- remove all the aliens from the map */ static void remove_aliens(TOID(struct alien) *ah) { while (!TOID_IS_NULL(*ah)) { TOID(struct alien) an = D_RW(*ah)->next; TX_FREE(*ah); *ah = an; } } /* * move_aliens -- process movement of the aliens */ static int move_aliens(PMEMobjpool *pop, TOID(struct root) r, int dx, int dy) { int ret = EVENT_NOP; int cnt = 0; TOID(struct alien) a = D_RO(r)->aliens; while (!TOID_IS_NULL(a)) { TX_ADD(a); struct alien *ap = D_RW(a); cnt++; if (dy) ap->y += dy; else ap->x += dx; if (ap->y >= PLAYER_Y) ret = EVENT_PLAYER_KILLED; else if (dy == 0 && (ap->x >= GAME_WIDTH - 2 || ap->x <= 2)) ret = EVENT_BOUNCE; a = ap->next; } if (cnt == 0) ret = EVENT_ALIENS_KILLED; /* all killed */ return ret; } /* * create_player -- spawn the player in the middle of the map */ static TOID(struct player) create_player(void) { TOID(struct player) p = TX_ZNEW(struct player); struct player *pp = D_RW(p); pp->x = GAME_WIDTH / 2; pp->timer = 1; return p; } /* * create_bullet -- spawn the bullet at the position of the player */ static TOID(struct bullet) create_bullet(unsigned x, TOID(struct bullet) next) { TOID(struct bullet) b = TX_ZNEW(struct bullet); struct bullet *bp = D_RW(b); bp->x = x; bp->y = PLAYER_Y - 1; bp->timer = 1; bp->prev = TOID_NULL(struct bullet); bp->next = next; if (!TOID_IS_NULL(next)) D_RW(next)->prev = b; return b; } /* * create_state -- create game state */ static TOID(struct state) create_state(void) { TOID(struct state) s = TX_ZNEW(struct state); struct state *sp = D_RW(s); sp->timer = 1; sp->score = 0; sp->high_score = 0; sp->level = 0; sp->new_level = 1; sp->dx = 1; sp->dy = 0; return s; } /* * new_level -- prepare map for the new game level */ static void new_level(PMEMobjpool *pop, TOID(struct root) r) { TX_BEGIN(pop) { TX_ADD(r); struct root *rp = D_RW(r); remove_aliens(&rp->aliens); create_aliens(r); TX_ADD(rp->state); struct state *sp = D_RW(rp->state); if (sp->new_level > 0 || sp->level > 1) sp->level += sp->new_level; sp->new_level = 0; sp->dx = 1; sp->dy = 0; sp->timer = MAX_ALIEN_TIMER - 100 * (sp->level - 1); } TX_END; } /* * update_score -- change player score and global high score */ static void update_score(struct state *sp, int m) { if (m < 0 && sp->score == 0) return; sp->score += m; if (sp->score < 0) sp->score = 0; if (sp->score > sp->high_score) sp->high_score = sp->score; } /* * process_aliens -- process movement of the aliens and game events */ static void process_aliens(PMEMobjpool *pop, TOID(struct root) r) { TX_BEGIN(pop) { TOID(struct state) s = D_RO(r)->state; TX_ADD(s); struct state *sp = D_RW(s); if (timer_tick(&sp->timer)) { sp->timer = MAX_ALIEN_TIMER - 50 * (sp->level - 1); switch (move_aliens(pop, r, sp->dx, sp->dy)) { case EVENT_ALIENS_KILLED: /* all aliens killed */ sp->new_level = 1; break; case EVENT_PLAYER_KILLED: /* player killed */ flash(); beep(); sp->new_level = -1; update_score(sp, -100); break; case EVENT_BOUNCE: /* move down + change direction */ sp->dy = 1; sp->dx = -sp->dx; break; case EVENT_NOP: /* do nothing */ sp->dy = 0; break; } } } TX_END; TOID(struct alien) a = D_RO(r)->aliens; while (!TOID_IS_NULL(a)) { const struct alien *ap = D_RO(a); draw_alien(ap); a = ap->next; } } /* * process_collision -- search for any aliens on the position of the bullet */ static int process_collision(PMEMobjpool *pop, TOID(struct root) r, struct state *sp, const struct bullet *bp) { int ret = 0; TX_BEGIN(pop) { TOID(struct alien) a = D_RO(r)->aliens; while (!TOID_IS_NULL(a)) { struct alien *aptr = D_RW(a); TOID(struct alien) ap = aptr->prev; TOID(struct alien) an = aptr->next; if (bp->x == aptr->x && bp->y == aptr->y) { update_score(sp, 1); if (!TOID_IS_NULL(ap)) { TX_ADD(ap); D_RW(ap)->next = an; } else { TX_ADD(r); D_RW(r)->aliens = an; } if (!TOID_IS_NULL(an)) { TX_ADD(an); D_RW(an)->prev = ap; } TX_FREE(a); ret = 1; break; } a = an; } } TX_END; return ret; } /* * process_bullets -- process bullets movement and collision */ static void process_bullets(PMEMobjpool *pop, TOID(struct root) r, struct state *sp) { TX_BEGIN(pop) { TOID(struct bullet) b = D_RO(r)->bullets; while (!TOID_IS_NULL(b)) { TX_ADD(b); struct bullet *bptr = D_RW(b); TOID(struct bullet) bp = bptr->prev; TOID(struct bullet) bn = bptr->next; if (timer_tick(&bptr->timer)) { bptr->timer = MAX_BULLET_TIMER; bptr->y--; } draw_bullet(bptr); if (bptr->y <= 0 || process_collision(pop, r, sp, bptr)) { if (!TOID_IS_NULL(bp)) { TX_ADD(bp); D_RW(bp)->next = bn; } else { TX_ADD(r); D_RW(r)->bullets = bn; } if (!TOID_IS_NULL(bn)) { TX_ADD(bn); D_RW(bn)->prev = bp; } TX_FREE(b); } b = bn; } } TX_END; } /* * process_player -- handle player actions */ static void process_player(PMEMobjpool *pop, TOID(struct root) r, int input) { TOID(struct player) p = D_RO(r)->player; TX_BEGIN(pop) { TX_ADD(r); TX_ADD(p); struct player *pp = D_RW(p); timer_tick(&pp->timer); if (input == KEY_LEFT || input == 'o') { unsigned dstx = pp->x - 1; if (dstx != 0) pp->x = dstx; } else if (input == KEY_RIGHT || input == 'p') { unsigned dstx = pp->x + 1; if (dstx != GAME_WIDTH) pp->x = dstx; } else if (input == ' ' && pp->timer == 0) { pp->timer = MAX_PLAYER_TIMER; D_RW(r)->bullets = create_bullet(pp->x, D_RW(r)->bullets); } } TX_END; draw_player(D_RO(p)); } /* * game_init -- create and initialize game state and the player */ static TOID(struct root) game_init(PMEMobjpool *pop) { TOID(struct root) r = POBJ_ROOT(pop, struct root); TX_BEGIN(pop) { TX_ADD(r); struct root *rp = D_RW(r); if (TOID_IS_NULL(rp->state)) rp->state = create_state(); if (TOID_IS_NULL(rp->player)) rp->player = create_player(); } TX_END; return r; } /* * game_loop -- process drawing and logic of the game */ static int game_loop(PMEMobjpool *pop, TOID(struct root) r) { int input = getch(); TOID(struct state) s = D_RO(r)->state; struct state *sp = D_RW(s); erase(); draw_score(sp); draw_border(); TX_BEGIN(pop) { TX_ADD(r); TX_ADD(s); if (sp->new_level != 0) new_level(pop, r); process_aliens(pop, r); process_bullets(pop, r, sp); process_player(pop, r, input); } TX_END; usleep(STEP); refresh(); if (input == 'q') return -1; else return 0; } /* * intro_loop -- process drawing of the intro animation */ static int intro_loop(PMEMobjpool *pop, TOID(struct root) r) { int input = getch(); erase(); draw_border(); TX_BEGIN(pop) { TX_ADD(r); struct root *rp = D_RW(r); if (TOID_IS_NULL(rp->stars)) create_stars(r); process_stars(pop, r); } TX_END; draw_title(); usleep(STEP); refresh(); switch (input) { case ' ': return 1; case 'q': return -1; default: return 0; } } int main(int argc, char *argv[]) { static PMEMobjpool *pop; int in; if (argc != 2) exit(1); srand(time(NULL)); if (access(argv[1], F_OK)) { if ((pop = pmemobj_create(argv[1], POBJ_LAYOUT_NAME(pminvaders2), POOL_SIZE, S_IRUSR | S_IWUSR)) == NULL) { fprintf(stderr, "%s", pmemobj_errormsg()); exit(1); } } else { if ((pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(pminvaders2))) == NULL) { fprintf(stderr, "%s", pmemobj_errormsg()); exit(1); } } initscr(); start_color(); init_pair(C_PLAYER, COLOR_GREEN, COLOR_BLACK); init_pair(C_ALIEN, COLOR_RED, COLOR_BLACK); init_pair(C_BULLET, COLOR_YELLOW, COLOR_BLACK); init_pair(C_STAR, COLOR_WHITE, COLOR_BLACK); init_pair(C_INTRO, COLOR_BLUE, COLOR_BLACK); nodelay(stdscr, true); curs_set(0); keypad(stdscr, true); TOID(struct root) r = game_init(pop); while ((in = intro_loop(pop, r)) == 0) ; if (in == -1) goto end; while ((in = game_loop(pop, r)) == 0) ; end: endwin(); pmemobj_close(pop); return 0; }
14,850
17.425558
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemblk/obj_pmemblk.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * obj_pmemblk.c -- alternate pmemblk implementation based on pmemobj * * usage: obj_pmemblk [co] file blk_size [cmd[:blk_num[:data]]...] * * c - create file * o - open file * * The "cmd" arguments match the pmemblk functions: * w - write to a block * r - read a block * z - zero a block * n - write out number of available blocks * e - put a block in error state */ #include <ex_common.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include "libpmemobj.h" #include "libpmem.h" #include "libpmemblk.h" #define USABLE_SIZE (7.0 / 10) #define POOL_SIZE ((size_t)(1024 * 1024 * 100)) #define MAX_POOL_SIZE ((size_t)1024 * 1024 * 1024 * 16) #define MAX_THREADS 256 #define BSIZE_MAX ((size_t)(1024 * 1024 * 10)) #define ZERO_MASK (1 << 0) #define ERROR_MASK (1 << 1) POBJ_LAYOUT_BEGIN(obj_pmemblk); POBJ_LAYOUT_ROOT(obj_pmemblk, struct base); POBJ_LAYOUT_TOID(obj_pmemblk, uint8_t); POBJ_LAYOUT_END(obj_pmemblk); /* The root object struct holding all necessary data */ struct base { TOID(uint8_t) data; /* contiguous memory region */ TOID(uint8_t) flags; /* block flags */ size_t bsize; /* block size */ size_t nblocks; /* number of available blocks */ PMEMmutex locks[MAX_THREADS]; /* thread synchronization locks */ }; /* * pmemblk_map -- (internal) read or initialize the blk pool */ static int pmemblk_map(PMEMobjpool *pop, size_t bsize, size_t fsize) { int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* read pool descriptor and validate user provided values */ if (D_RO(bp)->bsize) { if (bsize && D_RO(bp)->bsize != bsize) return -1; else return 0; } /* new pool, calculate and store metadata */ TX_BEGIN(pop) { TX_ADD(bp); D_RW(bp)->bsize = bsize; size_t pool_size = (size_t)(fsize * USABLE_SIZE); D_RW(bp)->nblocks = pool_size / bsize; D_RW(bp)->data = TX_ZALLOC(uint8_t, pool_size); D_RW(bp)->flags = TX_ZALLOC(uint8_t, sizeof(uint8_t) * D_RO(bp)->nblocks); } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemblk_open -- open a block memory pool */ PMEMblkpool * pmemblk_open(const char *path, size_t bsize) { PMEMobjpool *pop = pmemobj_open(path, POBJ_LAYOUT_NAME(obj_pmemblk)); if (pop == NULL) return NULL; struct stat buf; if (stat(path, &buf)) { perror("stat"); return NULL; } return pmemblk_map(pop, bsize, buf.st_size) ? NULL : (PMEMblkpool *)pop; } /* * pmemblk_create -- create a block memory pool */ PMEMblkpool * pmemblk_create(const char *path, size_t bsize, size_t poolsize, mode_t mode) { /* max size of a single allocation is 16GB */ if (poolsize > MAX_POOL_SIZE) { errno = EINVAL; return NULL; } PMEMobjpool *pop = pmemobj_create(path, POBJ_LAYOUT_NAME(obj_pmemblk), poolsize, mode); if (pop == NULL) return NULL; return pmemblk_map(pop, bsize, poolsize) ? NULL : (PMEMblkpool *)pop; } /* * pmemblk_close -- close a block memory pool */ void pmemblk_close(PMEMblkpool *pbp) { pmemobj_close((PMEMobjpool *)pbp); } /* * pmemblk_check -- block memory pool consistency check */ int pmemblk_check(const char *path, size_t bsize) { int ret = pmemobj_check(path, POBJ_LAYOUT_NAME(obj_pmemblk)); if (ret) return ret; /* open just to validate block size */ PMEMblkpool *pop = pmemblk_open(path, bsize); if (!pop) return -1; pmemblk_close(pop); return 0; } /* * pmemblk_set_error -- not available in this implementation */ int pmemblk_set_error(PMEMblkpool *pbp, long long blockno) { PMEMobjpool *pop = (PMEMobjpool *)pbp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); int retval = 0; if (blockno >= (long long)D_RO(bp)->nblocks) return 1; TX_BEGIN_PARAM(pop, TX_PARAM_MUTEX, &D_RW(bp)->locks[blockno % MAX_THREADS], TX_PARAM_NONE) { uint8_t *flags = D_RW(D_RW(bp)->flags) + blockno; /* add the modified flags to the undo log */ pmemobj_tx_add_range_direct(flags, sizeof(*flags)); *flags |= ERROR_MASK; } TX_ONABORT { retval = 1; } TX_END return retval; } /* * pmemblk_nblock -- return number of usable blocks in a block memory pool */ size_t pmemblk_nblock(PMEMblkpool *pbp) { PMEMobjpool *pop = (PMEMobjpool *)pbp; return ((struct base *)pmemobj_direct(pmemobj_root(pop, sizeof(struct base))))->nblocks; } /* * pmemblk_read -- read a block in a block memory pool */ int pmemblk_read(PMEMblkpool *pbp, void *buf, long long blockno) { PMEMobjpool *pop = (PMEMobjpool *)pbp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); if (blockno >= (long long)D_RO(bp)->nblocks) return 1; pmemobj_mutex_lock(pop, &D_RW(bp)->locks[blockno % MAX_THREADS]); /* check the error mask */ uint8_t *flags = D_RW(D_RW(bp)->flags) + blockno; if ((*flags & ERROR_MASK) != 0) { pmemobj_mutex_unlock(pop, &D_RW(bp)->locks[blockno % MAX_THREADS]); errno = EIO; return 1; } /* the block is zeroed, reverse zeroing logic */ if ((*flags & ZERO_MASK) == 0) { memset(buf, 0, D_RO(bp)->bsize); } else { size_t block_off = blockno * D_RO(bp)->bsize; uint8_t *src = D_RW(D_RW(bp)->data) + block_off; memcpy(buf, src, D_RO(bp)->bsize); } pmemobj_mutex_unlock(pop, &D_RW(bp)->locks[blockno % MAX_THREADS]); return 0; } /* * pmemblk_write -- write a block (atomically) in a block memory pool */ int pmemblk_write(PMEMblkpool *pbp, const void *buf, long long blockno) { PMEMobjpool *pop = (PMEMobjpool *)pbp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); if (blockno >= (long long)D_RO(bp)->nblocks) return 1; TX_BEGIN_PARAM(pop, TX_PARAM_MUTEX, &D_RW(bp)->locks[blockno % MAX_THREADS], TX_PARAM_NONE) { size_t block_off = blockno * D_RO(bp)->bsize; uint8_t *dst = D_RW(D_RW(bp)->data) + block_off; /* add the modified block to the undo log */ pmemobj_tx_add_range_direct(dst, D_RO(bp)->bsize); memcpy(dst, buf, D_RO(bp)->bsize); /* clear the error flag and set the zero flag */ uint8_t *flags = D_RW(D_RW(bp)->flags) + blockno; /* add the modified flags to the undo log */ pmemobj_tx_add_range_direct(flags, sizeof(*flags)); *flags &= ~ERROR_MASK; /* use reverse logic for zero mask */ *flags |= ZERO_MASK; } TX_ONABORT { retval = 1; } TX_END return retval; } /* * pmemblk_set_zero -- zero a block in a block memory pool */ int pmemblk_set_zero(PMEMblkpool *pbp, long long blockno) { PMEMobjpool *pop = (PMEMobjpool *)pbp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); if (blockno >= (long long)D_RO(bp)->nblocks) return 1; TX_BEGIN_PARAM(pop, TX_PARAM_MUTEX, &D_RW(bp)->locks[blockno % MAX_THREADS], TX_PARAM_NONE) { uint8_t *flags = D_RW(D_RW(bp)->flags) + blockno; /* add the modified flags to the undo log */ pmemobj_tx_add_range_direct(flags, sizeof(*flags)); /* use reverse logic for zero mask */ *flags &= ~ZERO_MASK; } TX_ONABORT { retval = 1; } TX_END return retval; } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "usage: %s [co] file blk_size"\ " [cmd[:blk_num[:data]]...]\n", argv[0]); return 1; } unsigned long bsize = strtoul(argv[3], NULL, 10); assert(bsize <= BSIZE_MAX); if (bsize == 0) { perror("blk_size cannot be 0"); return 1; } PMEMblkpool *pbp; if (strncmp(argv[1], "c", 1) == 0) { pbp = pmemblk_create(argv[2], bsize, POOL_SIZE, CREATE_MODE_RW); } else if (strncmp(argv[1], "o", 1) == 0) { pbp = pmemblk_open(argv[2], bsize); } else { fprintf(stderr, "usage: %s [co] file blk_size" " [cmd[:blk_num[:data]]...]\n", argv[0]); return 1; } if (pbp == NULL) { perror("pmemblk_create/pmemblk_open"); return 1; } /* process the command line arguments */ for (int i = 4; i < argc; i++) { switch (*argv[i]) { case 'w': { printf("write: %s\n", argv[i] + 2); const char *block_str = strtok(argv[i] + 2, ":"); const char *data = strtok(NULL, ":"); assert(block_str != NULL); assert(data != NULL); unsigned long block = strtoul(block_str, NULL, 10); if (pmemblk_write(pbp, data, block)) perror("pmemblk_write failed"); break; } case 'r': { printf("read: %s\n", argv[i] + 2); char *buf = (char *)malloc(bsize); assert(buf != NULL); const char *block_str = strtok(argv[i] + 2, ":"); assert(block_str != NULL); if (pmemblk_read(pbp, buf, strtoul(block_str, NULL, 10))) { perror("pmemblk_read failed"); free(buf); break; } buf[bsize - 1] = '\0'; printf("%s\n", buf); free(buf); break; } case 'z': { printf("zero: %s\n", argv[i] + 2); const char *block_str = strtok(argv[i] + 2, ":"); assert(block_str != NULL); if (pmemblk_set_zero(pbp, strtoul(block_str, NULL, 10))) perror("pmemblk_set_zero failed"); break; } case 'e': { printf("error: %s\n", argv[i] + 2); const char *block_str = strtok(argv[i] + 2, ":"); assert(block_str != NULL); if (pmemblk_set_error(pbp, strtoul(block_str, NULL, 10))) perror("pmemblk_set_error failed"); break; } case 'n': { printf("nblocks: "); printf("%zu\n", pmemblk_nblock(pbp)); break; } default: { fprintf(stderr, "unrecognized command %s\n", argv[i]); break; } }; } /* all done */ pmemblk_close(pbp); return 0; }
9,447
22.62
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemobjfs/pmemobjfs.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * pmemobjfs.c -- simple filesystem based on libpmemobj tx API */ #include <stdio.h> #include <fuse.h> #include <stdlib.h> #include <libpmemobj.h> #include <libpmem.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <libgen.h> #include <err.h> #include <sys/ioctl.h> #include <linux/kdev_t.h> #include <map.h> #include <map_ctree.h> #ifndef PMEMOBJFS_TRACK_BLOCKS #define PMEMOBJFS_TRACK_BLOCKS 1 #endif #if DEBUG static FILE *log_fh; static uint64_t log_cnt; #define log(fmt, args...) do {\ if (log_fh) {\ fprintf(log_fh, "[%016lx] %s: " fmt "\n", log_cnt, __func__, ## args);\ log_cnt++;\ fflush(log_fh);\ }\ } while (0) #else #define log(fmt, args...) do {} while (0) #endif #define PMEMOBJFS_MOUNT "pmemobjfs" #define PMEMOBJFS_MKFS "mkfs.pmemobjfs" #define PMEMOBJFS_TX_BEGIN "pmemobjfs.tx_begin" #define PMEMOBJFS_TX_COMMIT "pmemobjfs.tx_commit" #define PMEMOBJFS_TX_ABORT "pmemobjfs.tx_abort" #define PMEMOBJFS_TMP_TEMPLATE "/.tx_XXXXXX" #define PMEMOBJFS_CTL 'I' #define PMEMOBJFS_CTL_TX_BEGIN _IO(PMEMOBJFS_CTL, 1) #define PMEMOBJFS_CTL_TX_COMMIT _IO(PMEMOBJFS_CTL, 2) #define PMEMOBJFS_CTL_TX_ABORT _IO(PMEMOBJFS_CTL, 3) /* * struct pmemobjfs -- volatile state of pmemobjfs */ struct pmemobjfs { PMEMobjpool *pop; struct map_ctx *mapc; uint64_t pool_uuid_lo; int ioctl_cmd; uint64_t ioctl_off; uint64_t block_size; uint64_t max_name; }; #define PMEMOBJFS (struct pmemobjfs *)fuse_get_context()->private_data #define PDLL_ENTRY(type)\ struct {\ TOID(type) next;\ TOID(type) prev;\ } #define PDLL_HEAD(type)\ struct {\ TOID(type) first;\ TOID(type) last;\ } #define PDLL_HEAD_INIT(head) do {\ ((head)).first = ((typeof((head).first))OID_NULL);\ ((head)).last = ((typeof((head).first))OID_NULL);\ } while (0) #define PDLL_FOREACH(entry, head, field)\ for ((entry) = ((head)).first; !TOID_IS_NULL(entry);\ (entry) = D_RO(entry)->field.next) #define PDLL_FOREACH_SAFE(entry, next, head, field)\ for ((entry) = ((head)).first; !TOID_IS_NULL(entry) &&\ ((next) = D_RO(entry)->field.next, 1);\ (entry) = (next)) #define PDLL_INSERT_HEAD(head, entry, field) do {\ pmemobj_tx_add_range_direct(&(head).first, sizeof((head).first));\ TX_ADD_FIELD(entry, field);\ D_RW(entry)->field.next = (head).first;\ D_RW(entry)->field.prev =\ (typeof(D_RW(entry)->field.prev))OID_NULL;\ (head).first = entry;\ if (TOID_IS_NULL((head).last)) {\ pmemobj_tx_add_range_direct(&(head).last, sizeof((head).last));\ (head).last = entry;\ }\ typeof(entry) next = D_RO(entry)->field.next;\ if (!TOID_IS_NULL(next)) {\ pmemobj_tx_add_range_direct(&D_RW(next)->field.prev,\ sizeof(D_RW(next)->field.prev));\ D_RW(next)->field.prev = entry;\ }\ } while (0) #define PDLL_REMOVE(head, entry, field) do {\ if (TOID_EQUALS((head).first, entry) &&\ TOID_EQUALS((head).last, entry)) {\ pmemobj_tx_add_range_direct(&(head).first,\ sizeof((head).first));\ pmemobj_tx_add_range_direct(&(head).last, sizeof((head).last));\ (head).first = (typeof(D_RW(entry)->field.prev))OID_NULL;\ (head).last = (typeof(D_RW(entry)->field.prev))OID_NULL;\ } else if (TOID_EQUALS((head).first, entry)) {\ typeof(entry) next = D_RW(entry)->field.next;\ pmemobj_tx_add_range_direct(&D_RW(next)->field.prev,\ sizeof(D_RW(next)->field.prev));\ pmemobj_tx_add_range_direct(&(head).first,\ sizeof((head).first));\ (head).first = D_RO(entry)->field.next;\ D_RW(next)->field.prev.oid = OID_NULL;\ } else if (TOID_EQUALS((head).last, entry)) {\ typeof(entry) prev = D_RW(entry)->field.prev;\ pmemobj_tx_add_range_direct(&D_RW(prev)->field.next,\ sizeof(D_RW(prev)->field.next));\ pmemobj_tx_add_range_direct(&(head).last, sizeof((head).last));\ (head).last = D_RO(entry)->field.prev;\ D_RW(prev)->field.next.oid = OID_NULL;\ } else {\ typeof(entry) prev = D_RW(entry)->field.prev;\ typeof(entry) next = D_RW(entry)->field.next;\ pmemobj_tx_add_range_direct(&D_RW(prev)->field.next,\ sizeof(D_RW(prev)->field.next));\ pmemobj_tx_add_range_direct(&D_RW(next)->field.prev,\ sizeof(D_RW(next)->field.prev));\ D_RW(prev)->field.next = D_RO(entry)->field.next;\ D_RW(next)->field.prev = D_RO(entry)->field.prev;\ }\ } while (0) typedef uint8_t objfs_block_t; /* * pmemobjfs persistent layout */ POBJ_LAYOUT_BEGIN(pmemobjfs); POBJ_LAYOUT_ROOT(pmemobjfs, struct objfs_super); POBJ_LAYOUT_TOID(pmemobjfs, struct objfs_inode); POBJ_LAYOUT_TOID(pmemobjfs, struct objfs_dir_entry); POBJ_LAYOUT_TOID(pmemobjfs, objfs_block_t); POBJ_LAYOUT_TOID(pmemobjfs, char); POBJ_LAYOUT_END(pmemobjfs); #define PMEMOBJFS_MIN_BLOCK_SIZE ((size_t)(512 - 64)) /* * struct objfs_super -- pmemobjfs super (root) object */ struct objfs_super { TOID(struct objfs_inode) root_inode; /* root dir inode */ TOID(struct map) opened; /* map of opened files / dirs */ uint64_t block_size; /* size of data block */ }; /* * struct objfs_dir_entry -- pmemobjfs directory entry structure */ struct objfs_dir_entry { PDLL_ENTRY(struct objfs_dir_entry) pdll; /* list entry */ TOID(struct objfs_inode) inode; /* pointer to inode */ char name[]; /* name */ }; /* * struct objfs_dir -- pmemobjfs directory structure */ struct objfs_dir { PDLL_HEAD(struct objfs_dir_entry) entries; /* directory entries */ }; /* * key == 0 for ctree_map is not allowed */ #define GET_KEY(off) ((off) + 1) /* * struct objfs_file -- pmemobjfs file structure */ struct objfs_file { TOID(struct map) blocks; /* blocks map */ }; /* * struct objfs_symlink -- symbolic link */ struct objfs_symlink { uint64_t len; /* length of symbolic link */ TOID(char) name; /* symbolic link data */ }; /* * struct objfs_inode -- pmemobjfs inode structure */ struct objfs_inode { uint64_t size; /* size of file */ uint64_t flags; /* file flags */ uint64_t dev; /* device info */ uint32_t ctime; /* time of last status change */ uint32_t mtime; /* time of last modification */ uint32_t atime; /* time of last access */ uint32_t uid; /* user ID */ uint32_t gid; /* group ID */ uint32_t ref; /* reference counter */ struct objfs_file file; /* file specific data */ struct objfs_dir dir; /* directory specific data */ struct objfs_symlink symlink; /* symlink specific data */ }; /* * pmemobjfs_ioctl -- do the ioctl command */ static void pmemobjfs_ioctl(struct pmemobjfs *objfs) { switch (objfs->ioctl_cmd) { case PMEMOBJFS_CTL_TX_BEGIN: (void) pmemobj_tx_begin(objfs->pop, NULL, TX_PARAM_NONE); break; case PMEMOBJFS_CTL_TX_ABORT: pmemobj_tx_abort(-1); (void) pmemobj_tx_end(); break; case PMEMOBJFS_CTL_TX_COMMIT: pmemobj_tx_commit(); (void) pmemobj_tx_end(); break; default: break; } /* clear deferred inode offset and command */ objfs->ioctl_cmd = 0; objfs->ioctl_off = 0; } /* * pmemobjfs_inode_alloc -- allocate inode structure */ static TOID(struct objfs_inode) pmemobjfs_inode_alloc(struct pmemobjfs *objfs, uint64_t flags, uint32_t uid, uint32_t gid, uint64_t dev) { TOID(struct objfs_inode) inode = TOID_NULL(struct objfs_inode); TX_BEGIN(objfs->pop) { inode = TX_ZNEW(struct objfs_inode); time_t cur_time = time(NULL); D_RW(inode)->flags = flags; D_RW(inode)->dev = dev; D_RW(inode)->ctime = cur_time; D_RW(inode)->mtime = cur_time; D_RW(inode)->atime = cur_time; D_RW(inode)->uid = uid; D_RW(inode)->gid = gid; D_RW(inode)->ref = 0; } TX_ONABORT { inode = TOID_NULL(struct objfs_inode); } TX_END return inode; } /* * pmemobjfs_inode_init_dir -- initialize directory in inode */ static void pmemobjfs_inode_init_dir(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TX_BEGIN(objfs->pop) { PDLL_HEAD_INIT(D_RW(inode)->dir.entries); } TX_END; } /* * pmemobjfs_inode_destroy_dir -- destroy directory from inode */ static void pmemobjfs_inode_destroy_dir(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { /* nothing to do */ } /* * pmemobjfs_file_alloc -- allocate file structure */ static void pmemobjfs_inode_init_file(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TX_BEGIN(objfs->pop) { map_create(objfs->mapc, &D_RW(inode)->file.blocks, NULL); } TX_END } /* * pmemobjfs_file_free -- free file structure */ static void pmemobjfs_inode_destroy_file(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TX_BEGIN(objfs->pop) { map_destroy(objfs->mapc, &D_RW(inode)->file.blocks); } TX_END } /* * pmemobjfs_inode_hold -- increase reference counter of inode */ static void pmemobjfs_inode_hold(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { if (TOID_IS_NULL(inode)) return; TX_BEGIN(objfs->pop) { /* update number of references */ TX_ADD_FIELD(inode, ref); D_RW(inode)->ref++; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = time(NULL); } TX_END } /* * pmemobjfs_dir_entry_alloc -- allocate directory entry structure */ static TOID(struct objfs_dir_entry) pmemobjfs_dir_entry_alloc(struct pmemobjfs *objfs, const char *name, TOID(struct objfs_inode) inode) { TOID(struct objfs_dir_entry) entry = TOID_NULL(struct objfs_dir_entry); TX_BEGIN(objfs->pop) { size_t len = strlen(name) + 1; entry = TX_ALLOC(struct objfs_dir_entry, objfs->block_size); memcpy(D_RW(entry)->name, name, len); D_RW(entry)->inode = inode; pmemobjfs_inode_hold(objfs, inode); } TX_ONABORT { entry = TOID_NULL(struct objfs_dir_entry); } TX_END return entry; } /* * pmemobjfs_dir_entry_free -- free dir entry structure */ static void pmemobjfs_dir_entry_free(struct pmemobjfs *objfs, TOID(struct objfs_dir_entry) entry) { TX_BEGIN(objfs->pop) { TX_FREE(entry); } TX_END } /* * pmemobjfs_inode_init_symlink -- initialize symbolic link */ static void pmemobjfs_inode_init_symlink(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name) { TX_BEGIN(objfs->pop) { size_t len = strlen(name) + 1; D_RW(inode)->symlink.len = len; TOID_ASSIGN(D_RW(inode)->symlink.name, TX_STRDUP(name, TOID_TYPE_NUM(char))); } TX_END } /* * pmemobjfs_inode_destroy_symlink -- destroy symbolic link */ static void pmemobjfs_inode_destroy_symlink(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TX_BEGIN(objfs->pop) { TX_FREE(D_RO(inode)->symlink.name); } TX_END } /* * pmemobjfs_symlink_read -- read symlink to buffer */ static int pmemobjfs_symlink_read(TOID(struct objfs_inode) inode, char *buff, size_t size) { /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFLNK: break; case S_IFDIR: return -EISDIR; case S_IFREG: default: return -EINVAL; } char *name = D_RW(D_RW(inode)->symlink.name); strncpy(buff, name, size); return 0; } /* * pmemobjfs_symlink_size -- get size of symlink */ static size_t pmemobjfs_symlink_size(TOID(struct objfs_inode) inode) { return D_RO(inode)->symlink.len - 1; } /* * pmemobjfs_inode_free -- free inode structure */ static void pmemobjfs_inode_free(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TX_BEGIN(objfs->pop) { /* release data specific for inode type */ if (S_ISREG(D_RO(inode)->flags)) { pmemobjfs_inode_destroy_file(objfs, inode); } else if (S_ISDIR(D_RO(inode)->flags)) { pmemobjfs_inode_destroy_dir(objfs, inode); } else if (S_ISLNK(D_RO(inode)->flags)) { pmemobjfs_inode_destroy_symlink(objfs, inode); } TX_FREE(inode); } TX_END } /* * pmemobjfs_inode_put -- decrease reference counter of inode and free */ static void pmemobjfs_inode_put(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { if (TOID_IS_NULL(inode)) return; TX_BEGIN(objfs->pop) { /* update number of references */ TX_ADD_FIELD(inode, ref); D_RW(inode)->ref--; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = time(NULL); if (!D_RO(inode)->ref) pmemobjfs_inode_free(objfs, inode); } TX_END } /* * pmemobjfs_dir_get_inode -- get inode from dir of given name */ static TOID(struct objfs_inode) pmemobjfs_dir_get_inode(TOID(struct objfs_inode) inode, const char *name) { log("%s", name); TOID(struct objfs_dir_entry) entry; PDLL_FOREACH(entry, D_RW(inode)->dir.entries, pdll) { if (strcmp(name, D_RO(entry)->name) == 0) return D_RO(entry)->inode; } return TOID_NULL(struct objfs_inode); } /* * pmemobjfs_get_dir_entry -- get dir entry from dir of given name */ static TOID(struct objfs_dir_entry) pmemobjfs_get_dir_entry(TOID(struct objfs_inode) inode, const char *name) { log("%s", name); TOID(struct objfs_dir_entry) entry; PDLL_FOREACH(entry, D_RW(inode)->dir.entries, pdll) { if (strcmp(name, D_RO(entry)->name) == 0) return entry; } return TOID_NULL(struct objfs_dir_entry); } /* * pmemobjfs_inode_lookup_parent -- lookup for parent inode and child name */ static int pmemobjfs_inode_lookup_parent(struct pmemobjfs *objfs, const char *path, TOID(struct objfs_inode) *inodep, const char **child) { log("%s", path); TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); TOID(struct objfs_inode) cur = D_RO(super)->root_inode; TOID(struct objfs_inode) par = TOID_NULL(struct objfs_inode); if (path[0] == '/') path++; int ret = 0; char *p = strdup(path); char *name = p; char *ch = NULL; while (name && *name != '\0' && !TOID_IS_NULL(cur)) { char *slash = strchr(name, '/'); if (slash) { *slash = '\0'; slash++; } if (!S_ISDIR(D_RO(cur)->flags)) { ret = -ENOTDIR; goto out; } if (strlen(name) > objfs->max_name) { ret = -ENAMETOOLONG; goto out; } par = cur; cur = pmemobjfs_dir_get_inode(cur, name); ch = name; name = slash; } if (child) { if (strchr(ch, '/')) { ret = -ENOENT; goto out; } if (TOID_IS_NULL(par)) { ret = -ENOENT; goto out; } cur = par; size_t parent_len = ch - p; *child = path + parent_len; } else { if (TOID_IS_NULL(cur)) ret = -ENOENT; } if (inodep) *inodep = cur; out: free(p); return ret; } /* * pmemobjfs_inode_lookup -- get inode for given path */ static int pmemobjfs_inode_lookup(struct pmemobjfs *objfs, const char *path, TOID(struct objfs_inode) *inodep) { log("%s", path); return pmemobjfs_inode_lookup_parent(objfs, path, inodep, NULL); } /* * pmemobjfs_file_get_block -- get block at given offset */ static TOID(objfs_block_t) pmemobjfs_file_get_block(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, uint64_t offset) { TOID(objfs_block_t) block; PMEMoid block_oid = map_get(objfs->mapc, D_RO(inode)->file.blocks, GET_KEY(offset)); TOID_ASSIGN(block, block_oid); return block; } /* * pmemobjfs_file_get_block_for_write -- get or allocate block at given offset */ static TOID(objfs_block_t) pmemobjfs_file_get_block_for_write(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, uint64_t offset) { TOID(objfs_block_t) block = pmemobjfs_file_get_block(objfs, inode, offset); if (TOID_IS_NULL(block)) { TX_BEGIN(objfs->pop) { block = TX_ALLOC(objfs_block_t, objfs->block_size); map_insert(objfs->mapc, D_RW(inode)->file.blocks, GET_KEY(offset), block.oid); } TX_ONABORT { block = TOID_NULL(objfs_block_t); } TX_END } else { #if PMEMOBJFS_TRACK_BLOCKS TX_ADD(block); #endif } return block; } /* * pmemobjfs_truncate -- truncate file */ static int pmemobjfs_truncate(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, off_t off) { /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } int ret = 0; TX_BEGIN(objfs->pop) { off_t old_off = D_RO(inode)->size; if (old_off > off) { /* release blocks */ uint64_t old_boff = (old_off - 1) / objfs->block_size; uint64_t boff = (off + 1) / objfs->block_size; for (uint64_t o = boff; o <= old_boff; o++) { map_remove_free(objfs->mapc, D_RW(inode)->file.blocks, GET_KEY(o)); } } time_t t = time(NULL); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; /* update size */ TX_ADD_FIELD(inode, size); D_RW(inode)->size = off; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_read -- read from file */ static int pmemobjfs_read(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, char *buff, size_t size, off_t offset) { /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } uint64_t fsize = D_RO(inode)->size; size_t sz = size; size_t off = offset; while (sz > 0) { if (off >= fsize) break; uint64_t block_id = off / objfs->block_size; uint64_t block_off = off % objfs->block_size; uint64_t block_size = sz < objfs->block_size ? sz : objfs->block_size; TOID(objfs_block_t) block = pmemobjfs_file_get_block(objfs, inode, block_id); if (block_off + block_size > objfs->block_size) block_size = objfs->block_size - block_off; if (TOID_IS_NULL(block)) { memset(buff, 0, block_size); } else { memcpy(buff, &D_RW(block)[block_off], block_size); } buff += block_size; off += block_size; sz -= block_size; } return size - sz; } /* * pmemobjfs_write -- write to file */ static int pmemobjfs_write(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *buff, size_t size, off_t offset) { /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } int ret = 0; TX_BEGIN(objfs->pop) { size_t sz = size; off_t off = offset; while (sz > 0) { uint64_t block_id = off / objfs->block_size; uint64_t block_off = off % objfs->block_size; uint64_t block_size = sz < objfs->block_size ? sz : objfs->block_size; TOID(objfs_block_t) block = pmemobjfs_file_get_block_for_write(objfs, inode, block_id); if (TOID_IS_NULL(block)) return -ENOSPC; if (block_off + block_size > objfs->block_size) block_size = objfs->block_size - block_off; memcpy(&D_RW(block)[block_off], buff, block_size); buff += block_size; off += block_size; sz -= block_size; } time_t t = time(NULL); if (offset + size > D_RO(inode)->size) { /* update size */ TX_ADD_FIELD(inode, size); D_RW(inode)->size = offset + size; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; } /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; } TX_ONCOMMIT { ret = size; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_fallocate -- allocate blocks for file */ static int pmemobjfs_fallocate(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, off_t offset, off_t size) { /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } int ret = 0; TX_BEGIN(objfs->pop) { /* allocate blocks from requested range */ uint64_t b_off = offset / objfs->block_size; uint64_t e_off = (offset + size) / objfs->block_size; for (uint64_t off = b_off; off <= e_off; off++) pmemobjfs_file_get_block_for_write(objfs, inode, off); time_t t = time(NULL); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; /* update inode size */ D_RW(inode)->size = offset + size; TX_ADD_FIELD(inode, size); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_remove_dir_entry -- remove dir entry from directory */ static void pmemobjfs_remove_dir_entry(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, TOID(struct objfs_dir_entry) entry) { TX_BEGIN(objfs->pop) { pmemobjfs_inode_put(objfs, D_RO(entry)->inode); PDLL_REMOVE(D_RW(inode)->dir.entries, entry, pdll); pmemobjfs_dir_entry_free(objfs, entry); } TX_END } /* * pmemobjfs_remove_dir_entry_name -- remove dir entry of given name */ static void pmemobjfs_remove_dir_entry_name(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name) { TX_BEGIN(objfs->pop) { TOID(struct objfs_dir_entry) entry = pmemobjfs_get_dir_entry(inode, name); pmemobjfs_remove_dir_entry(objfs, inode, entry); } TX_END } /* * pmemobjfs_add_dir_entry -- add new directory entry */ static int pmemobjfs_add_dir_entry(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, TOID(struct objfs_dir_entry) entry) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; int ret = 0; TX_BEGIN(objfs->pop) { /* insert new dir entry to list */ PDLL_INSERT_HEAD(D_RW(inode)->dir.entries, entry, pdll); /* update dir size */ TX_ADD_FIELD(inode, size); D_RW(inode)->size++; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_unlink_dir_entry -- unlink directory entry */ static int pmemobjfs_unlink_dir_entry(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, TOID(struct objfs_dir_entry) entry) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; int ret = 0; TX_BEGIN(objfs->pop) { pmemobjfs_remove_dir_entry(objfs, inode, entry); /* update dir size */ TX_ADD_FIELD(inode, size); D_RW(inode)->size--; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_new_dir -- create new directory */ static TOID(struct objfs_inode) pmemobjfs_new_dir(struct pmemobjfs *objfs, TOID(struct objfs_inode) parent, const char *name, uint64_t flags, uint32_t uid, uint32_t gid) { TOID(struct objfs_inode) inode = TOID_NULL(struct objfs_inode); TX_BEGIN(objfs->pop) { inode = pmemobjfs_inode_alloc(objfs, flags, uid, gid, 0); pmemobjfs_inode_init_dir(objfs, inode); /* add . and .. to new directory */ TOID(struct objfs_dir_entry) dot = pmemobjfs_dir_entry_alloc(objfs, ".", inode); TOID(struct objfs_dir_entry) dotdot = pmemobjfs_dir_entry_alloc(objfs, "..", parent); pmemobjfs_add_dir_entry(objfs, inode, dot); pmemobjfs_add_dir_entry(objfs, inode, dotdot); } TX_ONABORT { inode = TOID_NULL(struct objfs_inode); } TX_END return inode; } /* * pmemobjfs_mkdir -- make new directory */ static int pmemobjfs_mkdir(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name, uint64_t flags, uint32_t uid, uint32_t gid) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; int ret = 0; TX_BEGIN(objfs->pop) { TOID(struct objfs_inode) new_inode = pmemobjfs_new_dir(objfs, inode, name, flags, uid, gid); TOID(struct objfs_dir_entry) entry = pmemobjfs_dir_entry_alloc(objfs, name, new_inode); pmemobjfs_add_dir_entry(objfs, inode, entry); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = time(NULL); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_remove_dir -- remove directory from directory */ static void pmemobjfs_remove_dir(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, TOID(struct objfs_dir_entry) entry) { /* removing entry inode */ TOID(struct objfs_inode) rinode = D_RO(entry)->inode; TX_BEGIN(objfs->pop) { /* remove . and .. from removing dir */ pmemobjfs_remove_dir_entry_name(objfs, rinode, "."); pmemobjfs_remove_dir_entry_name(objfs, rinode, ".."); /* remove dir entry from parent */ pmemobjfs_remove_dir_entry(objfs, inode, entry); } TX_END } /* * pmemobjfs_rmdir -- remove directory of given name */ static int pmemobjfs_rmdir(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name) { /* check parent inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; TOID(struct objfs_dir_entry) entry = pmemobjfs_get_dir_entry(inode, name); if (TOID_IS_NULL(entry)) return -ENOENT; TOID(struct objfs_inode) entry_inode = D_RO(entry)->inode; /* check removing dir type */ if (!S_ISDIR(D_RO(entry_inode)->flags)) return -ENOTDIR; /* check if dir is empty (contains only . and ..) */ if (D_RO(entry_inode)->size > 2) return -ENOTEMPTY; int ret = 0; TX_BEGIN(objfs->pop) { pmemobjfs_remove_dir(objfs, inode, entry); /* update dir size */ TX_ADD_FIELD(inode, size); D_RW(inode)->size--; /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = time(NULL); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_create -- create new file in directory */ static int pmemobjfs_create(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name, mode_t mode, uid_t uid, gid_t gid, TOID(struct objfs_inode) *inodep) { int ret = 0; uint64_t flags = mode | S_IFREG; TOID(struct objfs_dir_entry) entry = TOID_NULL(struct objfs_dir_entry); TX_BEGIN(objfs->pop) { TOID(struct objfs_inode) new_file= pmemobjfs_inode_alloc(objfs, flags, uid, gid, 0); pmemobjfs_inode_init_file(objfs, new_file); entry = pmemobjfs_dir_entry_alloc(objfs, name, new_file); pmemobjfs_add_dir_entry(objfs, inode, entry); time_t t = time(NULL); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; } TX_ONABORT { ret = -ECANCELED; } TX_ONCOMMIT { if (inodep) *inodep = D_RO(entry)->inode; } TX_END return ret; } /* * pmemobjfs_open -- open inode */ static int pmemobjfs_open(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); int ret = 0; TX_BEGIN(objfs->pop) { /* insert inode to opened inodes map */ map_insert(objfs->mapc, D_RW(super)->opened, inode.oid.off, inode.oid); /* hold inode */ pmemobjfs_inode_hold(objfs, inode); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_close -- release inode */ static int pmemobjfs_close(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode) { TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); int ret = 0; TX_BEGIN(objfs->pop) { /* remove inode from opened inodes map */ map_remove(objfs->mapc, D_RW(super)->opened, inode.oid.off); /* release inode */ pmemobjfs_inode_put(objfs, inode); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_rename -- rename/move inode */ static int pmemobjfs_rename(struct pmemobjfs *objfs, TOID(struct objfs_inode) src_parent, const char *src_name, TOID(struct objfs_inode) dst_parent, const char *dst_name) { /* check source and destination inodes type */ if (!S_ISDIR(D_RO(src_parent)->flags)) return -ENOTDIR; if (!S_ISDIR(D_RO(dst_parent)->flags)) return -ENOTDIR; /* get source dir entry */ TOID(struct objfs_dir_entry) src_entry = pmemobjfs_get_dir_entry(src_parent, src_name); TOID(struct objfs_inode) src_inode = D_RO(src_entry)->inode; if (TOID_IS_NULL(src_entry)) return -ENOENT; int ret = 0; TX_BEGIN(objfs->pop) { /* * Allocate new dir entry with destination name * and source inode. * NOTE: * This *must* be called before removing dir entry from * source directory because otherwise the source inode * could be released before inserting to new dir entry. */ TOID(struct objfs_dir_entry) dst_entry = pmemobjfs_dir_entry_alloc(objfs, dst_name, src_inode); /* remove old dir entry from source */ pmemobjfs_unlink_dir_entry(objfs, src_parent, src_entry); /* add new dir entry to destination */ pmemobjfs_add_dir_entry(objfs, dst_parent, dst_entry); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_symlink -- create symbolic link */ static int pmemobjfs_symlink(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name, const char *path, uid_t uid, gid_t gid) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; /* set 0777 permissions for symbolic links */ uint64_t flags = 0777 | S_IFLNK; int ret = 0; TX_BEGIN(objfs->pop) { TOID(struct objfs_inode) symlink = pmemobjfs_inode_alloc(objfs, flags, uid, gid, 0); pmemobjfs_inode_init_symlink(objfs, symlink, path); D_RW(symlink)->size = pmemobjfs_symlink_size(symlink); TOID(struct objfs_dir_entry) entry = pmemobjfs_dir_entry_alloc(objfs, name, symlink); pmemobjfs_add_dir_entry(objfs, inode, entry); time_t t = time(NULL); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_mknod -- create node */ static int pmemobjfs_mknod(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name, mode_t mode, uid_t uid, gid_t gid, dev_t dev) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; int ret = 0; TX_BEGIN(objfs->pop) { TOID(struct objfs_inode) node = pmemobjfs_inode_alloc(objfs, mode, uid, gid, dev); D_RW(node)->size = 0; TOID(struct objfs_dir_entry) entry = pmemobjfs_dir_entry_alloc(objfs, name, node); pmemobjfs_add_dir_entry(objfs, inode, entry); time_t t = time(NULL); /* update modification time */ TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = t; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = t; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_chmod -- change mode of inode */ static int pmemobjfs_chmod(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, mode_t mode) { int ret = 0; TX_BEGIN(objfs->pop) { TX_ADD_FIELD(inode, flags); /* mask file type bit fields */ uint64_t flags = D_RO(inode)->flags; flags = flags & S_IFMT; D_RW(inode)->flags = flags | (mode & ~S_IFMT); /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = time(NULL); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_chown -- change owner and group of inode */ static int pmemobjfs_chown(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, uid_t uid, gid_t gid) { int ret = 0; TX_BEGIN(objfs->pop) { TX_ADD_FIELD(inode, uid); D_RW(inode)->uid = uid; TX_ADD_FIELD(inode, gid); D_RW(inode)->gid = gid; /* update status change time */ TX_ADD_FIELD(inode, ctime); D_RW(inode)->ctime = time(NULL); } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_getattr -- get inode's attributes */ static int pmemobjfs_getattr(TOID(struct objfs_inode) inode, struct stat *statbuf) { memset(statbuf, 0, sizeof(*statbuf)); statbuf->st_size = D_RO(inode)->size; statbuf->st_ctime = D_RO(inode)->ctime; statbuf->st_mtime = D_RO(inode)->mtime; statbuf->st_atime = D_RO(inode)->atime; statbuf->st_mode = D_RO(inode)->flags; statbuf->st_uid = D_RO(inode)->uid; statbuf->st_gid = D_RO(inode)->gid; statbuf->st_rdev = D_RO(inode)->dev; return 0; } /* * pmemobjfs_utimens -- set atime and mtime */ static int pmemobjfs_utimens(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const struct timespec tv[2]) { int ret = 0; TX_BEGIN(objfs->pop) { TX_ADD_FIELD(inode, atime); D_RW(inode)->atime = tv[0].tv_sec; TX_ADD_FIELD(inode, mtime); D_RW(inode)->mtime = tv[0].tv_sec; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_unlink -- unlink file from inode */ static int pmemobjfs_unlink(struct pmemobjfs *objfs, TOID(struct objfs_inode) inode, const char *name) { /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; TOID(struct objfs_dir_entry) entry = pmemobjfs_get_dir_entry(inode, name); if (TOID_IS_NULL(entry)) return -ENOENT; TOID(struct objfs_inode) entry_inode = D_RO(entry)->inode; /* check unlinking inode type */ if (S_ISDIR(D_RO(entry_inode)->flags)) return -EISDIR; int ret = 0; TX_BEGIN(objfs->pop) { pmemobjfs_remove_dir_entry(objfs, inode, entry); TX_ADD_FIELD(inode, size); D_RW(inode)->size--; } TX_ONABORT { ret = -ECANCELED; } TX_END return ret; } /* * pmemobjfs_put_opened_cb -- release all opened inodes */ static int pmemobjfs_put_opened_cb(uint64_t key, PMEMoid value, void *arg) { struct pmemobjfs *objfs = arg; TOID(struct objfs_inode) inode; TOID_ASSIGN(inode, value); TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); /* * Set current value to OID_NULL so the tree_map_clear won't * free this inode and release the inode. */ map_insert(objfs->mapc, D_RW(super)->opened, key, OID_NULL); pmemobjfs_inode_put(objfs, inode); return 0; } /* * pmemobjfs_fuse_getattr -- (FUSE) get file attributes */ static int pmemobjfs_fuse_getattr(const char *path, struct stat *statbuf) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_getattr(inode, statbuf); } /* * pmemobjfs_fuse_opendir -- (FUSE) open directory */ static int pmemobjfs_fuse_opendir(const char *path, struct fuse_file_info *fi) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFDIR: break; case S_IFREG: return -ENOTDIR; default: return -EINVAL; } /* add inode to opened inodes map */ ret = pmemobjfs_open(objfs, inode); if (!ret) fi->fh = inode.oid.off; return ret; } /* * pmemobjfs_fuse_releasedir -- (FUSE) release opened dir */ static int pmemobjfs_fuse_releasedir(const char *path, struct fuse_file_info *fi) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; /* remove inode from opened inodes map */ int ret = pmemobjfs_close(objfs, inode); fi->fh = 0; return ret; } /* * pmemobjfs_fuse_readdir -- (FUSE) read directory entries */ static int pmemobjfs_fuse_readdir(const char *path, void *buff, fuse_fill_dir_t fill, off_t off, struct fuse_file_info *fi) { log("%s off = %lu", path, off); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; /* check inode type */ if (!S_ISDIR(D_RO(inode)->flags)) return -ENOTDIR; /* walk through all dir entries and fill fuse buffer */ int ret; TOID(struct objfs_dir_entry) entry; PDLL_FOREACH(entry, D_RW(inode)->dir.entries, pdll) { ret = fill(buff, D_RW(entry)->name, NULL, 0); if (ret) return ret; } return 0; } /* * pmemobjfs_fuse_mkdir -- (FUSE) create directory */ static int pmemobjfs_fuse_mkdir(const char *path, mode_t mode) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, path, &inode, &name); if (ret) return ret; uid_t uid = fuse_get_context()->uid; uid_t gid = fuse_get_context()->gid; return pmemobjfs_mkdir(objfs, inode, name, mode | S_IFDIR, uid, gid); } /* * pmemobjfs_fuse_rmdir -- (FUSE) remove directory */ static int pmemobjfs_fuse_rmdir(const char *path) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, path, &inode, &name); if (ret) return ret; return pmemobjfs_rmdir(objfs, inode, name); } /* * pmemobjfs_fuse_chmod -- (FUSE) change file permissions */ static int pmemobjfs_fuse_chmod(const char *path, mode_t mode) { log("%s 0%o", path, mode); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_chmod(objfs, inode, mode); } /* * pmemobjfs_fuse_chown -- (FUSE) change owner */ static int pmemobjfs_fuse_chown(const char *path, uid_t uid, gid_t gid) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_chown(objfs, inode, uid, gid); } /* * pmemobjfs_fuse_create -- (FUSE) create file */ static int pmemobjfs_fuse_create(const char *path, mode_t mode, struct fuse_file_info *fi) { log("%s mode %o", path, mode); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, path, &inode, &name); if (ret) return ret; if (!S_ISDIR(D_RO(inode)->flags)) return -EINVAL; uid_t uid = fuse_get_context()->uid; uid_t gid = fuse_get_context()->gid; TOID(struct objfs_inode) new_file; ret = pmemobjfs_create(objfs, inode, name, mode, uid, gid, &new_file); if (ret) return ret; /* add new inode to opened inodes */ ret = pmemobjfs_open(objfs, new_file); if (ret) return ret; fi->fh = new_file.oid.off; return 0; } /* * pmemobjfs_fuse_utimens -- (FUSE) update access and modification times */ static int pmemobjfs_fuse_utimens(const char *path, const struct timespec tv[2]) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_utimens(objfs, inode, tv); } /* * pmemobjfs_fuse_open -- (FUSE) open file */ static int pmemobjfs_fuse_open(const char *path, struct fuse_file_info *fi) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } ret = pmemobjfs_open(objfs, inode); if (!ret) fi->fh = inode.oid.off; return ret; } /* * pmemobjfs_fuse_release -- (FUSE) release opened file */ static int pmemobjfs_fuse_release(const char *path, struct fuse_file_info *fi) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; int ret = pmemobjfs_close(objfs, inode); /* perform deferred ioctl operation */ if (!ret && objfs->ioctl_off && objfs->ioctl_off == fi->fh) pmemobjfs_ioctl(objfs); fi->fh = 0; return ret; } /* * pmemobjfs_fuse_write -- (FUSE) write to file */ static int pmemobjfs_fuse_write(const char *path, const char *buff, size_t size, off_t offset, struct fuse_file_info *fi) { log("%s size = %zu off = %lu", path, size, offset); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; return pmemobjfs_write(objfs, inode, buff, size, offset); } /* * pmemobjfs_fuse_read -- (FUSE) read from file */ static int pmemobjfs_fuse_read(const char *path, char *buff, size_t size, off_t off, struct fuse_file_info *fi) { log("%s size = %zu off = %lu", path, size, off); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; return pmemobjfs_read(objfs, inode, buff, size, off); } /* * pmemobjfs_fuse_truncate -- (FUSE) truncate file */ static int pmemobjfs_fuse_truncate(const char *path, off_t off) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_truncate(objfs, inode, off); } /* * pmemobjfs_fuse_ftruncate -- (FUSE) truncate file */ static int pmemobjfs_fuse_ftruncate(const char *path, off_t off, struct fuse_file_info *fi) { log("%s off = %lu", path, off); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; return pmemobjfs_truncate(objfs, inode, off); } /* * pmemobjfs_fuse_unlink -- (FUSE) unlink inode */ static int pmemobjfs_fuse_unlink(const char *path) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, path, &inode, &name); if (ret) return ret; return pmemobjfs_unlink(objfs, inode, name); } /* * pmemobjfs_fuse_flush -- (FUSE) flush file */ static int pmemobjfs_fuse_flush(const char *path, struct fuse_file_info *fi) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; /* check inode type */ switch (D_RO(inode)->flags & S_IFMT) { case S_IFREG: break; case S_IFDIR: return -EISDIR; default: return -EINVAL; } /* nothing to do */ return 0; } /* * pmemobjfs_fuse_ioctl -- (FUSE) ioctl for file */ #ifdef __FreeBSD__ #define EBADFD EBADF /* XXX */ #endif static int pmemobjfs_fuse_ioctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi, unsigned flags, void *data) { log("%s cmd %d", path, _IOC_NR(cmd)); struct pmemobjfs *objfs = PMEMOBJFS; /* check transaction stage */ switch (cmd) { case PMEMOBJFS_CTL_TX_BEGIN: if (pmemobj_tx_stage() != TX_STAGE_NONE) return -EINPROGRESS; break; case PMEMOBJFS_CTL_TX_ABORT: if (pmemobj_tx_stage() != TX_STAGE_WORK) return -EBADFD; break; case PMEMOBJFS_CTL_TX_COMMIT: if (pmemobj_tx_stage() != TX_STAGE_WORK) return -EBADFD; break; default: return -EINVAL; } /* * Store the inode offset and command and defer ioctl * execution to releasing the file. This is required * to avoid unlinking .tx_XXXXXX file inside transaction * because one would be rolled back if transaction abort * would occur. */ objfs->ioctl_off = fi->fh; objfs->ioctl_cmd = cmd; return 0; } /* * pmemobjfs_fuse_rename -- (FUSE) rename file or directory */ static int pmemobjfs_fuse_rename(const char *path, const char *dest) { log("%s dest %s\n", path, dest); struct pmemobjfs *objfs = PMEMOBJFS; int ret; /* get source inode's parent and name */ TOID(struct objfs_inode) src_parent; const char *src_name; ret = pmemobjfs_inode_lookup_parent(objfs, path, &src_parent, &src_name); if (ret) return ret; /* get destination inode's parent and name */ TOID(struct objfs_inode) dst_parent; const char *dst_name; ret = pmemobjfs_inode_lookup_parent(objfs, dest, &dst_parent, &dst_name); if (ret) return ret; return pmemobjfs_rename(objfs, src_parent, src_name, dst_parent, dst_name); } /* * pmemobjfs_fuse_symlink -- (FUSE) create symbolic link */ static int pmemobjfs_fuse_symlink(const char *path, const char *link) { log("%s link %s", path, link); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, link, &inode, &name); if (ret) return ret; uid_t uid = fuse_get_context()->uid; uid_t gid = fuse_get_context()->gid; return pmemobjfs_symlink(objfs, inode, name, path, uid, gid); } /* * pmemobjfs_fuse_readlink -- (FUSE) read symbolic link */ static int pmemobjfs_fuse_readlink(const char *path, char *buff, size_t size) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; int ret = pmemobjfs_inode_lookup(objfs, path, &inode); if (ret) return ret; return pmemobjfs_symlink_read(inode, buff, size); } /* * pmemobjfs_fuse_mknod -- (FUSE) create node */ static int pmemobjfs_fuse_mknod(const char *path, mode_t mode, dev_t dev) { log("%s mode %o major %u minor %u", path, mode, (unsigned)MAJOR(dev), (unsigned)MINOR(dev)); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_inode) inode; const char *name; int ret = pmemobjfs_inode_lookup_parent(objfs, path, &inode, &name); if (ret) return ret; uid_t uid = fuse_get_context()->uid; uid_t gid = fuse_get_context()->gid; return pmemobjfs_mknod(objfs, inode, name, mode, uid, gid, dev); } /* * pmemobjfs_fuse_fallocate -- (FUSE) allocate blocks for file */ static int pmemobjfs_fuse_fallocate(const char *path, int mode, off_t offset, off_t size, struct fuse_file_info *fi) { log("%s mode %d offset %lu size %lu", path, mode, offset, size); struct pmemobjfs *objfs = PMEMOBJFS; if (!fi->fh) return -EINVAL; TOID(struct objfs_inode) inode; inode.oid.off = fi->fh; inode.oid.pool_uuid_lo = objfs->pool_uuid_lo; if (!TOID_VALID(inode)) return -EINVAL; return pmemobjfs_fallocate(objfs, inode, offset, size); } /* * pmemobjfs_fuse_statvfs -- (FUSE) get filesystem info */ static int pmemobjfs_fuse_statvfs(const char *path, struct statvfs *buff) { log("%s", path); struct pmemobjfs *objfs = PMEMOBJFS; memset(buff, 0, sizeof(*buff)); /* * Some fields are ignored by FUSE. * Some fields cannot be set due to the nature of pmemobjfs. */ buff->f_bsize = objfs->block_size; /* ignored buff->f_frsize */ /* unknown buff->f_blocks */ /* unknown buff->f_bfree */ /* unknown buff->f_bavail */ /* unknown buff->f_files */ /* unknown buff->f_ffree */ /* ignored buff->f_favail */ /* ignored buff->f_fsid */ /* ignored buff->f_flag */ buff->f_namemax = objfs->max_name; return 0; } /* * pmemobjfs_fuse_init -- (FUSE) initialization */ static void * pmemobjfs_fuse_init(struct fuse_conn_info *conn) { log(""); struct pmemobjfs *objfs = PMEMOBJFS; TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); /* fill some runtime information */ objfs->block_size = D_RO(super)->block_size; objfs->max_name = objfs->block_size - sizeof(struct objfs_dir_entry); objfs->pool_uuid_lo = super.oid.pool_uuid_lo; TX_BEGIN(objfs->pop) { /* release all opened inodes */ map_foreach(objfs->mapc, D_RW(super)->opened, pmemobjfs_put_opened_cb, objfs); /* clear opened inodes map */ map_clear(objfs->mapc, D_RW(super)->opened); } TX_ONABORT { objfs = NULL; } TX_END return objfs; } /* * pmemobjfs_ops -- fuse operations */ static struct fuse_operations pmemobjfs_ops = { /* filesystem operations */ .init = pmemobjfs_fuse_init, .statfs = pmemobjfs_fuse_statvfs, /* inode operations */ .getattr = pmemobjfs_fuse_getattr, .chmod = pmemobjfs_fuse_chmod, .chown = pmemobjfs_fuse_chown, .utimens = pmemobjfs_fuse_utimens, .ioctl = pmemobjfs_fuse_ioctl, /* directory operations */ .opendir = pmemobjfs_fuse_opendir, .releasedir = pmemobjfs_fuse_releasedir, .readdir = pmemobjfs_fuse_readdir, .mkdir = pmemobjfs_fuse_mkdir, .rmdir = pmemobjfs_fuse_rmdir, .rename = pmemobjfs_fuse_rename, .mknod = pmemobjfs_fuse_mknod, .symlink = pmemobjfs_fuse_symlink, .create = pmemobjfs_fuse_create, .unlink = pmemobjfs_fuse_unlink, /* regular file operations */ .open = pmemobjfs_fuse_open, .release = pmemobjfs_fuse_release, .write = pmemobjfs_fuse_write, .read = pmemobjfs_fuse_read, .flush = pmemobjfs_fuse_flush, .truncate = pmemobjfs_fuse_truncate, .ftruncate = pmemobjfs_fuse_ftruncate, .fallocate = pmemobjfs_fuse_fallocate, /* symlink operations */ .readlink = pmemobjfs_fuse_readlink, }; /* * pmemobjfs_mkfs -- create pmemobjfs filesystem */ static int pmemobjfs_mkfs(const char *fname, size_t size, size_t bsize, mode_t mode) { struct pmemobjfs *objfs = calloc(1, sizeof(*objfs)); if (!objfs) return -1; int ret = 0; objfs->block_size = bsize; objfs->pop = pmemobj_create(fname, POBJ_LAYOUT_NAME(pmemobjfs), size, mode); if (!objfs->pop) { fprintf(stderr, "error: %s\n", pmemobj_errormsg()); ret = -1; goto out_free_objfs; } objfs->mapc = map_ctx_init(MAP_CTREE, objfs->pop); if (!objfs->mapc) { perror("map_ctx_init"); ret = -1; goto out_close_pop; } TOID(struct objfs_super) super = POBJ_ROOT(objfs->pop, struct objfs_super); uid_t uid = getuid(); gid_t gid = getgid(); mode_t mask = umask(0); umask(mask); TX_BEGIN(objfs->pop) { /* inherit permissions from umask */ uint64_t root_flags = S_IFDIR | (~mask & 0777); TX_ADD(super); /* create an opened files map */ map_create(objfs->mapc, &D_RW(super)->opened, NULL); /* create root inode, inherit uid and gid from current user */ D_RW(super)->root_inode = pmemobjfs_new_dir(objfs, TOID_NULL(struct objfs_inode), "/", root_flags, uid, gid); D_RW(super)->block_size = bsize; } TX_ONABORT { fprintf(stderr, "error: creating pmemobjfs aborted\n"); ret = -ECANCELED; } TX_END map_ctx_free(objfs->mapc); out_close_pop: pmemobj_close(objfs->pop); out_free_objfs: free(objfs); return ret; } /* * parse_size -- parse size from string */ static int parse_size(const char *str, uint64_t *sizep) { uint64_t size = 0; int shift = 0; char unit[3] = {0}; int ret = sscanf(str, "%lu%3s", &size, unit); if (ret <= 0) return -1; if (ret == 2) { if ((unit[1] != '\0' && unit[1] != 'B') || unit[2] != '\0') return -1; switch (unit[0]) { case 'K': case 'k': shift = 10; break; case 'M': shift = 20; break; case 'G': shift = 30; break; case 'T': shift = 40; break; case 'P': shift = 50; break; default: return -1; } } if (sizep) *sizep = size << shift; return 0; } /* * pmemobjfs_mkfs_main -- parse arguments and create pmemobjfs */ static int pmemobjfs_mkfs_main(int argc, char *argv[]) { static const char *usage_str = "usage: %s " "[-h] " "[-s <size>] " "[-b <block_size>] " "<file>\n"; if (argc < 2) { fprintf(stderr, usage_str, argv[0]); return -1; } uint64_t size = PMEMOBJ_MIN_POOL; uint64_t bsize = PMEMOBJFS_MIN_BLOCK_SIZE; int opt; const char *optstr = "hs:b:"; int size_used = 0; while ((opt = getopt(argc, argv, optstr)) != -1) { switch (opt) { case 'h': printf(usage_str, argv[0]); return 0; case 'b': if (parse_size(optarg, &bsize)) { fprintf(stderr, "error: invalid block size " "value specified -- '%s'\n", optarg); return -1; } break; case 's': if (parse_size(optarg, &size)) { fprintf(stderr, "error: invalid size " "value specified -- '%s'\n", optarg); return -1; } size_used = 1; break; } } if (optind >= argc) { fprintf(stderr, usage_str, argv[0]); return -1; } const char *path = argv[optind]; if (!access(path, F_OK)) { if (size_used) { fprintf(stderr, "error: cannot use size option " "for existing file\n"); return -1; } size = 0; } else { if (size < PMEMOBJ_MIN_POOL) { fprintf(stderr, "error: minimum size is %lu\n", PMEMOBJ_MIN_POOL); return -1; } } if (bsize < PMEMOBJFS_MIN_BLOCK_SIZE) { fprintf(stderr, "error: minimum block size is %zu\n", PMEMOBJFS_MIN_BLOCK_SIZE); return -1; } return pmemobjfs_mkfs(path, size, bsize, 0777); } /* * pmemobjfs_tx_ioctl -- transaction ioctl * * In order to call the ioctl we need to create a temporary file in * specified directory and call the ioctl on that file. After calling the * ioctl the file is unlinked. The actual action is performed after unlinking * the file so if the operation was to start a transaction the temporary file * won't be unlinked within the transaction. */ static int pmemobjfs_tx_ioctl(const char *dir, int req) { int ret = 0; /* append temporary file template to specified path */ size_t dirlen = strlen(dir); size_t tmpllen = strlen(PMEMOBJFS_TMP_TEMPLATE); char *path = malloc(dirlen + tmpllen + 1); if (!path) return -1; memcpy(path, dir, dirlen); strcpy(path + dirlen, PMEMOBJFS_TMP_TEMPLATE); /* create temporary file */ mode_t prev_umask = umask(S_IRWXG | S_IRWXO); int fd = mkstemp(path); umask(prev_umask); if (fd < 0) { perror(path); ret = -1; goto out_free; } /* perform specified ioctl command */ ret = ioctl(fd, req); if (ret) { perror(path); goto out_unlink; } out_unlink: /* unlink temporary file */ ret = unlink(path); if (ret) perror(path); close(fd); out_free: free(path); return ret; } int main(int argc, char *argv[]) { char *bname = basename(argv[0]); if (strcmp(PMEMOBJFS_MKFS, bname) == 0) { return pmemobjfs_mkfs_main(argc, argv); } else if (strcmp(PMEMOBJFS_TX_BEGIN, bname) == 0) { if (argc != 2) { fprintf(stderr, "usage: %s <dir>\n", bname); return -1; } char *arg = argv[1]; return pmemobjfs_tx_ioctl(arg, PMEMOBJFS_CTL_TX_BEGIN); } else if (strcmp(PMEMOBJFS_TX_COMMIT, bname) == 0) { if (argc != 2) { fprintf(stderr, "usage: %s <dir>\n", bname); return -1; } char *arg = argv[1]; return pmemobjfs_tx_ioctl(arg, PMEMOBJFS_CTL_TX_COMMIT); } else if (strcmp(PMEMOBJFS_TX_ABORT, bname) == 0) { if (argc != 2) { fprintf(stderr, "usage: %s <dir>\n", bname); return -1; } char *arg = argv[1]; return pmemobjfs_tx_ioctl(arg, PMEMOBJFS_CTL_TX_ABORT); } #if DEBUG log_fh = fopen("pmemobjfs.log", "w+"); if (!log_fh) err(-1, "pmemobjfs.log"); log("\n\n\nPMEMOBJFS\n"); #endif const char *fname = argv[argc - 2]; struct pmemobjfs *objfs = calloc(1, sizeof(*objfs)); if (!objfs) { perror("malloc"); return -1; } int ret = 0; objfs->pop = pmemobj_open(fname, POBJ_LAYOUT_NAME(pmemobjfs)); if (objfs->pop == NULL) { perror("pmemobj_open"); ret = -1; goto out; } objfs->mapc = map_ctx_init(MAP_CTREE, objfs->pop); if (!objfs->mapc) { perror("map_ctx_init"); ret = -1; goto out; } argv[argc - 2] = argv[argc - 1]; argv[argc - 1] = NULL; argc--; ret = fuse_main(argc, argv, &pmemobjfs_ops, objfs); pmemobj_close(objfs->pop); out: free(objfs); log("ret = %d", ret); return ret; }
54,306
21.139013
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/slab_allocator/main.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2017, Intel Corporation */ /* * main.c -- example usage of a slab-like mechanism implemented in libpmemobj * * This application does nothing besides demonstrating the example slab * allocator mechanism. * * By using the CTL alloc class API we can instrument libpmemobj to optimally * manage memory for the pool. */ #include <ex_common.h> #include <assert.h> #include <stdio.h> #include "slab_allocator.h" POBJ_LAYOUT_BEGIN(slab_allocator); POBJ_LAYOUT_ROOT(slab_allocator, struct root); POBJ_LAYOUT_TOID(slab_allocator, struct bar); POBJ_LAYOUT_TOID(slab_allocator, struct foo); POBJ_LAYOUT_END(slab_allocator); struct foo { char data[100]; }; struct bar { char data[500]; }; struct root { TOID(struct foo) foop; TOID(struct bar) barp; }; int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: %s file-name\n", argv[0]); return 1; } const char *path = argv[1]; PMEMobjpool *pop; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(btree), PMEMOBJ_MIN_POOL, 0666)) == NULL) { perror("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(btree))) == NULL) { perror("failed to open pool\n"); return 1; } } struct slab_allocator *foo_producer = slab_new(pop, sizeof(struct foo)); assert(foo_producer != NULL); struct slab_allocator *bar_producer = slab_new(pop, sizeof(struct bar)); assert(bar_producer != NULL); TOID(struct root) root = POBJ_ROOT(pop, struct root); if (TOID_IS_NULL(D_RO(root)->foop)) { TX_BEGIN(pop) { TX_SET(root, foop.oid, slab_tx_alloc(foo_producer)); } TX_END } if (TOID_IS_NULL(D_RO(root)->barp)) { slab_alloc(bar_producer, &D_RW(root)->barp.oid, NULL, NULL); } assert(pmemobj_alloc_usable_size(D_RO(root)->foop.oid) == sizeof(struct foo)); assert(pmemobj_alloc_usable_size(D_RO(root)->barp.oid) == sizeof(struct bar)); slab_delete(foo_producer); slab_delete(bar_producer); pmemobj_close(pop); return 0; }
2,066
21.225806
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/slab_allocator/slab_allocator.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2017-2018, Intel Corporation */ /* * slab_allocator.c -- slab-like mechanism for libpmemobj */ #include "slab_allocator.h" #include <stdlib.h> struct slab_allocator { PMEMobjpool *pop; struct pobj_alloc_class_desc class; }; /* * slab_new -- creates a new slab allocator instance */ struct slab_allocator * slab_new(PMEMobjpool *pop, size_t size) { struct slab_allocator *slab = malloc(sizeof(struct slab_allocator)); if (slab == NULL) return NULL; slab->pop = pop; slab->class.header_type = POBJ_HEADER_NONE; slab->class.unit_size = size; slab->class.alignment = 0; /* should be a reasonably high number, but not too crazy */ slab->class.units_per_block = 1000; if (pmemobj_ctl_set(pop, "heap.alloc_class.new.desc", &slab->class) != 0) goto error; return slab; error: free(slab); return NULL; } /* * slab_delete -- deletes an existing slab allocator instance */ void slab_delete(struct slab_allocator *slab) { free(slab); } /* * slab_alloc -- works just like pmemobj_alloc but uses the predefined * blocks from the slab */ int slab_alloc(struct slab_allocator *slab, PMEMoid *oid, pmemobj_constr constructor, void *arg) { return pmemobj_xalloc(slab->pop, oid, slab->class.unit_size, 0, POBJ_CLASS_ID(slab->class.class_id), constructor, arg); } /* * slab_tx_alloc -- works just like pmemobj_tx_alloc but uses the predefined * blocks from the slab */ PMEMoid slab_tx_alloc(struct slab_allocator *slab) { return pmemobj_tx_xalloc(slab->class.unit_size, 0, POBJ_CLASS_ID(slab->class.class_id)); }
1,602
19.551282
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/slab_allocator/slab_allocator.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2017, Intel Corporation */ /* * slab_allocator.h -- slab-like mechanism for libpmemobj */ #ifndef SLAB_ALLOCATOR_H #define SLAB_ALLOCATOR_H #include <libpmemobj.h> struct slab_allocator; struct slab_allocator *slab_new(PMEMobjpool *pop, size_t size); void slab_delete(struct slab_allocator *slab); int slab_alloc(struct slab_allocator *slab, PMEMoid *oid, pmemobj_constr constructor, void *arg); PMEMoid slab_tx_alloc(struct slab_allocator *slab); #endif /* SLAB_ALLOCATOR_H */
542
22.608696
63
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/array/array.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * array.c -- example of arrays usage */ #include <ex_common.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/stat.h> #include <libpmemobj.h> #define TOID_ARRAY(x) TOID(x) #define COUNT_OF(x) (sizeof(x) / sizeof(x[0])) #define MAX_BUFFLEN 30 #define MAX_TYPE_NUM 8 POBJ_LAYOUT_BEGIN(array); POBJ_LAYOUT_TOID(array, struct array_elm); POBJ_LAYOUT_TOID(array, int); POBJ_LAYOUT_TOID(array, PMEMoid); POBJ_LAYOUT_TOID(array, TOID(struct array_elm)); POBJ_LAYOUT_TOID(array, struct array_info); POBJ_LAYOUT_END(array); static PMEMobjpool *pop; enum array_types { UNKNOWN_ARRAY_TYPE, INT_ARRAY_TYPE, PMEMOID_ARRAY_TYPE, TOID_ARRAY_TYPE, MAX_ARRAY_TYPE }; struct array_elm { int id; }; struct array_info { char name[MAX_BUFFLEN]; size_t size; enum array_types type; PMEMoid array; }; /* * print_usage -- print general usage */ static void print_usage(void) { printf("usage: ./array <file-name> " "<alloc|realloc|free|print>" " <array-name> [<size> [<TOID|PMEMoid|int>]]\n"); } /* * get type -- parse argument given as type of array */ static enum array_types get_type(const char *type_name) { const char *names[MAX_ARRAY_TYPE] = {"", "int", "PMEMoid", "TOID"}; enum array_types type; for (type = (enum array_types)(MAX_ARRAY_TYPE - 1); type > UNKNOWN_ARRAY_TYPE; type = (enum array_types)(type - 1)) { if (strcmp(names[type], type_name) == 0) break; } if (type == UNKNOWN_ARRAY_TYPE) fprintf(stderr, "unknown type: %s\n", type_name); return type; } /* * find_aray -- return info about array with proper name */ static TOID(struct array_info) find_array(const char *name) { TOID(struct array_info) info; POBJ_FOREACH_TYPE(pop, info) { if (strncmp(D_RO(info)->name, name, MAX_BUFFLEN) == 0) return info; } return TOID_NULL(struct array_info); } /* * elm_constructor -- constructor of array_elm type object */ static int elm_constructor(PMEMobjpool *pop, void *ptr, void *arg) { struct array_elm *obj = (struct array_elm *)ptr; int *id = (int *)arg; obj->id = *id; pmemobj_persist(pop, obj, sizeof(*obj)); return 0; } /* * print_int -- print array of int type */ static void print_int(struct array_info *info) { TOID(int) array; TOID_ASSIGN(array, info->array); for (size_t i = 0; i < info->size; i++) printf("%d ", D_RO(array)[i]); } /* * print_pmemoid -- print array of PMEMoid type */ static void print_pmemoid(struct array_info *info) { TOID(PMEMoid) array; TOID(struct array_elm) elm; TOID_ASSIGN(array, info->array); for (size_t i = 0; i < info->size; i++) { TOID_ASSIGN(elm, D_RW(array)[i]); printf("%d ", D_RO(elm)->id); } } /* * print_toid -- print array of TOID(struct array_elm) type */ static void print_toid(struct array_info *info) { TOID_ARRAY(TOID(struct array_elm)) array; TOID_ASSIGN(array, info->array); for (size_t i = 0; i < info->size; i++) printf("%d ", D_RO(D_RO(array)[i])->id); } typedef void (*fn_print)(struct array_info *info); static fn_print print_array[] = {NULL, print_int, print_pmemoid, print_toid}; /* * free_int -- de-allocate array of int type */ static void free_int(struct array_info *info) { TOID(int) array; TOID_ASSIGN(array, info->array); /* * When there is persistent array of simple type allocated, * there is enough to de-allocate persistent pointer */ POBJ_FREE(&array); } /* * free_pmemoid -- de-allocate array of PMEMoid type */ static void free_pmemoid(struct array_info *info) { TOID(PMEMoid) array; TOID_ASSIGN(array, info->array); /* * When there is persistent array of persistent pointer type allocated, * there is necessary to de-allocate each element, if they were * allocated earlier */ for (size_t i = 0; i < info->size; i++) pmemobj_free(&D_RW(array)[i]); POBJ_FREE(&array); } /* * free_toid -- de-allocate array of TOID(struct array_elm) type */ static void free_toid(struct array_info *info) { TOID_ARRAY(TOID(struct array_elm)) array; TOID_ASSIGN(array, info->array); /* * When there is persistent array of persistent pointer type allocated, * there is necessary to de-allocate each element, if they were * allocated earlier */ for (size_t i = 0; i < info->size; i++) POBJ_FREE(&D_RW(array)[i]); POBJ_FREE(&array); } typedef void (*fn_free)(struct array_info *info); static fn_free free_array[] = {NULL, free_int, free_pmemoid, free_toid}; /* * realloc_int -- reallocate array of int type */ static PMEMoid realloc_int(PMEMoid *info, size_t prev_size, size_t size) { TOID(int) array; TOID_ASSIGN(array, *info); POBJ_REALLOC(pop, &array, int, size * sizeof(int)); if (size > prev_size) { for (size_t i = prev_size; i < size; i++) D_RW(array)[i] = (int)i; pmemobj_persist(pop, D_RW(array) + prev_size, (size - prev_size) * sizeof(*D_RW(array))); } return array.oid; } /* * realloc_pmemoid -- reallocate array of PMEMoid type */ static PMEMoid realloc_pmemoid(PMEMoid *info, size_t prev_size, size_t size) { TOID(PMEMoid) array; TOID_ASSIGN(array, *info); pmemobj_zrealloc(pop, &array.oid, sizeof(PMEMoid) * size, TOID_TYPE_NUM(PMEMoid)); for (size_t i = prev_size; i < size; i++) { if (pmemobj_alloc(pop, &D_RW(array)[i], sizeof(struct array_elm), TOID_TYPE_NUM(PMEMoid), elm_constructor, &i)) { fprintf(stderr, "pmemobj_alloc\n"); assert(0); } } return array.oid; } /* * realloc_toid -- reallocate array of TOID(struct array_elm) type */ static PMEMoid realloc_toid(PMEMoid *info, size_t prev_size, size_t size) { TOID_ARRAY(TOID(struct array_elm)) array; TOID_ASSIGN(array, *info); pmemobj_zrealloc(pop, &array.oid, sizeof(TOID(struct array_elm)) * size, TOID_TYPE_NUM_OF(array)); for (size_t i = prev_size; i < size; i++) { POBJ_NEW(pop, &D_RW(array)[i], struct array_elm, elm_constructor, &i); if (TOID_IS_NULL(D_RW(array)[i])) { fprintf(stderr, "POBJ_ALLOC\n"); assert(0); } } return array.oid; } typedef PMEMoid (*fn_realloc)(PMEMoid *info, size_t prev_size, size_t size); static fn_realloc realloc_array[] = {NULL, realloc_int, realloc_pmemoid, realloc_toid}; /* * alloc_int -- allocate array of int type */ static PMEMoid alloc_int(size_t size) { TOID(int) array; /* * To allocate persistent array of simple type is enough to allocate * pointer with size equal to number of elements multiplied by size of * user-defined structure. */ POBJ_ALLOC(pop, &array, int, sizeof(int) * size, NULL, NULL); if (TOID_IS_NULL(array)) { fprintf(stderr, "POBJ_ALLOC\n"); return OID_NULL; } for (size_t i = 0; i < size; i++) D_RW(array)[i] = (int)i; pmemobj_persist(pop, D_RW(array), size * sizeof(*D_RW(array))); return array.oid; } /* * alloc_pmemoid -- allocate array of PMEMoid type */ static PMEMoid alloc_pmemoid(size_t size) { TOID(PMEMoid) array; /* * To allocate persistent array of PMEMoid type is necessary to allocate * pointer with size equal to number of elements multiplied by size of * PMEMoid and to allocate each of elements separately. */ POBJ_ALLOC(pop, &array, PMEMoid, sizeof(PMEMoid) * size, NULL, NULL); if (TOID_IS_NULL(array)) { fprintf(stderr, "POBJ_ALLOC\n"); return OID_NULL; } for (size_t i = 0; i < size; i++) { if (pmemobj_alloc(pop, &D_RW(array)[i], sizeof(struct array_elm), TOID_TYPE_NUM(PMEMoid), elm_constructor, &i)) { fprintf(stderr, "pmemobj_alloc\n"); } } return array.oid; } /* * alloc_toid -- allocate array of TOID(struct array_elm) type */ static PMEMoid alloc_toid(size_t size) { TOID_ARRAY(TOID(struct array_elm)) array; /* * To allocate persistent array of TOID with user-defined structure type * is necessary to allocate pointer with size equal to number of * elements multiplied by size of TOID of proper type and to allocate * each of elements separately. */ POBJ_ALLOC(pop, &array, TOID(struct array_elm), sizeof(TOID(struct array_elm)) * size, NULL, NULL); if (TOID_IS_NULL(array)) { fprintf(stderr, "POBJ_ALLOC\n"); return OID_NULL; } for (size_t i = 0; i < size; i++) { POBJ_NEW(pop, &D_RW(array)[i], struct array_elm, elm_constructor, &i); if (TOID_IS_NULL(D_RW(array)[i])) { fprintf(stderr, "POBJ_ALLOC\n"); assert(0); } } return array.oid; } typedef PMEMoid (*fn_alloc)(size_t size); static fn_alloc alloc_array[] = {NULL, alloc_int, alloc_pmemoid, alloc_toid}; /* * do_print -- print values stored by proper array */ static void do_print(int argc, char *argv[]) { if (argc != 1) { printf("usage: ./array <file-name> print <array-name>\n"); return; } TOID(struct array_info) array_info = find_array(argv[0]); if (TOID_IS_NULL(array_info)) { printf("%s doesn't exist\n", argv[0]); return; } printf("%s:\n", argv[0]); print_array[D_RO(array_info)->type](D_RW(array_info)); printf("\n"); } /* * do_free -- de-allocate proper array and proper TOID of array_info type */ static void do_free(int argc, char *argv[]) { if (argc != 1) { printf("usage: ./array <file-name> free <array-name>\n"); return; } TOID(struct array_info) array_info = find_array(argv[0]); if (TOID_IS_NULL(array_info)) { printf("%s doesn't exist\n", argv[0]); return; } free_array[D_RO(array_info)->type](D_RW(array_info)); POBJ_FREE(&array_info); } /* * do_realloc -- reallocate proper array to given size and update information * in array_info structure */ static void do_realloc(int argc, char *argv[]) { if (argc != 2) { printf("usage: ./array <file-name> realloc" " <array-name> <size>\n"); return; } size_t size = atoi(argv[1]); TOID(struct array_info) array_info = find_array(argv[0]); if (TOID_IS_NULL(array_info)) { printf("%s doesn't exist\n", argv[0]); return; } struct array_info *info = D_RW(array_info); info->array = realloc_array[info->type](&info->array, info->size, size); if (OID_IS_NULL(info->array)) { if (size != 0) printf("POBJ_REALLOC\n"); } info->size = size; pmemobj_persist(pop, info, sizeof(*info)); } /* * do_alloc -- allocate persistent array and TOID of array_info type * and set it with information about new array */ static void do_alloc(int argc, char *argv[]) { if (argc != 3) { printf("usage: ./array <file-name> alloc <array-name>" "<size> <type>\n"); return; } enum array_types type = get_type(argv[2]); if (type == UNKNOWN_ARRAY_TYPE) return; size_t size = atoi(argv[1]); TOID(struct array_info) array_info = find_array(argv[0]); if (!TOID_IS_NULL(array_info)) POBJ_FREE(&array_info); POBJ_ZNEW(pop, &array_info, struct array_info); struct array_info *info = D_RW(array_info); strncpy(info->name, argv[0], MAX_BUFFLEN - 1); info->name[MAX_BUFFLEN - 1] = '\0'; info->size = size; info->type = type; info->array = alloc_array[type](size); if (OID_IS_NULL(info->array)) assert(0); pmemobj_persist(pop, info, sizeof(*info)); } typedef void (*fn_op)(int argc, char *argv[]); static fn_op operations[] = {do_alloc, do_realloc, do_free, do_print}; int main(int argc, char *argv[]) { if (argc < 3) { print_usage(); return 1; } const char *path = argv[1]; pop = NULL; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(array), PMEMOBJ_MIN_POOL, CREATE_MODE_RW)) == NULL) { printf("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(array))) == NULL) { printf("failed to open pool\n"); return 1; } } const char *option = argv[2]; argv += 3; argc -= 3; const char *names[] = {"alloc", "realloc", "free", "print"}; unsigned i = 0; for (; i < COUNT_OF(names) && strcmp(option, names[i]) != 0; i++); if (i != COUNT_OF(names)) operations[i](argc, argv); else print_usage(); pmemobj_close(pop); return 0; }
11,844
22.595618
77
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx_type/writer.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * writer.c -- example from introduction part 3 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_create(argv[1], POBJ_LAYOUT_NAME(string_store), PMEMOBJ_MIN_POOL, 0666); if (pop == NULL) { perror("pmemobj_create"); return 1; } char buf[MAX_BUF_LEN] = {0}; int num = scanf("%9s", buf); if (num == EOF) { fprintf(stderr, "EOF\n"); return 1; } TOID(struct my_root) root = POBJ_ROOT(pop, struct my_root); TX_BEGIN(pop) { TX_MEMCPY(D_RW(root)->buf, buf, strlen(buf)); } TX_END pmemobj_close(pop); return 0; }
807
15.833333
60
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx_type/reader.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * reader.c -- example from introduction part 3 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(string_store)); if (pop == NULL) { perror("pmemobj_open"); return 1; } TOID(struct my_root) root = POBJ_ROOT(pop, struct my_root); printf("%s\n", D_RO(root)->buf); pmemobj_close(pop); return 0; }
615
15.648649
60
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx_type/layout.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * layout.h -- example from introduction part 3 */ #define MAX_BUF_LEN 10 POBJ_LAYOUT_BEGIN(string_store); POBJ_LAYOUT_ROOT(string_store, struct my_root); POBJ_LAYOUT_END(string_store); struct my_root { char buf[MAX_BUF_LEN]; };
324
18.117647
47
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/list_map/skiplist_map.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * skiplist_map.c -- Skiplist implementation */ #include <assert.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include "skiplist_map.h" #define SKIPLIST_LEVELS_NUM 4 #define NULL_NODE TOID_NULL(struct skiplist_map_node) #include <x86intrin.h> 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; } struct skiplist_map_entry { uint64_t key; PMEMoid value; }; struct skiplist_map_node { TOID(struct skiplist_map_node) next[SKIPLIST_LEVELS_NUM]; struct skiplist_map_entry entry; }; /* * skiplist_map_create -- allocates a new skiplist instance */ int skiplist_map_create(PMEMobjpool *pop, TOID(struct skiplist_map_node) *map, void *arg) { int ret = 0; TX_BEGIN(pop) { pmemobj_tx_add_range_direct(map, sizeof(*map)); *map = TX_ZNEW(struct skiplist_map_node); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * skiplist_map_clear -- removes all elements from the map */ int skiplist_map_clear(PMEMobjpool *pop, TOID(struct skiplist_map_node) map) { while (!TOID_EQUALS(D_RO(map)->next[0], NULL_NODE)) { TOID(struct skiplist_map_node) next = D_RO(map)->next[0]; skiplist_map_remove_free(pop, map, D_RO(next)->entry.key); } return 0; } /* * skiplist_map_destroy -- cleanups and frees skiplist instance */ int skiplist_map_destroy(PMEMobjpool *pop, TOID(struct skiplist_map_node) *map) { int ret = 0; TX_BEGIN(pop) { skiplist_map_clear(pop, *map); pmemobj_tx_add_range_direct(map, sizeof(*map)); TX_FREE(*map); *map = TOID_NULL(struct skiplist_map_node); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * skiplist_map_insert_new -- allocates a new object and inserts it into * the list */ int skiplist_map_insert_new(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { int ret = 0; TX_BEGIN(pop) { PMEMoid n = pmemobj_tx_alloc(size, type_num); constructor(pop, pmemobj_direct(n), arg); skiplist_map_insert(pop, map, key, n); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * skiplist_map_insert_node -- (internal) adds new node in selected place */ static void skiplist_map_insert_node(TOID(struct skiplist_map_node) new_node, TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]) { unsigned current_level = 0; do { TX_ADD_FIELD(path[current_level], next[current_level]); D_RW(new_node)->next[current_level] = D_RO(path[current_level])->next[current_level]; D_RW(path[current_level])->next[current_level] = new_node; } while (++current_level < SKIPLIST_LEVELS_NUM && rand() % 2 == 0); } /* * skiplist_map_map_find -- (internal) returns path to searched node, or if * node doesn't exist, it will return path to place where key should be. */ static void skiplist_map_find(uint64_t key, TOID(struct skiplist_map_node) map, TOID(struct skiplist_map_node) *path) { int current_level; TOID(struct skiplist_map_node) active = map; for (current_level = SKIPLIST_LEVELS_NUM - 1; current_level >= 0; current_level--) { for (TOID(struct skiplist_map_node) next = D_RO(active)->next[current_level]; !TOID_EQUALS(next, NULL_NODE) && D_RO(next)->entry.key < key; next = D_RO(active)->next[current_level]) { active = next; } path[current_level] = active; } } /* * skiplist_map_insert -- inserts a new key-value pair into the map */ #ifdef GET_NDP_BREAKDOWN uint64_t ulogCycles; uint64_t waitCycles; uint64_t resetCycles; #endif int skiplist_map_insert(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key, PMEMoid value) { int ret = 0; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif TOID(struct skiplist_map_node) new_node; TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { new_node = TX_ZNEW(struct skiplist_map_node); D_RW(new_node)->entry.key = key; D_RW(new_node)->entry.value = value; skiplist_map_find(key, map, path); skiplist_map_insert_node(new_node, path); } TX_ONABORT { ret = 1; } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("ctree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree tx cmd issue total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree tx total wait time = %f\n", (((double)waitCycles)/2000000000)); #endif return ret; } /* * skiplist_map_remove_free -- removes and frees an object from the list */ int skiplist_map_remove_free(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key) { int ret = 0; TX_BEGIN(pop) { PMEMoid val = skiplist_map_remove(pop, map, key); pmemobj_tx_free(val); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * skiplist_map_remove_node -- (internal) removes selected node */ static void skiplist_map_remove_node( TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]) { TOID(struct skiplist_map_node) to_remove = D_RO(path[0])->next[0]; int i; for (i = 0; i < SKIPLIST_LEVELS_NUM; i++) { if (TOID_EQUALS(D_RO(path[i])->next[i], to_remove)) { TX_ADD_FIELD(path[i], next[i]); D_RW(path[i])->next[i] = D_RO(to_remove)->next[i]; } } } /* * skiplist_map_remove -- removes key-value pair from the map */ PMEMoid skiplist_map_remove(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key) { PMEMoid ret = OID_NULL; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]; TOID(struct skiplist_map_node) to_remove; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { skiplist_map_find(key, map, path); to_remove = D_RO(path[0])->next[0]; if (!TOID_EQUALS(to_remove, NULL_NODE) && D_RO(to_remove)->entry.key == key) { ret = D_RO(to_remove)->entry.value; skiplist_map_remove_node(path); } } TX_ONABORT { ret = OID_NULL; } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("ctree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree tx cmd issue total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree tx total wait time = %f\n", (((double)waitCycles)/2000000000)); #endif return ret; } /* * skiplist_map_get -- searches for a value of the key */ PMEMoid skiplist_map_get(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key) { PMEMoid ret = OID_NULL; TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM], found; skiplist_map_find(key, map, path); found = D_RO(path[0])->next[0]; if (!TOID_EQUALS(found, NULL_NODE) && D_RO(found)->entry.key == key) { ret = D_RO(found)->entry.value; } return ret; } /* * skiplist_map_lookup -- searches if a key exists */ int skiplist_map_lookup(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key) { int ret = 0; TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM], found; skiplist_map_find(key, map, path); found = D_RO(path[0])->next[0]; if (!TOID_EQUALS(found, NULL_NODE) && D_RO(found)->entry.key == key) { ret = 1; } return ret; } /* * skiplist_map_foreach -- calls function for each node on a list */ int skiplist_map_foreach(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct skiplist_map_node) next = map; while (!TOID_EQUALS(D_RO(next)->next[0], NULL_NODE)) { next = D_RO(next)->next[0]; cb(D_RO(next)->entry.key, D_RO(next)->entry.value, arg); } return 0; } /* * skiplist_map_is_empty -- checks whether the list map is empty */ int skiplist_map_is_empty(PMEMobjpool *pop, TOID(struct skiplist_map_node) map) { return TOID_IS_NULL(D_RO(map)->next[0]); } /* * skiplist_map_check -- check if given persistent object is a skiplist */ int skiplist_map_check(PMEMobjpool *pop, TOID(struct skiplist_map_node) map) { return TOID_IS_NULL(map) || !TOID_VALID(map); }
8,913
23.899441
83
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/list_map/skiplist_map.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * skiplist_map.h -- sorted list collection implementation */ #ifndef SKIPLIST_MAP_H #define SKIPLIST_MAP_H #include <libpmemobj.h> #ifndef SKIPLIST_MAP_TYPE_OFFSET #define SKIPLIST_MAP_TYPE_OFFSET 2020 #endif struct skiplist_map_node; TOID_DECLARE(struct skiplist_map_node, SKIPLIST_MAP_TYPE_OFFSET + 0); int skiplist_map_check(PMEMobjpool *pop, TOID(struct skiplist_map_node) map); int skiplist_map_create(PMEMobjpool *pop, TOID(struct skiplist_map_node) *map, void *arg); int skiplist_map_destroy(PMEMobjpool *pop, TOID(struct skiplist_map_node) *map); int skiplist_map_insert(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key, PMEMoid value); int skiplist_map_insert_new(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg); PMEMoid skiplist_map_remove(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key); int skiplist_map_remove_free(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key); int skiplist_map_clear(PMEMobjpool *pop, TOID(struct skiplist_map_node) map); PMEMoid skiplist_map_get(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key); int skiplist_map_lookup(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key); int skiplist_map_foreach(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); int skiplist_map_is_empty(PMEMobjpool *pop, TOID(struct skiplist_map_node) map); #endif /* SKIPLIST_MAP_H */
1,688
36.533333
80
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ #ifndef HASHMAP_H #define HASHMAP_H /* common API provided by both implementations */ #include <stddef.h> #include <stdint.h> struct hashmap_args { uint32_t seed; }; enum hashmap_cmd { HASHMAP_CMD_REBUILD, HASHMAP_CMD_DEBUG, }; #endif /* HASHMAP_H */
345
15.47619
49
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_tx.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ #ifndef HASHMAP_TX_H #define HASHMAP_TX_H #include <stddef.h> #include <stdint.h> #include <hashmap.h> #include <libpmemobj.h> #ifndef HASHMAP_TX_TYPE_OFFSET #define HASHMAP_TX_TYPE_OFFSET 1004 #endif struct hashmap_tx; TOID_DECLARE(struct hashmap_tx, HASHMAP_TX_TYPE_OFFSET + 0); int hm_tx_check(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap); int hm_tx_create(PMEMobjpool *pop, TOID(struct hashmap_tx) *map, void *arg); int hm_tx_init(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap); int hm_tx_insert(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key, PMEMoid value); PMEMoid hm_tx_remove(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key); PMEMoid hm_tx_get(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key); int hm_tx_lookup(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key); int hm_tx_foreach(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); size_t hm_tx_count(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap); int hm_tx_cmd(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, unsigned cmd, uint64_t arg); #endif /* HASHMAP_TX_H */
1,270
34.305556
76
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_rp.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018, Intel Corporation */ #ifndef HASHMAP_RP_H #define HASHMAP_RP_H #include <stddef.h> #include <stdint.h> #include <hashmap.h> #include <libpmemobj.h> #ifndef HASHMAP_RP_TYPE_OFFSET #define HASHMAP_RP_TYPE_OFFSET 1008 #endif /* Flags to indicate if insertion is being made during rebuild process */ #define HASHMAP_RP_REBUILD 1 #define HASHMAP_RP_NO_REBUILD 0 /* Initial number of entries for hashamap_rp */ #define INIT_ENTRIES_NUM_RP 16 /* Load factor to indicate resize threshold */ #define HASHMAP_RP_LOAD_FACTOR 0.5f /* Maximum number of swaps allowed during single insertion */ #define HASHMAP_RP_MAX_SWAPS 150 /* Size of an action array used during single insertion */ #define HASHMAP_RP_MAX_ACTIONS (4 * HASHMAP_RP_MAX_SWAPS + 5) struct hashmap_rp; TOID_DECLARE(struct hashmap_rp, HASHMAP_RP_TYPE_OFFSET + 0); int hm_rp_check(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap); int hm_rp_create(PMEMobjpool *pop, TOID(struct hashmap_rp) *map, void *arg); int hm_rp_init(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap); int hm_rp_insert(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key, PMEMoid value); PMEMoid hm_rp_remove(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key); PMEMoid hm_rp_get(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key); int hm_rp_lookup(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key); int hm_rp_foreach(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); size_t hm_rp_count(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap); int hm_rp_cmd(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, unsigned cmd, uint64_t arg); #endif /* HASHMAP_RP_H */
1,780
36.104167
76
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_internal.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ #ifndef HASHSET_INTERNAL_H #define HASHSET_INTERNAL_H /* large prime number used as a hashing function coefficient */ #define HASH_FUNC_COEFF_P 32212254719ULL /* initial number of buckets */ #define INIT_BUCKETS_NUM 10 /* number of values in a bucket which trigger hashtable rebuild check */ #define MIN_HASHSET_THRESHOLD 5 /* number of values in a bucket which force hashtable rebuild */ #define MAX_HASHSET_THRESHOLD 10 #endif
521
25.1
72
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_tx.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* integer hash set implementation which uses only transaction APIs */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <inttypes.h> #include <libpmemobj.h> #include "hashmap_tx.h" #include "hashmap_internal.h" 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; } /* layout definition */ TOID_DECLARE(struct buckets, HASHMAP_TX_TYPE_OFFSET + 1); TOID_DECLARE(struct entry, HASHMAP_TX_TYPE_OFFSET + 2); struct entry { uint64_t key; PMEMoid value; /* next entry list pointer */ TOID(struct entry) next; }; struct buckets { /* number of buckets */ size_t nbuckets; /* array of lists */ TOID(struct entry) bucket[]; }; struct hashmap_tx { /* random number generator seed */ uint32_t seed; /* hash function coefficients */ uint32_t hash_fun_a; uint32_t hash_fun_b; uint64_t hash_fun_p; /* number of values inserted */ uint64_t count; /* buckets */ TOID(struct buckets) buckets; }; /* * create_hashmap -- hashmap initializer */ static void create_hashmap(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint32_t seed) { size_t len = INIT_BUCKETS_NUM; size_t sz = sizeof(struct buckets) + len * sizeof(TOID(struct entry)); TX_BEGIN(pop) { TX_ADD(hashmap); D_RW(hashmap)->seed = seed; do { D_RW(hashmap)->hash_fun_a = (uint32_t)rand(); } while (D_RW(hashmap)->hash_fun_a == 0); D_RW(hashmap)->hash_fun_b = (uint32_t)rand(); D_RW(hashmap)->hash_fun_p = HASH_FUNC_COEFF_P; D_RW(hashmap)->buckets = TX_ZALLOC(struct buckets, sz); D_RW(D_RW(hashmap)->buckets)->nbuckets = len; } TX_ONABORT { fprintf(stderr, "%s: transaction aborted: %s\n", __func__, pmemobj_errormsg()); abort(); } TX_END } /* * hash -- the simplest hashing function, * see https://en.wikipedia.org/wiki/Universal_hashing#Hashing_integers */ static uint64_t hash(const TOID(struct hashmap_tx) *hashmap, const TOID(struct buckets) *buckets, uint64_t value) { uint32_t a = D_RO(*hashmap)->hash_fun_a; uint32_t b = D_RO(*hashmap)->hash_fun_b; uint64_t p = D_RO(*hashmap)->hash_fun_p; size_t len = D_RO(*buckets)->nbuckets; return ((a * value + b) % p) % len; } /* * hm_tx_rebuild -- rebuilds the hashmap with a new number of buckets */ static void hm_tx_rebuild(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, size_t new_len) { TOID(struct buckets) buckets_old = D_RO(hashmap)->buckets; if (new_len == 0) new_len = D_RO(buckets_old)->nbuckets; size_t sz_old = sizeof(struct buckets) + D_RO(buckets_old)->nbuckets * sizeof(TOID(struct entry)); size_t sz_new = sizeof(struct buckets) + new_len * sizeof(TOID(struct entry)); TX_BEGIN(pop) { TX_ADD_FIELD(hashmap, buckets); TOID(struct buckets) buckets_new = TX_ZALLOC(struct buckets, sz_new); D_RW(buckets_new)->nbuckets = new_len; pmemobj_tx_add_range(buckets_old.oid, 0, sz_old); for (size_t i = 0; i < D_RO(buckets_old)->nbuckets; ++i) { while (!TOID_IS_NULL(D_RO(buckets_old)->bucket[i])) { TOID(struct entry) en = D_RO(buckets_old)->bucket[i]; uint64_t h = hash(&hashmap, &buckets_new, D_RO(en)->key); D_RW(buckets_old)->bucket[i] = D_RO(en)->next; TX_ADD_FIELD(en, next); D_RW(en)->next = D_RO(buckets_new)->bucket[h]; D_RW(buckets_new)->bucket[h] = en; } } D_RW(hashmap)->buckets = buckets_new; TX_FREE(buckets_old); } TX_ONABORT { fprintf(stderr, "%s: transaction aborted: %s\n", __func__, pmemobj_errormsg()); /* * We don't need to do anything here, because everything is * consistent. The only thing affected is performance. */ } TX_END } /* * hm_tx_insert -- inserts specified value into the hashmap, * returns: * - 0 if successful, * - 1 if value already existed, * - -1 if something bad happened */ #ifdef GET_NDP_BREAKDOWN uint64_t ulogCycles; uint64_t waitCycles; uint64_t resetCycles; #endif int hm_tx_insert(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key, PMEMoid value) { int ret = 0; TOID(struct buckets) buckets = D_RO(hashmap)->buckets; // TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); int num = 0; /* for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) { if (D_RO(var)->key == key) return 1; num++; } */ #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif //uint64_t startCycles1,endCycles1; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { TX_ADD_FIELD(D_RO(hashmap)->buckets, bucket[h]); TX_ADD_FIELD(hashmap, count); TOID(struct entry) e = TX_NEW(struct entry); D_RW(e)->key = key; D_RW(e)->value = value; D_RW(e)->next = D_RO(buckets)->bucket[h]; D_RW(buckets)->bucket[h] = e; D_RW(hashmap)->count++; num++; //printf("parallel time = %f\n", (((double)(endCycles1 - startCycles1)))); } TX_ONABORT { fprintf(stderr, "transaction aborted: %s\n", pmemobj_errormsg()); ret = -1; } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("btree TX/s = %f\ntotal tx total time = %f\n", RUN_COUNT/totTime, totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("total tx cmd issue time = %f\n", (((double)ulogCycles)/2000000000)); printf("total tx wait time = %f\n", (((double)waitCycles)/2000000000)); printf("total tx reset time = %f\n", (((double)resetCycles)/2000000000)); #endif if (ret) return ret; return 0; } /* * hm_tx_remove -- removes specified value from the hashmap, * returns: * - key's value if successful, * - OID_NULL if value didn't exist or if something bad happened */ PMEMoid hm_tx_remove(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { int ret = 0; PMEMoid retoid; TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var, prev = TOID_NULL(struct entry); #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); prev = var, var = D_RO(var)->next) { if (D_RO(var)->key == key) break; } if (TOID_IS_NULL(var)) return OID_NULL; retoid = D_RO(var)->value; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { if (TOID_IS_NULL(prev)) TX_ADD_FIELD(D_RO(hashmap)->buckets, bucket[h]); else TX_ADD_FIELD(prev, next); TX_ADD_FIELD(hashmap, count); if (TOID_IS_NULL(prev)) D_RW(buckets)->bucket[h] = D_RO(var)->next; else D_RW(prev)->next = D_RO(var)->next; D_RW(hashmap)->count--; TX_FREE(var); } TX_ONABORT { fprintf(stderr, "transaction aborted: %s\n", pmemobj_errormsg()); ret = -1; } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("btree TX/s = %f\ntotal tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("total tx ulog time = %f\n", (((double)ulogCycles)/2000000000)); printf("total tx wait time = %f\n", (((double)waitCycles)/2000000000)); #endif if (ret) return OID_NULL; if (D_RO(hashmap)->count < D_RO(buckets)->nbuckets) hm_tx_rebuild(pop, hashmap, D_RO(buckets)->nbuckets / 2); return retoid; } /* * hm_tx_foreach -- prints all values from the hashmap */ int hm_tx_foreach(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; int ret = 0; for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) { if (TOID_IS_NULL(D_RO(buckets)->bucket[i])) continue; for (var = D_RO(buckets)->bucket[i]; !TOID_IS_NULL(var); var = D_RO(var)->next) { ret = cb(D_RO(var)->key, D_RO(var)->value, arg); if (ret) break; } } return ret; } /* * hm_tx_debug -- prints complete hashmap state */ static void hm_tx_debug(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, FILE *out) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; fprintf(out, "a: %u b: %u p: %" PRIu64 "\n", D_RO(hashmap)->hash_fun_a, D_RO(hashmap)->hash_fun_b, D_RO(hashmap)->hash_fun_p); fprintf(out, "count: %" PRIu64 ", buckets: %zu\n", D_RO(hashmap)->count, D_RO(buckets)->nbuckets); for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) { if (TOID_IS_NULL(D_RO(buckets)->bucket[i])) continue; int num = 0; fprintf(out, "%zu: ", i); for (var = D_RO(buckets)->bucket[i]; !TOID_IS_NULL(var); var = D_RO(var)->next) { fprintf(out, "%" PRIu64 " ", D_RO(var)->key); num++; } fprintf(out, "(%d)\n", num); } } /* * hm_tx_get -- checks whether specified value is in the hashmap */ PMEMoid hm_tx_get(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) if (D_RO(var)->key == key) return D_RO(var)->value; return OID_NULL; } /* * hm_tx_lookup -- checks whether specified value exists */ int hm_tx_lookup(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) if (D_RO(var)->key == key) return 1; return 0; } /* * hm_tx_count -- returns number of elements */ size_t hm_tx_count(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { return D_RO(hashmap)->count; } /* * hm_tx_init -- recovers hashmap state, called after pmemobj_open */ int hm_tx_init(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { srand(D_RO(hashmap)->seed); return 0; } /* * hm_tx_create -- allocates new hashmap */ int hm_tx_create(PMEMobjpool *pop, TOID(struct hashmap_tx) *map, void *arg) { struct hashmap_args *args = (struct hashmap_args *)arg; int ret = 0; TX_BEGIN(pop) { TX_ADD_DIRECT(map); *map = TX_ZNEW(struct hashmap_tx); uint32_t seed = args ? args->seed : 0; create_hashmap(pop, *map, seed); } TX_ONABORT { ret = -1; } TX_END return ret; } /* * hm_tx_check -- checks if specified persistent object is an * instance of hashmap */ int hm_tx_check(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { return TOID_IS_NULL(hashmap) || !TOID_VALID(hashmap); } /* * hm_tx_cmd -- execute cmd for hashmap */ int hm_tx_cmd(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, unsigned cmd, uint64_t arg) { switch (cmd) { case HASHMAP_CMD_REBUILD: hm_tx_rebuild(pop, hashmap, arg); return 0; case HASHMAP_CMD_DEBUG: if (!arg) return -EINVAL; hm_tx_debug(pop, hashmap, (FILE *)arg); return 0; default: return -EINVAL; } }
11,602
22.825462
83
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_rp.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018, Intel Corporation */ /* * Integer hash set implementation with open addressing Robin Hood collision * resolution which uses action.h reserve/publish API. */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <inttypes.h> #include <libpmemobj.h> #include "hashmap_rp.h" #define TOMBSTONE_MASK (1ULL << 63) #ifdef DEBUG #define HM_ASSERT(cnd) assert(cnd) #else #define HM_ASSERT(cnd) #endif /* layout definition */ TOID_DECLARE(struct entry, HASHMAP_RP_TYPE_OFFSET + 1); struct entry { uint64_t key; PMEMoid value; uint64_t hash; }; struct add_entry { struct entry data; /* position index in hashmap, where data should be inserted/updated */ size_t pos; /* Action array to perform addition in set of actions */ struct pobj_action *actv; /* Action array index counter */ size_t actv_cnt; #ifdef DEBUG /* Swaps counter for current insertion. Enabled in debug mode */ int swaps; #endif }; struct hashmap_rp { /* number of values inserted */ uint64_t count; /* container capacity */ uint64_t capacity; /* resize threshold */ uint64_t resize_threshold; /* entries */ TOID(struct entry) entries; }; int *swaps_array = NULL; #ifdef DEBUG static inline int is_power_of_2(uint64_t v) { return v && !(v & (v - 1)); } #endif /* * entry_is_deleted -- checks 'tombstone' bit if hash is deleted */ static inline int entry_is_deleted(uint64_t hash) { return (hash & TOMBSTONE_MASK) > 0; } /* * entry_is_empty -- checks if entry is empty */ static inline int entry_is_empty(uint64_t hash) { return hash == 0 || entry_is_deleted(hash); } /* * increment_pos -- increment position index, skip 0 */ static uint64_t increment_pos(const struct hashmap_rp *hashmap, uint64_t pos) { HM_ASSERT(is_power_of_2(hashmap->capacity)); pos = (pos + 1) & (hashmap->capacity - 1); return pos == 0 ? 1 : pos; } /* * probe_distance -- returns probe number, an indicator how far from * desired position given hash is stored in hashmap */ static uint64_t probe_distance(const struct hashmap_rp *hashmap, uint64_t hash_key, uint64_t slot_index) { uint64_t capacity = hashmap->capacity; HM_ASSERT(is_power_of_2(hashmap->capacity)); return (int)(slot_index + capacity - hash_key) & (capacity - 1); } /* * hash -- hash function based on Austin Appleby MurmurHash3 64-bit finalizer. * Returned value is modified to work with special values for unused and * and deleted hashes. */ static uint64_t hash(const struct hashmap_rp *hashmap, uint64_t key) { key ^= key >> 33; key *= 0xff51afd7ed558ccd; key ^= key >> 33; key *= 0xc4ceb9fe1a85ec53; key ^= key >> 33; HM_ASSERT(is_power_of_2(hashmap->capacity)); key &= hashmap->capacity - 1; /* first, 'tombstone' bit is used to indicate deleted item */ key &= ~TOMBSTONE_MASK; /* * Ensure that we never return 0 as a hash, since we use 0 to * indicate that element has never been used at all. */ return key == 0 ? 1 : key; } /* * hashmap_create -- hashmap initializer */ static void hashmap_create(PMEMobjpool *pop, TOID(struct hashmap_rp) *hashmap_p, uint32_t seed) { struct pobj_action actv[4]; size_t actv_cnt = 0; TOID(struct hashmap_rp) hashmap = POBJ_RESERVE_NEW(pop, struct hashmap_rp, &actv[actv_cnt]); if (TOID_IS_NULL(hashmap)) goto reserve_err; actv_cnt++; D_RW(hashmap)->count = 0; D_RW(hashmap)->capacity = INIT_ENTRIES_NUM_RP; D_RW(hashmap)->resize_threshold = (uint64_t)(INIT_ENTRIES_NUM_RP * HASHMAP_RP_LOAD_FACTOR); size_t sz = sizeof(struct entry) * D_RO(hashmap)->capacity; /* init entries with zero in order to track unused hashes */ D_RW(hashmap)->entries = POBJ_XRESERVE_ALLOC(pop, struct entry, sz, &actv[actv_cnt], POBJ_XALLOC_ZERO); if (TOID_IS_NULL(D_RO(hashmap)->entries)) goto reserve_err; actv_cnt++; pmemobj_persist(pop, D_RW(hashmap), sizeof(struct hashmap_rp)); pmemobj_set_value(pop, &actv[actv_cnt++], &hashmap_p->oid.pool_uuid_lo, hashmap.oid.pool_uuid_lo); pmemobj_set_value(pop, &actv[actv_cnt++], &hashmap_p->oid.off, hashmap.oid.off); pmemobj_publish(pop, actv, actv_cnt); #ifdef DEBUG swaps_array = (int *)calloc(INIT_ENTRIES_NUM_RP, sizeof(int)); if (!swaps_array) abort(); #endif return; reserve_err: fprintf(stderr, "hashmap alloc failed: %s\n", pmemobj_errormsg()); pmemobj_cancel(pop, actv, actv_cnt); abort(); } /* * entry_update -- updates entry in given hashmap with given arguments */ static void entry_update(PMEMobjpool *pop, struct hashmap_rp *hashmap, struct add_entry *args, int rebuild) { HM_ASSERT(HASHMAP_RP_MAX_ACTIONS > args->actv_cnt + 4); struct entry *entry_p = D_RW(hashmap->entries); entry_p += args->pos; if (rebuild == HASHMAP_RP_REBUILD) { entry_p->key = args->data.key; entry_p->value = args->data.value; entry_p->hash = args->data.hash; } else { pmemobj_set_value(pop, args->actv + args->actv_cnt++, &entry_p->key, args->data.key); pmemobj_set_value(pop, args->actv + args->actv_cnt++, &entry_p->value.pool_uuid_lo, args->data.value.pool_uuid_lo); pmemobj_set_value(pop, args->actv + args->actv_cnt++, &entry_p->value.off, args->data.value.off); pmemobj_set_value(pop, args->actv + args->actv_cnt++, &entry_p->hash, args->data.hash); } #ifdef DEBUG assert(sizeof(swaps_array) / sizeof(swaps_array[0]) > args->pos); swaps_array[args->pos] = args->swaps; #endif } /* * entry_add -- increments given hashmap's elements counter and calls * entry_update */ static void entry_add(PMEMobjpool *pop, struct hashmap_rp *hashmap, struct add_entry *args, int rebuild) { HM_ASSERT(HASHMAP_RP_MAX_ACTIONS > args->actv_cnt + 1); if (rebuild == HASHMAP_RP_REBUILD) hashmap->count++; else { pmemobj_set_value(pop, args->actv + args->actv_cnt++, &hashmap->count, hashmap->count + 1); } entry_update(pop, hashmap, args, rebuild); } /* * insert_helper -- inserts specified value into the hashmap * If function was called during rebuild process, no redo logs will be used. * returns: * - 0 if successful, * - 1 if value already existed * - -1 on error */ static int insert_helper(PMEMobjpool *pop, struct hashmap_rp *hashmap, uint64_t key, PMEMoid value, int rebuild) { HM_ASSERT(hashmap->count + 1 < hashmap->resize_threshold); struct pobj_action actv[HASHMAP_RP_MAX_ACTIONS]; struct add_entry args; args.data.key = key; args.data.value = value; args.data.hash = hash(hashmap, key); args.pos = args.data.hash; if (rebuild != HASHMAP_RP_REBUILD) { args.actv = actv; args.actv_cnt = 0; } uint64_t dist = 0; struct entry *entry_p = NULL; #ifdef DEBUG int swaps = 0; #endif for (int n = 0; n < HASHMAP_RP_MAX_SWAPS; ++n) { entry_p = D_RW(hashmap->entries); entry_p += args.pos; #ifdef DEBUG args.swaps = swaps; #endif /* Case 1: key already exists, override value */ if (!entry_is_empty(entry_p->hash) && entry_p->key == args.data.key) { entry_update(pop, hashmap, &args, rebuild); if (rebuild != HASHMAP_RP_REBUILD) pmemobj_publish(pop, args.actv, args.actv_cnt); return 1; } /* Case 2: slot is empty from the beginning */ if (entry_p->hash == 0) { entry_add(pop, hashmap, &args, rebuild); if (rebuild != HASHMAP_RP_REBUILD) pmemobj_publish(pop, args.actv, args.actv_cnt); return 0; } /* * Case 3: existing element (or tombstone) has probed less than * current element. Swap them (or put into tombstone slot) and * keep going to find another slot for that element. */ uint64_t existing_dist = probe_distance(hashmap, entry_p->hash, args.pos); if (existing_dist < dist) { if (entry_is_deleted(entry_p->hash)) { entry_add(pop, hashmap, &args, rebuild); if (rebuild != HASHMAP_RP_REBUILD) pmemobj_publish(pop, args.actv, args.actv_cnt); return 0; } struct entry temp = *entry_p; entry_update(pop, hashmap, &args, rebuild); args.data = temp; #ifdef DEBUG swaps++; #endif dist = existing_dist; } /* * Case 4: increment slot number and probe counter, keep going * to find free slot */ args.pos = increment_pos(hashmap, args.pos); dist += 1; } fprintf(stderr, "insertion requires too many swaps\n"); if (rebuild != HASHMAP_RP_REBUILD) pmemobj_cancel(pop, args.actv, args.actv_cnt); return -1; } /* * index_lookup -- checks if given key exists in hashmap. * Returns index number if key was found, 0 otherwise. */ static uint64_t index_lookup(const struct hashmap_rp *hashmap, uint64_t key) { const uint64_t hash_lookup = hash(hashmap, key); uint64_t pos = hash_lookup; uint64_t dist = 0; const struct entry *entry_p = NULL; do { entry_p = D_RO(hashmap->entries); entry_p += pos; if (entry_p->hash == hash_lookup && entry_p->key == key) return pos; pos = increment_pos(hashmap, pos); } while (entry_p->hash != 0 && (dist++) <= probe_distance(hashmap, entry_p->hash, pos) - 1); return 0; } /* * entries_cache -- cache entries from second argument in entries from first * argument */ static int entries_cache(PMEMobjpool *pop, struct hashmap_rp *dest, const struct hashmap_rp *src) { const struct entry *e_begin = D_RO(src->entries); const struct entry *e_end = e_begin + src->capacity; for (const struct entry *e = e_begin; e != e_end; ++e) { if (entry_is_empty(e->hash)) continue; if (insert_helper(pop, dest, e->key, e->value, HASHMAP_RP_REBUILD) == -1) return -1; } HM_ASSERT(src->count == dest->count); return 0; } /* * hm_rp_rebuild -- rebuilds the hashmap with a new capacity. * Returns 0 on success, -1 otherwise. */ static int hm_rp_rebuild(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, size_t capacity_new) { /* * We will need 6 actions: * - 1 action to set new capacity * - 1 action to set new resize threshold * - 1 action to alloc memory for new entries * - 1 action to free old entries * - 2 actions to set new oid pointing to new entries */ struct pobj_action actv[6]; size_t actv_cnt = 0; size_t sz_alloc = sizeof(struct entry) * capacity_new; uint64_t resize_threshold_new = (uint64_t)(capacity_new * HASHMAP_RP_LOAD_FACTOR); pmemobj_set_value(pop, &actv[actv_cnt++], &D_RW(hashmap)->capacity, capacity_new); pmemobj_set_value(pop, &actv[actv_cnt++], &D_RW(hashmap)->resize_threshold, resize_threshold_new); struct hashmap_rp hashmap_rebuild; hashmap_rebuild.count = 0; hashmap_rebuild.capacity = capacity_new; hashmap_rebuild.resize_threshold = resize_threshold_new; hashmap_rebuild.entries = POBJ_XRESERVE_ALLOC(pop, struct entry, sz_alloc, &actv[actv_cnt], POBJ_XALLOC_ZERO); if (TOID_IS_NULL(hashmap_rebuild.entries)) { fprintf(stderr, "hashmap rebuild failed: %s\n", pmemobj_errormsg()); goto rebuild_err; } actv_cnt++; #ifdef DEBUG free(swaps_array); swaps_array = (int *)calloc(capacity_new, sizeof(int)); if (!swaps_array) goto rebuild_err; #endif if (entries_cache(pop, &hashmap_rebuild, D_RW(hashmap)) == -1) goto rebuild_err; pmemobj_persist(pop, D_RW(hashmap_rebuild.entries), sz_alloc); pmemobj_defer_free(pop, D_RW(hashmap)->entries.oid, &actv[actv_cnt++]); pmemobj_set_value(pop, &actv[actv_cnt++], &D_RW(hashmap)->entries.oid.pool_uuid_lo, hashmap_rebuild.entries.oid.pool_uuid_lo); pmemobj_set_value(pop, &actv[actv_cnt++], &D_RW(hashmap)->entries.oid.off, hashmap_rebuild.entries.oid.off); HM_ASSERT(sizeof(actv) / sizeof(actv[0]) >= actv_cnt); pmemobj_publish(pop, actv, actv_cnt); return 0; rebuild_err: pmemobj_cancel(pop, actv, actv_cnt); #ifdef DEBUG free(swaps_array); #endif return -1; } /* * hm_rp_create -- initializes hashmap state, called after pmemobj_create */ int hm_rp_create(PMEMobjpool *pop, TOID(struct hashmap_rp) *map, void *arg) { struct hashmap_args *args = (struct hashmap_args *)arg; uint32_t seed = args ? args->seed : 0; hashmap_create(pop, map, seed); return 0; } /* * hm_rp_check -- checks if specified persistent object is an instance of * hashmap */ int hm_rp_check(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap) { return TOID_IS_NULL(hashmap) || !TOID_VALID(hashmap); } /* * hm_rp_init -- recovers hashmap state, called after pmemobj_open. * Since hashmap_rp is performing rebuild/insertion completely or not at all, * function is dummy and simply returns 0. */ int hm_rp_init(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap) { return 0; } /* * hm_rp_insert -- rebuilds hashmap if necessary and wraps insert_helper. * returns: * - 0 if successful, * - 1 if value already existed * - -1 if something bad happened */ int hm_rp_insert(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key, PMEMoid value) { if (D_RO(hashmap)->count + 1 >= D_RO(hashmap)->resize_threshold) { uint64_t capacity_new = D_RO(hashmap)->capacity * 2; if (hm_rp_rebuild(pop, hashmap, capacity_new) != 0) return -1; } return insert_helper(pop, D_RW(hashmap), key, value, HASHMAP_RP_NO_REBUILD); } /* * hm_rp_remove -- removes specified key from the hashmap, * returns: * - key's value if successful, * - OID_NULL if value didn't exist or if something bad happened */ PMEMoid hm_rp_remove(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key) { const uint64_t pos = index_lookup(D_RO(hashmap), key); if (pos == 0) return OID_NULL; struct entry *entry_p = D_RW(D_RW(hashmap)->entries); entry_p += pos; PMEMoid ret = entry_p->value; size_t actvcnt = 0; struct pobj_action actv[5]; pmemobj_set_value(pop, &actv[actvcnt++], &entry_p->hash, entry_p->hash | TOMBSTONE_MASK); pmemobj_set_value(pop, &actv[actvcnt++], &entry_p->value.pool_uuid_lo, 0); pmemobj_set_value(pop, &actv[actvcnt++], &entry_p->value.off, 0); pmemobj_set_value(pop, &actv[actvcnt++], &entry_p->key, 0); pmemobj_set_value(pop, &actv[actvcnt++], &D_RW(hashmap)->count, D_RW(hashmap)->count - 1); HM_ASSERT(sizeof(actv) / sizeof(actv[0]) >= actvcnt); pmemobj_publish(pop, actv, actvcnt); uint64_t reduced_threshold = (uint64_t) (((uint64_t)(D_RO(hashmap)->capacity / 2)) * HASHMAP_RP_LOAD_FACTOR); if (reduced_threshold >= INIT_ENTRIES_NUM_RP && D_RW(hashmap)->count < reduced_threshold && hm_rp_rebuild(pop, hashmap, D_RO(hashmap)->capacity / 2)) return OID_NULL; return ret; } /* * hm_rp_get -- checks whether specified key is in the hashmap. * Returns associated value if key exists, OID_NULL otherwise. */ PMEMoid hm_rp_get(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key) { struct entry *entry_p = (struct entry *)pmemobj_direct(D_RW(hashmap)->entries.oid); uint64_t pos = index_lookup(D_RO(hashmap), key); return pos == 0 ? OID_NULL : (entry_p + pos)->value; } /* * hm_rp_lookup -- checks whether specified key is in the hashmap. * Returns 1 if key was found, 0 otherwise. */ int hm_rp_lookup(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, uint64_t key) { return index_lookup(D_RO(hashmap), key) != 0; } /* * hm_rp_foreach -- calls cb for all values from the hashmap */ int hm_rp_foreach(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { struct entry *entry_p = (struct entry *)pmemobj_direct(D_RO(hashmap)->entries.oid); int ret = 0; for (size_t i = 0; i < D_RO(hashmap)->capacity; ++i, ++entry_p) { uint64_t hash = entry_p->hash; if (entry_is_empty(hash)) continue; ret = cb(entry_p->key, entry_p->value, arg); if (ret) return ret; } return 0; } /* * hm_rp_debug -- prints complete hashmap state */ static void hm_rp_debug(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, FILE *out) { #ifdef DEBUG fprintf(out, "debug: true, "); #endif fprintf(out, "capacity: %" PRIu64 ", count: %" PRIu64 "\n", D_RO(hashmap)->capacity, D_RO(hashmap)->count); struct entry *entry_p = D_RW((D_RW(hashmap)->entries)); for (size_t i = 0; i < D_RO(hashmap)->capacity; ++i, ++entry_p) { uint64_t hash = entry_p->hash; if (entry_is_empty(hash)) continue; uint64_t key = entry_p->key; #ifdef DEBUG fprintf(out, "%zu: %" PRIu64 " hash: %" PRIu64 " dist:%" PRIu32 " swaps:%u\n", i, key, hash, probe_distance(D_RO(hashmap), hash, i), swaps_array[i]); #else fprintf(out, "%zu: %" PRIu64 " dist:%" PRIu64 "\n", i, key, probe_distance(D_RO(hashmap), hash, i)); #endif } } /* * hm_rp_count -- returns number of elements */ size_t hm_rp_count(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap) { return D_RO(hashmap)->count; } /* * hm_rp_cmd -- execute cmd for hashmap */ int hm_rp_cmd(PMEMobjpool *pop, TOID(struct hashmap_rp) hashmap, unsigned cmd, uint64_t arg) { switch (cmd) { case HASHMAP_CMD_REBUILD: hm_rp_rebuild(pop, hashmap, D_RO(hashmap)->capacity); return 0; case HASHMAP_CMD_DEBUG: if (!arg) return -EINVAL; hm_rp_debug(pop, hashmap, (FILE *)arg); return 0; default: return -EINVAL; } }
16,890
23.338617
79
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_atomic.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ #ifndef HASHMAP_ATOMIC_H #define HASHMAP_ATOMIC_H #include <stddef.h> #include <stdint.h> #include <hashmap.h> #include <libpmemobj.h> #ifndef HASHMAP_ATOMIC_TYPE_OFFSET #define HASHMAP_ATOMIC_TYPE_OFFSET 1000 #endif struct hashmap_atomic; TOID_DECLARE(struct hashmap_atomic, HASHMAP_ATOMIC_TYPE_OFFSET + 0); int hm_atomic_check(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap); int hm_atomic_create(PMEMobjpool *pop, TOID(struct hashmap_atomic) *map, void *arg); int hm_atomic_init(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap); int hm_atomic_insert(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key, PMEMoid value); PMEMoid hm_atomic_remove(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key); PMEMoid hm_atomic_get(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key); int hm_atomic_lookup(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key); int hm_atomic_foreach(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); size_t hm_atomic_count(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap); int hm_atomic_cmd(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, unsigned cmd, uint64_t arg); #endif /* HASHMAP_ATOMIC_H */
1,384
36.432432
79
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/hashmap/hashmap_atomic.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* integer hash set implementation which uses only atomic APIs */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <inttypes.h> #include <libpmemobj.h> #include "hashmap_atomic.h" #include "hashmap_internal.h" /* layout definition */ TOID_DECLARE(struct buckets, HASHMAP_ATOMIC_TYPE_OFFSET + 1); TOID_DECLARE(struct entry, HASHMAP_ATOMIC_TYPE_OFFSET + 2); struct entry { uint64_t key; PMEMoid value; /* list pointer */ POBJ_LIST_ENTRY(struct entry) list; }; struct entry_args { uint64_t key; PMEMoid value; }; POBJ_LIST_HEAD(entries_head, struct entry); struct buckets { /* number of buckets */ size_t nbuckets; /* array of lists */ struct entries_head bucket[]; }; struct hashmap_atomic { /* random number generator seed */ uint32_t seed; /* hash function coefficients */ uint32_t hash_fun_a; uint32_t hash_fun_b; uint64_t hash_fun_p; /* number of values inserted */ uint64_t count; /* whether "count" should be updated */ uint32_t count_dirty; /* buckets */ TOID(struct buckets) buckets; /* buckets, used during rehashing, null otherwise */ TOID(struct buckets) buckets_tmp; }; /* * create_entry -- entry initializer */ static int create_entry(PMEMobjpool *pop, void *ptr, void *arg) { struct entry *e = (struct entry *)ptr; struct entry_args *args = (struct entry_args *)arg; e->key = args->key; e->value = args->value; memset(&e->list, 0, sizeof(e->list)); pmemobj_persist(pop, e, sizeof(*e)); return 0; } /* * create_buckets -- buckets initializer */ static int create_buckets(PMEMobjpool *pop, void *ptr, void *arg) { struct buckets *b = (struct buckets *)ptr; b->nbuckets = *((size_t *)arg); pmemobj_memset_persist(pop, &b->bucket, 0, b->nbuckets * sizeof(b->bucket[0])); pmemobj_persist(pop, &b->nbuckets, sizeof(b->nbuckets)); return 0; } /* * create_hashmap -- hashmap initializer */ static void create_hashmap(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint32_t seed) { D_RW(hashmap)->seed = seed; do { D_RW(hashmap)->hash_fun_a = (uint32_t)rand(); } while (D_RW(hashmap)->hash_fun_a == 0); D_RW(hashmap)->hash_fun_b = (uint32_t)rand(); D_RW(hashmap)->hash_fun_p = HASH_FUNC_COEFF_P; size_t len = INIT_BUCKETS_NUM; size_t sz = sizeof(struct buckets) + len * sizeof(struct entries_head); if (POBJ_ALLOC(pop, &D_RW(hashmap)->buckets, struct buckets, sz, create_buckets, &len)) { fprintf(stderr, "root alloc failed: %s\n", pmemobj_errormsg()); abort(); } pmemobj_persist(pop, D_RW(hashmap), sizeof(*D_RW(hashmap))); } /* * hash -- the simplest hashing function, * see https://en.wikipedia.org/wiki/Universal_hashing#Hashing_integers */ static uint64_t hash(const TOID(struct hashmap_atomic) *hashmap, const TOID(struct buckets) *buckets, uint64_t value) { uint32_t a = D_RO(*hashmap)->hash_fun_a; uint32_t b = D_RO(*hashmap)->hash_fun_b; uint64_t p = D_RO(*hashmap)->hash_fun_p; size_t len = D_RO(*buckets)->nbuckets; return ((a * value + b) % p) % len; } /* * hm_atomic_rebuild_finish -- finishes rebuild, assumes buckets_tmp is not null */ static void hm_atomic_rebuild_finish(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap) { TOID(struct buckets) cur = D_RO(hashmap)->buckets; TOID(struct buckets) tmp = D_RO(hashmap)->buckets_tmp; for (size_t i = 0; i < D_RO(cur)->nbuckets; ++i) { while (!POBJ_LIST_EMPTY(&D_RO(cur)->bucket[i])) { TOID(struct entry) en = POBJ_LIST_FIRST(&D_RO(cur)->bucket[i]); uint64_t h = hash(&hashmap, &tmp, D_RO(en)->key); if (POBJ_LIST_MOVE_ELEMENT_HEAD(pop, &D_RW(cur)->bucket[i], &D_RW(tmp)->bucket[h], en, list, list)) { fprintf(stderr, "move failed: %s\n", pmemobj_errormsg()); abort(); } } } POBJ_FREE(&D_RO(hashmap)->buckets); D_RW(hashmap)->buckets = D_RO(hashmap)->buckets_tmp; pmemobj_persist(pop, &D_RW(hashmap)->buckets, sizeof(D_RW(hashmap)->buckets)); /* * We have to set offset manually instead of substituting OID_NULL, * because we won't be able to recover easily if crash happens after * pool_uuid_lo, but before offset is set. Another reason why everyone * should use transaction API. * See recovery process in hm_init and TOID_IS_NULL macro definition. */ D_RW(hashmap)->buckets_tmp.oid.off = 0; pmemobj_persist(pop, &D_RW(hashmap)->buckets_tmp, sizeof(D_RW(hashmap)->buckets_tmp)); } /* * hm_atomic_rebuild -- rebuilds the hashmap with a new number of buckets */ static void hm_atomic_rebuild(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, size_t new_len) { if (new_len == 0) new_len = D_RO(D_RO(hashmap)->buckets)->nbuckets; size_t sz = sizeof(struct buckets) + new_len * sizeof(struct entries_head); POBJ_ALLOC(pop, &D_RW(hashmap)->buckets_tmp, struct buckets, sz, create_buckets, &new_len); if (TOID_IS_NULL(D_RO(hashmap)->buckets_tmp)) { fprintf(stderr, "failed to allocate temporary space of size: %zu" ", %s\n", new_len, pmemobj_errormsg()); return; } hm_atomic_rebuild_finish(pop, hashmap); } /* * hm_atomic_insert -- inserts specified value into the hashmap, * returns: * - 0 if successful, * - 1 if value already existed, * - -1 if something bad happened */ int hm_atomic_insert(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key, PMEMoid value) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); int num = 0; POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[h], list) { if (D_RO(var)->key == key) return 1; num++; } D_RW(hashmap)->count_dirty = 1; pmemobj_persist(pop, &D_RW(hashmap)->count_dirty, sizeof(D_RW(hashmap)->count_dirty)); struct entry_args args; args.key = key; args.value = value; PMEMoid oid = POBJ_LIST_INSERT_NEW_HEAD(pop, &D_RW(buckets)->bucket[h], list, sizeof(struct entry), create_entry, &args); if (OID_IS_NULL(oid)) { fprintf(stderr, "failed to allocate entry: %s\n", pmemobj_errormsg()); return -1; } D_RW(hashmap)->count++; pmemobj_persist(pop, &D_RW(hashmap)->count, sizeof(D_RW(hashmap)->count)); D_RW(hashmap)->count_dirty = 0; pmemobj_persist(pop, &D_RW(hashmap)->count_dirty, sizeof(D_RW(hashmap)->count_dirty)); num++; if (num > MAX_HASHSET_THRESHOLD || (num > MIN_HASHSET_THRESHOLD && D_RO(hashmap)->count > 2 * D_RO(buckets)->nbuckets)) hm_atomic_rebuild(pop, hashmap, D_RW(buckets)->nbuckets * 2); return 0; } /* * hm_atomic_remove -- removes specified value from the hashmap, * returns: * - key's value if successful, * - OID_NULL if value didn't exist or if something bad happened */ PMEMoid hm_atomic_remove(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); POBJ_LIST_FOREACH(var, &D_RW(buckets)->bucket[h], list) { if (D_RO(var)->key == key) break; } if (TOID_IS_NULL(var)) return OID_NULL; D_RW(hashmap)->count_dirty = 1; pmemobj_persist(pop, &D_RW(hashmap)->count_dirty, sizeof(D_RW(hashmap)->count_dirty)); if (POBJ_LIST_REMOVE_FREE(pop, &D_RW(buckets)->bucket[h], var, list)) { fprintf(stderr, "list remove failed: %s\n", pmemobj_errormsg()); return OID_NULL; } D_RW(hashmap)->count--; pmemobj_persist(pop, &D_RW(hashmap)->count, sizeof(D_RW(hashmap)->count)); D_RW(hashmap)->count_dirty = 0; pmemobj_persist(pop, &D_RW(hashmap)->count_dirty, sizeof(D_RW(hashmap)->count_dirty)); if (D_RO(hashmap)->count < D_RO(buckets)->nbuckets) hm_atomic_rebuild(pop, hashmap, D_RO(buckets)->nbuckets / 2); return D_RO(var)->value; } /* * hm_atomic_foreach -- prints all values from the hashmap */ int hm_atomic_foreach(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; int ret = 0; for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[i], list) { ret = cb(D_RO(var)->key, D_RO(var)->value, arg); if (ret) return ret; } return 0; } /* * hm_atomic_debug -- prints complete hashmap state */ static void hm_atomic_debug(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, FILE *out) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; fprintf(out, "a: %u b: %u p: %" PRIu64 "\n", D_RO(hashmap)->hash_fun_a, D_RO(hashmap)->hash_fun_b, D_RO(hashmap)->hash_fun_p); fprintf(out, "count: %" PRIu64 ", buckets: %zu\n", D_RO(hashmap)->count, D_RO(buckets)->nbuckets); for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) { if (POBJ_LIST_EMPTY(&D_RO(buckets)->bucket[i])) continue; int num = 0; fprintf(out, "%zu: ", i); POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[i], list) { fprintf(out, "%" PRIu64 " ", D_RO(var)->key); num++; } fprintf(out, "(%d)\n", num); } } /* * hm_atomic_get -- checks whether specified value is in the hashmap */ PMEMoid hm_atomic_get(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[h], list) if (D_RO(var)->key == key) return D_RO(var)->value; return OID_NULL; } /* * hm_atomic_lookup -- checks whether specified value is in the hashmap */ int hm_atomic_lookup(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[h], list) if (D_RO(var)->key == key) return 1; return 0; } /* * hm_atomic_create -- initializes hashmap state, called after pmemobj_create */ int hm_atomic_create(PMEMobjpool *pop, TOID(struct hashmap_atomic) *map, void *arg) { struct hashmap_args *args = (struct hashmap_args *)arg; uint32_t seed = args ? args->seed : 0; POBJ_ZNEW(pop, map, struct hashmap_atomic); create_hashmap(pop, *map, seed); return 0; } /* * hm_atomic_init -- recovers hashmap state, called after pmemobj_open */ int hm_atomic_init(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap) { srand(D_RO(hashmap)->seed); /* handle rebuild interruption */ if (!TOID_IS_NULL(D_RO(hashmap)->buckets_tmp)) { printf("rebuild, previous attempt crashed\n"); if (TOID_EQUALS(D_RO(hashmap)->buckets, D_RO(hashmap)->buckets_tmp)) { /* see comment in hm_rebuild_finish */ D_RW(hashmap)->buckets_tmp.oid.off = 0; pmemobj_persist(pop, &D_RW(hashmap)->buckets_tmp, sizeof(D_RW(hashmap)->buckets_tmp)); } else if (TOID_IS_NULL(D_RW(hashmap)->buckets)) { D_RW(hashmap)->buckets = D_RW(hashmap)->buckets_tmp; pmemobj_persist(pop, &D_RW(hashmap)->buckets, sizeof(D_RW(hashmap)->buckets)); /* see comment in hm_rebuild_finish */ D_RW(hashmap)->buckets_tmp.oid.off = 0; pmemobj_persist(pop, &D_RW(hashmap)->buckets_tmp, sizeof(D_RW(hashmap)->buckets_tmp)); } else { hm_atomic_rebuild_finish(pop, hashmap); } } /* handle insert or remove interruption */ if (D_RO(hashmap)->count_dirty) { printf("count dirty, recalculating\n"); TOID(struct entry) var; TOID(struct buckets) buckets = D_RO(hashmap)->buckets; uint64_t cnt = 0; for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) POBJ_LIST_FOREACH(var, &D_RO(buckets)->bucket[i], list) cnt++; printf("old count: %" PRIu64 ", new count: %" PRIu64 "\n", D_RO(hashmap)->count, cnt); D_RW(hashmap)->count = cnt; pmemobj_persist(pop, &D_RW(hashmap)->count, sizeof(D_RW(hashmap)->count)); D_RW(hashmap)->count_dirty = 0; pmemobj_persist(pop, &D_RW(hashmap)->count_dirty, sizeof(D_RW(hashmap)->count_dirty)); } return 0; } /* * hm_atomic_check -- checks if specified persistent object is an * instance of hashmap */ int hm_atomic_check(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap) { return TOID_IS_NULL(hashmap) || !TOID_VALID(hashmap); } /* * hm_atomic_count -- returns number of elements */ size_t hm_atomic_count(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap) { return D_RO(hashmap)->count; } /* * hm_atomic_cmd -- execute cmd for hashmap */ int hm_atomic_cmd(PMEMobjpool *pop, TOID(struct hashmap_atomic) hashmap, unsigned cmd, uint64_t arg) { switch (cmd) { case HASHMAP_CMD_REBUILD: hm_atomic_rebuild(pop, hashmap, arg); return 0; case HASHMAP_CMD_DEBUG: if (!arg) return -EINVAL; hm_atomic_debug(pop, hashmap, (FILE *)arg); return 0; default: return -EINVAL; } }
12,825
24.001949
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemlog/obj_pmemlog_simple.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * obj_pmemlog_simple.c -- alternate pmemlog implementation based on pmemobj * * usage: obj_pmemlog_simple [co] file [cmd[:param]...] * * c - create file * o - open file * * The "cmd" arguments match the pmemlog functions: * a - append * v - appendv * r - rewind * w - walk * n - nbyte * t - tell * "a", "w" and "v" require a parameter string(s) separated by a colon */ #include <ex_common.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include "libpmemobj.h" #include "libpmem.h" #include "libpmemlog.h" #define USABLE_SIZE (9.0 / 10) #define MAX_POOL_SIZE (((size_t)1024 * 1024 * 1024 * 16)) #define POOL_SIZE ((size_t)(1024 * 1024 * 100)) POBJ_LAYOUT_BEGIN(obj_pmemlog_simple); POBJ_LAYOUT_ROOT(obj_pmemlog_simple, struct base); POBJ_LAYOUT_TOID(obj_pmemlog_simple, struct log); POBJ_LAYOUT_END(obj_pmemlog_simple); /* log entry header */ struct log_hdr { uint64_t write_offset; /* data write offset */ size_t data_size; /* size available for data */ }; /* struct log stores the entire log entry */ struct log { struct log_hdr hdr; char data[]; }; /* struct base has the lock and log OID */ struct base { PMEMrwlock rwlock; /* lock covering entire log */ TOID(struct log) log; }; /* * pmemblk_map -- (internal) read or initialize the log pool */ static int pmemlog_map(PMEMobjpool *pop, size_t fsize) { int retval = 0; TOID(struct base)bp; bp = POBJ_ROOT(pop, struct base); /* log already initialized */ if (!TOID_IS_NULL(D_RO(bp)->log)) return retval; size_t pool_size = (size_t)(fsize * USABLE_SIZE); /* max size of a single allocation is 16GB */ if (pool_size > MAX_POOL_SIZE) { errno = EINVAL; return 1; } TX_BEGIN(pop) { TX_ADD(bp); D_RW(bp)->log = TX_ZALLOC(struct log, pool_size); D_RW(D_RW(bp)->log)->hdr.data_size = pool_size - sizeof(struct log_hdr); } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemlog_open -- pool open wrapper */ PMEMlogpool * pmemlog_open(const char *path) { PMEMobjpool *pop = pmemobj_open(path, POBJ_LAYOUT_NAME(obj_pmemlog_simple)); assert(pop != NULL); struct stat buf; if (stat(path, &buf)) { perror("stat"); return NULL; } return pmemlog_map(pop, buf.st_size) ? NULL : (PMEMlogpool *)pop; } /* * pmemlog_create -- pool create wrapper */ PMEMlogpool * pmemlog_create(const char *path, size_t poolsize, mode_t mode) { PMEMobjpool *pop = pmemobj_create(path, POBJ_LAYOUT_NAME(obj_pmemlog_simple), poolsize, mode); assert(pop != NULL); struct stat buf; if (stat(path, &buf)) { perror("stat"); return NULL; } return pmemlog_map(pop, buf.st_size) ? NULL : (PMEMlogpool *)pop; } /* * pool_close -- pool close wrapper */ void pmemlog_close(PMEMlogpool *plp) { pmemobj_close((PMEMobjpool *)plp); } /* * pmemlog_nbyte -- return usable size of a log memory pool */ size_t pmemlog_nbyte(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct log) logp; logp = D_RO(POBJ_ROOT(pop, struct base))->log; return D_RO(logp)->hdr.data_size; } /* * pmemlog_append -- add data to a log memory pool */ int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count) { PMEMobjpool *pop = (PMEMobjpool *)plp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); TOID(struct log) logp; logp = D_RW(bp)->log; /* check for overrun */ if ((D_RO(logp)->hdr.write_offset + count) > D_RO(logp)->hdr.data_size) { errno = ENOMEM; return 1; } /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { char *dst = D_RW(logp)->data + D_RO(logp)->hdr.write_offset; /* add hdr to undo log */ TX_ADD_FIELD(logp, hdr); /* copy and persist data */ pmemobj_memcpy_persist(pop, dst, buf, count); /* set the new offset */ D_RW(logp)->hdr.write_offset += count; } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemlog_appendv -- add gathered data to a log memory pool */ int pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt) { PMEMobjpool *pop = (PMEMobjpool *)plp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); uint64_t total_count = 0; /* calculate required space */ for (int i = 0; i < iovcnt; ++i) total_count += iov[i].iov_len; TOID(struct log) logp; logp = D_RW(bp)->log; /* check for overrun */ if ((D_RO(logp)->hdr.write_offset + total_count) > D_RO(logp)->hdr.data_size) { errno = ENOMEM; return 1; } /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { TX_ADD(D_RW(bp)->log); /* append the data */ for (int i = 0; i < iovcnt; ++i) { char *buf = (char *)iov[i].iov_base; size_t count = iov[i].iov_len; char *dst = D_RW(logp)->data + D_RO(logp)->hdr.write_offset; /* copy and persist data */ pmemobj_memcpy_persist(pop, dst, buf, count); /* set the new offset */ D_RW(logp)->hdr.write_offset += count; } } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemlog_tell -- return current write point in a log memory pool */ long long pmemlog_tell(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct log) logp; logp = D_RO(POBJ_ROOT(pop, struct base))->log; return D_RO(logp)->hdr.write_offset; } /* * pmemlog_rewind -- discard all data, resetting a log memory pool to empty */ void pmemlog_rewind(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { /* add the hdr to the undo log */ TX_ADD_FIELD(D_RW(bp)->log, hdr); /* reset the write offset */ D_RW(D_RW(bp)->log)->hdr.write_offset = 0; } TX_END } /* * 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) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* acquire a rdlock here */ int err; if ((err = pmemobj_rwlock_rdlock(pop, &D_RW(bp)->rwlock)) != 0) { errno = err; return; } TOID(struct log) logp; logp = D_RW(bp)->log; size_t read_size = chunksize ? chunksize : D_RO(logp)->hdr.data_size; char *read_ptr = D_RW(logp)->data; const char *write_ptr = (D_RO(logp)->data + D_RO(logp)->hdr.write_offset); while (read_ptr < write_ptr) { read_size = MIN(read_size, (size_t)(write_ptr - read_ptr)); (*process_chunk)(read_ptr, read_size, arg); read_ptr += read_size; } pmemobj_rwlock_unlock(pop, &D_RW(bp)->rwlock); } /* * process_chunk -- (internal) process function for log_walk */ static int process_chunk(const void *buf, size_t len, void *arg) { char *tmp = (char *)malloc(len + 1); if (tmp == NULL) { fprintf(stderr, "malloc error\n"); return 0; } memcpy(tmp, buf, len); tmp[len] = '\0'; printf("log contains:\n"); printf("%s\n", tmp); free(tmp); return 1; /* continue */ } /* * count_iovec -- (internal) count the number of iovec items */ static int count_iovec(char *arg) { int count = 1; char *pch = strchr(arg, ':'); while (pch != NULL) { ++count; pch = strchr(++pch, ':'); } return count; } /* * fill_iovec -- (internal) fill out the iovec */ static void fill_iovec(struct iovec *iov, char *arg) { char *pch = strtok(arg, ":"); while (pch != NULL) { iov->iov_base = pch; iov->iov_len = strlen((char *)iov->iov_base); ++iov; pch = strtok(NULL, ":"); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } PMEMlogpool *plp; if (strncmp(argv[1], "c", 1) == 0) { plp = pmemlog_create(argv[2], POOL_SIZE, CREATE_MODE_RW); } else if (strncmp(argv[1], "o", 1) == 0) { plp = pmemlog_open(argv[2]); } else { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } if (plp == NULL) { perror("pmemlog_create/pmemlog_open"); return 1; } /* process the command line arguments */ for (int i = 3; i < argc; i++) { switch (*argv[i]) { case 'a': { printf("append: %s\n", argv[i] + 2); if (pmemlog_append(plp, argv[i] + 2, strlen(argv[i] + 2))) fprintf(stderr, "pmemlog_append" " error\n"); break; } case 'v': { printf("appendv: %s\n", argv[i] + 2); int count = count_iovec(argv[i] + 2); struct iovec *iov = (struct iovec *)malloc( count * sizeof(struct iovec)); if (iov == NULL) { fprintf(stderr, "malloc error\n"); return 1; } fill_iovec(iov, argv[i] + 2); if (pmemlog_appendv(plp, iov, count)) fprintf(stderr, "pmemlog_appendv" " error\n"); free(iov); break; } case 'r': { printf("rewind\n"); pmemlog_rewind(plp); break; } case 'w': { printf("walk\n"); unsigned long walksize = strtoul(argv[i] + 2, NULL, 10); pmemlog_walk(plp, walksize, process_chunk, NULL); break; } case 'n': { printf("nbytes: %zu\n", pmemlog_nbyte(plp)); break; } case 't': { printf("offset: %lld\n", pmemlog_tell(plp)); break; } default: { fprintf(stderr, "unrecognized command %s\n", argv[i]); break; } }; } /* all done */ pmemlog_close(plp); return 0; }
9,720
21.043084
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemlog/obj_pmemlog.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * obj_pmemlog.c -- alternate pmemlog implementation based on pmemobj * * usage: obj_pmemlog [co] file [cmd[:param]...] * * c - create file * o - open file * * The "cmd" arguments match the pmemlog functions: * a - append * v - appendv * r - rewind * w - walk * n - nbyte * t - tell * "a" and "v" require a parameter string(s) separated by a colon */ #include <ex_common.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include "libpmemobj.h" #include "libpmem.h" #include "libpmemlog.h" #define LAYOUT_NAME "obj_pmemlog" #define POOL_SIZE ((size_t)(1024 * 1024 * 100)) /* types of allocations */ enum types { LOG_TYPE, LOG_HDR_TYPE, BASE_TYPE, MAX_TYPES }; /* log entry header */ struct log_hdr { PMEMoid next; /* object ID of the next log buffer */ size_t size; /* size of this log buffer */ }; /* struct log stores the entire log entry */ struct log { struct log_hdr hdr; /* entry header */ char data[]; /* log entry data */ }; /* struct base keeps track of the beginning of the log list */ struct base { PMEMoid head; /* object ID of the first log buffer */ PMEMoid tail; /* object ID of the last log buffer */ PMEMrwlock rwlock; /* lock covering entire log */ size_t bytes_written; /* number of bytes stored in the pool */ }; /* * pmemlog_open -- pool open wrapper */ PMEMlogpool * pmemlog_open(const char *path) { return (PMEMlogpool *)pmemobj_open(path, LAYOUT_NAME); } /* * pmemlog_create -- pool create wrapper */ PMEMlogpool * pmemlog_create(const char *path, size_t poolsize, mode_t mode) { return (PMEMlogpool *)pmemobj_create(path, LAYOUT_NAME, poolsize, mode); } /* * pmemlog_close -- pool close wrapper */ void pmemlog_close(PMEMlogpool *plp) { pmemobj_close((PMEMobjpool *)plp); } /* * pmemlog_nbyte -- not available in this implementation */ size_t pmemlog_nbyte(PMEMlogpool *plp) { /* N/A */ return 0; } /* * pmemlog_append -- add data to a log memory pool */ int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count) { PMEMobjpool *pop = (PMEMobjpool *)plp; PMEMoid baseoid = pmemobj_root(pop, sizeof(struct base)); struct base *bp = pmemobj_direct(baseoid); /* set the return point */ jmp_buf env; if (setjmp(env)) { /* end the transaction */ (void) pmemobj_tx_end(); return 1; } /* begin a transaction, also acquiring the write lock for the log */ if (pmemobj_tx_begin(pop, env, TX_PARAM_RWLOCK, &bp->rwlock, TX_PARAM_NONE)) return -1; /* allocate the new node to be inserted */ PMEMoid log = pmemobj_tx_alloc(count + sizeof(struct log_hdr), LOG_TYPE); struct log *logp = pmemobj_direct(log); logp->hdr.size = count; memcpy(logp->data, buf, count); logp->hdr.next = OID_NULL; /* add the modified root object to the undo log */ pmemobj_tx_add_range(baseoid, 0, sizeof(struct base)); if (bp->tail.off == 0) { /* update head */ bp->head = log; } else { /* add the modified tail entry to the undo log */ pmemobj_tx_add_range(bp->tail, 0, sizeof(struct log)); ((struct log *)pmemobj_direct(bp->tail))->hdr.next = log; } bp->tail = log; /* update tail */ bp->bytes_written += count; pmemobj_tx_commit(); (void) pmemobj_tx_end(); return 0; } /* * pmemlog_appendv -- add gathered data to a log memory pool */ int pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt) { PMEMobjpool *pop = (PMEMobjpool *)plp; PMEMoid baseoid = pmemobj_root(pop, sizeof(struct base)); struct base *bp = pmemobj_direct(baseoid); /* set the return point */ jmp_buf env; if (setjmp(env)) { /* end the transaction */ pmemobj_tx_end(); return 1; } /* begin a transaction, also acquiring the write lock for the log */ if (pmemobj_tx_begin(pop, env, TX_PARAM_RWLOCK, &bp->rwlock, TX_PARAM_NONE)) return -1; /* add the base object to the undo log - once for the transaction */ pmemobj_tx_add_range(baseoid, 0, sizeof(struct base)); /* add the tail entry once to the undo log, if it is set */ if (!OID_IS_NULL(bp->tail)) pmemobj_tx_add_range(bp->tail, 0, sizeof(struct log)); /* append the data */ for (int i = 0; i < iovcnt; ++i) { char *buf = iov[i].iov_base; size_t count = iov[i].iov_len; /* allocate the new node to be inserted */ PMEMoid log = pmemobj_tx_alloc(count + sizeof(struct log_hdr), LOG_TYPE); struct log *logp = pmemobj_direct(log); logp->hdr.size = count; memcpy(logp->data, buf, count); logp->hdr.next = OID_NULL; if (bp->tail.off == 0) { bp->head = log; /* update head */ } else { ((struct log *)pmemobj_direct(bp->tail))->hdr.next = log; } bp->tail = log; /* update tail */ bp->bytes_written += count; } pmemobj_tx_commit(); (void) pmemobj_tx_end(); return 0; } /* * pmemlog_tell -- returns the current write point for the log */ long long pmemlog_tell(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; struct base *bp = pmemobj_direct(pmemobj_root(pop, sizeof(struct base))); if (pmemobj_rwlock_rdlock(pop, &bp->rwlock) != 0) return 0; long long bytes_written = bp->bytes_written; pmemobj_rwlock_unlock(pop, &bp->rwlock); return bytes_written; } /* * pmemlog_rewind -- discard all data, resetting a log memory pool to empty */ void pmemlog_rewind(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; PMEMoid baseoid = pmemobj_root(pop, sizeof(struct base)); struct base *bp = pmemobj_direct(baseoid); /* set the return point */ jmp_buf env; if (setjmp(env)) { /* end the transaction */ pmemobj_tx_end(); return; } /* begin a transaction, also acquiring the write lock for the log */ if (pmemobj_tx_begin(pop, env, TX_PARAM_RWLOCK, &bp->rwlock, TX_PARAM_NONE)) return; /* add the root object to the undo log */ pmemobj_tx_add_range(baseoid, 0, sizeof(struct base)); /* free all log nodes */ while (bp->head.off != 0) { PMEMoid nextoid = ((struct log *)pmemobj_direct(bp->head))->hdr.next; pmemobj_tx_free(bp->head); bp->head = nextoid; } bp->head = OID_NULL; bp->tail = OID_NULL; bp->bytes_written = 0; pmemobj_tx_commit(); (void) pmemobj_tx_end(); } /* * pmemlog_walk -- walk through all data in a log memory pool * * As this implementation holds the size of each entry, the chunksize is ignored * and the process_chunk function gets the actual entry length. */ void pmemlog_walk(PMEMlogpool *plp, size_t chunksize, int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg) { PMEMobjpool *pop = (PMEMobjpool *)plp; struct base *bp = pmemobj_direct(pmemobj_root(pop, sizeof(struct base))); if (pmemobj_rwlock_rdlock(pop, &bp->rwlock) != 0) return; /* process all chunks */ struct log *next = pmemobj_direct(bp->head); while (next != NULL) { (*process_chunk)(next->data, next->hdr.size, arg); next = pmemobj_direct(next->hdr.next); } pmemobj_rwlock_unlock(pop, &bp->rwlock); } /* * process_chunk -- (internal) process function for log_walk */ static int process_chunk(const void *buf, size_t len, void *arg) { char *tmp = malloc(len + 1); if (tmp == NULL) { fprintf(stderr, "malloc error\n"); return 0; } memcpy(tmp, buf, len); tmp[len] = '\0'; printf("log contains:\n"); printf("%s\n", tmp); free(tmp); return 1; } /* * count_iovec -- (internal) count the number of iovec items */ static int count_iovec(char *arg) { int count = 1; char *pch = strchr(arg, ':'); while (pch != NULL) { ++count; pch = strchr(++pch, ':'); } return count; } /* * fill_iovec -- (internal) fill out the iovec */ static void fill_iovec(struct iovec *iov, char *arg) { char *pch = strtok(arg, ":"); while (pch != NULL) { iov->iov_base = pch; iov->iov_len = strlen((char *)iov->iov_base); ++iov; pch = strtok(NULL, ":"); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } PMEMlogpool *plp; if (strncmp(argv[1], "c", 1) == 0) { plp = pmemlog_create(argv[2], POOL_SIZE, CREATE_MODE_RW); } else if (strncmp(argv[1], "o", 1) == 0) { plp = pmemlog_open(argv[2]); } else { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } if (plp == NULL) { perror("pmemlog_create/pmemlog_open"); return 1; } /* process the command line arguments */ for (int i = 3; i < argc; i++) { switch (*argv[i]) { case 'a': { printf("append: %s\n", argv[i] + 2); if (pmemlog_append(plp, argv[i] + 2, strlen(argv[i] + 2))) fprintf(stderr, "pmemlog_append" " error\n"); break; } case 'v': { printf("appendv: %s\n", argv[i] + 2); int count = count_iovec(argv[i] + 2); struct iovec *iov = calloc(count, sizeof(struct iovec)); fill_iovec(iov, argv[i] + 2); if (pmemlog_appendv(plp, iov, count)) fprintf(stderr, "pmemlog_appendv" " error\n"); free(iov); break; } case 'r': { printf("rewind\n"); pmemlog_rewind(plp); break; } case 'w': { printf("walk\n"); pmemlog_walk(plp, 0, process_chunk, NULL); break; } case 'n': { printf("nbytes: %zu\n", pmemlog_nbyte(plp)); break; } case 't': { printf("offset: %lld\n", pmemlog_tell(plp)); break; } default: { fprintf(stderr, "unrecognized command %s\n", argv[i]); break; } }; } /* all done */ pmemlog_close(plp); return 0; }
9,486
20.960648
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemlog/obj_pmemlog_minimal.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * obj_pmemlog_macros.c -- alternate pmemlog implementation based on pmemobj * * usage: obj_pmemlog_macros [co] file [cmd[:param]...] * * c - create file * o - open file * * The "cmd" arguments match the pmemlog functions: * a - append * v - appendv * r - rewind * w - walk * n - nbyte * t - tell * "a" and "v" require a parameter string(s) separated by a colon */ #include <ex_common.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include "libpmemobj.h" #include "libpmem.h" #include "libpmemlog.h" #define POOL_SIZE ((size_t)(1024 * 1024 * 100)) POBJ_LAYOUT_BEGIN(obj_pmemlog_minimal); POBJ_LAYOUT_TOID(obj_pmemlog_minimal, struct log); POBJ_LAYOUT_END(obj_pmemlog_minimal); /* struct log stores the entire log entry */ struct log { size_t size; char data[]; }; /* structure containing arguments for the alloc constructor */ struct create_args { size_t size; const void *src; }; /* * create_log_entry -- (internal) constructor for the log entry */ static int create_log_entry(PMEMobjpool *pop, void *ptr, void *arg) { struct log *logptr = ptr; struct create_args *carg = arg; logptr->size = carg->size; pmemobj_persist(pop, &logptr->size, sizeof(logptr->size)); pmemobj_memcpy_persist(pop, logptr->data, carg->src, carg->size); return 0; } /* * pmemlog_open -- pool open wrapper */ PMEMlogpool * pmemlog_open(const char *path) { return (PMEMlogpool *)pmemobj_open(path, POBJ_LAYOUT_NAME(obj_pmemlog_minimal)); } /* * pmemlog_create -- pool create wrapper */ PMEMlogpool * pmemlog_create(const char *path, size_t poolsize, mode_t mode) { return (PMEMlogpool *)pmemobj_create(path, POBJ_LAYOUT_NAME(obj_pmemlog_minimal), poolsize, mode); } /* * pool_close -- pool close wrapper */ void pmemlog_close(PMEMlogpool *plp) { pmemobj_close((PMEMobjpool *)plp); } /* * pmemlog_nbyte -- not available in this implementation */ size_t pmemlog_nbyte(PMEMlogpool *plp) { /* N/A */ return 0; } /* * pmemlog_append -- add data to a log memory pool */ int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count) { PMEMobjpool *pop = (PMEMobjpool *)plp; struct create_args args = { count, buf }; size_t obj_size = sizeof(size_t) + count; /* alloc-construct to an internal list */ PMEMoid obj; pmemobj_alloc(pop, &obj, obj_size, 0, create_log_entry, &args); return 0; } /* * pmemlog_appendv -- add gathered data to a log memory pool */ int pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt) { PMEMobjpool *pop = (PMEMobjpool *)plp; /* append the data */ for (int i = 0; i < iovcnt; ++i) { struct create_args args = { iov[i].iov_len, iov[i].iov_base }; size_t obj_size = sizeof(size_t) + args.size; /* alloc-construct to an internal list */ pmemobj_alloc(pop, NULL, obj_size, 0, create_log_entry, &args); } return 0; } /* * pmemlog_tell -- not available in this implementation */ long long pmemlog_tell(PMEMlogpool *plp) { /* N/A */ return 0; } /* * pmemlog_rewind -- discard all data, resetting a log memory pool to empty */ void pmemlog_rewind(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; PMEMoid iter, next; /* go through each list and remove all entries */ POBJ_FOREACH_SAFE(pop, iter, next) { pmemobj_free(&iter); } } /* * pmemlog_walk -- walk through all data in a log memory pool * * As this implementation holds the size of each entry, the chunksize is ignored * and the process_chunk function gets the actual entry length. */ void pmemlog_walk(PMEMlogpool *plp, size_t chunksize, int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg) { PMEMobjpool *pop = (PMEMobjpool *)plp; PMEMoid iter; /* process each allocated object */ POBJ_FOREACH(pop, iter) { struct log *logptr = pmemobj_direct(iter); (*process_chunk)(logptr->data, logptr->size, arg); } } /* * process_chunk -- (internal) process function for log_walk */ static int process_chunk(const void *buf, size_t len, void *arg) { char *tmp = malloc(len + 1); if (tmp == NULL) { fprintf(stderr, "malloc error\n"); return 0; } memcpy(tmp, buf, len); tmp[len] = '\0'; printf("log contains:\n"); printf("%s\n", tmp); free(tmp); return 1; /* continue */ } /* * count_iovec -- (internal) count the number of iovec items */ static int count_iovec(char *arg) { int count = 1; char *pch = strchr(arg, ':'); while (pch != NULL) { ++count; pch = strchr(++pch, ':'); } return count; } /* * fill_iovec -- (internal) fill out the iovec */ static void fill_iovec(struct iovec *iov, char *arg) { char *pch = strtok(arg, ":"); while (pch != NULL) { iov->iov_base = pch; iov->iov_len = strlen((char *)iov->iov_base); ++iov; pch = strtok(NULL, ":"); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } PMEMlogpool *plp; if (strncmp(argv[1], "c", 1) == 0) { plp = pmemlog_create(argv[2], POOL_SIZE, CREATE_MODE_RW); } else if (strncmp(argv[1], "o", 1) == 0) { plp = pmemlog_open(argv[2]); } else { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } if (plp == NULL) { perror("pmemlog_create/pmemlog_open"); return 1; } /* process the command line arguments */ for (int i = 3; i < argc; i++) { switch (*argv[i]) { case 'a': { printf("append: %s\n", argv[i] + 2); if (pmemlog_append(plp, argv[i] + 2, strlen(argv[i] + 2))) fprintf(stderr, "pmemlog_append" " error\n"); break; } case 'v': { printf("appendv: %s\n", argv[i] + 2); int count = count_iovec(argv[i] + 2); struct iovec *iov = calloc(count, sizeof(struct iovec)); if (iov == NULL) { fprintf(stderr, "malloc error\n"); return 1; } fill_iovec(iov, argv[i] + 2); if (pmemlog_appendv(plp, iov, count)) fprintf(stderr, "pmemlog_appendv" " error\n"); free(iov); break; } case 'r': { printf("rewind\n"); pmemlog_rewind(plp); break; } case 'w': { printf("walk\n"); pmemlog_walk(plp, 0, process_chunk, NULL); break; } case 'n': { printf("nbytes: %zu\n", pmemlog_nbyte(plp)); break; } case 't': { printf("offset: %lld\n", pmemlog_tell(plp)); break; } default: { fprintf(stderr, "unrecognized command %s\n", argv[i]); break; } }; } /* all done */ pmemlog_close(plp); return 0; }
6,606
19.266871
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/pmemlog/obj_pmemlog_macros.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * obj_pmemlog_macros.c -- alternate pmemlog implementation based on pmemobj * * usage: obj_pmemlog_macros [co] file [cmd[:param]...] * * c - create file * o - open file * * The "cmd" arguments match the pmemlog functions: * a - append * v - appendv * r - rewind * w - walk * n - nbyte * t - tell * "a" and "v" require a parameter string(s) separated by a colon */ #include <ex_common.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include "libpmemobj.h" #include "libpmem.h" #include "libpmemlog.h" #define POOL_SIZE ((size_t)(1024 * 1024 * 100)) POBJ_LAYOUT_BEGIN(obj_pmemlog_macros); POBJ_LAYOUT_ROOT(obj_pmemlog_macros, struct base); POBJ_LAYOUT_TOID(obj_pmemlog_macros, struct log); POBJ_LAYOUT_END(obj_pmemlog_macros); /* log entry header */ struct log_hdr { TOID(struct log) next; /* object ID of the next log buffer */ size_t size; /* size of this log buffer */ }; /* struct log stores the entire log entry */ struct log { struct log_hdr hdr; /* entry header */ char data[]; /* log entry data */ }; /* struct base keeps track of the beginning of the log list */ struct base { TOID(struct log) head; /* object ID of the first log buffer */ TOID(struct log) tail; /* object ID of the last log buffer */ PMEMrwlock rwlock; /* lock covering entire log */ size_t bytes_written; /* number of bytes stored in the pool */ }; /* * pmemlog_open -- pool open wrapper */ PMEMlogpool * pmemlog_open(const char *path) { return (PMEMlogpool *)pmemobj_open(path, POBJ_LAYOUT_NAME(obj_pmemlog_macros)); } /* * pmemlog_create -- pool create wrapper */ PMEMlogpool * pmemlog_create(const char *path, size_t poolsize, mode_t mode) { return (PMEMlogpool *)pmemobj_create(path, POBJ_LAYOUT_NAME(obj_pmemlog_macros), poolsize, mode); } /* * pool_close -- pool close wrapper */ void pmemlog_close(PMEMlogpool *plp) { pmemobj_close((PMEMobjpool *)plp); } /* * pmemlog_nbyte -- not available in this implementation */ size_t pmemlog_nbyte(PMEMlogpool *plp) { /* N/A */ return 0; } /* * pmemlog_append -- add data to a log memory pool */ int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count) { PMEMobjpool *pop = (PMEMobjpool *)plp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { /* allocate the new node to be inserted */ TOID(struct log) logp; logp = TX_ALLOC(struct log, count + sizeof(struct log_hdr)); D_RW(logp)->hdr.size = count; memcpy(D_RW(logp)->data, buf, count); D_RW(logp)->hdr.next = TOID_NULL(struct log); /* add the modified root object to the undo log */ TX_ADD(bp); if (TOID_IS_NULL(D_RO(bp)->tail)) { /* update head */ D_RW(bp)->head = logp; } else { /* add the modified tail entry to the undo log */ TX_ADD(D_RW(bp)->tail); D_RW(D_RW(bp)->tail)->hdr.next = logp; } D_RW(bp)->tail = logp; /* update tail */ D_RW(bp)->bytes_written += count; } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemlog_appendv -- add gathered data to a log memory pool */ int pmemlog_appendv(PMEMlogpool *plp, const struct iovec *iov, int iovcnt) { PMEMobjpool *pop = (PMEMobjpool *)plp; int retval = 0; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { /* add the base object and tail entry to the undo log */ TX_ADD(bp); if (!TOID_IS_NULL(D_RO(bp)->tail)) TX_ADD(D_RW(bp)->tail); /* append the data */ for (int i = 0; i < iovcnt; ++i) { char *buf = (char *)iov[i].iov_base; size_t count = iov[i].iov_len; /* allocate the new node to be inserted */ TOID(struct log) logp; logp = TX_ALLOC(struct log, count + sizeof(struct log_hdr)); D_RW(logp)->hdr.size = count; memcpy(D_RW(logp)->data, buf, count); D_RW(logp)->hdr.next = TOID_NULL(struct log); /* update head or tail accordingly */ if (TOID_IS_NULL(D_RO(bp)->tail)) D_RW(bp)->head = logp; else D_RW(D_RW(bp)->tail)->hdr.next = logp; /* update tail */ D_RW(bp)->tail = logp; D_RW(bp)->bytes_written += count; } } TX_ONABORT { retval = -1; } TX_END return retval; } /* * pmemlog_tell -- returns the current write point for the log */ long long pmemlog_tell(PMEMlogpool *plp) { TOID(struct base) bp; bp = POBJ_ROOT((PMEMobjpool *)plp, struct base); return D_RO(bp)->bytes_written; } /* * pmemlog_rewind -- discard all data, resetting a log memory pool to empty */ void pmemlog_rewind(PMEMlogpool *plp) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* begin a transaction, also acquiring the write lock for the log */ TX_BEGIN_PARAM(pop, TX_PARAM_RWLOCK, &D_RW(bp)->rwlock, TX_PARAM_NONE) { /* add the root object to the undo log */ TX_ADD(bp); while (!TOID_IS_NULL(D_RO(bp)->head)) { TOID(struct log) nextp; nextp = D_RW(D_RW(bp)->head)->hdr.next; TX_FREE(D_RW(bp)->head); D_RW(bp)->head = nextp; } D_RW(bp)->head = TOID_NULL(struct log); D_RW(bp)->tail = TOID_NULL(struct log); D_RW(bp)->bytes_written = 0; } TX_END } /* * pmemlog_walk -- walk through all data in a log memory pool * * As this implementation holds the size of each entry, the chunksize is ignored * and the process_chunk function gets the actual entry length. */ void pmemlog_walk(PMEMlogpool *plp, size_t chunksize, int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg) { PMEMobjpool *pop = (PMEMobjpool *)plp; TOID(struct base) bp; bp = POBJ_ROOT(pop, struct base); /* acquire a read lock */ if (pmemobj_rwlock_rdlock(pop, &D_RW(bp)->rwlock) != 0) return; TOID(struct log) next; next = D_RO(bp)->head; /* process all chunks */ while (!TOID_IS_NULL(next)) { (*process_chunk)(D_RO(next)->data, D_RO(next)->hdr.size, arg); next = D_RO(next)->hdr.next; } pmemobj_rwlock_unlock(pop, &D_RW(bp)->rwlock); } /* * process_chunk -- (internal) process function for log_walk */ static int process_chunk(const void *buf, size_t len, void *arg) { char *tmp = (char *)malloc(len + 1); if (tmp == NULL) { fprintf(stderr, "malloc error\n"); return 0; } memcpy(tmp, buf, len); tmp[len] = '\0'; printf("log contains:\n"); printf("%s\n", tmp); free(tmp); return 1; /* continue */ } /* * count_iovec -- (internal) count the number of iovec items */ static int count_iovec(char *arg) { int count = 1; char *pch = strchr(arg, ':'); while (pch != NULL) { ++count; pch = strchr(++pch, ':'); } return count; } /* * fill_iovec -- (internal) fill out the iovec */ static void fill_iovec(struct iovec *iov, char *arg) { char *pch = strtok(arg, ":"); while (pch != NULL) { iov->iov_base = pch; iov->iov_len = strlen((char *)iov->iov_base); ++iov; pch = strtok(NULL, ":"); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } PMEMlogpool *plp; if (strncmp(argv[1], "c", 1) == 0) { plp = pmemlog_create(argv[2], POOL_SIZE, CREATE_MODE_RW); } else if (strncmp(argv[1], "o", 1) == 0) { plp = pmemlog_open(argv[2]); } else { fprintf(stderr, "usage: %s [o,c] file [val...]\n", argv[0]); return 1; } if (plp == NULL) { perror("pmemlog_create/pmemlog_open"); return 1; } /* process the command line arguments */ for (int i = 3; i < argc; i++) { switch (*argv[i]) { case 'a': { printf("append: %s\n", argv[i] + 2); if (pmemlog_append(plp, argv[i] + 2, strlen(argv[i] + 2))) fprintf(stderr, "pmemlog_append" " error\n"); break; } case 'v': { printf("appendv: %s\n", argv[i] + 2); int count = count_iovec(argv[i] + 2); struct iovec *iov = (struct iovec *)malloc( count * sizeof(struct iovec)); if (iov == NULL) { fprintf(stderr, "malloc error\n"); break; } fill_iovec(iov, argv[i] + 2); if (pmemlog_appendv(plp, iov, count)) fprintf(stderr, "pmemlog_appendv" " error\n"); free(iov); break; } case 'r': { printf("rewind\n"); pmemlog_rewind(plp); break; } case 'w': { printf("walk\n"); pmemlog_walk(plp, 0, process_chunk, NULL); break; } case 'n': { printf("nbytes: %zu\n", pmemlog_nbyte(plp)); break; } case 't': { printf("offset: %lld\n", pmemlog_tell(plp)); break; } default: { fprintf(stderr, "unrecognized command %s\n", argv[i]); break; } }; } /* all done */ pmemlog_close(plp); return 0; }
8,866
21.448101
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree_examine.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree_examine.c * * Description: implementation of examine function for ART tree structures * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #include <stdio.h> #include <libgen.h> #include <string.h> #include <unistd.h> #include <inttypes.h> #include <stdlib.h> #include <getopt.h> #include <stdint.h> #include <stdbool.h> #include "arttree_structures.h" /* * examine context */ struct examine_ctx { struct pmem_context *pmem_ctx; char *offset_string; uint64_t offset; char *type_name; int32_t type; int32_t hexdump; }; static struct examine_ctx *ex_ctx = NULL; struct examine { const char *name; const char *brief; int (*func)(char *, struct examine_ctx *, off_t); void (*help)(char *); }; /* local functions */ static int examine_parse_args(char *appname, int ac, char *av[], struct examine_ctx *ex_ctx); static struct examine *get_examine(char *type_name); static void print_usage(char *appname); static void dump_PMEMoid(char *prefix, PMEMoid *oid); static int examine_PMEMoid(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_tree_root(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_node_u(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_node4(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_node16(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_node48(char *appname, struct examine_ctx *ctx, off_t off); static int examine_art_node256(char *appname, struct examine_ctx *ctx, off_t off); #if 0 /* XXX */ static int examine_art_node(char *appname, struct examine_ctx *ctx, off_t off); #else static int examine_art_node(art_node *an); #endif static int examine_art_leaf(char *appname, struct examine_ctx *ctx, off_t off); static int examine_var_string(char *appname, struct examine_ctx *ctx, off_t off); /* global visible interface */ void arttree_examine_help(char *appname); int arttree_examine_func(char *appname, struct pmem_context *ctx, int ac, char *av[]); static const char *arttree_examine_help_str = "Examine data structures (objects) of ART tree\n" "Arguments: <offset> <type>\n" " <offset> offset of object in pmem file\n" " <type> one of art_tree_root, art_node_u, art_node," " art_node4, art_node16, art_node48, art_node256, art_leaf\n" ; static const struct option long_options[] = { {"hexdump", no_argument, NULL, 'x'}, {NULL, 0, NULL, 0 }, }; static struct examine ex_funcs[] = { { .name = "PMEMobj", .brief = "examine PMEMoid structure", .func = examine_PMEMoid, .help = NULL, }, { .name = "art_tree_root", .brief = "examine art_tree_root structure", .func = examine_art_tree_root, .help = NULL, }, { .name = "art_node_u", .brief = "examine art_node_u structure", .func = examine_art_node_u, .help = NULL, }, { .name = "art_node4", .brief = "examine art_node4 structure", .func = examine_art_node4, .help = NULL, }, { .name = "art_node16", .brief = "examine art_node16 structure", .func = examine_art_node16, .help = NULL, }, { .name = "art_node48", .brief = "examine art_node48 structure", .func = examine_art_node48, .help = NULL, }, { .name = "art_node256", .brief = "examine art_node256 structure", .func = examine_art_node256, .help = NULL, }, { .name = "art_leaf", .brief = "examine art_leaf structure", .func = examine_art_leaf, .help = NULL, }, { .name = "var_string", .brief = "examine var_string structure", .func = examine_var_string, .help = NULL, }, }; /* * number of arttree examine commands */ #define COMMANDS_NUMBER (sizeof(ex_funcs) / sizeof(ex_funcs[0])) void arttree_examine_help(char *appname) { printf("%s %s\n", appname, arttree_examine_help_str); } int arttree_examine_func(char *appname, struct pmem_context *ctx, int ac, char *av[]) { int errors = 0; off_t offset; struct examine *ex; if (ctx == NULL) { return -1; } if (ex_ctx == NULL) { ex_ctx = (struct examine_ctx *) calloc(1, sizeof(struct examine_ctx)); if (ex_ctx == NULL) { return -1; } } ex_ctx->pmem_ctx = ctx; if (examine_parse_args(appname, ac, av, ex_ctx) != 0) { fprintf(stderr, "%s::%s: error parsing arguments\n", appname, __FUNCTION__); errors++; } if (!errors) { offset = (off_t)strtol(ex_ctx->offset_string, NULL, 0); ex = get_examine(ex_ctx->type_name); if (ex != NULL) { ex->func(appname, ex_ctx, offset); } } return errors; } static int examine_parse_args(char *appname, int ac, char *av[], struct examine_ctx *ex_ctx) { int ret = 0; int opt; optind = 0; while ((opt = getopt_long(ac, av, "x", long_options, NULL)) != -1) { switch (opt) { case 'x': ex_ctx->hexdump = 1; break; default: print_usage(appname); ret = 1; } } if (ret == 0) { ex_ctx->offset_string = strdup(av[optind + 0]); ex_ctx->type_name = strdup(av[optind + 1]); } return ret; } static void print_usage(char *appname) { printf("%s: examine <offset> <type>\n", appname); } /* * get_command -- returns command for specified command name */ static struct examine * get_examine(char *type_name) { if (type_name == NULL) { return NULL; } for (size_t i = 0; i < COMMANDS_NUMBER; i++) { if (strcmp(type_name, ex_funcs[i].name) == 0) return &ex_funcs[i]; } return NULL; } static void dump_PMEMoid(char *prefix, PMEMoid *oid) { printf("%s { PMEMoid pool_uuid_lo %" PRIx64 " off 0x%" PRIx64 " = %" PRId64 " }\n", prefix, oid->pool_uuid_lo, oid->off, oid->off); } static int examine_PMEMoid(char *appname, struct examine_ctx *ctx, off_t off) { void *p = (void *)(ctx->pmem_ctx->addr + off); dump_PMEMoid("PMEMoid", p); return 0; } static int examine_art_tree_root(char *appname, struct examine_ctx *ctx, off_t off) { art_tree_root *tree_root = (art_tree_root *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_tree_root {\n", (long long)off); printf(" size %d\n", tree_root->size); dump_PMEMoid(" art_node_u", (PMEMoid *)&(tree_root->root)); printf("\n};\n"); return 0; } static int examine_art_node_u(char *appname, struct examine_ctx *ctx, off_t off) { art_node_u *node_u = (art_node_u *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node_u {\n", (long long)off); printf(" type %d [%s]\n", node_u->art_node_type, art_node_names[node_u->art_node_type]); printf(" tag %d\n", node_u->art_node_tag); switch (node_u->art_node_type) { case ART_NODE4: dump_PMEMoid(" art_node4 oid", &(node_u->u.an4.oid)); break; case ART_NODE16: dump_PMEMoid(" art_node16 oid", &(node_u->u.an16.oid)); break; case ART_NODE48: dump_PMEMoid(" art_node48 oid", &(node_u->u.an48.oid)); break; case ART_NODE256: dump_PMEMoid(" art_node256 oid", &(node_u->u.an256.oid)); break; case ART_LEAF: dump_PMEMoid(" art_leaf oid", &(node_u->u.al.oid)); break; default: printf("ERROR: unknown node type\n"); break; } printf("\n};\n"); return 0; } static int examine_art_node4(char *appname, struct examine_ctx *ctx, off_t off) { art_node4 *an4 = (art_node4 *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node4 {\n", (long long)off); examine_art_node(&(an4->n)); printf("keys ["); for (int i = 0; i < 4; i++) { printf("%c ", an4->keys[i]); } printf("]\nnodes [\n"); for (int i = 0; i < 4; i++) { dump_PMEMoid(" art_node_u oid", &(an4->children[i].oid)); } printf("\n]"); printf("\n};\n"); return 0; } static int examine_art_node16(char *appname, struct examine_ctx *ctx, off_t off) { art_node16 *an16 = (art_node16 *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node16 {\n", (long long)off); examine_art_node(&(an16->n)); printf("keys ["); for (int i = 0; i < 16; i++) { printf("%c ", an16->keys[i]); } printf("]\nnodes [\n"); for (int i = 0; i < 16; i++) { dump_PMEMoid(" art_node_u oid", &(an16->children[i].oid)); } printf("\n]"); printf("\n};\n"); return 0; } static int examine_art_node48(char *appname, struct examine_ctx *ctx, off_t off) { art_node48 *an48 = (art_node48 *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node48 {\n", (long long)off); examine_art_node(&(an48->n)); printf("keys ["); for (int i = 0; i < 256; i++) { printf("%c ", an48->keys[i]); } printf("]\nnodes [\n"); for (int i = 0; i < 48; i++) { dump_PMEMoid(" art_node_u oid", &(an48->children[i].oid)); } printf("\n]"); printf("\n};\n"); return 0; } static int examine_art_node256(char *appname, struct examine_ctx *ctx, off_t off) { art_node256 *an256 = (art_node256 *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node256 {\n", (long long)off); examine_art_node(&(an256->n)); printf("nodes [\n"); for (int i = 0; i < 256; i++) { dump_PMEMoid(" art_node_u oid", &(an256->children[i].oid)); } printf("\n]"); printf("\n};\n"); return 0; } #if 0 /* XXX */ static int examine_art_node(char *appname, struct examine_ctx *ctx, off_t off) { art_node *an = (art_node *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_node {\n", (long long)off); printf(" num_children %d\n", an->num_children); printf(" partial_len %d\n", an->partial_len); printf(" partial ["); for (int i = 0; i < 10; i++) { printf("%c ", an->partial[i]); } printf("\n]"); printf("\n};\n"); return 0; } #else static int examine_art_node(art_node *an) { printf("art_node {\n"); printf(" num_children %d\n", an->num_children); printf(" partial_len %" PRIu32 "\n", an->partial_len); printf(" partial ["); for (int i = 0; i < 10; i++) { printf("%c ", an->partial[i]); } printf("\n]"); printf("\n};\n"); return 0; } #endif static int examine_art_leaf(char *appname, struct examine_ctx *ctx, off_t off) { art_leaf *al = (art_leaf *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, art_leaf {\n", (long long)off); dump_PMEMoid(" var_string key oid ", &(al->key.oid)); dump_PMEMoid(" var_string value oid", &(al->value.oid)); printf("\n};\n"); return 0; } static int examine_var_string(char *appname, struct examine_ctx *ctx, off_t off) { var_string *vs = (var_string *)(ctx->pmem_ctx->addr + off); printf("at offset 0x%llx, var_string {\n", (long long)off); printf(" len %zu s [%s]", vs->len, vs->s); printf("\n};\n"); return 0; }
12,509
24.478615
78
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree_structures.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree_structures.c * * Description: Examine pmem structures; structures and unions taken from * the preprocessor output of a libpmemobj compatible program. * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #ifdef __FreeBSD__ #define _WITH_GETLINE #endif #include <stdio.h> #include <fcntl.h> #include <libgen.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <getopt.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <sys/mman.h> #include <sys/stat.h> #include "arttree_structures.h" #include <stdarg.h> #define APPNAME "examine_arttree" #define SRCVERSION "0.2" size_t art_node_sizes[art_node_types] = { sizeof(art_node4), sizeof(art_node16), sizeof(art_node48), sizeof(art_node256), sizeof(art_leaf), sizeof(art_node_u), sizeof(art_node), sizeof(art_tree_root), sizeof(var_string), }; char *art_node_names[art_node_types] = { "art_node4", "art_node16", "art_node48", "art_node256", "art_leaf", "art_node_u", "art_node", "art_tree_root", "var_string" }; /* * long_options -- command line arguments */ static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 }, }; /* * command -- struct for commands definition */ struct command { const char *name; const char *brief; int (*func)(char *, struct pmem_context *, int, char *[]); void (*help)(char *); }; /* * number of arttree_structures commands */ #define COMMANDS_NUMBER (sizeof(commands) / sizeof(commands[0])) static void print_help(char *appname); static void print_usage(char *appname); static void print_version(char *appname); static int quit_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]); static void quit_help(char *appname); static int set_root_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]); static void set_root_help(char *appname); static int help_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]); static void help_help(char *appname); static struct command *get_command(char *cmd_str); static int ctx_init(struct pmem_context *ctx, char *filename); static int arttree_structures_func(char *appname, struct pmem_context *ctx, int ac, char *av[]); static void arttree_structures_help(char *appname); static int arttree_info_func(char *appname, struct pmem_context *ctx, int ac, char *av[]); static void arttree_info_help(char *appname); extern int arttree_examine_func(); extern void arttree_examine_help(); extern int arttree_search_func(); extern void arttree_search_help(); void outv_err(const char *fmt, ...); void outv_err_vargs(const char *fmt, va_list ap); static struct command commands[] = { { .name = "structures", .brief = "print information about ART structures", .func = arttree_structures_func, .help = arttree_structures_help, }, { .name = "info", .brief = "print information and statistics" " about an ART tree pool", .func = arttree_info_func, .help = arttree_info_help, }, { .name = "examine", .brief = "examine data structures from an ART tree", .func = arttree_examine_func, .help = arttree_examine_help, }, { .name = "search", .brief = "search for a key in an ART tree", .func = arttree_search_func, .help = arttree_search_help, }, { .name = "set_root", .brief = "define offset of root of an ART tree", .func = set_root_func, .help = set_root_help, }, { .name = "help", .brief = "print help text about a command", .func = help_func, .help = help_help, }, { .name = "quit", .brief = "quit ART tree structure examiner", .func = quit_func, .help = quit_help, }, }; static struct pmem_context ctx; /* * 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) { fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); if (!strchr(fmt, '\n')) fprintf(stderr, "\n"); } /* * print_usage -- prints usage message */ static void print_usage(char *appname) { printf("usage: %s [--help] <pmem file> <command> [<args>]\n", appname); } /* * print_version -- prints version message */ static void print_version(char *appname) { printf("%s %s\n", appname, SRCVERSION); } /* * print_help -- prints help message */ static void print_help(char *appname) { print_usage(appname); print_version(appname); printf("\n"); printf("Options:\n"); printf(" -h, --help display this help and exit\n"); printf("\n"); printf("The available commands are:\n"); for (size_t i = 0; i < COMMANDS_NUMBER; i++) printf("%s\t- %s\n", commands[i].name, commands[i].brief); printf("\n"); } /* * set_root_help -- prints help message for set root command */ static void set_root_help(char *appname) { printf("Usage: set_root <offset>\n"); printf(" define the offset of the art tree root\n"); } /* * set_root_func -- set_root define the offset of the art tree root */ static int set_root_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]) { int retval = 0; uint64_t root_offset; if (argc == 2) { root_offset = strtol(argv[1], NULL, 0); ctx->art_tree_root_offset = root_offset; } else { set_root_help(appname); retval = 1; } return retval; } /* * quit_help -- prints help message for quit command */ static void quit_help(char *appname) { printf("Usage: quit\n"); printf(" terminate arttree structure examiner\n"); } /* * quit_func -- quit arttree structure examiner */ static int quit_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]) { printf("\n"); exit(0); return 0; } /* * help_help -- prints help message for help command */ static void help_help(char *appname) { printf("Usage: %s help <command>\n", appname); } /* * help_func -- prints help message for specified command */ static int help_func(char *appname, struct pmem_context *ctx, int argc, char *argv[]) { if (argc > 1) { char *cmd_str = argv[1]; 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; } } static const char *arttree_structures_help_str = "Show information about known ART tree structures\n" ; static void arttree_structures_help(char *appname) { printf("%s %s\n", appname, arttree_structures_help_str); } static int arttree_structures_func(char *appname, struct pmem_context *ctx, int ac, char *av[]) { (void) appname; (void) ac; (void) av; printf( "typedef struct pmemoid {\n" " uint64_t pool_uuid_lo;\n" " uint64_t off;\n" "} PMEMoid;\n"); printf("sizeof(PMEMoid) = %zu\n\n\n", sizeof(PMEMoid)); printf( "struct _art_node_u; typedef struct _art_node_u art_node_u;\n" "struct _art_node_u { \n" " uint8_t art_node_type; \n" " uint8_t art_node_tag; \n" "};\n"); printf("sizeof(art_node_u) = %zu\n\n\n", sizeof(art_node_u)); printf( "struct _art_node; typedef struct _art_node art_node;\n" "struct _art_node {\n" " uint8_t type;\n" " uint8_t num_children;\n" " uint32_t partial_len;\n" " unsigned char partial[10];\n" "};\n"); printf("sizeof(art_node) = %zu\n\n\n", sizeof(art_node)); printf( "typedef uint8_t _toid_art_node_toid_type_num[8];\n"); printf("sizeof(_toid_art_node_toid_type_num[8]) = %zu\n\n\n", sizeof(_toid_art_node_toid_type_num[8])); printf( "union _toid_art_node_u_toid {\n" " PMEMoid oid;\n" " art_node_u *_type;\n" " _toid_art_node_u_toid_type_num *_type_num;\n" "};\n"); printf("sizeof(union _toid_art_node_u_toid) = %zu\n\n\n", sizeof(union _toid_art_node_u_toid)); printf( "typedef uint8_t _toid_art_node_toid_type_num[8];\n"); printf("sizeof(_toid_art_node_toid_type_num[8]) = %zu\n\n\n", sizeof(_toid_art_node_toid_type_num[8])); printf( "union _toid_art_node_toid {\n" " PMEMoid oid; \n" " art_node *_type; \n" " _toid_art_node_toid_type_num *_type_num;\n" "};\n"); printf("sizeof(union _toid_art_node_toid) = %zu\n\n\n", sizeof(union _toid_art_node_toid)); printf( "struct _art_node4; typedef struct _art_node4 art_node4;\n" "struct _art_node4 {\n" " art_node n;\n" " unsigned char keys[4];\n" " union _toid_art_node_u_toid children[4];\n" "};\n"); printf("sizeof(art_node4) = %zu\n\n\n", sizeof(art_node4)); printf( "struct _art_node16; typedef struct _art_node16 art_node16;\n" "struct _art_node16 {\n" " art_node n;\n" " unsigned char keys[16];\n" " union _toid_art_node_u_toid children[16];\n" "};\n"); printf("sizeof(art_node16) = %zu\n\n\n", sizeof(art_node16)); printf( "struct _art_node48; typedef struct _art_node48 art_node48;\n" "struct _art_node48 {\n" " art_node n;\n" " unsigned char keys[256];\n" " union _toid_art_node_u_toid children[48];\n" "};\n"); printf("sizeof(art_node48) = %zu\n\n\n", sizeof(art_node48)); printf( "struct _art_node256; typedef struct _art_node256 art_node256;\n" "struct _art_node256 {\n" " art_ndoe n;\n" " union _toid_art_node_u_toid children[256];\n" "};\n"); printf("sizeof(art_node256) = %zu\n\n\n", sizeof(art_node256)); printf( "struct _art_leaf; typedef struct _art_leaf art_leaf;\n" "struct _art_leaf {\n" " union _toid_var_string_toid value;\n" " union _toid_var_string_toid key;\n" "};\n"); printf("sizeof(art_leaf) = %zu\n\n\n", sizeof(art_leaf)); return 0; } static const char *arttree_info_help_str = "Show information about known ART tree structures\n" ; static void arttree_info_help(char *appname) { printf("%s %s\n", appname, arttree_info_help_str); } static int arttree_info_func(char *appname, struct pmem_context *ctx, int ac, char *av[]) { printf("%s: %s not yet implemented\n", appname, __FUNCTION__); return 0; } /* * get_command -- returns command for specified command name */ static struct command * get_command(char *cmd_str) { if (cmd_str == NULL) { return NULL; } for (size_t i = 0; i < COMMANDS_NUMBER; i++) { if (strcmp(cmd_str, commands[i].name) == 0) return &commands[i]; } return NULL; } static int ctx_init(struct pmem_context *ctx, char *filename) { int errors = 0; if (filename == NULL) errors++; if (ctx == NULL) errors++; if (errors) return errors; ctx->filename = strdup(filename); assert(ctx->filename != NULL); ctx->fd = -1; ctx->addr = NULL; ctx->art_tree_root_offset = 0; if (access(ctx->filename, F_OK) != 0) return 1; if ((ctx->fd = open(ctx->filename, O_RDONLY)) == -1) return 1; struct stat stbuf; if (fstat(ctx->fd, &stbuf) < 0) return 1; ctx->psize = stbuf.st_size; if ((ctx->addr = mmap(NULL, ctx->psize, PROT_READ, MAP_SHARED, ctx->fd, 0)) == MAP_FAILED) return 1; return 0; } static void ctx_fini(struct pmem_context *ctx) { munmap(ctx->addr, ctx->psize); close(ctx->fd); free(ctx->filename); } int main(int ac, char *av[]) { int opt; int option_index; int ret = 0; size_t len; ssize_t read; char *cmd_str; char *args[20]; int nargs; char *line; struct command *cmdp = NULL; while ((opt = getopt_long(ac, av, "h", long_options, &option_index)) != -1) { switch (opt) { case 'h': print_help(APPNAME); return 0; default: print_usage(APPNAME); return -1; } } if (optind >= ac) { fprintf(stderr, "ERROR: missing arguments\n"); print_usage(APPNAME); return -1; } ctx_init(&ctx, av[optind]); if (optind + 1 < ac) { /* execute command as given on command line */ cmd_str = av[optind + 1]; cmdp = get_command(cmd_str); if (cmdp != NULL) { ret = cmdp->func(APPNAME, &ctx, ac - 2, av + 2); } } else { /* interactive mode: read commands and execute them */ line = NULL; printf("\n> "); while ((read = getline(&line, &len, stdin)) != -1) { if (line[read - 1] == '\n') { line[read - 1] = '\0'; } args[0] = strtok(line, " "); cmdp = get_command(args[0]); if (cmdp == NULL) { printf("[%s]: command not supported\n", args[0] ? args[0] : "NULL"); printf("\n> "); continue; } nargs = 1; while (1) { args[nargs] = strtok(NULL, " "); if (args[nargs] == NULL) { break; } nargs++; } ret = cmdp->func(APPNAME, &ctx, nargs, args); printf("\n> "); } if (line != NULL) { free(line); } } ctx_fini(&ctx); return ret; }
14,768
22.898058
79
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/art.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * Copyright 2012, Armon Dadgar. 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. */ /* * =========================================================================== * * Filename: art.c * * Description: implement ART tree using libpmemobj based on libart * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * ============================================================================ */ /* * based on https://github.com/armon/libart/src/art.c */ #include <assert.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <stdbool.h> #include <fcntl.h> #include <emmintrin.h> #include <sys/types.h> #include "libpmemobj.h" #include "art.h" TOID(var_string) null_var_string; TOID(art_leaf) null_art_leaf; TOID(art_node_u) null_art_node_u; int art_tree_init(PMEMobjpool *pop, int *newpool); TOID(art_node_u) make_leaf(PMEMobjpool *pop, const unsigned char *key, int key_len, void *value, int val_len); int fill_leaf(PMEMobjpool *pop, TOID(art_leaf) al, const unsigned char *key, int key_len, void *value, int val_len); TOID(art_node_u) alloc_node(PMEMobjpool *pop, art_node_type node_type); TOID(var_string) art_insert(PMEMobjpool *pop, const unsigned char *key, int key_len, void *value, int val_len); TOID(var_string) art_delete(PMEMobjpool *pop, const unsigned char *key, int key_len); static TOID(var_string) recursive_insert(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, const unsigned char *key, int key_len, void *value, int val_len, int depth, int *old_val); static TOID(art_leaf) recursive_delete(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, const unsigned char *key, int key_len, int depth); static int leaf_matches(TOID(art_leaf) n, const unsigned char *key, int key_len, int depth); static int longest_common_prefix(TOID(art_leaf) l1, TOID(art_leaf) l2, int depth); static int prefix_mismatch(TOID(art_node_u) n, unsigned char *key, int key_len, int depth); #ifdef LIBART_ITER_PREFIX static int leaf_prefix_matches(TOID(art_leaf) n, const unsigned char *prefix, int prefix_len); #endif static TOID(art_leaf) minimum(TOID(art_node_u) n_u); static TOID(art_leaf) maximum(TOID(art_node_u) n_u); static void copy_header(art_node *dest, art_node *src); static void add_child(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child); static void add_child4(PMEMobjpool *pop, TOID(art_node4) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child); static void add_child16(PMEMobjpool *pop, TOID(art_node16) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child); static void add_child48(PMEMobjpool *pop, TOID(art_node48) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child); static void add_child256(PMEMobjpool *pop, TOID(art_node256) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child); static void remove_child(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) *l); static void remove_child4(PMEMobjpool *pop, TOID(art_node4) n, TOID(art_node_u) *ref, TOID(art_node_u) *l); static void remove_child16(PMEMobjpool *pop, TOID(art_node16) n, TOID(art_node_u) *ref, TOID(art_node_u) *l); static void remove_child48(PMEMobjpool *pop, TOID(art_node48) n, TOID(art_node_u) *ref, unsigned char c); static void remove_child256(PMEMobjpool *pop, TOID(art_node256) n, TOID(art_node_u) *ref, unsigned char c); static TOID(art_node_u)* find_child(TOID(art_node_u) n, unsigned char c); static int check_prefix(const art_node *n, const unsigned char *key, int key_len, int depth); static int leaf_matches(TOID(art_leaf) n, const unsigned char *key, int key_len, int depth); TOID(art_leaf) art_minimum(TOID(struct art_tree_root) t); TOID(art_leaf) art_maximum(TOID(struct art_tree_root) t); #if 0 static void destroy_node(TOID(art_node_u) n_u); #endif int art_iter(PMEMobjpool *pop, art_callback cb, void *data); static void PMEMOIDcopy(PMEMoid *dest, const PMEMoid *src, const int n); static void PMEMOIDmove(PMEMoid *dest, PMEMoid *src, const int n); static void PMEMOIDcopy(PMEMoid *dest, const PMEMoid *src, const int n) { int i; for (i = 0; i < n; i++) { dest[i] = src[i]; } } static void PMEMOIDmove(PMEMoid *dest, PMEMoid *src, const int n) { int i; if (dest > src) { for (i = n - 1; i >= 0; i--) { dest[i] = src[i]; } } else { for (i = 0; i < n; i++) { dest[i] = src[i]; } } } TOID(art_node_u) alloc_node(PMEMobjpool *pop, art_node_type node_type) { TOID(art_node_u) node; TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; TOID(art_leaf) al; node = TX_ZNEW(art_node_u); D_RW(node)->art_node_type = (uint8_t)node_type; switch (node_type) { case NODE4: an4 = TX_ZNEW(art_node4); D_RW(node)->u.an4 = an4; break; case NODE16: an16 = TX_ZNEW(art_node16); D_RW(node)->u.an16 = an16; break; case NODE48: an48 = TX_ZNEW(art_node48); D_RW(node)->u.an48 = an48; break; case NODE256: an256 = TX_ZNEW(art_node256); D_RW(node)->u.an256 = an256; break; case art_leaf_t: al = TX_ZNEW(art_leaf); D_RW(node)->u.al = al; break; default: /* invalid node type */ D_RW(node)->art_node_type = (uint8_t)art_node_types; break; } return node; } int art_tree_init(PMEMobjpool *pop, int *newpool) { int errors = 0; TOID(struct art_tree_root) root; if (pop == NULL) { errors++; } null_var_string.oid = OID_NULL; null_art_leaf.oid = OID_NULL; null_art_node_u.oid = OID_NULL; if (!errors) { TX_BEGIN(pop) { root = POBJ_ROOT(pop, struct art_tree_root); if (*newpool) { TX_ADD(root); D_RW(root)->root.oid = OID_NULL; D_RW(root)->size = 0; *newpool = 0; } } TX_END } return errors; } #if 0 // Recursively destroys the tree static void destroy_node(TOID(art_node_u) n_u) { // Break if null if (TOID_IS_NULL(n_u)) return; // Special case leafs if (IS_LEAF(D_RO(n_u))) { TX_FREE(n_u); return; } // Handle each node type int i; TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; switch (D_RO(n_u)->art_node_type) { case NODE4: an4 = D_RO(n_u)->u.an4; for (i = 0; i < D_RO(an4)->n.num_children; i++) { destroy_node(D_RW(an4)->children[i]); } break; case NODE16: an16 = D_RO(n_u)->u.an16; for (i = 0; i < D_RO(an16)->n.num_children; i++) { destroy_node(D_RW(an16)->children[i]); } break; case NODE48: an48 = D_RO(n_u)->u.an48; for (i = 0; i < D_RO(an48)->n.num_children; i++) { destroy_node(D_RW(an48)->children[i]); } break; case NODE256: an256 = D_RO(n_u)->u.an256; for (i = 0; i < D_RO(an256)->n.num_children; i++) { if (!(TOID_IS_NULL(D_RO(an256)->children[i]))) { destroy_node(D_RW(an256)->children[i]); } } break; default: abort(); } // Free ourself on the way up TX_FREE(n_u); } /* * Destroys an ART tree * @return 0 on success. */ static int art_tree_destroy(TOID(struct art_tree_root) t) { destroy_node(D_RO(t)->root); return 0; } #endif static TOID(art_node_u)* find_child(TOID(art_node_u) n, unsigned char c) { int i; int mask; int bitfield; TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; switch (D_RO(n)->art_node_type) { case NODE4: an4 = D_RO(n)->u.an4; for (i = 0; i < D_RO(an4)->n.num_children; i++) { if (D_RO(an4)->keys[i] == c) { return &(D_RW(an4)->children[i]); } } break; case NODE16: { __m128i cmp; an16 = D_RO(n)->u.an16; // Compare the key to all 16 stored keys cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), _mm_loadu_si128((__m128i *)D_RO(an16)->keys)); // Use a mask to ignore children that don't exist mask = (1 << D_RO(an16)->n.num_children) - 1; bitfield = _mm_movemask_epi8(cmp) & mask; /* * If we have a match (any bit set) then we can * return the pointer match using ctz to get the index. */ if (bitfield) { return &(D_RW(an16)->children[__builtin_ctz(bitfield)]); } break; } case NODE48: an48 = D_RO(n)->u.an48; i = D_RO(an48)->keys[c]; if (i) { return &(D_RW(an48)->children[i - 1]); } break; case NODE256: an256 = D_RO(n)->u.an256; if (!TOID_IS_NULL(D_RO(an256)->children[c])) { return &(D_RW(an256)->children[c]); } break; default: abort(); } return &null_art_node_u; } static inline int min(int a, int b) { return (a < b) ? a : b; } /* * Returns the number of prefix characters shared between * the key and node. */ static int check_prefix(const art_node *n, const unsigned char *key, int key_len, int depth) { int max_cmp = min(min(n->partial_len, MAX_PREFIX_LEN), key_len - depth); int idx; for (idx = 0; idx < max_cmp; idx++) { if (n->partial[idx] != key[depth + idx]) return idx; } return idx; } /* * Checks if a leaf matches * @return 0 on success. */ static int leaf_matches(TOID(art_leaf) n, const unsigned char *key, int key_len, int depth) { (void) depth; // Fail if the key lengths are different if (D_RO(D_RO(n)->key)->len != (uint32_t)key_len) return 1; // Compare the keys starting at the depth return memcmp(D_RO(D_RO(n)->key)->s, key, key_len); } /* * Searches for a value in the ART tree * @arg t The tree * @arg key The key * @arg key_len The length of the key * @return NULL if the item was not found, otherwise * the value pointer is returned. */ TOID(var_string) art_search(PMEMobjpool *pop, const unsigned char *key, int key_len) { TOID(struct art_tree_root)t = POBJ_ROOT(pop, struct art_tree_root); TOID(art_node_u) *child; TOID(art_node_u) n = D_RO(t)->root; const art_node *n_an; int prefix_len; int depth = 0; while (!TOID_IS_NULL(n)) { // Might be a leaf if (IS_LEAF(D_RO(n))) { // n = LEAF_RAW(n); // Check if the expanded path matches if (!leaf_matches(D_RO(n)->u.al, key, key_len, depth)) { return (D_RO(D_RO(n)->u.al))->value; } return null_var_string; } switch (D_RO(n)->art_node_type) { case NODE4: n_an = &(D_RO(D_RO(n)->u.an4)->n); break; case NODE16: n_an = &(D_RO(D_RO(n)->u.an16)->n); break; case NODE48: n_an = &(D_RO(D_RO(n)->u.an48)->n); break; case NODE256: n_an = &(D_RO(D_RO(n)->u.an256)->n); break; default: return null_var_string; } // Bail if the prefix does not match if (n_an->partial_len) { prefix_len = check_prefix(n_an, key, key_len, depth); if (prefix_len != min(MAX_PREFIX_LEN, n_an->partial_len)) return null_var_string; depth = depth + n_an->partial_len; } // Recursively search child = find_child(n, key[depth]); if (TOID_IS_NULL(*child)) { n.oid = OID_NULL; } else { n = *child; } depth++; } return null_var_string; } // Find the minimum leaf under a node static TOID(art_leaf) minimum(TOID(art_node_u) n_u) { TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; // Handle base cases if (TOID_IS_NULL(n_u)) return null_art_leaf; if (IS_LEAF(D_RO(n_u))) return D_RO(n_u)->u.al; int idx; switch (D_RO(n_u)->art_node_type) { case NODE4: an4 = D_RO(n_u)->u.an4; return minimum(D_RO(an4)->children[0]); case NODE16: an16 = D_RO(n_u)->u.an16; return minimum(D_RO(an16)->children[0]); case NODE48: an48 = D_RO(n_u)->u.an48; idx = 0; while (!(D_RO(an48)->keys[idx])) idx++; idx = D_RO(an48)->keys[idx] - 1; assert(idx < 48); return minimum(D_RO(an48)->children[idx]); case NODE256: an256 = D_RO(n_u)->u.an256; idx = 0; while (!(TOID_IS_NULL(D_RO(an256)->children[idx]))) idx++; return minimum(D_RO(an256)->children[idx]); default: abort(); } } // Find the maximum leaf under a node static TOID(art_leaf) maximum(TOID(art_node_u) n_u) { TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; const art_node *n_an; // Handle base cases if (TOID_IS_NULL(n_u)) return null_art_leaf; if (IS_LEAF(D_RO(n_u))) return D_RO(n_u)->u.al; int idx; switch (D_RO(n_u)->art_node_type) { case NODE4: an4 = D_RO(n_u)->u.an4; n_an = &(D_RO(an4)->n); return maximum(D_RO(an4)->children[n_an->num_children - 1]); case NODE16: an16 = D_RO(n_u)->u.an16; n_an = &(D_RO(an16)->n); return maximum(D_RO(an16)->children[n_an->num_children - 1]); case NODE48: an48 = D_RO(n_u)->u.an48; idx = 255; while (!(D_RO(an48)->keys[idx])) idx--; idx = D_RO(an48)->keys[idx] - 1; assert((idx >= 0) && (idx < 48)); return maximum(D_RO(an48)->children[idx]); case NODE256: an256 = D_RO(n_u)->u.an256; idx = 255; while (!(TOID_IS_NULL(D_RO(an256)->children[idx]))) idx--; return maximum(D_RO(an256)->children[idx]); default: abort(); } } /* * Returns the minimum valued leaf */ TOID(art_leaf) art_minimum(TOID(struct art_tree_root) t) { return minimum(D_RO(t)->root); } /* * Returns the maximum valued leaf */ TOID(art_leaf) art_maximum(TOID(struct art_tree_root) t) { return maximum(D_RO(t)->root); } TOID(art_node_u) make_leaf(PMEMobjpool *pop, const unsigned char *key, int key_len, void *value, int val_len) { TOID(art_node_u)newleaf; newleaf = alloc_node(pop, art_leaf_t); fill_leaf(pop, D_RW(newleaf)->u.al, key, key_len, value, val_len); return newleaf; } static int longest_common_prefix(TOID(art_leaf) l1, TOID(art_leaf) l2, int depth) { TOID(var_string) l1_key = D_RO(l1)->key; TOID(var_string) l2_key = D_RO(l2)->key; int max_cmp; int idx; max_cmp = min(D_RO(l1_key)->len, D_RO(l2_key)->len) - depth; for (idx = 0; idx < max_cmp; idx++) { if (D_RO(l1_key)->s[depth + idx] != D_RO(l2_key)->s[depth + idx]) return idx; } return idx; } static void copy_header(art_node *dest, art_node *src) { dest->num_children = src->num_children; dest->partial_len = src->partial_len; memcpy(dest->partial, src->partial, min(MAX_PREFIX_LEN, src->partial_len)); } static void add_child256(PMEMobjpool *pop, TOID(art_node256) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child) { art_node *n_an; (void) ref; TX_ADD(n); n_an = &(D_RW(n)->n); n_an->num_children++; D_RW(n)->children[c] = child; } static void add_child48(PMEMobjpool *pop, TOID(art_node48) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child) { art_node *n_an; n_an = &(D_RW(n)->n); if (n_an->num_children < 48) { int pos = 0; TX_ADD(n); while (!(TOID_IS_NULL(D_RO(n)->children[pos]))) pos++; D_RW(n)->children[pos] = child; D_RW(n)->keys[c] = pos + 1; n_an->num_children++; } else { TOID(art_node_u) newnode_u = alloc_node(pop, NODE256); TOID(art_node256) newnode = D_RO(newnode_u)->u.an256; pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); for (int i = 0; i < 256; i++) { if (D_RO(n)->keys[i]) { D_RW(newnode)->children[i] = D_RO(n)->children[D_RO(n)->keys[i] - 1]; } } copy_header(&(D_RW(newnode)->n), n_an); *ref = newnode_u; TX_FREE(n); add_child256(pop, newnode, ref, c, child); } } static void add_child16(PMEMobjpool *pop, TOID(art_node16) n, TOID(art_node_u)*ref, unsigned char c, TOID(art_node_u) child) { art_node *n_an; n_an = &(D_RW(n)->n); if (n_an->num_children < 16) { __m128i cmp; TX_ADD(n); // Compare the key to all 16 stored keys cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), _mm_loadu_si128((__m128i *)(D_RO(n)->keys))); // Use a mask to ignore children that don't exist unsigned mask = (1 << n_an->num_children) - 1; unsigned bitfield = _mm_movemask_epi8(cmp) & mask; // Check if less than any unsigned idx; if (bitfield) { idx = __builtin_ctz(bitfield); memmove(&(D_RW(n)->keys[idx + 1]), &(D_RO(n)->keys[idx]), n_an->num_children - idx); PMEMOIDmove(&(D_RW(n)->children[idx + 1].oid), &(D_RW(n)->children[idx].oid), n_an->num_children - idx); } else { idx = n_an->num_children; } // Set the child D_RW(n)->keys[idx] = c; D_RW(n)->children[idx] = child; n_an->num_children++; } else { TOID(art_node_u) newnode_u = alloc_node(pop, NODE48); TOID(art_node48) newnode = D_RO(newnode_u)->u.an48; // Copy the child pointers and populate the key map PMEMOIDcopy(&(D_RW(newnode)->children[0].oid), &(D_RO(n)->children[0].oid), n_an->num_children); for (int i = 0; i < n_an->num_children; i++) { D_RW(newnode)->keys[D_RO(n)->keys[i]] = i + 1; } copy_header(&(D_RW(newnode))->n, n_an); *ref = newnode_u; TX_FREE(n); add_child48(pop, newnode, ref, c, child); } } static void add_child4(PMEMobjpool *pop, TOID(art_node4) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child) { art_node *n_an; n_an = &(D_RW(n)->n); if (n_an->num_children < 4) { int idx; TX_ADD(n); for (idx = 0; idx < n_an->num_children; idx++) { if (c < D_RO(n)->keys[idx]) break; } // Shift to make room memmove(D_RW(n)->keys + idx + 1, D_RO(n)->keys + idx, n_an->num_children - idx); assert((idx + 1) < 4); PMEMOIDmove(&(D_RW(n)->children[idx + 1].oid), &(D_RW(n)->children[idx].oid), n_an->num_children - idx); // Insert element D_RW(n)->keys[idx] = c; D_RW(n)->children[idx] = child; n_an->num_children++; } else { TOID(art_node_u) newnode_u = alloc_node(pop, NODE16); TOID(art_node16) newnode = D_RO(newnode_u)->u.an16; pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); // Copy the child pointers and the key map PMEMOIDcopy(&(D_RW(newnode)->children[0].oid), &(D_RO(n)->children[0].oid), n_an->num_children); memcpy(D_RW(newnode)->keys, D_RO(n)->keys, n_an->num_children); copy_header(&(D_RW(newnode)->n), n_an); *ref = newnode_u; TX_FREE(n); add_child16(pop, newnode, ref, c, child); } } static void add_child(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) child) { switch (D_RO(n)->art_node_type) { case NODE4: add_child4(pop, D_RO(n)->u.an4, ref, c, child); break; case NODE16: add_child16(pop, D_RO(n)->u.an16, ref, c, child); break; case NODE48: add_child48(pop, D_RO(n)->u.an48, ref, c, child); break; case NODE256: add_child256(pop, D_RO(n)->u.an256, ref, c, child); break; default: abort(); } } static int prefix_mismatch(TOID(art_node_u) n, unsigned char *key, int key_len, int depth) { const art_node *n_an; int max_cmp; int idx; switch (D_RO(n)->art_node_type) { case NODE4: n_an = &(D_RO(D_RO(n)->u.an4)->n); break; case NODE16: n_an = &(D_RO(D_RO(n)->u.an16)->n); break; case NODE48: n_an = &(D_RO(D_RO(n)->u.an48)->n); break; case NODE256: n_an = &(D_RO(D_RO(n)->u.an256)->n); break; default: return 0; } max_cmp = min(min(MAX_PREFIX_LEN, n_an->partial_len), key_len - depth); for (idx = 0; idx < max_cmp; idx++) { if (n_an->partial[idx] != key[depth + idx]) return idx; } // If the prefix is short we can avoid finding a leaf if (n_an->partial_len > MAX_PREFIX_LEN) { // Prefix is longer than what we've checked, find a leaf TOID(art_leaf) l = minimum(n); max_cmp = min(D_RO(D_RO(l)->key)->len, key_len) - depth; for (; idx < max_cmp; idx++) { if (D_RO(D_RO(l)->key)->s[idx + depth] != key[depth + idx]) return idx; } } return idx; } static TOID(var_string) recursive_insert(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, const unsigned char *key, int key_len, void *value, int val_len, int depth, int *old) { art_node *n_an; TOID(var_string) retval; // If we are at a NULL node, inject a leaf if (TOID_IS_NULL(n)) { *ref = make_leaf(pop, key, key_len, value, val_len); TX_ADD(*ref); SET_LEAF(D_RW(*ref)); retval = null_var_string; return retval; } // If we are at a leaf, we need to replace it with a node if (IS_LEAF(D_RO(n))) { TOID(art_leaf)l = D_RO(n)->u.al; // Check if we are updating an existing value if (!leaf_matches(l, key, key_len, depth)) { *old = 1; retval = D_RO(l)->value; TX_ADD(D_RW(l)->value); COPY_BLOB(D_RW(l)->value, value, val_len); return retval; } // New value, we must split the leaf into a node4 pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); TOID(art_node_u) newnode_u = alloc_node(pop, NODE4); TOID(art_node4) newnode = D_RO(newnode_u)->u.an4; art_node *newnode_n = &(D_RW(newnode)->n); // Create a new leaf TOID(art_node_u) l2_u = make_leaf(pop, key, key_len, value, val_len); TOID(art_leaf) l2 = D_RO(l2_u)->u.al; // Determine longest prefix int longest_prefix = longest_common_prefix(l, l2, depth); newnode_n->partial_len = longest_prefix; memcpy(newnode_n->partial, key + depth, min(MAX_PREFIX_LEN, longest_prefix)); // Add the leafs to the newnode node4 *ref = newnode_u; add_child4(pop, newnode, ref, D_RO(D_RO(l)->key)->s[depth + longest_prefix], n); add_child4(pop, newnode, ref, D_RO(D_RO(l2)->key)->s[depth + longest_prefix], l2_u); return null_var_string; } // Check if given node has a prefix switch (D_RO(n)->art_node_type) { case NODE4: n_an = &(D_RW(D_RW(n)->u.an4)->n); break; case NODE16: n_an = &(D_RW(D_RW(n)->u.an16)->n); break; case NODE48: n_an = &(D_RW(D_RW(n)->u.an48)->n); break; case NODE256: n_an = &(D_RW(D_RW(n)->u.an256)->n); break; default: abort(); } if (n_an->partial_len) { // Determine if the prefixes differ, since we need to split int prefix_diff = prefix_mismatch(n, (unsigned char *)key, key_len, depth); if ((uint32_t)prefix_diff >= n_an->partial_len) { depth += n_an->partial_len; goto RECURSE_SEARCH; } // Create a new node pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); pmemobj_tx_add_range_direct(n_an, sizeof(art_node)); TOID(art_node_u) newnode_u = alloc_node(pop, NODE4); TOID(art_node4) newnode = D_RO(newnode_u)->u.an4; art_node *newnode_n = &(D_RW(newnode)->n); *ref = newnode_u; newnode_n->partial_len = prefix_diff; memcpy(newnode_n->partial, n_an->partial, min(MAX_PREFIX_LEN, prefix_diff)); // Adjust the prefix of the old node if (n_an->partial_len <= MAX_PREFIX_LEN) { add_child4(pop, newnode, ref, n_an->partial[prefix_diff], n); n_an->partial_len -= (prefix_diff + 1); memmove(n_an->partial, n_an->partial + prefix_diff + 1, min(MAX_PREFIX_LEN, n_an->partial_len)); } else { unsigned char *dst; const unsigned char *src; size_t len; n_an->partial_len -= (prefix_diff + 1); TOID(art_leaf) l = minimum(n); add_child4(pop, newnode, ref, D_RO(D_RO(l)->key)->s[depth + prefix_diff], n); dst = n_an->partial; src = &(D_RO(D_RO(l)->key)->s[depth + prefix_diff + 1 ]); len = min(MAX_PREFIX_LEN, n_an->partial_len); memcpy(dst, src, len); } // Insert the new leaf TOID(art_node_u) l = make_leaf(pop, key, key_len, value, val_len); SET_LEAF(D_RW(l)); add_child4(pop, newnode, ref, key[depth + prefix_diff], l); return null_var_string; } RECURSE_SEARCH:; // Find a child to recurse to TOID(art_node_u) *child = find_child(n, key[depth]); if (!TOID_IS_NULL(*child)) { return recursive_insert(pop, *child, child, key, key_len, value, val_len, depth + 1, old); } // No child, node goes within us TOID(art_node_u) l = make_leaf(pop, key, key_len, value, val_len); SET_LEAF(D_RW(l)); add_child(pop, n, ref, key[depth], l); retval = null_var_string; return retval; } /* * Returns the size of the ART tree */ uint64_t art_size(PMEMobjpool *pop) { TOID(struct art_tree_root) root; root = POBJ_ROOT(pop, struct art_tree_root); return D_RO(root)->size; } /* * Inserts a new value into the ART tree * @arg t The tree * @arg key The key * @arg key_len The length of the key * @arg value Opaque value. * @return NULL if the item was newly inserted, otherwise * the old value pointer is returned. */ TOID(var_string) art_insert(PMEMobjpool *pop, const unsigned char *key, int key_len, void *value, int val_len) { int old_val = 0; TOID(var_string) old; TOID(struct art_tree_root) root; TX_BEGIN(pop) { root = POBJ_ROOT(pop, struct art_tree_root); TX_ADD(root); old = recursive_insert(pop, D_RO(root)->root, &(D_RW(root)->root), (const unsigned char *)key, key_len, value, val_len, 0, &old_val); if (!old_val) D_RW(root)->size++; } TX_ONABORT { abort(); } TX_END return old; } static void remove_child256(PMEMobjpool *pop, TOID(art_node256) n, TOID(art_node_u) *ref, unsigned char c) { art_node *n_an = &(D_RW(n)->n); TX_ADD(n); D_RW(n)->children[c].oid = OID_NULL; n_an->num_children--; // Resize to a node48 on underflow, not immediately to prevent // trashing if we sit on the 48/49 boundary if (n_an->num_children == 37) { TOID(art_node_u) newnode_u = alloc_node(pop, NODE48); TOID(art_node48) newnode_an48 = D_RO(newnode_u)->u.an48; pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); *ref = newnode_u; copy_header(&(D_RW(newnode_an48)->n), n_an); int pos = 0; for (int i = 0; i < 256; i++) { if (!TOID_IS_NULL(D_RO(n)->children[i])) { assert(pos < 48); D_RW(newnode_an48)->children[pos] = D_RO(n)->children[i]; D_RW(newnode_an48)->keys[i] = pos + 1; pos++; } } TX_FREE(n); } } static void remove_child48(PMEMobjpool *pop, TOID(art_node48) n, TOID(art_node_u) *ref, unsigned char c) { int pos = D_RO(n)->keys[c]; art_node *n_an = &(D_RW(n)->n); TX_ADD(n); D_RW(n)->keys[c] = 0; D_RW(n)->children[pos - 1].oid = OID_NULL; n_an->num_children--; if (n_an->num_children == 12) { TOID(art_node_u) newnode_u = alloc_node(pop, NODE16); TOID(art_node16) newnode_an16 = D_RO(newnode_u)->u.an16; pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); *ref = newnode_u; copy_header(&(D_RW(newnode_an16)->n), n_an); int child = 0; for (int i = 0; i < 256; i++) { pos = D_RO(n)->keys[i]; if (pos) { assert(child < 16); D_RW(newnode_an16)->keys[child] = i; D_RW(newnode_an16)->children[child] = D_RO(n)->children[pos - 1]; child++; } } TX_FREE(n); } } static void remove_child16(PMEMobjpool *pop, TOID(art_node16) n, TOID(art_node_u) *ref, TOID(art_node_u) *l) { int pos = l - &(D_RO(n)->children[0]); uint8_t num_children = ((D_RW(n)->n).num_children); TX_ADD(n); memmove(D_RW(n)->keys + pos, D_RO(n)->keys + pos + 1, num_children - 1 - pos); memmove(D_RW(n)->children + pos, D_RO(n)->children + pos + 1, (num_children - 1 - pos) * sizeof(void *)); ((D_RW(n)->n).num_children)--; if (--num_children == 3) { TOID(art_node_u) newnode_u = alloc_node(pop, NODE4); TOID(art_node4) newnode_an4 = D_RO(newnode_u)->u.an4; pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); *ref = newnode_u; copy_header(&(D_RW(newnode_an4)->n), &(D_RW(n)->n)); memcpy(D_RW(newnode_an4)->keys, D_RO(n)->keys, 4); memcpy(D_RW(newnode_an4)->children, D_RO(n)->children, 4 * sizeof(TOID(art_node_u))); TX_FREE(n); } } static void remove_child4(PMEMobjpool *pop, TOID(art_node4) n, TOID(art_node_u) *ref, TOID(art_node_u) *l) { int pos = l - &(D_RO(n)->children[0]); uint8_t *num_children = &((D_RW(n)->n).num_children); TX_ADD(n); memmove(D_RW(n)->keys + pos, D_RO(n)->keys + pos + 1, *num_children - 1 - pos); memmove(D_RW(n)->children + pos, D_RO(n)->children + pos + 1, (*num_children - 1 - pos) * sizeof(void *)); (*num_children)--; // Remove nodes with only a single child if (*num_children == 1) { TOID(art_node_u) child_u = D_RO(n)->children[0]; art_node *child = &(D_RW(D_RW(child_u)->u.an4)->n); pmemobj_tx_add_range_direct(ref, sizeof(TOID(art_node_u))); if (!IS_LEAF(D_RO(child_u))) { // Concatenate the prefixes int prefix = (D_RW(n)->n).partial_len; if (prefix < MAX_PREFIX_LEN) { (D_RW(n)->n).partial[prefix] = D_RO(n)->keys[0]; prefix++; } if (prefix < MAX_PREFIX_LEN) { int sub_prefix = min(child->partial_len, MAX_PREFIX_LEN - prefix); memcpy((D_RW(n)->n).partial + prefix, child->partial, sub_prefix); prefix += sub_prefix; } // Store the prefix in the child memcpy(child->partial, (D_RO(n)->n).partial, min(prefix, MAX_PREFIX_LEN)); child->partial_len += (D_RO(n)->n).partial_len + 1; } *ref = child_u; TX_FREE(n); } } static void remove_child(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, unsigned char c, TOID(art_node_u) *l) { switch (D_RO(n)->art_node_type) { case NODE4: return remove_child4(pop, D_RO(n)->u.an4, ref, l); case NODE16: return remove_child16(pop, D_RO(n)->u.an16, ref, l); case NODE48: return remove_child48(pop, D_RO(n)->u.an48, ref, c); case NODE256: return remove_child256(pop, D_RO(n)->u.an256, ref, c); default: abort(); } } static TOID(art_leaf) recursive_delete(PMEMobjpool *pop, TOID(art_node_u) n, TOID(art_node_u) *ref, const unsigned char *key, int key_len, int depth) { const art_node *n_an; // Search terminated if (TOID_IS_NULL(n)) return null_art_leaf; // Handle hitting a leaf node if (IS_LEAF(D_RO(n))) { TOID(art_leaf) l = D_RO(n)->u.al; if (!leaf_matches(l, key, key_len, depth)) { *ref = null_art_node_u; return l; } return null_art_leaf; } // get art_node component switch (D_RO(n)->art_node_type) { case NODE4: n_an = &(D_RO(D_RO(n)->u.an4)->n); break; case NODE16: n_an = &(D_RO(D_RO(n)->u.an16)->n); break; case NODE48: n_an = &(D_RO(D_RO(n)->u.an48)->n); break; case NODE256: n_an = &(D_RO(D_RO(n)->u.an256)->n); break; default: abort(); } // Bail if the prefix does not match if (n_an->partial_len) { int prefix_len = check_prefix(n_an, key, key_len, depth); if (prefix_len != min(MAX_PREFIX_LEN, n_an->partial_len)) { return null_art_leaf; } depth = depth + n_an->partial_len; } // Find child node TOID(art_node_u) *child = find_child(n, key[depth]); if (TOID_IS_NULL(*child)) return null_art_leaf; // If the child is leaf, delete from this node if (IS_LEAF(D_RO(*child))) { TOID(art_leaf)l = D_RO(*child)->u.al; if (!leaf_matches(l, key, key_len, depth)) { remove_child(pop, n, ref, key[depth], child); return l; } return null_art_leaf; } else { // Recurse return recursive_delete(pop, *child, child, (const unsigned char *)key, key_len, depth + 1); } } /* * Deletes a value from the ART tree * @arg t The tree * @arg key The key * @arg key_len The length of the key * @return NULL if the item was not found, otherwise * the value pointer is returned. */ TOID(var_string) art_delete(PMEMobjpool *pop, const unsigned char *key, int key_len) { TOID(struct art_tree_root)root = POBJ_ROOT(pop, struct art_tree_root); TOID(art_leaf) l; TOID(var_string) retval; retval = null_var_string; TX_BEGIN(pop) { TX_ADD(root); l = recursive_delete(pop, D_RO(root)->root, &D_RW(root)->root, key, key_len, 0); if (!TOID_IS_NULL(l)) { D_RW(root)->size--; TOID(var_string)old = D_RO(l)->value; TX_FREE(l); retval = old; } } TX_ONABORT { abort(); } TX_END return retval; } // Recursively iterates over the tree static int recursive_iter(TOID(art_node_u)n, art_callback cb, void *data) { const art_node *n_an; TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; TOID(art_leaf) l; TOID(var_string) key; TOID(var_string) value; cb_data cbd; // Handle base cases if (TOID_IS_NULL(n)) { return 0; } cbd.node = n; cbd.child_idx = -1; if (IS_LEAF(D_RO(n))) { l = D_RO(n)->u.al; key = D_RO(l)->key; value = D_RO(l)->value; return cb(&cbd, D_RO(key)->s, D_RO(key)->len, D_RO(value)->s, D_RO(value)->len); } int idx, res; switch (D_RO(n)->art_node_type) { case NODE4: an4 = D_RO(n)->u.an4; n_an = &(D_RO(an4)->n); for (int i = 0; i < n_an->num_children; i++) { cbd.child_idx = i; cb(&cbd, NULL, 0, NULL, 0); res = recursive_iter(D_RO(an4)->children[i], cb, data); if (res) return res; } break; case NODE16: an16 = D_RO(n)->u.an16; n_an = &(D_RO(an16)->n); for (int i = 0; i < n_an->num_children; i++) { cbd.child_idx = i; cb(&cbd, NULL, 0, NULL, 0); res = recursive_iter(D_RO(an16)->children[i], cb, data); if (res) return res; } break; case NODE48: an48 = D_RO(n)->u.an48; for (int i = 0; i < 256; i++) { idx = D_RO(an48)->keys[i]; if (!idx) continue; cbd.child_idx = idx - 1; cb(&cbd, NULL, 0, NULL, 0); res = recursive_iter(D_RO(an48)->children[idx - 1], cb, data); if (res) return res; } break; case NODE256: an256 = D_RO(n)->u.an256; for (int i = 0; i < 256; i++) { if (TOID_IS_NULL(D_RO(an256)->children[i])) continue; cbd.child_idx = i; cb(&cbd, NULL, 0, NULL, 0); res = recursive_iter(D_RO(an256)->children[i], cb, data); if (res) return res; } break; default: abort(); } return 0; } /* * Iterates through the entries pairs in the map, * invoking a callback for each. The call back gets a * key, value for each and returns an integer stop value. * If the callback returns non-zero, then the iteration stops. * @arg t The tree to iterate over * @arg cb The callback function to invoke * @arg data Opaque handle passed to the callback * @return 0 on success, or the return of the callback. */ int art_iter(PMEMobjpool *pop, art_callback cb, void *data) { TOID(struct art_tree_root) t = POBJ_ROOT(pop, struct art_tree_root); return recursive_iter(D_RO(t)->root, cb, data); } #ifdef LIBART_ITER_PREFIX /* { */ /* * Checks if a leaf prefix matches * @return 0 on success. */ static int leaf_prefix_matches(TOID(art_leaf) n, const unsigned char *prefix, int prefix_len) { // Fail if the key length is too short if (D_RO(D_RO(n)->key)->len < (uint32_t)prefix_len) return 1; // Compare the keys return memcmp(D_RO(D_RO(n)->key)->s, prefix, prefix_len); } /* * Iterates through the entries pairs in the map, * invoking a callback for each that matches a given prefix. * The call back gets a key, value for each and returns an integer stop value. * If the callback returns non-zero, then the iteration stops. * @arg t The tree to iterate over * @arg prefix The prefix of keys to read * @arg prefix_len The length of the prefix * @arg cb The callback function to invoke * @arg data Opaque handle passed to the callback * @return 0 on success, or the return of the callback. */ int art_iter_prefix(art_tree *t, const unsigned char *key, int key_len, art_callback cb, void *data) { art_node **child; art_node *n = t->root; int prefix_len, depth = 0; while (n) { // Might be a leaf if (IS_LEAF(n)) { n = LEAF_RAW(n); // Check if the expanded path matches if (!leaf_prefix_matches((art_leaf *)n, key, key_len)) { art_leaf *l = (art_leaf *)n; return cb(data, (const unsigned char *)l->key, l->key_len, l->value); } return 0; } // If the depth matches the prefix, we need to handle this node if (depth == key_len) { art_leaf *l = minimum(n); if (!leaf_prefix_matches(l, key, key_len)) return recursive_iter(n, cb, data); return 0; } // Bail if the prefix does not match if (n->partial_len) { prefix_len = prefix_mismatch(n, key, key_len, depth); // If there is no match, search is terminated if (!prefix_len) return 0; // If we've matched the prefix, iterate on this node else if (depth + prefix_len == key_len) { return recursive_iter(n, cb, data); } // if there is a full match, go deeper depth = depth + n->partial_len; } // Recursively search child = find_child(n, key[depth]); n = (child) ? *child : NULL; depth++; } return 0; } #endif /* } LIBART_ITER_PREFIX */ int fill_leaf(PMEMobjpool *pop, TOID(art_leaf) al, const unsigned char *key, int key_len, void *value, int val_len) { int retval = 0; size_t l_key; size_t l_val; TOID(var_string) Tkey; TOID(var_string) Tval; l_key = (sizeof(var_string) + key_len); l_val = (sizeof(var_string) + val_len); Tkey = TX_ALLOC(var_string, l_key); Tval = TX_ALLOC(var_string, l_val); COPY_BLOB(Tkey, key, key_len); COPY_BLOB(Tval, value, val_len); D_RW(al)->key = Tkey; D_RW(al)->value = Tval; return retval; }
38,338
24.559333
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree_structures.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree_structures.h * * Description: known structures of the ART tree * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #ifndef _ARTTREE_STRUCTURES_H #define _ARTTREE_STRUCTURES_H #define MAX_PREFIX_LEN 10 /* * pmem_context -- structure for pmempool file */ struct pmem_context { char *filename; size_t psize; int fd; char *addr; uint64_t art_tree_root_offset; }; struct _art_node_u; typedef struct _art_node_u art_node_u; struct _art_node; typedef struct _art_node art_node; struct _art_node4; typedef struct _art_node4 art_node4; struct _art_node16; typedef struct _art_node16 art_node16; struct _art_node48; typedef struct _art_node48 art_node48; struct _art_node256; typedef struct _art_node256 art_node256; struct _var_string; typedef struct _var_string var_string; struct _art_leaf; typedef struct _art_leaf art_leaf; struct _art_tree_root; typedef struct _art_tree_root art_tree_root; typedef uint8_t art_tree_root_toid_type_num[65535]; typedef uint8_t _toid_art_node_u_toid_type_num[2]; typedef uint8_t _toid_art_node_toid_type_num[3]; typedef uint8_t _toid_art_node4_toid_type_num[4]; typedef uint8_t _toid_art_node16_toid_type_num[5]; typedef uint8_t _toid_art_node48_toid_type_num[6]; typedef uint8_t _toid_art_node256_toid_type_num[7]; typedef uint8_t _toid_art_leaf_toid_type_num[8]; typedef uint8_t _toid_var_string_toid_type_num[9]; typedef struct pmemoid { uint64_t pool_uuid_lo; uint64_t off; } PMEMoid; union _toid_art_node_u_toid { PMEMoid oid; art_node_u *_type; _toid_art_node_u_toid_type_num *_type_num; }; union art_tree_root_toid { PMEMoid oid; struct art_tree_root *_type; art_tree_root_toid_type_num *_type_num; }; union _toid_art_node_toid { PMEMoid oid; art_node *_type; _toid_art_node_toid_type_num *_type_num; }; union _toid_art_node4_toid { PMEMoid oid; art_node4 *_type; _toid_art_node4_toid_type_num *_type_num; }; union _toid_art_node16_toid { PMEMoid oid; art_node16 *_type; _toid_art_node16_toid_type_num *_type_num; }; union _toid_art_node48_toid { PMEMoid oid; art_node48 *_type; _toid_art_node48_toid_type_num *_type_num; }; union _toid_art_node256_toid { PMEMoid oid; art_node256 *_type; _toid_art_node256_toid_type_num *_type_num; }; union _toid_var_string_toid { PMEMoid oid; var_string *_type; _toid_var_string_toid_type_num *_type_num; }; union _toid_art_leaf_toid { PMEMoid oid; art_leaf *_type; _toid_art_leaf_toid_type_num *_type_num; }; struct _art_tree_root { int size; union _toid_art_node_u_toid root; }; struct _art_node { uint8_t num_children; uint32_t partial_len; unsigned char partial[MAX_PREFIX_LEN]; }; struct _art_node4 { art_node n; unsigned char keys[4]; union _toid_art_node_u_toid children[4]; }; struct _art_node16 { art_node n; unsigned char keys[16]; union _toid_art_node_u_toid children[16]; }; struct _art_node48 { art_node n; unsigned char keys[256]; union _toid_art_node_u_toid children[48]; }; struct _art_node256 { art_node n; union _toid_art_node_u_toid children[256]; }; struct _var_string { size_t len; unsigned char s[]; }; struct _art_leaf { union _toid_var_string_toid value; union _toid_var_string_toid key; }; struct _art_node_u { uint8_t art_node_type; uint8_t art_node_tag; union { union _toid_art_node4_toid an4; union _toid_art_node16_toid an16; union _toid_art_node48_toid an48; union _toid_art_node256_toid an256; union _toid_art_leaf_toid al; } u; }; typedef enum { ART_NODE4 = 0, ART_NODE16 = 1, ART_NODE48 = 2, ART_NODE256 = 3, ART_LEAF = 4, ART_NODE_U = 5, ART_NODE = 6, ART_TREE_ROOT = 7, VAR_STRING = 8, art_node_types = 9 /* number of different art_nodes */ } art_node_type; #define VALID_NODE_TYPE(n) (((n) >= 0) && ((n) < art_node_types)) extern size_t art_node_sizes[]; extern char *art_node_names[]; #endif /* _ARTTREE_STRUCTURES_H */
5,923
25.927273
78
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree.c * * Description: implement ART tree using libpmemobj based on libart * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #include <assert.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <strings.h> #ifdef __FreeBSD__ #define _WITH_GETLINE #endif #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <stdbool.h> #include <inttypes.h> #include <fcntl.h> #include <emmintrin.h> #include <sys/types.h> #include <sys/mman.h> #include "libpmemobj.h" #include "arttree.h" /* * dummy structure so far; this should correspond to the datastore * structure as defined in examples/libpmemobj/tree_map/datastore */ struct datastore { void *priv; }; /* * context - main context of datastore */ struct ds_context { char *filename; /* name of pool file */ int mode; /* operation mode */ int insertions; /* number of insert operations to perform */ int newpool; /* complete new memory pool */ size_t psize; /* size of pool */ PMEMobjpool *pop; /* pmemobj handle */ bool fileio; unsigned fmode; int fd; /* file descriptor for file io mode */ char *addr; /* base mapping address for file io mode */ unsigned char *key; /* for SEARCH, INSERT and REMOVE */ uint32_t key_len; unsigned char *value; /* for INSERT */ uint32_t val_len; }; #define FILL (1 << 1) #define DUMP (1 << 2) #define GRAPH (1 << 3) #define INSERT (1 << 4) #define SEARCH (1 << 5) #define REMOVE (1 << 6) struct ds_context my_context; extern TOID(var_string) null_var_string; extern TOID(art_leaf) null_art_leaf; extern TOID(art_node_u) null_art_node_u; #define read_key(p) read_line(p) #define read_value(p) read_line(p) int initialize_context(struct ds_context *ctx, int ac, char *av[]); int initialize_pool(struct ds_context *ctx); int add_elements(struct ds_context *ctx); int insert_element(struct ds_context *ctx); int search_element(struct ds_context *ctx); int delete_element(struct ds_context *ctx); ssize_t read_line(unsigned char **line); void exit_handler(struct ds_context *ctx); int art_tree_map_init(struct datastore *ds, struct ds_context *ctx); void pmemobj_ds_set_priv(struct datastore *ds, void *priv); static int dump_art_leaf_callback(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *val, uint32_t val_len); static int dump_art_node_callback(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *val, uint32_t val_len); static void print_node_info(char *nodetype, uint64_t off, const art_node *an); static int parse_keyval(struct ds_context *ctx, char *arg, int mode); int initialize_context(struct ds_context *ctx, int ac, char *av[]) { int errors = 0; int opt; char mode; if ((ctx == NULL) || (ac < 2)) { errors++; } if (!errors) { ctx->filename = NULL; ctx->psize = PMEMOBJ_MIN_POOL; ctx->newpool = 0; ctx->pop = NULL; ctx->fileio = false; ctx->fmode = 0666; ctx->mode = 0; ctx->fd = -1; } if (!errors) { while ((opt = getopt(ac, av, "s:m:n:")) != -1) { switch (opt) { case 'm': mode = optarg[0]; if (mode == 'f') { ctx->mode |= FILL; } else if (mode == 'd') { ctx->mode |= DUMP; } else if (mode == 'g') { ctx->mode |= GRAPH; } else if (mode == 'i') { ctx->mode |= INSERT; parse_keyval(ctx, av[optind], INSERT); optind++; } else if (mode == 's') { ctx->mode |= SEARCH; parse_keyval(ctx, av[optind], SEARCH); optind++; } else if (mode == 'r') { ctx->mode |= REMOVE; parse_keyval(ctx, av[optind], REMOVE); optind++; } else { errors++; } break; case 'n': { long insertions; insertions = strtol(optarg, NULL, 0); if (insertions > 0 && insertions < LONG_MAX) { ctx->insertions = insertions; } break; } case 's': { unsigned long poolsize; poolsize = strtoul(optarg, NULL, 0); if (poolsize >= PMEMOBJ_MIN_POOL) { ctx->psize = poolsize; } break; } default: errors++; break; } } } if (!errors) { ctx->filename = strdup(av[optind]); } return errors; } static int parse_keyval(struct ds_context *ctx, char *arg, int mode) { int errors = 0; char *p; p = strtok(arg, ":"); if (p == NULL) { errors++; } if (!errors) { if (ctx->mode & (SEARCH|REMOVE|INSERT)) { ctx->key = (unsigned char *)strdup(p); assert(ctx->key != NULL); ctx->key_len = strlen(p) + 1; } if (ctx->mode & INSERT) { p = strtok(NULL, ":"); assert(p != NULL); ctx->value = (unsigned char *)strdup(p); assert(ctx->value != NULL); ctx->val_len = strlen(p) + 1; } } return errors; } void exit_handler(struct ds_context *ctx) { if (!ctx->fileio) { if (ctx->pop) { pmemobj_close(ctx->pop); } } else { if (ctx->fd > (-1)) { close(ctx->fd); } } } int art_tree_map_init(struct datastore *ds, struct ds_context *ctx) { int errors = 0; char *error_string; /* calculate a required pool size */ if (ctx->psize < PMEMOBJ_MIN_POOL) ctx->psize = PMEMOBJ_MIN_POOL; if (!ctx->fileio) { if (access(ctx->filename, F_OK) != 0) { error_string = "pmemobj_create"; ctx->pop = pmemobj_create(ctx->filename, POBJ_LAYOUT_NAME(arttree_tx), ctx->psize, ctx->fmode); ctx->newpool = 1; } else { error_string = "pmemobj_open"; ctx->pop = pmemobj_open(ctx->filename, POBJ_LAYOUT_NAME(arttree_tx)); } if (ctx->pop == NULL) { perror(error_string); errors++; } } else { int flags = O_CREAT | O_RDWR | O_SYNC; /* Create a file if it does not exist. */ if ((ctx->fd = open(ctx->filename, flags, ctx->fmode)) < 0) { perror(ctx->filename); errors++; } /* allocate the pmem */ if ((errno = posix_fallocate(ctx->fd, 0, ctx->psize)) != 0) { perror("posix_fallocate"); errors++; } /* map file to memory */ if ((ctx->addr = mmap(NULL, ctx->psize, PROT_READ, MAP_SHARED, ctx->fd, 0)) == MAP_FAILED) { perror("mmap"); errors++; } } if (!errors) { pmemobj_ds_set_priv(ds, ctx); } else { if (ctx->fileio) { if (ctx->addr != NULL) { munmap(ctx->addr, ctx->psize); } if (ctx->fd >= 0) { close(ctx->fd); } } else { if (ctx->pop) { pmemobj_close(ctx->pop); } } } return errors; } /* * pmemobj_ds_set_priv -- set private structure of datastore */ void pmemobj_ds_set_priv(struct datastore *ds, void *priv) { ds->priv = priv; } struct datastore myds; static void usage(char *progname) { printf("usage: %s -m [f|d|g] file\n", progname); printf(" -m mode known modes are\n"); printf(" f fill create and fill art tree\n"); printf(" i insert insert an element into the art tree\n"); printf(" s search search for a key in the art tree\n"); printf(" r remove remove an element from the art tree\n"); printf(" d dump dump art tree\n"); printf(" g graph dump art tree as a graphviz dot graph\n"); printf(" -n <number> number of key-value pairs to insert" " into the art tree\n"); printf(" -s <size> size in bytes of the memory pool" " (minimum and default: 8 MB)"); printf("\nfilling an art tree is done by reading key-value pairs\n" "from standard input.\n" "Both keys and values are single line only.\n"); } int main(int argc, char *argv[]) { if (initialize_context(&my_context, argc, argv) != 0) { usage(argv[0]); return 1; } if (art_tree_map_init(&myds, &my_context) != 0) { fprintf(stderr, "failed to initialize memory pool file\n"); return 1; } if (my_context.pop == NULL) { perror("pool initialization"); return 1; } if (art_tree_init(my_context.pop, &my_context.newpool)) { perror("pool setup"); return 1; } if ((my_context.mode & FILL)) { if (add_elements(&my_context)) { perror("add elements"); return 1; } } if ((my_context.mode & INSERT)) { if (insert_element(&my_context)) { perror("insert elements"); return 1; } } if ((my_context.mode & SEARCH)) { if (search_element(&my_context)) { perror("search elements"); return 1; } } if ((my_context.mode & REMOVE)) { if (delete_element(&my_context)) { perror("delete elements"); return 1; } } if (my_context.mode & DUMP) { art_iter(my_context.pop, dump_art_leaf_callback, NULL); } if (my_context.mode & GRAPH) { printf("digraph g {\nrankdir=LR;\n"); art_iter(my_context.pop, dump_art_node_callback, NULL); printf("}"); } exit_handler(&my_context); return 0; } int add_elements(struct ds_context *ctx) { PMEMobjpool *pop; int errors = 0; int i; int key_len; int val_len; unsigned char *key; unsigned char *value; if (ctx == NULL) { errors++; } else if (ctx->pop == NULL) { errors++; } if (!errors) { pop = ctx->pop; for (i = 0; i < ctx->insertions; i++) { key = NULL; value = NULL; key_len = read_key(&key); val_len = read_value(&value); art_insert(pop, key, key_len, value, val_len); if (key != NULL) free(key); if (value != NULL) free(value); } } return errors; } int insert_element(struct ds_context *ctx) { PMEMobjpool *pop; int errors = 0; if (ctx == NULL) { errors++; } else if (ctx->pop == NULL) { errors++; } if (!errors) { pop = ctx->pop; art_insert(pop, ctx->key, ctx->key_len, ctx->value, ctx->val_len); } return errors; } int search_element(struct ds_context *ctx) { PMEMobjpool *pop; TOID(var_string) value; int errors = 0; if (ctx == NULL) { errors++; } else if (ctx->pop == NULL) { errors++; } if (!errors) { pop = ctx->pop; printf("search key [%s]: ", (char *)ctx->key); value = art_search(pop, ctx->key, ctx->key_len); if (TOID_IS_NULL(value)) { printf("not found\n"); } else { printf("value [%s]\n", D_RO(value)->s); } } return errors; } int delete_element(struct ds_context *ctx) { PMEMobjpool *pop; int errors = 0; if (ctx == NULL) { errors++; } else if (ctx->pop == NULL) { errors++; } if (!errors) { pop = ctx->pop; art_delete(pop, ctx->key, ctx->key_len); } return errors; } ssize_t read_line(unsigned char **line) { size_t len = -1; ssize_t read = -1; *line = NULL; if ((read = getline((char **)line, &len, stdin)) > 0) { (*line)[read - 1] = '\0'; } return read; } static int dump_art_leaf_callback(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *val, uint32_t val_len) { cb_data *cbd; if (data != NULL) { cbd = (cb_data *)data; printf("node type %d ", D_RO(cbd->node)->art_node_type); if (D_RO(cbd->node)->art_node_type == art_leaf_t) { printf("key len %" PRIu32 " = [%s], value len %" PRIu32 " = [%s]", key_len, key != NULL ? (char *)key : (char *)"NULL", val_len, val != NULL ? (char *)val : (char *)"NULL"); } printf("\n"); } else { printf("key len %" PRIu32 " = [%s], value len %" PRIu32 " = [%s]\n", key_len, key != NULL ? (char *)key : (char *)"NULL", val_len, val != NULL ? (char *)val : (char *)"NULL"); } return 0; } static void print_node_info(char *nodetype, uint64_t off, const art_node *an) { int p_len, i; p_len = an->partial_len; printf("N%" PRIx64 " [label=\"%s at\\n0x%" PRIx64 "\\n%d children", off, nodetype, off, an->num_children); if (p_len != 0) { printf("\\nlen %d", p_len); printf(": "); for (i = 0; i < p_len; i++) { printf("%c", an->partial[i]); } } printf("\"];\n"); } static int dump_art_node_callback(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *val, uint32_t val_len) { cb_data *cbd; const art_node *an; TOID(art_node4) an4; TOID(art_node16) an16; TOID(art_node48) an48; TOID(art_node256) an256; TOID(art_leaf) al; TOID(art_node_u) child; TOID(var_string) oid_key; TOID(var_string) oid_value; if (data != NULL) { cbd = (cb_data *)data; switch (D_RO(cbd->node)->art_node_type) { case NODE4: an4 = D_RO(cbd->node)->u.an4; an = &(D_RO(an4)->n); child = D_RO(an4)->children[cbd->child_idx]; if (!TOID_IS_NULL(child)) { print_node_info("node4", cbd->node.oid.off, an); printf("N%" PRIx64 " -> N%" PRIx64 " [label=\"%c\"];\n", cbd->node.oid.off, child.oid.off, D_RO(an4)->keys[cbd->child_idx]); } break; case NODE16: an16 = D_RO(cbd->node)->u.an16; an = &(D_RO(an16)->n); child = D_RO(an16)->children[cbd->child_idx]; if (!TOID_IS_NULL(child)) { print_node_info("node16", cbd->node.oid.off, an); printf("N%" PRIx64 " -> N%" PRIx64 " [label=\"%c\"];\n", cbd->node.oid.off, child.oid.off, D_RO(an16)->keys[cbd->child_idx]); } break; case NODE48: an48 = D_RO(cbd->node)->u.an48; an = &(D_RO(an48)->n); child = D_RO(an48)->children[cbd->child_idx]; if (!TOID_IS_NULL(child)) { print_node_info("node48", cbd->node.oid.off, an); printf("N%" PRIx64 " -> N%" PRIx64 " [label=\"%c\"];\n", cbd->node.oid.off, child.oid.off, D_RO(an48)->keys[cbd->child_idx]); } break; case NODE256: an256 = D_RO(cbd->node)->u.an256; an = &(D_RO(an256)->n); child = D_RO(an256)->children[cbd->child_idx]; if (!TOID_IS_NULL(child)) { print_node_info("node256", cbd->node.oid.off, an); printf("N%" PRIx64 " -> N%" PRIx64 " [label=\"0x%x\"];\n", cbd->node.oid.off, child.oid.off, (char)((cbd->child_idx) & 0xff)); } break; case art_leaf_t: al = D_RO(cbd->node)->u.al; oid_key = D_RO(al)->key; oid_value = D_RO(al)->value; printf("N%" PRIx64 " [shape=box," "label=\"leaf at\\n0x%" PRIx64 "\"];\n", cbd->node.oid.off, cbd->node.oid.off); printf("N%" PRIx64 " [shape=box," "label=\"key at 0x%" PRIx64 ": %s\"];\n", oid_key.oid.off, oid_key.oid.off, D_RO(oid_key)->s); printf("N%" PRIx64 " [shape=box," "label=\"value at 0x%" PRIx64 ": %s\"];\n", oid_value.oid.off, oid_value.oid.off, D_RO(oid_value)->s); printf("N%" PRIx64 " -> N%" PRIx64 ";\n", cbd->node.oid.off, oid_key.oid.off); printf("N%" PRIx64 " -> N%" PRIx64 ";\n", cbd->node.oid.off, oid_value.oid.off); break; default: break; } } else { printf("leaf: key len %" PRIu32 " = [%s], value len %" PRIu32 " = [%s]\n", key_len, key, val_len, val); } return 0; }
16,439
22.688761
78
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/art.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * Copyright 2012, Armon Dadgar. 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. */ /* * =========================================================================== * * Filename: art.h * * Description: header file for art tree on pmem implementation * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ /* * based on https://github.com/armon/libart/src/art.h */ #ifndef _ART_H #define _ART_H #ifdef __cplusplus extern "C" { #endif #define MAX_PREFIX_LEN 10 typedef enum { NODE4 = 0, NODE16 = 1, NODE48 = 2, NODE256 = 3, art_leaf_t = 4, art_node_types = 5 /* number of different art_nodes */ } art_node_type; char *art_node_names[] = { "art_node4", "art_node16", "art_node48", "art_node256", "art_leaf" }; /* * forward declarations; these are required when typedef shall be * used instead of struct */ struct _art_node_u; typedef struct _art_node_u art_node_u; struct _art_node; typedef struct _art_node art_node; struct _art_node4; typedef struct _art_node4 art_node4; struct _art_node16; typedef struct _art_node16 art_node16; struct _art_node48; typedef struct _art_node48 art_node48; struct _art_node256; typedef struct _art_node256 art_node256; struct _art_leaf; typedef struct _art_leaf art_leaf; struct _var_string; typedef struct _var_string var_string; POBJ_LAYOUT_BEGIN(arttree_tx); POBJ_LAYOUT_ROOT(arttree_tx, struct art_tree_root); POBJ_LAYOUT_TOID(arttree_tx, art_node_u); POBJ_LAYOUT_TOID(arttree_tx, art_node4); POBJ_LAYOUT_TOID(arttree_tx, art_node16); POBJ_LAYOUT_TOID(arttree_tx, art_node48); POBJ_LAYOUT_TOID(arttree_tx, art_node256); POBJ_LAYOUT_TOID(arttree_tx, art_leaf); POBJ_LAYOUT_TOID(arttree_tx, var_string); POBJ_LAYOUT_END(arttree_tx); struct _var_string { size_t len; unsigned char s[]; }; /* * This struct is included as part of all the various node sizes */ struct _art_node { uint8_t num_children; uint32_t partial_len; unsigned char partial[MAX_PREFIX_LEN]; }; /* * Small node with only 4 children */ struct _art_node4 { art_node n; unsigned char keys[4]; TOID(art_node_u) children[4]; }; /* * Node with 16 children */ struct _art_node16 { art_node n; unsigned char keys[16]; TOID(art_node_u) children[16]; }; /* * Node with 48 children, but a full 256 byte field. */ struct _art_node48 { art_node n; unsigned char keys[256]; TOID(art_node_u) children[48]; }; /* * Full node with 256 children */ struct _art_node256 { art_node n; TOID(art_node_u) children[256]; }; /* * Represents a leaf. These are of arbitrary size, as they include the key. */ struct _art_leaf { TOID(var_string) value; TOID(var_string) key; }; struct _art_node_u { uint8_t art_node_type; uint8_t art_node_tag; union { TOID(art_node4) an4; /* starts with art_node */ TOID(art_node16) an16; /* starts with art_node */ TOID(art_node48) an48; /* starts with art_node */ TOID(art_node256) an256; /* starts with art_node */ TOID(art_leaf) al; } u; }; struct art_tree_root { int size; TOID(art_node_u) root; }; typedef struct _cb_data { TOID(art_node_u) node; int child_idx; } cb_data; /* * Macros to manipulate art_node tags */ #define IS_LEAF(x) (((x)->art_node_type == art_leaf_t)) #define SET_LEAF(x) (((x)->art_node_tag = art_leaf_t)) #define COPY_BLOB(_obj, _blob, _len) \ D_RW(_obj)->len = _len; \ TX_MEMCPY(D_RW(_obj)->s, _blob, _len); \ D_RW(_obj)->s[(_len) - 1] = '\0'; typedef int(*art_callback)(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *value, uint32_t val_len); extern int art_tree_init(PMEMobjpool *pop, int *newpool); extern uint64_t art_size(PMEMobjpool *pop); extern int art_iter(PMEMobjpool *pop, art_callback cb, void *data); extern TOID(var_string) art_insert(PMEMobjpool *pop, const unsigned char *key, int key_len, void *value, int val_len); extern TOID(var_string) art_search(PMEMobjpool *pop, const unsigned char *key, int key_len); extern TOID(var_string) art_delete(PMEMobjpool *pop, const unsigned char *key, int key_len); #ifdef __cplusplus } #endif #endif /* _ART_H */
5,998
26.773148
78
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree_search.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree_search.c * * Description: implementation of search function for ART tree * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #include <stdio.h> #include <inttypes.h> #include <libgen.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <getopt.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <sys/mman.h> #include "arttree_structures.h" /* * search context */ struct search_ctx { struct pmem_context *pmem_ctx; unsigned char *search_key; int32_t hexdump; }; static struct search_ctx *s_ctx = NULL; struct search { const char *name; const char *brief; char *(*func)(char *, struct search_ctx *); void (*help)(char *); }; /* local functions */ static int search_parse_args(char *appname, int ac, char *av[], struct search_ctx *s_ctx); static struct search *get_search(char *type_name); static void print_usage(char *appname); static void dump_PMEMoid(char *prefix, PMEMoid *oid); static char *search_key(char *appname, struct search_ctx *ctx); static int leaf_matches(struct search_ctx *ctx, art_leaf *n, unsigned char *key, size_t key_len, int depth); static int check_prefix(art_node *an, unsigned char *key, int key_len, int depth); static uint64_t find_child(art_node *n, int node_type, unsigned char key); static void *get_node(struct search_ctx *ctx, int node_type, uint64_t off); static uint64_t get_offset_an(art_node_u *au); static void dump_PMEMoid(char *prefix, PMEMoid *oid); static void dump_art_tree_root(char *prefix, uint64_t off, void *p); /* global visible interface */ void arttree_search_help(char *appname); int arttree_search_func(char *appname, struct pmem_context *ctx, int ac, char *av[]); static const char *arttree_search_help_str = "Search for key in ART tree\n" "Arguments: <key>\n" " <key> key\n" ; static const struct option long_options[] = { {"hexdump", no_argument, NULL, 'x'}, {NULL, 0, NULL, 0 }, }; static struct search s_funcs[] = { { .name = "key", .brief = "search for key", .func = search_key, .help = NULL, } }; /* Simple inlined function */ static inline int min(int a, int b) { return (a < b) ? b : a; } /* * number of arttree examine commands */ #define COMMANDS_NUMBER (sizeof(s_funcs) / sizeof(s_funcs[0])) void arttree_search_help(char *appname) { printf("%s %s\n", appname, arttree_search_help_str); } int arttree_search_func(char *appname, struct pmem_context *ctx, int ac, char *av[]) { int errors = 0; struct search *s; char *value; value = NULL; if (ctx == NULL) { return -1; } if (s_ctx == NULL) { s_ctx = (struct search_ctx *)malloc(sizeof(struct search_ctx)); if (s_ctx == NULL) { return -1; } memset(s_ctx, 0, sizeof(struct search_ctx)); } if (ctx->art_tree_root_offset == 0) { fprintf(stderr, "search functions require knowledge" " about the art_tree_root.\n"); fprintf(stderr, "Use \"set_root <offset>\"" " to define where the \nart_tree_root object" " resides in the pmem file.\n"); errors++; } s_ctx->pmem_ctx = ctx; if (search_parse_args(appname, ac, av, s_ctx) != 0) { fprintf(stderr, "%s::%s: error parsing arguments\n", appname, __FUNCTION__); errors++; } if (!errors) { s = get_search("key"); if (s != NULL) { value = s->func(appname, s_ctx); } if (value != NULL) { printf("key [%s] found, value [%s]\n", s_ctx->search_key, value); } else { printf("key [%s] not found\n", s_ctx->search_key); } } if (s_ctx->search_key != NULL) { free(s_ctx->search_key); } free(s_ctx); return errors; } static int search_parse_args(char *appname, int ac, char *av[], struct search_ctx *s_ctx) { int ret = 0; int opt; optind = 0; while ((opt = getopt_long(ac, av, "x", long_options, NULL)) != -1) { switch (opt) { case 'x': s_ctx->hexdump = 1; break; default: print_usage(appname); ret = 1; } } if (ret == 0) { s_ctx->search_key = (unsigned char *)strdup(av[optind + 0]); } return ret; } static void print_usage(char *appname) { printf("%s: search <key>\n", appname); } /* * get_search -- returns command for specified command name */ static struct search * get_search(char *type_name) { if (type_name == NULL) { return NULL; } for (size_t i = 0; i < COMMANDS_NUMBER; i++) { if (strcmp(type_name, s_funcs[i].name) == 0) return &s_funcs[i]; } return NULL; } static void * get_node(struct search_ctx *ctx, int node_type, uint64_t off) { if (!VALID_NODE_TYPE(node_type)) return NULL; printf("%s at off 0x%" PRIx64 "\n", art_node_names[node_type], off); return ctx->pmem_ctx->addr + off; } static int leaf_matches(struct search_ctx *ctx, art_leaf *n, unsigned char *key, size_t key_len, int depth) { var_string *n_key; (void) depth; n_key = (var_string *)get_node(ctx, VAR_STRING, n->key.oid.off); if (n_key == NULL) return 1; // HACK for stupid null-terminated strings.... // else if (n_key->len != key_len) // ret = 1; if (n_key->len != key_len + 1) return 1; return memcmp(n_key->s, key, key_len); } static int check_prefix(art_node *n, unsigned char *key, int key_len, int depth) { int max_cmp = min(min(n->partial_len, MAX_PREFIX_LEN), key_len - depth); int idx; for (idx = 0; idx < max_cmp; idx++) { if (n->partial[idx] != key[depth + idx]) return idx; } return idx; } static uint64_t find_child(art_node *n, int node_type, unsigned char c) { int i; union { art_node4 *p1; art_node16 *p2; art_node48 *p3; art_node256 *p4; } p; printf("[%s] children %d search key %c [", art_node_names[node_type], n->num_children, c); switch (node_type) { case ART_NODE4: p.p1 = (art_node4 *)n; for (i = 0; i < n->num_children; i++) { printf("%c ", p.p1->keys[i]); if (p.p1->keys[i] == c) { printf("]\n"); return p.p1->children[i].oid.off; } } break; case ART_NODE16: p.p2 = (art_node16 *)n; for (i = 0; i < n->num_children; i++) { printf("%c ", p.p2->keys[i]); if (p.p2->keys[i] == c) { printf("]\n"); return p.p2->children[i].oid.off; } } break; case ART_NODE48: p.p3 = (art_node48 *)n; i = p.p3->keys[c]; printf("%d ", p.p3->keys[c]); if (i) { printf("]\n"); return p.p3->children[i - 1].oid.off; } break; case ART_NODE256: p.p4 = (art_node256 *)n; printf("0x%" PRIx64, p.p4->children[c].oid.off); if (p.p4->children[c].oid.off != 0) { printf("]\n"); return p.p4->children[c].oid.off; } break; default: abort(); } printf("]\n"); return 0; } static uint64_t get_offset_an(art_node_u *au) { uint64_t offset = 0; switch (au->art_node_type) { case ART_NODE4: offset = au->u.an4.oid.off; break; case ART_NODE16: offset = au->u.an16.oid.off; break; case ART_NODE48: offset = au->u.an48.oid.off; break; case ART_NODE256: offset = au->u.an256.oid.off; break; case ART_LEAF: offset = au->u.al.oid.off; break; default: break; } return offset; } static char * search_key(char *appname, struct search_ctx *ctx) { int errors = 0; void *p; /* something */ off_t p_off; art_node_u *p_au; /* art_node_u */ off_t p_au_off; void *p_an; /* specific art node from art_node_u */ off_t p_an_off; art_node *an; /* art node */ var_string *n_value; char *value; int prefix_len; int depth = 0; int key_len; uint64_t child_off; key_len = strlen((char *)(ctx->search_key)); value = NULL; p_off = ctx->pmem_ctx->art_tree_root_offset; p = get_node(ctx, ART_TREE_ROOT, p_off); assert(p != NULL); dump_art_tree_root("art_tree_root", p_off, p); p_au_off = ((art_tree_root *)p)->root.oid.off; p_au = (art_node_u *)get_node(ctx, ART_NODE_U, p_au_off); if (p_au == NULL) errors++; if (!errors) { while (p_au) { p_an_off = get_offset_an(p_au); p_an = get_node(ctx, p_au->art_node_type, p_an_off); assert(p_an != NULL); if (p_au->art_node_type == ART_LEAF) { if (!leaf_matches(ctx, (art_leaf *)p_an, ctx->search_key, key_len, depth)) { n_value = (var_string *) get_node(ctx, VAR_STRING, ((art_leaf *)p_an)->value.oid.off); return (char *)(n_value->s); } } an = (art_node *)p_an; if (an->partial_len) { prefix_len = check_prefix(an, ctx->search_key, key_len, depth); if (prefix_len != min(MAX_PREFIX_LEN, an->partial_len)) { return NULL; } depth = depth + an->partial_len; } child_off = find_child(an, p_au->art_node_type, ctx->search_key[depth]); if (child_off != 0) { p_au_off = child_off; p_au = get_node(ctx, ART_NODE_U, p_au_off); } else { p_au = NULL; } depth++; } } if (errors) { return NULL; } else { return value; } } static void dump_art_tree_root(char *prefix, uint64_t off, void *p) { art_tree_root *tree_root; tree_root = (art_tree_root *)p; printf("at offset 0x%" PRIx64 ", art_tree_root {\n", off); printf(" size %d\n", tree_root->size); dump_PMEMoid(" art_node_u", (PMEMoid *)&(tree_root->root)); printf("\n};\n"); } static void dump_PMEMoid(char *prefix, PMEMoid *oid) { printf("%s { PMEMoid pool_uuid_lo %" PRIx64 " off 0x%" PRIx64 " = %" PRId64 " }\n", prefix, oid->pool_uuid_lo, oid->off, oid->off); }
11,265
22.717895
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/libart/arttree.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2017, Intel Corporation */ /* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * * 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. */ /* * =========================================================================== * * Filename: arttree.h * * Description: header file for art tree on pmem implementation * * Author: Andreas Bluemle, Dieter Kasper * Andreas.Bluemle.external@ts.fujitsu.com * dieter.kasper@ts.fujitsu.com * * Organization: FUJITSU TECHNOLOGY SOLUTIONS GMBH * * =========================================================================== */ #ifndef _ARTTREE_H #define _ARTTREE_H #ifdef __cplusplus extern "C" { #endif #include "art.h" #ifdef __cplusplus } #endif #endif /* _ARTTREE_H */
2,337
34.969231
78
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/queuebuppage.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. */ /* * queue.c -- array based queue example */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libpmem.h> #include <libpmemobj.h> #include <time.h> #include <x86intrin.h> #include <bits/types/sig_atomic_t.h> #include <bits/types/sigset_t.h> #include <signal.h> #include <unistd.h> #include <sys/mman.h> POBJ_LAYOUT_BEGIN(queue); POBJ_LAYOUT_ROOT(queue, struct root); POBJ_LAYOUT_TOID(queue, struct entry); POBJ_LAYOUT_TOID(queue, struct queue); POBJ_LAYOUT_END(queue); /////////////////Page fault handling///////////////// #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*/ /*typedef struct { void *ss_sp; int ss_flags; size_t ss_size; } stack_t; */ stack_t _sigstk; /// @brief Signal handler to trap SEGVs. static void segvHandle(int signum, siginfo_t * siginfo, void * context) { void * addr = siginfo->si_addr; // address of access uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); // Check if this was a SEGV that we are supposed to trap. if (siginfo->si_code == SEGV_ACCERR) { mprotect(pageStart, 4096, PROT_READ|PROT_WRITE); //printf("test1\n"); } else if (siginfo->si_code == SEGV_MAPERR) { fprintf (stderr, "%d : map error with addr %p!\n", getpid(), addr); abort(); } else { fprintf (stderr, "%d : other access error with addr %p.\n", getpid(), addr); abort(); } } static void installSignalHandler(void) { // Set up an alternate signal stack. printf("page fault handler initialized!!\n"); _sigstk.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); _sigstk.ss_size = SIGSTKSZ; _sigstk.ss_flags = 0; sigaltstack(&_sigstk, (stack_t *) 0); // Now set up a signal handler for SIGSEGV events. struct sigaction siga; sigemptyset(&siga.sa_mask); // Set the following signals to a set sigaddset(&siga.sa_mask, SIGSEGV); sigaddset(&siga.sa_mask, SIGALRM); sigprocmask(SIG_BLOCK, &siga.sa_mask, NULL); // Point to the handler function. siga.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART | SA_NODEFER; siga.sa_sigaction = segvHandle; if (sigaction(SIGSEGV, &siga, NULL) == -1) { perror("sigaction(SIGSEGV)"); exit(-1); } sigprocmask(SIG_UNBLOCK, &siga.sa_mask, NULL); return 0; } static void resetpage(void * addr){ uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); mprotect(pageStart, 4096, PROT_READ); return; } ///////////////////////////////////////////////////// uint64_t page_pointer_store[64]; int size_page_store = 0; int update_count = 0; int global_update_count = 0; void * checkpointptr; static inline void insert_page(void * ptr){ update_count++; uint64_t page = (uint64_t)ptr & 0xFFFFFFFFFFFFC000; for(int i=0; i<size_page_store; i++){ if(page_pointer_store[i] == page) return; } page_pointer_store[size_page_store] = page; size_page_store++; } static inline void checkpoint(PMEMobjpool *pop){ for(int i=0; i<size_page_store; i++){ memcpy(checkpointptr + i*4096, (void *)(page_pointer_store[i]), 4096); pmemobj_persist(pop, checkpointptr + i*4096,4096); // pmemobj_drain(pop); } //pmemobj_drain(pop); size_page_store = 0; } //////////////////////////////////////////////////// static inline void cpuid(){ asm volatile ("CPUID" : : : "%rax", "%rbx", "%rcx", "%rdx"); } 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; } static inline uint64_t getCycle2(){ cpuid(); return getCycle(); } struct entry { /* queue entry that contains arbitrary data */ size_t len; /* length of the data buffer */ char data[]; }; struct queue { /* array-based queue container */ size_t front; /* position of the first entry */ size_t back; /* position of the last entry */ size_t capacity; /* size of the entries array */ //TOID(struct entry) entries[]; struct entry entries[]; }; struct root { //TOID(struct queue) queue; struct queue queue; }; /* * queue_constructor -- constructor of the queue container */ static int queue_constructor(PMEMobjpool *pop, void *ptr, void *arg) { struct queue *q = ptr; size_t *capacity = arg; q->front = 0; q->back = 0; q->capacity = *capacity; /* atomic API requires that objects are persisted in the constructor */ pmemobj_persist(pop, q, sizeof(*q)); return 0; } /* * queue_new -- allocates a new queue container using the atomic API */ static int queue_new(PMEMobjpool *pop, TOID(struct queue) *q, size_t nentries) { return POBJ_ALLOC(pop, q, struct queue, sizeof(struct queue) + sizeof(TOID(struct entry)) * nentries, queue_constructor, &nentries); } /* * queue_nentries -- returns the number of entries */ static size_t queue_nentries(struct queue *queue) { return queue->back - queue->front; } /* * queue_enqueue -- allocates and inserts a new entry into the queue */ static int queue_enqueue(PMEMobjpool *pop, struct queue *queue, const char *data, size_t len, double * tottime) { //printf("inserting %ld %ld %ld %ld %ld\n", queue->capacity, queue_nentries(queue), queue->back, queue->front, sizeof(struct entry)); if (queue->capacity - queue_nentries(queue) == 0) return -1; /* at capacity */ /* back is never decreased, need to calculate the real position */ size_t pos = queue->back % queue->capacity; int ret = 0; //printf("inserting %zu: %s\n", pos, data); clock_t start, end; start = clock(); uint64_t startCycles = getCycle(); insert_page(&(queue->back)); insert_page(&(queue->entries[pos])); // if(update_count >= 1999) // { // checkpoint(pop); // update_count = 0; // } //TX_BEGIN(pop) { /* let's first reserve the space at the end of the queue */ //TX_ADD_DIRECT(&queue->back); //TX_ADD_DIRECT(&queue->entries[pos]); queue->back += 1; /* now we can safely allocate and initialize the new entry */ //TOID(struct entry) entry = TX_ALLOC(struct entry, // sizeof(struct entry) + len); //D_RW(entry)->len = len; //PMEMoid root = pmemobj_root(pop, sizeof(struct entry)); //uint64_t* tmp = pmemobj_direct(root); struct entry *entry = (struct entry *)(queue + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry)*global_update_count); //pmemobj_direct(root); //printf(" %d %ld\n",size_page_store, sizeof(struct entry)); //memcpy(D_RW(entry)->data, data, len); memcpy(entry->data, data, len); /* and then snapshot the queue entry that we will modify */ queue->entries[pos] = *entry; pmemobj_persist(pop,&(queue->entries[pos]),sizeof(struct entry)); pmemobj_persist(pop,queue,sizeof(struct queue)); if(update_count >= 1) { resetpage(&(queue->entries[pos])); resetpage(queue); update_count = 0; } //pmemobj_drain(pop); //pmemobj_persist(pop,entry,sizeof(struct entry)); //pmemobj_drain(pop); //pmem_persist(queue->entries[pos],sizeof(struct entry)); //} TX_ONABORT { /* don't forget about error handling! ;) */ // ret = -1; //} TX_END uint64_t endCycles = getCycle(); //printf("tx cycles: %ld\n",endCycles - startCycles); end = clock(); *tottime += ((double) (end - start)) / CLOCKS_PER_SEC; global_update_count++; return ret; } /* * queue_dequeue - removes and frees the first element from the queue */ static int queue_dequeue(PMEMobjpool *pop, struct queue *queue, double * tottime) { if (queue_nentries(queue) == 0) return -1; /* no entries to remove */ /* front is also never decreased */ size_t pos = queue->front % queue->capacity; int ret = 0; printf("removing %zu: %s\n", pos, queue->entries[pos].data); clock_t start, end; start = clock(); uint64_t startCycles = getCycle(); TX_BEGIN(pop) { /* move the queue forward */ TX_ADD_DIRECT(&queue->front); queue->front += 1; /* and since this entry is now unreachable, free it */ //TX_FREE(queue->entries[pos]); /* notice that we do not change the PMEMoid itself */ } TX_ONABORT { ret = -1; } TX_END uint64_t endCycles = getCycle(); printf("tx cycles: %ld\n",endCycles - startCycles); end = clock(); *tottime += ((double) (end - start)) / CLOCKS_PER_SEC; return ret; } /* * queue_show -- prints all queue entries */ static void queue_show(PMEMobjpool *pop, struct queue *queue) { size_t nentries = queue_nentries(queue); printf("Entries %zu/%zu\n", nentries, queue->capacity); for (size_t i = queue->front; i < queue->back; ++i) { size_t pos = i % queue->capacity; printf("%zu: %s\n", pos, queue->entries[pos].data); } } /* available queue operations */ enum queue_op { UNKNOWN_QUEUE_OP, QUEUE_NEW, QUEUE_ENQUEUE, QUEUE_DEQUEUE, QUEUE_SHOW, MAX_QUEUE_OP, }; /* queue operations strings */ static const char *ops_str[MAX_QUEUE_OP] = {"", "new", "enqueue", "dequeue", "show"}; /* * parse_queue_op -- parses the operation string and returns matching queue_op */ static enum queue_op queue_op_parse(const char *str) { for (int i = 0; i < MAX_QUEUE_OP; ++i) if (strcmp(str, ops_str[i]) == 0) return (enum queue_op)i; return UNKNOWN_QUEUE_OP; } /* * fail -- helper function to exit the application in the event of an error */ static void __attribute__((noreturn)) /* this function terminates */ fail(const char *msg) { fprintf(stderr, "%s\n", msg); exit(EXIT_FAILURE); } void pf(void){ printf("test1\n"); } void installSignalHandler (void) __attribute__ ((constructor)); //void pf (void) __attribute__ ((constructor)); main(int argc, char *argv[]) { enum queue_op op; if (argc < 3 || (op = queue_op_parse(argv[2])) == UNKNOWN_QUEUE_OP) fail("usage: file-name [new <n>|show|enqueue <data>|dequeue]"); PMEMobjpool *pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(queue)); if (pop == NULL) fail("failed to open the pool"); /* TOID(struct root) root = POBJ_ROOT(pop, struct root); struct root *rootp = D_RW(root); size_t capacity; double totaltime = 0; switch (op) { case QUEUE_NEW: if (argc != 4) fail("missing size of the queue"); char *end; errno = 0; capacity = strtoull(argv[3], &end, 0); if (errno == ERANGE || *end != '\0') fail("invalid size of the queue"); printf("size %ld\n",capacity); if (queue_new(pop, &rootp->queue, capacity) != 0) fail("failed to create a new queue"); break; case QUEUE_ENQUEUE: if (argc != 4) fail("missing new entry data"); if (D_RW(rootp->queue) == NULL) fail("queue must exist"); */ double totaltime = 0; PMEMoid root = pmemobj_root(pop, sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000 + 4096*10); struct queue *qu = pmemobj_direct(root); checkpointptr = (void *)(qu + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000); printf("root1 %ld\n",(uint64_t)qu); qu->front = 0; qu->back = 0; qu->capacity = 10000; pmemobj_persist(pop, qu, sizeof(*qu)); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_enqueue(pop, qu, "hello", 6,&totaltime) != 0) fail("failed to insert new entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); /* break; case QUEUE_DEQUEUE: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_dequeue(pop, D_RW(rootp->queue),&totaltime) != 0) fail("failed to remove entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); break; case QUEUE_SHOW: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); queue_show(pop, D_RW(rootp->queue)); break; default: assert(0); // unreachable break; } */ pmemobj_close(pop); return 0; }
13,990
25.957611
169
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/multirun.sh
#!/bin/bash sudo rm -rf /mnt/mem/queue.pool sudo pmempool create --layout="queue" obj myobjpool.set sudo ./queue /mnt/mem/queue.pool new 10000 #for (( c=1; c<=10000; c++ )) #do #echo "$c" sudo ./queue /mnt/mem/queue.pool enqueue hello #done
246
23.7
55
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/run.sh
sudo rm -rf /mnt/mem/queue.pool sudo pmempool create --layout="queue" obj myobjpool.set #sudo ../../../tools/pmempool/pmempool create obj /mnt/mem/queue.pool --layout queue sudo ./queue /mnt/mem/queue.pool new 10000 sudo ./queue /mnt/mem/queue.pool enqueue hello>enqueue sudo ./queue /mnt/mem/queue.pool show grep tx enqueue | awk '{print $3}'>file grep tx dequeue | awk '{print $3}'>file make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000 EXTRA_CFLAGS="-Wno-error"
497
40.5
105
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/runall.sh
make -j12 EXTRA_CFLAGS+=-DGET_NDP_PERFORMENCE EXTRA_CFLAGS+=-DRUN_COUNT=10000 EXTRA_CFLAGS="-Wno-error" sudo rm -rf /mnt/mem/queue.pool sudo pmempool create --layout="queue" obj myobjpool.set #sudo ../../../tools/pmempool/pmempool create obj /mnt/mem/queue.pool --layout queue sudo ./queue /mnt/mem/queue.pool new 10000
324
39.625
105
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/queue.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. */ /* * queue.c -- array based queue example */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libpmem.h> #include <libpmemobj.h> #include <time.h> #include <x86intrin.h> POBJ_LAYOUT_BEGIN(queue); POBJ_LAYOUT_ROOT(queue, struct root); POBJ_LAYOUT_TOID(queue, struct entry); POBJ_LAYOUT_TOID(queue, struct queue); POBJ_LAYOUT_END(queue); ///////////////////////////////////////////////////// uint64_t page_pointer_store[64]; int size_page_store = 0; int update_count = 0; int global_update_count = 0; void * checkpointptr; static inline void insert_page(void * ptr){ update_count++; uint64_t page = (uint64_t)ptr & 0xFFFFFFFFFFFFC000; for(int i=0; i<size_page_store; i++){ if(page_pointer_store[i] == page) return; } page_pointer_store[size_page_store] = page; size_page_store++; } static inline void checkpoint(PMEMobjpool *pop){ for(int i=0; i<size_page_store; i++){ memcpy(checkpointptr + i*4096, (void *)(page_pointer_store[i]), 4096); pmemobj_persist(pop, checkpointptr + i*4096,4096); // pmemobj_drain(pop); } //pmemobj_drain(pop); size_page_store = 0; } //////////////////////////////////////////////////// static inline void cpuid(){ asm volatile ("CPUID" : : : "%rax", "%rbx", "%rcx", "%rdx"); } 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; } static inline uint64_t getCycle2(){ cpuid(); return getCycle(); } struct entry { /* queue entry that contains arbitrary data */ size_t len; /* length of the data buffer */ char data[]; }; struct queue { /* array-based queue container */ size_t front; /* position of the first entry */ size_t back; /* position of the last entry */ size_t capacity; /* size of the entries array */ //TOID(struct entry) entries[]; struct entry entries[]; }; struct root { //TOID(struct queue) queue; struct queue queue; }; /* * queue_constructor -- constructor of the queue container */ static int queue_constructor(PMEMobjpool *pop, void *ptr, void *arg) { struct queue *q = ptr; size_t *capacity = arg; q->front = 0; q->back = 0; q->capacity = *capacity; /* atomic API requires that objects are persisted in the constructor */ pmemobj_persist(pop, q, sizeof(*q)); return 0; } /* * queue_new -- allocates a new queue container using the atomic API */ static int queue_new(PMEMobjpool *pop, TOID(struct queue) *q, size_t nentries) { return POBJ_ALLOC(pop, q, struct queue, sizeof(struct queue) + sizeof(TOID(struct entry)) * nentries, queue_constructor, &nentries); } /* * queue_nentries -- returns the number of entries */ static size_t queue_nentries(struct queue *queue) { return queue->back - queue->front; } /* * queue_enqueue -- allocates and inserts a new entry into the queue */ static int queue_enqueue(PMEMobjpool *pop, struct queue *queue, const char *data, size_t len, double * tottime) { //printf("inserting %ld %ld %ld %ld %ld\n", queue->capacity, queue_nentries(queue), queue->back, queue->front, sizeof(struct entry)); if (queue->capacity - queue_nentries(queue) == 0) return -1; /* at capacity */ /* back is never decreased, need to calculate the real position */ size_t pos = queue->back % queue->capacity; int ret = 0; //printf("inserting %zu: %s\n", pos, data); clock_t start, end; start = clock(); uint64_t startCycles = getCycle(); insert_page(&(queue->back)); insert_page(&(queue->entries[pos])); if(update_count >= 9) { checkpoint(pop); update_count = 0; } //TX_BEGIN(pop) { /* let's first reserve the space at the end of the queue */ //TX_ADD_DIRECT(&queue->back); //TX_ADD_DIRECT(&queue->entries[pos]); queue->back += 1; /* now we can safely allocate and initialize the new entry */ //TOID(struct entry) entry = TX_ALLOC(struct entry, // sizeof(struct entry) + len); //D_RW(entry)->len = len; //PMEMoid root = pmemobj_root(pop, sizeof(struct entry)); //uint64_t* tmp = pmemobj_direct(root); struct entry *entry = (struct entry *)(queue + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry)*global_update_count); //pmemobj_direct(root); //printf(" %d %ld\n",size_page_store, sizeof(struct entry)); //memcpy(D_RW(entry)->data, data, len); memcpy(entry->data, data, len); /* and then snapshot the queue entry that we will modify */ queue->entries[pos] = *entry; pmemobj_persist(pop,&(queue->entries[pos]),sizeof(struct entry)); pmemobj_persist(pop,queue,sizeof(struct queue)); //pmemobj_drain(pop); //pmemobj_persist(pop,entry,sizeof(struct entry)); //pmemobj_drain(pop); //pmem_persist(queue->entries[pos],sizeof(struct entry)); //} TX_ONABORT { /* don't forget about error handling! ;) */ // ret = -1; //} TX_END uint64_t endCycles = getCycle(); //printf("tx cycles: %ld\n",endCycles - startCycles); end = clock(); *tottime += ((double) (end - start)) / CLOCKS_PER_SEC; global_update_count++; return ret; } /* * queue_dequeue - removes and frees the first element from the queue */ static int queue_dequeue(PMEMobjpool *pop, struct queue *queue, double * tottime) { if (queue_nentries(queue) == 0) return -1; /* no entries to remove */ /* front is also never decreased */ size_t pos = queue->front % queue->capacity; int ret = 0; printf("removing %zu: %s\n", pos, queue->entries[pos].data); clock_t start, end; start = clock(); uint64_t startCycles = getCycle(); TX_BEGIN(pop) { /* move the queue forward */ TX_ADD_DIRECT(&queue->front); queue->front += 1; /* and since this entry is now unreachable, free it */ //TX_FREE(queue->entries[pos]); /* notice that we do not change the PMEMoid itself */ } TX_ONABORT { ret = -1; } TX_END uint64_t endCycles = getCycle(); printf("tx cycles: %ld\n",endCycles - startCycles); end = clock(); *tottime += ((double) (end - start)) / CLOCKS_PER_SEC; return ret; } /* * queue_show -- prints all queue entries */ static void queue_show(PMEMobjpool *pop, struct queue *queue) { size_t nentries = queue_nentries(queue); printf("Entries %zu/%zu\n", nentries, queue->capacity); for (size_t i = queue->front; i < queue->back; ++i) { size_t pos = i % queue->capacity; printf("%zu: %s\n", pos, queue->entries[pos].data); } } /* available queue operations */ enum queue_op { UNKNOWN_QUEUE_OP, QUEUE_NEW, QUEUE_ENQUEUE, QUEUE_DEQUEUE, QUEUE_SHOW, MAX_QUEUE_OP, }; /* queue operations strings */ static const char *ops_str[MAX_QUEUE_OP] = {"", "new", "enqueue", "dequeue", "show"}; /* * parse_queue_op -- parses the operation string and returns matching queue_op */ static enum queue_op queue_op_parse(const char *str) { for (int i = 0; i < MAX_QUEUE_OP; ++i) if (strcmp(str, ops_str[i]) == 0) return (enum queue_op)i; return UNKNOWN_QUEUE_OP; } /* * fail -- helper function to exit the application in the event of an error */ static void __attribute__((noreturn)) /* this function terminates */ fail(const char *msg) { fprintf(stderr, "%s\n", msg); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { enum queue_op op; if (argc < 3 || (op = queue_op_parse(argv[2])) == UNKNOWN_QUEUE_OP) fail("usage: file-name [new <n>|show|enqueue <data>|dequeue]"); PMEMobjpool *pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(queue)); if (pop == NULL) fail("failed to open the pool"); /* TOID(struct root) root = POBJ_ROOT(pop, struct root); struct root *rootp = D_RW(root); size_t capacity; double totaltime = 0; switch (op) { case QUEUE_NEW: if (argc != 4) fail("missing size of the queue"); char *end; errno = 0; capacity = strtoull(argv[3], &end, 0); if (errno == ERANGE || *end != '\0') fail("invalid size of the queue"); printf("size %ld\n",capacity); if (queue_new(pop, &rootp->queue, capacity) != 0) fail("failed to create a new queue"); break; case QUEUE_ENQUEUE: if (argc != 4) fail("missing new entry data"); if (D_RW(rootp->queue) == NULL) fail("queue must exist"); */ double totaltime = 0; PMEMoid root = pmemobj_root(pop, sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000 + 4096*10); struct queue *qu = pmemobj_direct(root); checkpointptr = (void *)(qu + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000); printf("root1 %ld\n",(uint64_t)qu); qu->front = 0; qu->back = 0; qu->capacity = 10000; pmemobj_persist(pop, qu, sizeof(*qu)); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_enqueue(pop, qu, "hello", 6,&totaltime) != 0) fail("failed to insert new entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); /* break; case QUEUE_DEQUEUE: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_dequeue(pop, D_RW(rootp->queue),&totaltime) != 0) fail("failed to remove entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); break; case QUEUE_SHOW: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); queue_show(pop, D_RW(rootp->queue)); break; default: assert(0); // unreachable break; } */ pmemobj_close(pop); return 0; }
11,286
26.002392
169
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/queue/queue1.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. */ /* * queue.c -- array based queue example */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <libpmem.h> #include <libpmemobj.h> #include <time.h> #include <x86intrin.h> POBJ_LAYOUT_BEGIN(queue); POBJ_LAYOUT_ROOT(queue, struct root); POBJ_LAYOUT_TOID(queue, struct entry); POBJ_LAYOUT_TOID(queue, struct queue); POBJ_LAYOUT_END(queue); ///////////////////////////////////////////////////// uint64_t page_pointer_store[64]; int size_page_store = 0; int update_count = 0; int global_update_count = 0; void * checkpointptr; static inline void insert_page(void * ptr){ update_count++; uint64_t page = (uint64_t)ptr & 0xFFFFFFFFFFFFC000; for(int i=0; i<size_page_store; i++){ if(page_pointer_store[i] == page) return; } page_pointer_store[size_page_store] = page; size_page_store++; } static inline void checkpoint(PMEMobjpool *pop){ for(int i=0; i<size_page_store; i++){ memcpy(checkpointptr + i*4096, (void *)(page_pointer_store[i]), 4096); pmemobj_persist(pop, checkpointptr + i*4096,4096); // pmemobj_drain(pop); } //pmemobj_drain(pop); size_page_store = 0; } //////////////////////////////////////////////////// static inline void cpuid(){ asm volatile ("CPUID" : : : "%rax", "%rbx", "%rcx", "%rdx"); } 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; } static inline uint64_t getCycle2(){ cpuid(); return getCycle(); } struct entry { /* queue entry that contains arbitrary data */ size_t len; /* length of the data buffer */ char data[]; }; struct queue { /* array-based queue container */ size_t front; /* position of the first entry */ size_t back; /* position of the last entry */ size_t capacity; /* size of the entries array */ //TOID(struct entry) entries[]; struct entry entries[]; }; struct root { //TOID(struct queue) queue; struct queue queue; }; /* * queue_enqueue -- allocates and inserts a new entry into the queue */ static int queue_enqueue(PMEMobjpool *pop, struct queue *queue, const char *data, size_t len, double * tottime) { //printf("inserting %ld %ld %ld %ld %ld\n", queue->capacity, queue_nentries(queue), queue->back, queue->front, sizeof(struct entry)); if (queue->capacity - queue_nentries(queue) == 0) return -1; /* at capacity */ /* back is never decreased, need to calculate the real position */ size_t pos = queue->back % queue->capacity; int ret = 0; //printf("inserting %zu: %s\n", pos, data); clock_t start, end; start = clock(); uint64_t startCycles = getCycle(); insert_page(&(queue->back)); insert_page(&(queue->entries[pos])); if(update_count >= 100) { checkpoint(pop); update_count = 0; } //TX_BEGIN(pop) { /* let's first reserve the space at the end of the queue */ //TX_ADD_DIRECT(&queue->back); //TX_ADD_DIRECT(&queue->entries[pos]); queue->back += 1; /* now we can safely allocate and initialize the new entry */ //TOID(struct entry) entry = TX_ALLOC(struct entry, // sizeof(struct entry) + len); //D_RW(entry)->len = len; //PMEMoid root = pmemobj_root(pop, sizeof(struct entry)); //uint64_t* tmp = pmemobj_direct(root); struct entry *entry = (struct entry *)(queue + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry)*global_update_count); //pmemobj_direct(root); //printf(" %d %ld\n",size_page_store, sizeof(struct entry)); //memcpy(D_RW(entry)->data, data, len); memcpy(entry->data, data, len); /* and then snapshot the queue entry that we will modify */ queue->entries[pos] = *entry; pmemobj_persist(pop,&(queue->entries[pos]),sizeof(struct entry)); pmemobj_persist(pop,queue,sizeof(struct queue)); pmemobj_drain(pop); //pmemobj_persist(pop,entry,sizeof(struct entry)); //pmemobj_drain(pop); //pmem_persist(queue->entries[pos],sizeof(struct entry)); //} TX_ONABORT { /* don't forget about error handling! ;) */ // ret = -1; //} TX_END uint64_t endCycles = getCycle(); //printf("tx cycles: %ld\n",endCycles - startCycles); end = clock(); *tottime += ((double) (end - start)) / CLOCKS_PER_SEC; global_update_count++; return ret; } int main(int argc, char *argv[]) { enum queue_op op; if (argc < 3 || (op = queue_op_parse(argv[2])) == UNKNOWN_QUEUE_OP) fail("usage: file-name [new <n>|show|enqueue <data>|dequeue]"); PMEMobjpool *pop = pmemobj_open(argv[1], POBJ_LAYOUT_NAME(queue)); if (pop == NULL) fail("failed to open the pool"); /* TOID(struct root) root = POBJ_ROOT(pop, struct root); struct root *rootp = D_RW(root); size_t capacity; double totaltime = 0; switch (op) { case QUEUE_NEW: if (argc != 4) fail("missing size of the queue"); char *end; errno = 0; capacity = strtoull(argv[3], &end, 0); if (errno == ERANGE || *end != '\0') fail("invalid size of the queue"); printf("size %ld\n",capacity); if (queue_new(pop, &rootp->queue, capacity) != 0) fail("failed to create a new queue"); break; case QUEUE_ENQUEUE: if (argc != 4) fail("missing new entry data"); if (D_RW(rootp->queue) == NULL) fail("queue must exist"); */ double totaltime = 0; PMEMoid root = pmemobj_root(pop, sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000 + 4096*10); struct queue *qu = pmemobj_direct(root); checkpointptr = (void *)(qu + sizeof(struct queue) + sizeof(struct entry) * 10000 + sizeof(struct entry) * 10000); printf("root1 %ld\n",(uint64_t)qu); qu->front = 0; qu->back = 0; qu->capacity = 10000; pmemobj_persist(pop, qu, sizeof(*qu)); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_enqueue(pop, qu, argv[3], strlen(argv[3]) + 1,&totaltime) != 0) fail("failed to insert new entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); /* break; case QUEUE_DEQUEUE: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); totaltime = 0; for(int i=0;i<10000;i++){ if (queue_dequeue(pop, D_RW(rootp->queue),&totaltime) != 0) fail("failed to remove entry"); } printf("TX/s = %f %f\n",10000/totaltime, totaltime); // printf("TX avg cycles = %ld \n",totaltime/10000); break; case QUEUE_SHOW: if (D_RW(rootp->queue) == NULL) fail("queue must exist"); queue_show(pop, D_RW(rootp->queue)); break; default: assert(0); // unreachable break; } */ pmemobj_close(pop); return 0; }
8,411
28.310105
169
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/linkedlist/run.sh
sudo rm -rf /mnt/mem/fifo.pool sudo pmempool create --layout="list" obj myobjpool.set sudo ../../../tools/pmempool/pmempool create obj /mnt/mem/fifo.pool --layout list sudo ./fifo /mnt/mem/fifo.pool insert a sudo ./fifo /mnt/mem/fifo.pool remove a
249
34.714286
81
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/linkedlist/pmemobj_list.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * pmemobj_list.h -- macro definitions for persistent * singly linked list and tail queue */ #ifndef PMEMOBJ_LISTS_H #define PMEMOBJ_LISTS_H #include <libpmemobj.h> /* * This file defines two types of persistent data structures: * singly-linked lists and tail queue. * * All macros defined in this file must be used within libpmemobj * transactional API. Following snippet presents example of usage: * * TX_BEGIN(pop) { * POBJ_TAILQ_INIT(head); * } TX_ONABORT { * abort(); * } TX_END * * SLIST TAILQ * _HEAD + + * _ENTRY + + * _INIT + + * _EMPTY + + * _FIRST + + * _NEXT + + * _PREV - + * _LAST - + * _FOREACH + + * _FOREACH_REVERSE - + * _INSERT_HEAD + + * _INSERT_BEFORE - + * _INSERT_AFTER + + * _INSERT_TAIL - + * _MOVE_ELEMENT_HEAD - + * _MOVE_ELEMENT_TAIL - + * _REMOVE_HEAD + - * _REMOVE + + * _REMOVE_FREE + + * _SWAP_HEAD_TAIL - + */ /* * Singly-linked List definitions. */ #define POBJ_SLIST_HEAD(name, type)\ struct name {\ TOID(type) pe_first;\ } #define POBJ_SLIST_ENTRY(type)\ struct {\ TOID(type) pe_next;\ } /* * Singly-linked List access methods. */ #define POBJ_SLIST_EMPTY(head) (TOID_IS_NULL((head)->pe_first)) #define POBJ_SLIST_FIRST(head) ((head)->pe_first) #define POBJ_SLIST_NEXT(elm, field) (D_RO(elm)->field.pe_next) /* * Singly-linked List functions. */ #define POBJ_SLIST_INIT(head) do {\ TX_ADD_DIRECT(&(head)->pe_first);\ TOID_ASSIGN((head)->pe_first, OID_NULL);\ } while (0) #define POBJ_SLIST_INSERT_HEAD(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ TX_ADD_DIRECT(&elm_ptr->field.pe_next);\ elm_ptr->field.pe_next = (head)->pe_first;\ TX_SET_DIRECT(head, pe_first, elm);\ } while (0) #define POBJ_SLIST_INSERT_AFTER(slistelm, elm, field) do {\ TOID_TYPEOF(slistelm) *slistelm_ptr = D_RW(slistelm);\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ TX_ADD_DIRECT(&elm_ptr->field.pe_next);\ elm_ptr->field.pe_next = slistelm_ptr->field.pe_next;\ TX_ADD_DIRECT(&slistelm_ptr->field.pe_next);\ slistelm_ptr->field.pe_next = elm;\ } while (0) #define POBJ_SLIST_REMOVE_HEAD(head, field) do {\ TX_ADD_DIRECT(&(head)->pe_first);\ (head)->pe_first = D_RO((head)->pe_first)->field.pe_next;\ } while (0) #define POBJ_SLIST_REMOVE(head, elm, field) do {\ if (TOID_EQUALS((head)->pe_first, elm)) {\ POBJ_SLIST_REMOVE_HEAD(head, field);\ } else {\ TOID_TYPEOF(elm) *curelm_ptr = D_RW((head)->pe_first);\ while (!TOID_EQUALS(curelm_ptr->field.pe_next, elm))\ curelm_ptr = D_RW(curelm_ptr->field.pe_next);\ TX_ADD_DIRECT(&curelm_ptr->field.pe_next);\ curelm_ptr->field.pe_next = D_RO(elm)->field.pe_next;\ }\ } while (0) #define POBJ_SLIST_REMOVE_FREE(head, elm, field) do {\ POBJ_SLIST_REMOVE(head, elm, field);\ TX_FREE(elm);\ } while (0) #define POBJ_SLIST_FOREACH(var, head, field)\ for ((var) = POBJ_SLIST_FIRST(head);\ !TOID_IS_NULL(var);\ var = POBJ_SLIST_NEXT(var, field)) /* * Tail-queue definitions. */ #define POBJ_TAILQ_ENTRY(type)\ struct {\ TOID(type) pe_next;\ TOID(type) pe_prev;\ } #define POBJ_TAILQ_HEAD(name, type)\ struct name {\ TOID(type) pe_first;\ TOID(type) pe_last;\ } /* * Tail-queue access methods. */ #define POBJ_TAILQ_FIRST(head) ((head)->pe_first) #define POBJ_TAILQ_LAST(head) ((head)->pe_last) #define POBJ_TAILQ_EMPTY(head) (TOID_IS_NULL((head)->pe_first)) #define POBJ_TAILQ_NEXT(elm, field) (D_RO(elm)->field.pe_next) #define POBJ_TAILQ_PREV(elm, field) (D_RO(elm)->field.pe_prev) /* * Tail-queue List internal methods. */ #define _POBJ_SWAP_PTR(elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ TX_ADD_DIRECT(&elm_ptr->field);\ __typeof__(elm) temp = elm_ptr->field.pe_prev;\ elm_ptr->field.pe_prev = elm_ptr->field.pe_next;\ elm_ptr->field.pe_next = temp;\ } while (0) /* * Tail-queue functions. */ #define POBJ_TAILQ_SWAP_HEAD_TAIL(head, field) do {\ __typeof__((head)->pe_first) temp = (head)->pe_first;\ TX_ADD_DIRECT(head);\ (head)->pe_first = (head)->pe_last;\ (head)->pe_last = temp;\ } while (0) #define POBJ_TAILQ_FOREACH(var, head, field)\ for ((var) = POBJ_TAILQ_FIRST(head);\ !TOID_IS_NULL(var);\ var = POBJ_TAILQ_NEXT(var, field)) #define POBJ_TAILQ_FOREACH_REVERSE(var, head, field)\ for ((var) = POBJ_TAILQ_LAST(head);\ !TOID_IS_NULL(var);\ var = POBJ_TAILQ_PREV(var, field)) #define POBJ_TAILQ_INIT(head) do {\ TX_ADD_FIELD_DIRECT(head, pe_first);\ TOID_ASSIGN((head)->pe_first, OID_NULL);\ TX_ADD_FIELD_DIRECT(head, pe_last);\ TOID_ASSIGN((head)->pe_last, OID_NULL);\ } while (0) #define POBJ_TAILQ_INSERT_HEAD(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ if (TOID_IS_NULL((head)->pe_first)) {\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = (head)->pe_first;\ elm_ptr->field.pe_next = (head)->pe_first;\ TX_ADD_DIRECT(head);\ (head)->pe_first = elm;\ (head)->pe_last = elm;\ } else {\ TOID_TYPEOF(elm) *first = D_RW((head)->pe_first);\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_next = (head)->pe_first;\ elm_ptr->field.pe_prev = first->field.pe_prev;\ TX_ADD_DIRECT(&first->field.pe_prev);\ first->field.pe_prev = elm;\ TX_SET_DIRECT(head, pe_first, elm);\ }\ } while (0) #define POBJ_TAILQ_INSERT_TAIL(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ if (TOID_IS_NULL((head)->pe_last)) {\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = (head)->pe_last;\ elm_ptr->field.pe_next = (head)->pe_last;\ TX_ADD_DIRECT(head);\ (head)->pe_first = elm;\ (head)->pe_last = elm;\ } else {\ TOID_TYPEOF(elm) *last = D_RW((head)->pe_last);\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = (head)->pe_last;\ elm_ptr->field.pe_next = last->field.pe_next;\ TX_ADD_DIRECT(&last->field.pe_next);\ last->field.pe_next = elm;\ TX_SET_DIRECT(head, pe_last, elm);\ }\ } while (0) #define POBJ_TAILQ_INSERT_AFTER(listelm, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ TOID_TYPEOF(listelm) *listelm_ptr = D_RW(listelm);\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = listelm;\ elm_ptr->field.pe_next = listelm_ptr->field.pe_next;\ if (TOID_IS_NULL(listelm_ptr->field.pe_next)) {\ TX_SET_DIRECT(head, pe_last, elm);\ } else {\ TOID_TYPEOF(elm) *next = D_RW(listelm_ptr->field.pe_next);\ TX_ADD_DIRECT(&next->field.pe_prev);\ next->field.pe_prev = elm;\ }\ TX_ADD_DIRECT(&listelm_ptr->field.pe_next);\ listelm_ptr->field.pe_next = elm;\ } while (0) #define POBJ_TAILQ_INSERT_BEFORE(listelm, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ TOID_TYPEOF(listelm) *listelm_ptr = D_RW(listelm);\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_next = listelm;\ elm_ptr->field.pe_prev = listelm_ptr->field.pe_prev;\ if (TOID_IS_NULL(listelm_ptr->field.pe_prev)) {\ TX_SET_DIRECT(head, pe_first, elm);\ } else {\ TOID_TYPEOF(elm) *prev = D_RW(listelm_ptr->field.pe_prev);\ TX_ADD_DIRECT(&prev->field.pe_next);\ prev->field.pe_next = elm; \ }\ TX_ADD_DIRECT(&listelm_ptr->field.pe_prev);\ listelm_ptr->field.pe_prev = elm;\ } while (0) #define POBJ_TAILQ_REMOVE(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ if (TOID_IS_NULL(elm_ptr->field.pe_prev) &&\ TOID_IS_NULL(elm_ptr->field.pe_next)) {\ TX_ADD_DIRECT(head);\ (head)->pe_first = elm_ptr->field.pe_prev;\ (head)->pe_last = elm_ptr->field.pe_next;\ } else {\ if (TOID_IS_NULL(elm_ptr->field.pe_prev)) {\ TX_SET_DIRECT(head, pe_first, elm_ptr->field.pe_next);\ TOID_TYPEOF(elm) *next = D_RW(elm_ptr->field.pe_next);\ TX_ADD_DIRECT(&next->field.pe_prev);\ next->field.pe_prev = elm_ptr->field.pe_prev;\ } else {\ TOID_TYPEOF(elm) *prev = D_RW(elm_ptr->field.pe_prev);\ TX_ADD_DIRECT(&prev->field.pe_next);\ prev->field.pe_next = elm_ptr->field.pe_next;\ }\ if (TOID_IS_NULL(elm_ptr->field.pe_next)) {\ TX_SET_DIRECT(head, pe_last, elm_ptr->field.pe_prev);\ TOID_TYPEOF(elm) *prev = D_RW(elm_ptr->field.pe_prev);\ TX_ADD_DIRECT(&prev->field.pe_next);\ prev->field.pe_next = elm_ptr->field.pe_next;\ } else {\ TOID_TYPEOF(elm) *next = D_RW(elm_ptr->field.pe_next);\ TX_ADD_DIRECT(&next->field.pe_prev);\ next->field.pe_prev = elm_ptr->field.pe_prev;\ }\ }\ } while (0) #define POBJ_TAILQ_REMOVE_FREE(head, elm, field) do {\ POBJ_TAILQ_REMOVE(head, elm, field);\ TX_FREE(elm);\ } while (0) /* * 2 cases: only two elements, the rest possibilities * including that elm is the last one */ #define POBJ_TAILQ_MOVE_ELEMENT_HEAD(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ if (TOID_EQUALS((head)->pe_last, elm) &&\ TOID_EQUALS(D_RO((head)->pe_first)->field.pe_next, elm)) {\ _POBJ_SWAP_PTR(elm, field);\ _POBJ_SWAP_PTR((head)->pe_first, field);\ POBJ_TAILQ_SWAP_HEAD_TAIL(head, field);\ } else {\ TOID_TYPEOF(elm) *prev = D_RW(elm_ptr->field.pe_prev);\ TX_ADD_DIRECT(&prev->field.pe_next);\ prev->field.pe_next = elm_ptr->field.pe_next;\ if (TOID_EQUALS((head)->pe_last, elm)) {\ TX_SET_DIRECT(head, pe_last, elm_ptr->field.pe_prev);\ } else {\ TOID_TYPEOF(elm) *next = D_RW(elm_ptr->field.pe_next);\ TX_ADD_DIRECT(&next->field.pe_prev);\ next->field.pe_prev = elm_ptr->field.pe_prev;\ }\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = D_RO((head)->pe_first)->field.pe_prev;\ elm_ptr->field.pe_next = (head)->pe_first;\ TOID_TYPEOF(elm) *first = D_RW((head)->pe_first);\ TX_ADD_DIRECT(&first->field.pe_prev);\ first->field.pe_prev = elm;\ TX_SET_DIRECT(head, pe_first, elm);\ }\ } while (0) #define POBJ_TAILQ_MOVE_ELEMENT_TAIL(head, elm, field) do {\ TOID_TYPEOF(elm) *elm_ptr = D_RW(elm);\ if (TOID_EQUALS((head)->pe_first, elm) &&\ TOID_EQUALS(D_RO((head)->pe_last)->field.pe_prev, elm)) {\ _POBJ_SWAP_PTR(elm, field);\ _POBJ_SWAP_PTR((head)->pe_last, field);\ POBJ_TAILQ_SWAP_HEAD_TAIL(head, field);\ } else {\ TOID_TYPEOF(elm) *next = D_RW(elm_ptr->field.pe_next);\ TX_ADD_DIRECT(&next->field.pe_prev);\ next->field.pe_prev = elm_ptr->field.pe_prev;\ if (TOID_EQUALS((head)->pe_first, elm)) {\ TX_SET_DIRECT(head, pe_first, elm_ptr->field.pe_next);\ } else { \ TOID_TYPEOF(elm) *prev = D_RW(elm_ptr->field.pe_prev);\ TX_ADD_DIRECT(&prev->field.pe_next);\ prev->field.pe_next = elm_ptr->field.pe_next;\ }\ TX_ADD_DIRECT(&elm_ptr->field);\ elm_ptr->field.pe_prev = (head)->pe_last;\ elm_ptr->field.pe_next = D_RO((head)->pe_last)->field.pe_next;\ __typeof__(elm_ptr) last = D_RW((head)->pe_last);\ TX_ADD_DIRECT(&last->field.pe_next);\ last->field.pe_next = elm;\ TX_SET_DIRECT(head, pe_last, elm);\ } \ } while (0) #endif /* PMEMOBJ_LISTS_H */
11,243
30.762712
66
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/linkedlist/fifo.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * fifo.c - example of tail queue usage */ #include <ex_common.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pmemobj_list.h" POBJ_LAYOUT_BEGIN(list); POBJ_LAYOUT_ROOT(list, struct fifo_root); POBJ_LAYOUT_TOID(list, struct tqnode); POBJ_LAYOUT_END(list); POBJ_TAILQ_HEAD(tqueuehead, struct tqnode); struct fifo_root { struct tqueuehead head; }; struct tqnode { char data; POBJ_TAILQ_ENTRY(struct tqnode) tnd; }; static void print_help(void) { printf("usage: fifo <pool> <option> [<type>]\n"); printf("\tAvailable options:\n"); printf("\tinsert, <character> Insert character into FIFO\n"); printf("\tremove, Remove element from FIFO\n"); printf("\tprint, Print all FIFO elements\n"); } int main(int argc, const char *argv[]) { PMEMobjpool *pop; const char *path; if (argc < 3) { print_help(); return 0; } path = argv[1]; if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(list), PMEMOBJ_MIN_POOL, 0666)) == NULL) { perror("failed to create pool\n"); return -1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(list))) == NULL) { perror("failed to open pool\n"); return -1; } } TOID(struct fifo_root) root = POBJ_ROOT(pop, struct fifo_root); struct tqueuehead *tqhead = &D_RW(root)->head; TOID(struct tqnode) node; double totaltime = 0; if (strcmp(argv[2], "insert") == 0) { if (argc == 4) { totaltime = 0; for(int i=0;i<1000000;i++){ clock_t start, end; start = clock(); TX_BEGIN(pop) { node = TX_NEW(struct tqnode); D_RW(node)->data = *argv[3]; POBJ_TAILQ_INSERT_HEAD(tqhead, node, tnd); } TX_ONABORT { abort(); } TX_END end = clock(); totaltime += ((double) (end - start)) / CLOCKS_PER_SEC; } printf("TX/s = %f %f\n",1000000/totaltime, totaltime); printf("Added %c to FIFO\n", *argv[3]); } else { print_help(); } } else if (strcmp(argv[2], "remove") == 0) { totaltime = 0; for(int i=0;i<1000000;i++){ clock_t start, end; start = clock(); if (POBJ_TAILQ_EMPTY(tqhead)) { printf("FIFO is empty\n"); } else { node = POBJ_TAILQ_LAST(tqhead); TX_BEGIN(pop) { POBJ_TAILQ_REMOVE_FREE(tqhead, node, tnd); } TX_ONABORT { abort(); } TX_END printf("Removed element from FIFO\n"); } end = clock(); totaltime += ((double) (end - start)) / CLOCKS_PER_SEC; } printf("TX/s = %f %f\n",1000000/totaltime, totaltime); } else if (strcmp(argv[2], "print") == 0) { printf("Elements in FIFO:\n"); POBJ_TAILQ_FOREACH(node, tqhead, tnd) { printf("%c\t", D_RO(node)->data); } printf("\n"); } else { print_help(); } pmemobj_close(pop); return 0; }
2,782
21.264
64
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_atomic.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map_hashmap_atomic.h -- common interface for maps */ #ifndef MAP_HASHMAP_ATOMIC_H #define MAP_HASHMAP_ATOMIC_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops hashmap_atomic_ops; #define MAP_HASHMAP_ATOMIC (&hashmap_atomic_ops) #ifdef __cplusplus } #endif #endif /* MAP_HASHMAP_ATOMIC_H */
421
15.230769
52
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/kv_server_test.sh
#!/usr/bin/env bash # SPDX-License-Identifier: BSD-3-Clause # Copyright 2015-2016, Intel Corporation set -euo pipefail MAP=ctree PORT=9100 POOL=$1 # start a new server instance ./kv_server $MAP $POOL $PORT & # wait for the server to properly start sleep 1 # insert a new key value pair and disconnect RESP=`echo -e "INSERT foo bar\nGET foo\nBYE" | nc 127.0.0.1 $PORT` echo $RESP # remove previously inserted key value pair and shutdown the server RESP=`echo -e "GET foo\nREMOVE foo\nGET foo\nKILL" | nc 127.0.0.1 $PORT` echo $RESP
537
21.416667
72
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_btree.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map_ctree.h -- common interface for maps */ #ifndef MAP_BTREE_H #define MAP_BTREE_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops btree_map_ops; #define MAP_BTREE (&btree_map_ops) #ifdef __cplusplus } #endif #endif /* MAP_BTREE_H */
366
13.115385
44
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_tx.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map_hashmap_tx.c -- common interface for maps */ #include <map.h> #include <hashmap_tx.h> #include "map_hashmap_tx.h" /* * map_hm_tx_check -- wrapper for hm_tx_check */ static int map_hm_tx_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_check(pop, hashmap_tx); } /* * map_hm_tx_count -- wrapper for hm_tx_count */ static size_t map_hm_tx_count(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_count(pop, hashmap_tx); } /* * map_hm_tx_init -- wrapper for hm_tx_init */ static int map_hm_tx_init(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_init(pop, hashmap_tx); } /* * map_hm_tx_create -- wrapper for hm_tx_create */ static int map_hm_tx_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct hashmap_tx) *hashmap_tx = (TOID(struct hashmap_tx) *)map; return hm_tx_create(pop, hashmap_tx, arg); } /* * map_hm_tx_insert -- wrapper for hm_tx_insert */ static int map_hm_tx_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_insert(pop, hashmap_tx, key, value); } /* * map_hm_tx_remove -- wrapper for hm_tx_remove */ static PMEMoid map_hm_tx_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_remove(pop, hashmap_tx, key); } /* * map_hm_tx_get -- wrapper for hm_tx_get */ static PMEMoid map_hm_tx_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_get(pop, hashmap_tx, key); } /* * map_hm_tx_lookup -- wrapper for hm_tx_lookup */ static int map_hm_tx_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_lookup(pop, hashmap_tx, key); } /* * map_hm_tx_foreach -- wrapper for hm_tx_foreach */ static int map_hm_tx_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_foreach(pop, hashmap_tx, cb, arg); } /* * map_hm_tx_cmd -- wrapper for hm_tx_cmd */ static int map_hm_tx_cmd(PMEMobjpool *pop, TOID(struct map) map, unsigned cmd, uint64_t arg) { TOID(struct hashmap_tx) hashmap_tx; TOID_ASSIGN(hashmap_tx, map.oid); return hm_tx_cmd(pop, hashmap_tx, cmd, arg); } struct map_ops hashmap_tx_ops = { /* .check = */ map_hm_tx_check, /* .create = */ map_hm_tx_create, /* .delete = */ NULL, /* .init = */ map_hm_tx_init, /* .insert = */ map_hm_tx_insert, /* .insert_new = */ NULL, /* .remove = */ map_hm_tx_remove, /* .remove_free = */ NULL, /* .clear = */ NULL, /* .get = */ map_hm_tx_get, /* .lookup = */ map_hm_tx_lookup, /* .foreach = */ map_hm_tx_foreach, /* .is_empty = */ NULL, /* .count = */ map_hm_tx_count, /* .cmd = */ map_hm_tx_cmd, };
3,316
20.966887
70
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_rtree.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2018, Intel Corporation */ /* * map_rtree.h -- common interface for maps */ #ifndef MAP_RTREE_H #define MAP_RTREE_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops rtree_map_ops; #define MAP_RTREE (&rtree_map_ops) #ifdef __cplusplus } #endif #endif /* MAP_RTREE_H */
366
13.115385
44
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/kv_server.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * kv_server.c -- persistent tcp key-value store server */ #include <uv.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "libpmemobj.h" #include "map.h" #include "map_ctree.h" #include "map_btree.h" #include "map_rtree.h" #include "map_rbtree.h" #include "map_hashmap_atomic.h" #include "map_hashmap_tx.h" #include "map_hashmap_rp.h" #include "map_skiplist.h" #include "kv_protocol.h" #define COUNT_OF(x) (sizeof(x) / sizeof(0[x])) #define COMPILE_ERROR_ON(cond) ((void)sizeof(char[(cond) ? -1 : 1])) int use_ndp_redo = 0; POBJ_LAYOUT_BEGIN(kv_server); POBJ_LAYOUT_ROOT(kv_server, struct root); POBJ_LAYOUT_TOID(kv_server, struct map_value); POBJ_LAYOUT_TOID(kv_server, uint64_t); POBJ_LAYOUT_END(kv_server); struct map_value { uint64_t len; char buf[]; }; struct root { TOID(struct map) map; }; static struct map_ctx *mapc; static PMEMobjpool *pop; static TOID(struct map) map; static uv_tcp_t server; static uv_loop_t *loop; typedef int (*msg_handler)(uv_stream_t *client, const char *msg, size_t len); struct write_req { uv_write_t req; uv_buf_t buf; }; struct client_data { char *buf; /* current message, always NULL terminated */ size_t buf_len; /* sizeof(buf) */ size_t len; /* actual length of the message (while parsing) */ }; /* * djb2_hash -- string hashing function by Dan Bernstein */ static uint32_t djb2_hash(const char *str) { uint32_t hash = 5381; int c; while ((c = *str++)) hash = ((hash << 5) + hash) + c; return hash; } /* * write_done_cb -- callback after message write completes */ static void write_done_cb(uv_write_t *req, int status) { struct write_req *wr = (struct write_req *)req; free(wr); if (status == -1) { printf("response failed"); } } /* * client_close_cb -- callback after client tcp connection closes */ static void client_close_cb(uv_handle_t *handle) { struct client_data *d = handle->data; free(d->buf); free(handle->data); free(handle); } /* * response_write -- response writing helper */ static void response_write(uv_stream_t *client, char *resp, size_t len) { struct write_req *wr = malloc(sizeof(struct write_req)); assert(wr != NULL); wr->buf = uv_buf_init(resp, len); uv_write(&wr->req, client, &wr->buf, 1, write_done_cb); } /* * response_msg -- predefined message writing helper */ static void response_msg(uv_stream_t *client, enum resp_messages msg) { response_write(client, (char *)resp_msg[msg], strlen(resp_msg[msg])); } /* * cmsg_insert_handler -- handler of INSERT client message */ static int cmsg_insert_handler(uv_stream_t *client, const char *msg, size_t len) { int result = 0; TX_BEGIN(pop) { /* * For simplicity sake the length of the value buffer is just * a length of the message. */ TOID(struct map_value) val = TX_ZALLOC(struct map_value, sizeof(struct map_value) + len); char key[MAX_KEY_LEN]; int ret = sscanf(msg, "INSERT %254s %s\n", key, D_RW(val)->buf); assert(ret == 2); D_RW(val)->len = len; /* properly terminate the value */ D_RW(val)->buf[strlen(D_RO(val)->buf)] = '\n'; map_insert(mapc, map, djb2_hash(key), val.oid); } TX_ONABORT { result = 1; } TX_END response_msg(client, result); return 0; } /* * cmsg_remove_handler -- handler of REMOVE client message */ static int cmsg_remove_handler(uv_stream_t *client, const char *msg, size_t len) { char key[MAX_KEY_LEN] = {0}; /* check if the constant used in sscanf() below has the correct value */ COMPILE_ERROR_ON(MAX_KEY_LEN - 1 != 254); int ret = sscanf(msg, "REMOVE %254s\n", key); assert(ret == 1); int result = map_remove_free(mapc, map, djb2_hash(key)); response_msg(client, result); return 0; } /* * cmsg_get_handler -- handler of GET client message */ static int cmsg_get_handler(uv_stream_t *client, const char *msg, size_t len) { char key[MAX_KEY_LEN]; /* check if the constant used in sscanf() below has the correct value */ COMPILE_ERROR_ON(MAX_KEY_LEN - 1 != 254); int ret = sscanf(msg, "GET %254s\n", key); assert(ret == 1); TOID(struct map_value) value; TOID_ASSIGN(value, map_get(mapc, map, djb2_hash(key))); if (TOID_IS_NULL(value)) { response_msg(client, RESP_MSG_NULL); } else { response_write(client, D_RW(value)->buf, D_RO(value)->len); } return 0; } /* * cmsg_bye_handler -- handler of BYE client message */ static int cmsg_bye_handler(uv_stream_t *client, const char *msg, size_t len) { uv_close((uv_handle_t *)client, client_close_cb); return 0; } /* * cmsg_bye_handler -- handler of KILL client message */ static int cmsg_kill_handler(uv_stream_t *client, const char *msg, size_t len) { uv_close((uv_handle_t *)client, client_close_cb); uv_close((uv_handle_t *)&server, NULL); return 0; } /* kv protocol implementation */ static msg_handler protocol_impl[MAX_CMSG] = { cmsg_insert_handler, cmsg_remove_handler, cmsg_get_handler, cmsg_bye_handler, cmsg_kill_handler }; /* * cmsg_handle -- handles current client message */ static int cmsg_handle(uv_stream_t *client, struct client_data *data) { int ret = 0; int i; for (i = 0; i < MAX_CMSG; ++i) if (strncmp(kv_cmsg_token[i], data->buf, strlen(kv_cmsg_token[i])) == 0) break; if (i == MAX_CMSG) { response_msg(client, RESP_MSG_UNKNOWN); } else { ret = protocol_impl[i](client, data->buf, data->len); } data->len = 0; /* reset the message length */ return ret; } /* * cmsg_handle_stream -- handle incoming tcp stream from clients */ static int cmsg_handle_stream(uv_stream_t *client, struct client_data *data, const char *buf, ssize_t nread) { char *last; int ret; size_t len; /* * A single read operation can contain zero or more operations, so this * has to be handled appropriately. Client messages are terminated by * newline character. */ while ((last = memchr(buf, '\n', nread)) != NULL) { len = last - buf + 1; nread -= len; assert(data->len + len <= data->buf_len); memcpy(data->buf + data->len, buf, len); data->len += len; if ((ret = cmsg_handle(client, data)) != 0) return ret; buf = last + 1; } if (nread != 0) { memcpy(data->buf + data->len, buf, nread); data->len += nread; } return 0; } static uv_buf_t msg_buf = {0}; /* * get_read_buf_cb -- returns buffer for incoming client message */ static void get_read_buf_cb(uv_handle_t *handle, size_t size, uv_buf_t *buf) { buf->base = msg_buf.base; buf->len = msg_buf.len; } /* * read_cb -- async tcp read from clients */ static void read_cb(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { if (nread <= 0) { printf("client connection closed\n"); uv_close((uv_handle_t *)client, client_close_cb); return; } struct client_data *d = client->data; if (d->buf_len < (d->len + nread + 1)) { char *cbuf = realloc(d->buf, d->buf_len + nread + 1); assert(cbuf != NULL); /* zero only the new memory */ memset(cbuf + d->buf_len, 0, nread + 1); d->buf_len += nread + 1; d->buf = cbuf; } if (cmsg_handle_stream(client, client->data, buf->base, nread)) { printf("client disconnect\n"); uv_close((uv_handle_t *)client, client_close_cb); } } /* * connection_cb -- async incoming client request */ static void connection_cb(uv_stream_t *server, int status) { if (status != 0) { printf("client connect error\n"); return; } printf("new client\n"); uv_tcp_t *client = malloc(sizeof(uv_tcp_t)); assert(client != NULL); client->data = calloc(1, sizeof(struct client_data)); assert(client->data != NULL); uv_tcp_init(loop, client); if (uv_accept(server, (uv_stream_t *)client) == 0) { uv_read_start((uv_stream_t *)client, get_read_buf_cb, read_cb); } else { uv_close((uv_handle_t *)client, client_close_cb); } } static const struct { struct map_ops *ops; const char *name; } maps[] = { {MAP_HASHMAP_TX, "hashmap_tx"}, {MAP_HASHMAP_ATOMIC, "hashmap_atomic"}, {MAP_HASHMAP_RP, "hashmap_rp"}, {MAP_CTREE, "ctree"}, {MAP_BTREE, "btree"}, {MAP_RTREE, "rtree"}, {MAP_RBTREE, "rbtree"}, {MAP_SKIPLIST, "skiplist"} }; /* * get_map_ops_by_string -- parse the type string and return the associated ops */ static const struct map_ops * get_map_ops_by_string(const char *type) { for (int i = 0; i < COUNT_OF(maps); ++i) if (strcmp(maps[i].name, type) == 0) return maps[i].ops; return NULL; } #define KV_SIZE (PMEMOBJ_MIN_POOL) #define MAX_READ_LEN (64 * 1024) /* 64 kilobytes */ int main(int argc, char *argv[]) { if (argc < 4) { printf("usage: %s hashmap_tx|hashmap_atomic|hashmap_rp|" "ctree|btree|rtree|rbtree|skiplist file-name port\n", argv[0]); return 1; } const char *path = argv[2]; const char *type = argv[1]; int port = atoi(argv[3]); /* use only a single buffer for all incoming data */ void *read_buf = malloc(MAX_READ_LEN); assert(read_buf != NULL); msg_buf = uv_buf_init(read_buf, MAX_READ_LEN); if (access(path, F_OK) != 0) { pop = pmemobj_create(path, POBJ_LAYOUT_NAME(kv_server), KV_SIZE, 0666); if (pop == NULL) { fprintf(stderr, "failed to create pool: %s\n", pmemobj_errormsg()); return 1; } } else { pop = pmemobj_open(path, POBJ_LAYOUT_NAME(kv_server)); if (pop == NULL) { fprintf(stderr, "failed to open pool: %s\n", pmemobj_errormsg()); return 1; } } /* map context initialization */ mapc = map_ctx_init(get_map_ops_by_string(type), pop); if (!mapc) { pmemobj_close(pop); fprintf(stderr, "map_ctx_init failed (wrong type?)\n"); return 1; } /* initialize the actual map */ TOID(struct root) root = POBJ_ROOT(pop, struct root); if (TOID_IS_NULL(D_RO(root)->map)) { /* create new if it doesn't exist (a fresh pool) */ map_create(mapc, &D_RW(root)->map, NULL); } map = D_RO(root)->map; loop = uv_default_loop(); /* tcp server initialization */ uv_tcp_init(loop, &server); struct sockaddr_in bind_addr; uv_ip4_addr("0.0.0.0", port, &bind_addr); int ret = uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0); assert(ret == 0); ret = uv_listen((uv_stream_t *)&server, SOMAXCONN, connection_cb); assert(ret == 0); ret = uv_run(loop, UV_RUN_DEFAULT); assert(ret == 0); /* no more events in the loop, release resources and quit */ uv_loop_delete(loop); map_ctx_free(mapc); pmemobj_close(pop); free(read_buf); return 0; }
10,374
20.524896
79
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_skiplist.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * map_skiplist.h -- common interface for maps */ #ifndef MAP_SKIPLIST_H #define MAP_SKIPLIST_H #include "map.h" extern struct map_ops skiplist_map_ops; #define MAP_SKIPLIST (&skiplist_map_ops) #endif /* MAP_SKIPLIST_H */
313
16.444444
46
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map.h -- common interface for maps */ #ifndef MAP_H #define MAP_H #include <libpmemobj.h> #ifdef __cplusplus extern "C" { #endif #ifndef MAP_TYPE_OFFSET #define MAP_TYPE_OFFSET 1000 #endif TOID_DECLARE(struct map, MAP_TYPE_OFFSET + 0); struct map; struct map_ctx; struct map_ops { int(*check)(PMEMobjpool *pop, TOID(struct map) map); int(*create)(PMEMobjpool *pop, TOID(struct map) *map, void *arg); int(*destroy)(PMEMobjpool *pop, TOID(struct map) *map); int(*init)(PMEMobjpool *pop, TOID(struct map) map); int(*insert)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value); int(*insert_new)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void(*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg); PMEMoid(*remove)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key); int(*remove_free)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key); int(*clear)(PMEMobjpool *pop, TOID(struct map) map); PMEMoid(*get)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key); int(*lookup)(PMEMobjpool *pop, TOID(struct map) map, uint64_t key); int(*foreach)(PMEMobjpool *pop, TOID(struct map) map, int(*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); int(*is_empty)(PMEMobjpool *pop, TOID(struct map) map); size_t(*count)(PMEMobjpool *pop, TOID(struct map) map); int(*cmd)(PMEMobjpool *pop, TOID(struct map) map, unsigned cmd, uint64_t arg); }; struct map_ctx { PMEMobjpool *pop; const struct map_ops *ops; }; struct map_ctx *map_ctx_init(const struct map_ops *ops, PMEMobjpool *pop); void map_ctx_free(struct map_ctx *mapc); int map_check(struct map_ctx *mapc, TOID(struct map) map); int map_create(struct map_ctx *mapc, TOID(struct map) *map, void *arg); int map_destroy(struct map_ctx *mapc, TOID(struct map) *map); int map_init(struct map_ctx *mapc, TOID(struct map) map); int map_insert(struct map_ctx *mapc, TOID(struct map) map, uint64_t key, PMEMoid value); int map_insert_new(struct map_ctx *mapc, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void(*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg); PMEMoid map_remove(struct map_ctx *mapc, TOID(struct map) map, uint64_t key); int map_remove_free(struct map_ctx *mapc, TOID(struct map) map, uint64_t key); int map_clear(struct map_ctx *mapc, TOID(struct map) map); PMEMoid map_get(struct map_ctx *mapc, TOID(struct map) map, uint64_t key); int map_lookup(struct map_ctx *mapc, TOID(struct map) map, uint64_t key); int map_foreach(struct map_ctx *mapc, TOID(struct map) map, int(*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); int map_is_empty(struct map_ctx *mapc, TOID(struct map) map); size_t map_count(struct map_ctx *mapc, TOID(struct map) map); int map_cmd(struct map_ctx *mapc, TOID(struct map) map, unsigned cmd, uint64_t arg); #ifdef __cplusplus } #endif #endif /* MAP_H */
3,010
31.728261
78
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_rp.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018, Intel Corporation */ /* * map_hashmap_rp.h -- common interface for maps */ #ifndef MAP_HASHMAP_RP_H #define MAP_HASHMAP_RP_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops hashmap_rp_ops; #define MAP_HASHMAP_RP (&hashmap_rp_ops) #ifdef __cplusplus } #endif #endif /* MAP_HASHMAP_RP_H */
388
13.961538
48
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/data_store.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * data_store.c -- tree_map example usage */ #include <ex_common.h> #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #include "map.h" #include "map_ctree.h" #include "map_btree.h" #include "map_rbtree.h" #include "map_hashmap_atomic.h" #include "map_hashmap_tx.h" #include "map_hashmap_rp.h" #include "map_skiplist.h" POBJ_LAYOUT_BEGIN(data_store); POBJ_LAYOUT_ROOT(data_store, struct store_root); POBJ_LAYOUT_TOID(data_store, struct store_item); POBJ_LAYOUT_END(data_store); /////////////////Page fault handling///////////////// #include <bits/types/sig_atomic_t.h> #include <bits/types/sigset_t.h> #include <signal.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #define SIGSTKSZ 8192 #define SA_SIGINFO 4 #define SA_ONSTACK 0x08000000 /* Use signal stack by using `sa_restorer'. */ #define SA_RESTART 0x10000000 /* Restart syscall on signal return. */ #define SA_NODEFER 0x40000000 /* Don't automatically block the signal when*/ stack_t _sigstk; int updated_page_count = 0; int all_updates = 0; int start_timing = 0; void * checkpoint_start; void * page[50]; PMEMobjpool *pop; void * device; int tot_data_counter=0; #define CHPSIZE 2048 void cmd_issue( uint32_t opcode, uint32_t TXID, uint32_t TID, uint32_t OID, uint64_t data_addr, uint32_t data_size, void * ptr){ //command with thread id encoded as first 8 bits of each word uint32_t issue_cmd[7]; issue_cmd[0] = (TID<<24)|(opcode<<16)|(TXID<<8)|TID; issue_cmd[1] = (TID<<24)|(OID<<16)|(data_addr>>48); issue_cmd[2] = (TID<<24)|((data_addr & 0x0000FFFFFFFFFFFF)>>24); issue_cmd[3] = (TID<<24)|(data_addr & 0x0000000000FFFFFF); issue_cmd[4] = (TID<<24)|(data_size<<8); issue_cmd[5] = (TID<<24)|(0X00FFFFFF>>16); issue_cmd[6] = (TID<<24)|((0X00FFFFFF & 0x0000FFFF)<<8); for(int i=0;i<7;i++){ // printf("%08x\n",issue_cmd[i]); *((u_int32_t *) ptr) = issue_cmd[i]; } } static inline uint64_t getCycle(){ uint32_t cycles_high, cycles_low, pid; asm volatile ("RDTSCP\n\t" // rdtscp into eax and edx "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" "mov %%ecx, %2\n\t" :"=r" (cycles_high), "=r" (cycles_low), "=r" (pid) //store in vars :// no input :"%eax", "%edx", "%ecx" // clobbered by rdtscp ); return((uint64_t)cycles_high << 32) | cycles_low; } /// @brief Signal handler to trap SEGVs. static void segvHandle(int signum, siginfo_t * siginfo, void * context) { #define CPTIME #ifdef CPTIME uint64_t endCycles, startCycles,totalCycles; startCycles = getCycle(); #endif void * addr = siginfo->si_addr; // address of access uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); // Check if this was a SEGV that we are supposed to trap. if (siginfo->si_code == SEGV_ACCERR) { mprotect(pageStart, 4096, PROT_READ|PROT_WRITE); if(all_updates >= 0 || updated_page_count == 50){ for(int i=0;i<updated_page_count;i++){ //memcpy(checkpoint_start + 4096, pageStart,4096); //pmemobj_persist(pop, checkpoint_start + 4096,4096); cmd_issue(2,0,0,0, pageStart + i*4096,4096,device); tot_data_counter++; page[updated_page_count] = 0; } updated_page_count = 0; all_updates = 0; } all_updates ++; //printf("te\n"); for(int i=0; i<updated_page_count; i++){ if(page[i] == pageStart){ #ifdef CPTIME endCycles = getCycle(); totalCycles = endCycles - startCycles; double totTime = ((double)totalCycles)/2000000000; printf("cp %f\n", totTime); #endif return;} } page[updated_page_count] = pageStart; //printf("test1 %lx %d %d\n",page[updated_page_count],updated_page_count,all_updates); updated_page_count++; #ifdef CPTIME endCycles = getCycle(); totalCycles = endCycles - startCycles; double totTime = ((double)totalCycles)/2000000000; printf("cp %f\n", totTime); #endif //*((int *)checkpoint_start) = 10; //test++; //printf("test1 %lx %d\n",updated_page_count); } else if (siginfo->si_code == SEGV_MAPERR) { fprintf (stderr, "%d : map error with addr %p!\n", getpid(), addr); abort(); } else { fprintf (stderr, "%d : other access error with addr %p.\n", getpid(), addr); abort(); } } static void installSignalHandler(void) { // Set up an alternate signal stack. printf("page fault handler initialized!!\n"); _sigstk.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); _sigstk.ss_size = SIGSTKSZ; _sigstk.ss_flags = 0; sigaltstack(&_sigstk, (stack_t *) 0); // Now set up a signal handler for SIGSEGV events. struct sigaction siga; sigemptyset(&siga.sa_mask); // Set the following signals to a set sigaddset(&siga.sa_mask, SIGSEGV); sigaddset(&siga.sa_mask, SIGALRM); sigprocmask(SIG_BLOCK, &siga.sa_mask, NULL); // Point to the handler function. siga.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART | SA_NODEFER; siga.sa_sigaction = segvHandle; if (sigaction(SIGSEGV, &siga, NULL) == -1) { perror("sigaction(SIGSEGV)"); exit(-1); } sigprocmask(SIG_UNBLOCK, &siga.sa_mask, NULL); return; } static void setpage(void * addr){ uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); mprotect(pageStart, 4096, PROT_READ); return; } static void resetpage(void * addr){ uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); mprotect(pageStart, 4096, PROT_READ|PROT_WRITE); return; } void* open_device(const char* pathname) { //int fd = os_open("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0",O_RDWR|O_SYNC); int fd = open(pathname,O_RDWR|O_SYNC); if(fd == -1) { printf("Couldnt opene file!!\n"); exit(0); } void * ptr = mmap(0,4096,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0); if(ptr == (void *)-1) { printf("Could not map memory!!\n"); exit(0); } printf("opened device without error!!\n"); return ptr; } /////////////////////////////////////////////////////////////// #define MAX_INSERTS 100000 int use_ndp_redo = 0; static uint64_t nkeys; static uint64_t keys[MAX_INSERTS]; //int page_skip_counter = 0; TOID_DECLARE(struct page_checkpoint, 0); struct page_checkpoint{ char page[50][4096]; }; struct store_item { uint64_t item_data; }; struct store_root { TOID(struct map) map; }; /* * new_store_item -- transactionally creates and initializes new item */ static TOID(struct store_item) new_store_item(void) { TOID(struct store_item) item = TX_NEW(struct store_item); D_RW(item)->item_data = rand(); return item; } /* * get_keys -- inserts the keys of the items by key order (sorted, descending) */ static int get_keys(uint64_t key, PMEMoid value, void *arg) { keys[nkeys++] = key; return 0; } /* * dec_keys -- decrements the keys count for every item */ static int dec_keys(uint64_t key, PMEMoid value, void *arg) { nkeys--; return 0; } /* * parse_map_type -- parse type of map */ static const struct map_ops * parse_map_type(const char *type) { if (strcmp(type, "ctree") == 0) return MAP_CTREE; else if (strcmp(type, "btree") == 0) return MAP_BTREE; else if (strcmp(type, "rbtree") == 0) return MAP_RBTREE; else if (strcmp(type, "hashmap_atomic") == 0) return MAP_HASHMAP_ATOMIC; else if (strcmp(type, "hashmap_tx") == 0) return MAP_HASHMAP_TX; else if (strcmp(type, "hashmap_rp") == 0) return MAP_HASHMAP_RP; else if (strcmp(type, "skiplist") == 0) return MAP_SKIPLIST; return NULL; } void installSignalHandler (void) __attribute__ ((constructor)); int current_tx1; int main(int argc, const char *argv[]) { if (argc < 3) { printf("usage: %s " "<ctree|btree|rbtree|hashmap_atomic|hashmap_rp|" "hashmap_tx|skiplist> file-name [nops]\n", argv[0]); return 1; } const char *type = argv[1]; const char *path = argv[2]; const struct map_ops *map_ops = parse_map_type(type); if (!map_ops) { fprintf(stderr, "invalid container type -- '%s'\n", type); return 1; } int nops = MAX_INSERTS; if (argc > 3) { nops = atoi(argv[3]); if (nops <= 0 || nops > MAX_INSERTS) { fprintf(stderr, "number of operations must be " "in range 1..%d\n", MAX_INSERTS); return 1; } } //PMEMobjpool *pop; srand((unsigned)time(NULL)); if (file_exists(path) != 0) { if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(data_store), (1024*1024*512), 0666)) == NULL) { perror("failed to create pool\n"); return 1; } } else { if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(data_store))) == NULL) { perror("failed to open pool\n"); return 1; } } device = open_device("/sys/devices/pci0000:00/0000:00:00.2/iommu/ivhd0/devices/0000:0a:00.0/resource0"); //TOID(struct store_root) root = (TOID(struct store_root))pmemobj_root(pop, 1024*1024*512); //struct queue *qu = pmemobj_direct(root); //checkpoint_start = (void *)(qu + ); TOID(struct store_root) root = POBJ_ROOT(pop, struct store_root); //checkpoint_start = D_RW(root) + (1024*1024*256); TX_BEGIN(pop) { checkpoint_start = D_RW(TX_NEW(struct page_checkpoint))->page; } TX_END struct map_ctx *mapc = map_ctx_init(map_ops, pop); if (!mapc) { perror("cannot allocate map context\n"); return 1; } /* delete the map if it exists */ if (!map_check(mapc, D_RW(root)->map)) map_destroy(mapc, &D_RW(root)->map); /* insert random items in a transaction */ int aborted = 0; uint64_t endCycles, startCycles,totalCycles; TX_BEGIN(pop) { map_create(mapc, &D_RW(root)->map, NULL); } TX_END //warmup database /*for (int i = 0; i < 10000; ++i) { TX_BEGIN(pop) { int keyused = rand(); map_insert(mapc, D_RW(root)->map, keyused, new_store_item().oid); } TX_ONABORT { perror("transaction aborted y\n"); map_ctx_free(mapc); aborted = 1; } TX_END }*/ int keyread[10000]; startCycles = getCycle(); PMEMoid readval; int readCount = 0; for (int i = 0; i < nops; ++i) { start_timing = 1; TX_BEGIN(pop) { if(i<(10000 -readCount)){ int keyused = rand(); keyread[i]= keyused; map_insert(mapc, D_RW(root)->map, keyused, new_store_item().oid); } else { if(readCount == 7500) readval = map_get(mapc, D_RW(root)->map, keyread[rand()%2500]); else readval = map_get(mapc, D_RW(root)->map, keyread[rand()%(10000 - readCount)]); } } TX_ONABORT { perror("transaction aborted y\n"); map_ctx_free(mapc); aborted = 1; } TX_END //updated_page_count = 0; } /* for (int i = 0; i < nops; ++i) { current_tx1 = 1; TX_BEGIN(pop) { int keyused = rand(); map_insert(mapc, D_RW(root)->map, keyused, new_store_item().oid); } TX_ONABORT { perror("transaction aborted y\n"); map_ctx_free(mapc); aborted = 1; } TX_END //updated_page_count = 0; } */ endCycles = getCycle(); totalCycles = endCycles - startCycles; double totTime = ((double)totalCycles)/2000000000; printf("TX/s %f\ntottime %f\n", nops/totTime, totTime);//RUN_COUNT/totTime, totTime); map_ctx_free(mapc); pmemobj_close(pop); return 0; }
11,362
23.38412
117
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/run.sh
#!/usr/bin/env bash sudo rm -rf /mnt/mem/* sudo ./data_store $1 /mnt/mem/map 10000 > out tx=$(grep "TX" out) tot=$(grep "tottime" out) grep "cp" out > time cp=$(awk '{sum+= $2;} END{print sum;}' time) echo $1$tx echo $1$tot echo $1'cp' $cp
242
17.692308
45
sh
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_rtree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * map_rtree.c -- common interface for maps */ #include <rtree_map.h> #include "map_rtree.h" /* * map_rtree_check -- wrapper for rtree_map_check */ static int map_rtree_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_check(pop, rtree_map); } /* * map_rtree_create -- wrapper for rtree_map_new */ static int map_rtree_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct rtree_map) *rtree_map = (TOID(struct rtree_map) *)map; return rtree_map_create(pop, rtree_map, arg); } /* * map_rtree_destroy -- wrapper for rtree_map_delete */ static int map_rtree_destroy(PMEMobjpool *pop, TOID(struct map) *map) { TOID(struct rtree_map) *rtree_map = (TOID(struct rtree_map) *)map; return rtree_map_destroy(pop, rtree_map); } /* * map_rtree_insert -- wrapper for rtree_map_insert */ static int map_rtree_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_insert(pop, rtree_map, (unsigned char *)&key, sizeof(key), value); } /* * map_rtree_insert_new -- wrapper for rtree_map_insert_new */ static int map_rtree_insert_new(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_insert_new(pop, rtree_map, (unsigned char *)&key, sizeof(key), size, type_num, constructor, arg); } /* * map_rtree_remove -- wrapper for rtree_map_remove */ static PMEMoid map_rtree_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_remove(pop, rtree_map, (unsigned char *)&key, sizeof(key)); } /* * map_rtree_remove_free -- wrapper for rtree_map_remove_free */ static int map_rtree_remove_free(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_remove_free(pop, rtree_map, (unsigned char *)&key, sizeof(key)); } /* * map_rtree_clear -- wrapper for rtree_map_clear */ static int map_rtree_clear(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_clear(pop, rtree_map); } /* * map_rtree_get -- wrapper for rtree_map_get */ static PMEMoid map_rtree_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_get(pop, rtree_map, (unsigned char *)&key, sizeof(key)); } /* * map_rtree_lookup -- wrapper for rtree_map_lookup */ static int map_rtree_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_lookup(pop, rtree_map, (unsigned char *)&key, sizeof(key)); } struct cb_arg2 { int (*cb)(uint64_t key, PMEMoid value, void *arg); void *arg; }; /* * map_rtree_foreach_cb -- wrapper for callback */ static int map_rtree_foreach_cb(const unsigned char *key, uint64_t key_size, PMEMoid value, void *arg2) { const struct cb_arg2 *const a2 = (const struct cb_arg2 *)arg2; const uint64_t *const k2 = (uint64_t *)key; return a2->cb(*k2, value, a2->arg); } /* * map_rtree_foreach -- wrapper for rtree_map_foreach */ static int map_rtree_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { struct cb_arg2 arg2 = {cb, arg}; TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_foreach(pop, rtree_map, map_rtree_foreach_cb, &arg2); } /* * map_rtree_is_empty -- wrapper for rtree_map_is_empty */ static int map_rtree_is_empty(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rtree_map) rtree_map; TOID_ASSIGN(rtree_map, map.oid); return rtree_map_is_empty(pop, rtree_map); } struct map_ops rtree_map_ops = { /* .check = */map_rtree_check, /* .create = */map_rtree_create, /* .destroy = */map_rtree_destroy, /* .init = */NULL, /* .insert = */map_rtree_insert, /* .insert_new = */map_rtree_insert_new, /* .remove = */map_rtree_remove, /* .remove_free = */map_rtree_remove_free, /* .clear = */map_rtree_clear, /* .get = */map_rtree_get, /* .lookup = */map_rtree_lookup, /* .foreach = */map_rtree_foreach, /* .is_empty = */map_rtree_is_empty, /* .count = */NULL, /* .cmd = */NULL, };
4,700
21.710145
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/mapcli.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ #include <ex_common.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <inttypes.h> #include <libpmemobj.h> #include "map.h" #include "map_ctree.h" #include "map_btree.h" #include "map_rtree.h" #include "map_rbtree.h" #include "map_hashmap_atomic.h" #include "map_hashmap_tx.h" #include "map_hashmap_rp.h" #include "map_skiplist.h" #include "hashmap/hashmap.h" #define PM_HASHSET_POOL_SIZE (160 * 1024 * 1024) int use_ndp_redo = 0; POBJ_LAYOUT_BEGIN(map); POBJ_LAYOUT_ROOT(map, struct root); POBJ_LAYOUT_END(map); struct root { TOID(struct map) map; }; static PMEMobjpool *pop; static struct map_ctx *mapc; static TOID(struct root) root; static TOID(struct map) map; /* * str_insert -- hs_insert wrapper which works on strings */ static void str_insert(const char *str) { uint64_t key; if (sscanf(str, "%" PRIu64, &key) > 0){ // double totaltime = 0; // for(int i=0;i<10;i++){ // clock_t start, end; // start = clock(); map_insert(mapc, map, key, OID_NULL); //map_insert(mapc, map, key + i , OID_NULL); // end = clock(); // totaltime += ((double) (end - start)) / CLOCKS_PER_SEC; // } // printf("TX/s = %f %f\n",1/totaltime, totaltime); } else fprintf(stderr, "insert: invalid syntax\n"); } /* * str_remove -- hs_remove wrapper which works on strings */ static void str_remove(const char *str) { uint64_t key; if (sscanf(str, "%" PRIu64, &key) > 0) { double totaltime = 0; for(int i=0;i<10000;i++){ clock_t start, end; start = clock(); int l = map_lookup(mapc, map, key); if (l) map_remove(mapc, map, key); else fprintf(stderr, "no such value\n"); end = clock(); totaltime += ((double) (end - start)) / CLOCKS_PER_SEC; } printf("TX/s = %f %f\n",10000/totaltime, totaltime); } else fprintf(stderr, "remove: invalid syntax\n"); } /* * str_check -- hs_check wrapper which works on strings */ static void str_check(const char *str) { uint64_t key; if (sscanf(str, "%" PRIu64, &key) > 0) { int r = map_lookup(mapc, map, key); printf("%d\n", r); } else { fprintf(stderr, "check: invalid syntax\n"); } } /* * str_insert_random -- inserts specified (as string) number of random numbers */ static void str_insert_random(const char *str) { uint64_t val; if (sscanf(str, "%" PRIu64, &val) > 0) for (uint64_t i = 0; i < val; ) { uint64_t r = ((uint64_t)rand()) << 32 | rand(); int ret = map_insert(mapc, map, r, OID_NULL); if (ret < 0) break; if (ret == 0) i += 1; } else fprintf(stderr, "random insert: invalid syntax\n"); } /* * rebuild -- rebuilds hashmap and measures execution time */ static void rebuild(void) { printf("rebuild "); fflush(stdout); time_t t1 = time(NULL); map_cmd(mapc, map, HASHMAP_CMD_REBUILD, 0); printf("%" PRIu64"s\n", (uint64_t)(time(NULL) - t1)); } /* * str_rebuild -- hs_rebuild wrapper which executes specified number of times */ static void str_rebuild(const char *str) { uint64_t val; if (sscanf(str, "%" PRIu64, &val) > 0) { for (uint64_t i = 0; i < val; ++i) { printf("%2" PRIu64 " ", i); rebuild(); } } else { rebuild(); } } static void help(void) { printf("h - help\n"); printf("i $value - insert $value\n"); printf("r $value - remove $value\n"); printf("c $value - check $value, returns 0/1\n"); printf("n $value - insert $value random values\n"); printf("p - print all values\n"); printf("d - print debug info\n"); printf("b [$value] - rebuild $value (default: 1) times\n"); printf("q - quit\n"); } static void unknown_command(const char *str) { fprintf(stderr, "unknown command '%c', use 'h' for help\n", str[0]); } static int hashmap_print(uint64_t key, PMEMoid value, void *arg) { printf("%" PRIu64 " ", key); return 0; } static void print_all(void) { if (mapc->ops->count) printf("count: %zu\n", map_count(mapc, map)); map_foreach(mapc, map, hashmap_print, NULL); printf("\n"); } #define INPUT_BUF_LEN 1000 int main(int argc, char *argv[]) { if (argc < 3 || argc > 4) { printf("usage: %s " "hashmap_tx|hashmap_atomic|hashmap_rp|" "ctree|btree|rtree|rbtree|skiplist" " file-name [<seed>]\n", argv[0]); return 1; } const struct map_ops *ops = NULL; const char *path = argv[2]; const char *type = argv[1]; if (strcmp(type, "hashmap_tx") == 0) { ops = MAP_HASHMAP_TX; } else if (strcmp(type, "hashmap_atomic") == 0) { ops = MAP_HASHMAP_ATOMIC; } else if (strcmp(type, "hashmap_rp") == 0) { ops = MAP_HASHMAP_RP; } else if (strcmp(type, "ctree") == 0) { ops = MAP_CTREE; } else if (strcmp(type, "btree") == 0) { ops = MAP_BTREE; } else if (strcmp(type, "rtree") == 0) { ops = MAP_RTREE; } else if (strcmp(type, "rbtree") == 0) { ops = MAP_RBTREE; } else if (strcmp(type, "skiplist") == 0) { ops = MAP_SKIPLIST; } else { fprintf(stderr, "invalid container type -- '%s'\n", type); return 1; } if (file_exists(path) != 0) { pop = pmemobj_create(path, POBJ_LAYOUT_NAME(map), PM_HASHSET_POOL_SIZE, CREATE_MODE_RW); if (pop == NULL) { fprintf(stderr, "failed to create pool: %s\n", pmemobj_errormsg()); return 1; } struct hashmap_args args; if (argc > 3) args.seed = atoi(argv[3]); else args.seed = (uint32_t)time(NULL); srand(args.seed); mapc = map_ctx_init(ops, pop); if (!mapc) { pmemobj_close(pop); perror("map_ctx_init"); return 1; } root = POBJ_ROOT(pop, struct root); printf("seed: %u\n", args.seed); map_create(mapc, &D_RW(root)->map, &args); map = D_RO(root)->map; } else { pop = pmemobj_open(path, POBJ_LAYOUT_NAME(map)); if (pop == NULL) { fprintf(stderr, "failed to open pool: %s\n", pmemobj_errormsg()); return 1; } mapc = map_ctx_init(ops, pop); if (!mapc) { pmemobj_close(pop); perror("map_ctx_init"); return 1; } root = POBJ_ROOT(pop, struct root); map = D_RO(root)->map; } char buf[INPUT_BUF_LEN]; if (isatty(fileno(stdout))) printf("Type 'h' for help\n$ "); while (fgets(buf, sizeof(buf), stdin)) { if (buf[0] == 0 || buf[0] == '\n') continue; switch (buf[0]) { case 'i': str_insert(buf + 1); break; case 'r': str_remove(buf + 1); break; case 'c': str_check(buf + 1); break; case 'n': str_insert_random(buf + 1); break; case 'p': print_all(); break; case 'd': map_cmd(mapc, map, HASHMAP_CMD_DEBUG, (uint64_t)stdout); break; case 'b': str_rebuild(buf + 1); break; case 'q': fclose(stdin); break; case 'h': help(); break; default: unknown_command(buf); break; } if (isatty(fileno(stdout))) printf("$ "); } map_ctx_free(mapc); pmemobj_close(pop); return 0; }
6,831
19.516517
78
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_rp.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018, Intel Corporation */ /* * map_hashmap_rp.c -- common interface for maps */ #include <map.h> #include <hashmap_rp.h> #include "map_hashmap_rp.h" /* * map_hm_rp_check -- wrapper for hm_rp_check */ static int map_hm_rp_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_check(pop, hashmap_rp); } /* * map_hm_rp_count -- wrapper for hm_rp_count */ static size_t map_hm_rp_count(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_count(pop, hashmap_rp); } /* * map_hm_rp_init -- wrapper for hm_rp_init */ static int map_hm_rp_init(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_init(pop, hashmap_rp); } /* * map_hm_rp_create -- wrapper for hm_rp_create */ static int map_hm_rp_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct hashmap_rp) *hashmap_rp = (TOID(struct hashmap_rp) *)map; return hm_rp_create(pop, hashmap_rp, arg); } /* * map_hm_rp_insert -- wrapper for hm_rp_insert */ static int map_hm_rp_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_insert(pop, hashmap_rp, key, value); } /* * map_hm_rp_remove -- wrapper for hm_rp_remove */ static PMEMoid map_hm_rp_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_remove(pop, hashmap_rp, key); } /* * map_hm_rp_get -- wrapper for hm_rp_get */ static PMEMoid map_hm_rp_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_get(pop, hashmap_rp, key); } /* * map_hm_rp_lookup -- wrapper for hm_rp_lookup */ static int map_hm_rp_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_lookup(pop, hashmap_rp, key); } /* * map_hm_rp_foreach -- wrapper for hm_rp_foreach */ static int map_hm_rp_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_foreach(pop, hashmap_rp, cb, arg); } /* * map_hm_rp_cmd -- wrapper for hm_rp_cmd */ static int map_hm_rp_cmd(PMEMobjpool *pop, TOID(struct map) map, unsigned cmd, uint64_t arg) { TOID(struct hashmap_rp) hashmap_rp; TOID_ASSIGN(hashmap_rp, map.oid); return hm_rp_cmd(pop, hashmap_rp, cmd, arg); } struct map_ops hashmap_rp_ops = { /* .check = */ map_hm_rp_check, /* .create = */ map_hm_rp_create, /* .destroy = */ NULL, /* .init = */ map_hm_rp_init, /* .insert = */ map_hm_rp_insert, /* .insert_new = */ NULL, /* .remove = */ map_hm_rp_remove, /* .remove_free = */ NULL, /* .clear = */ NULL, /* .get = */ map_hm_rp_get, /* .lookup = */ map_hm_rp_lookup, /* .foreach = */ map_hm_rp_foreach, /* .is_empty = */ NULL, /* .count = */ map_hm_rp_count, /* .cmd = */ map_hm_rp_cmd, };
3,315
20.532468
70
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/hashmap_tx.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* integer hash set implementation which uses only transaction APIs */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <inttypes.h> #include <libpmemobj.h> #include "hashmap_tx.h" #include "hashmap_internal.h" /* layout definition */ TOID_DECLARE(struct buckets, HASHMAP_TX_TYPE_OFFSET + 1); TOID_DECLARE(struct entry, HASHMAP_TX_TYPE_OFFSET + 2); struct entry { uint64_t key; PMEMoid value; /* next entry list pointer */ TOID(struct entry) next; }; struct buckets { /* number of buckets */ size_t nbuckets; /* array of lists */ TOID(struct entry) bucket[]; }; struct hashmap_tx { /* random number generator seed */ uint32_t seed; /* hash function coefficients */ uint32_t hash_fun_a; uint32_t hash_fun_b; uint64_t hash_fun_p; /* number of values inserted */ uint64_t count; /* buckets */ TOID(struct buckets) buckets; }; /* * create_hashmap -- hashmap initializer */ static void create_hashmap(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint32_t seed) { size_t len = INIT_BUCKETS_NUM; size_t sz = sizeof(struct buckets) + len * sizeof(TOID(struct entry)); TX_BEGIN(pop) { TX_ADD(hashmap); D_RW(hashmap)->seed = seed; do { D_RW(hashmap)->hash_fun_a = (uint32_t)rand(); } while (D_RW(hashmap)->hash_fun_a == 0); D_RW(hashmap)->hash_fun_b = (uint32_t)rand(); D_RW(hashmap)->hash_fun_p = HASH_FUNC_COEFF_P; D_RW(hashmap)->buckets = TX_ZALLOC(struct buckets, sz); D_RW(D_RW(hashmap)->buckets)->nbuckets = len; } TX_ONABORT { fprintf(stderr, "%s: transaction aborted: %s\n", __func__, pmemobj_errormsg()); abort(); } TX_END } /* * hash -- the simplest hashing function, * see https://en.wikipedia.org/wiki/Universal_hashing#Hashing_integers */ static uint64_t hash(const TOID(struct hashmap_tx) *hashmap, const TOID(struct buckets) *buckets, uint64_t value) { uint32_t a = D_RO(*hashmap)->hash_fun_a; uint32_t b = D_RO(*hashmap)->hash_fun_b; uint64_t p = D_RO(*hashmap)->hash_fun_p; size_t len = D_RO(*buckets)->nbuckets; return ((a * value + b) % p) % len; } /* * hm_tx_rebuild -- rebuilds the hashmap with a new number of buckets */ static void hm_tx_rebuild(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, size_t new_len) { TOID(struct buckets) buckets_old = D_RO(hashmap)->buckets; if (new_len == 0) new_len = D_RO(buckets_old)->nbuckets; size_t sz_old = sizeof(struct buckets) + D_RO(buckets_old)->nbuckets * sizeof(TOID(struct entry)); size_t sz_new = sizeof(struct buckets) + new_len * sizeof(TOID(struct entry)); TX_BEGIN(pop) { TX_ADD_FIELD(hashmap, buckets); TOID(struct buckets) buckets_new = TX_ZALLOC(struct buckets, sz_new); D_RW(buckets_new)->nbuckets = new_len; pmemobj_tx_add_range(buckets_old.oid, 0, sz_old); for (size_t i = 0; i < D_RO(buckets_old)->nbuckets; ++i) { while (!TOID_IS_NULL(D_RO(buckets_old)->bucket[i])) { TOID(struct entry) en = D_RO(buckets_old)->bucket[i]; uint64_t h = hash(&hashmap, &buckets_new, D_RO(en)->key); D_RW(buckets_old)->bucket[i] = D_RO(en)->next; TX_ADD_FIELD(en, next); D_RW(en)->next = D_RO(buckets_new)->bucket[h]; D_RW(buckets_new)->bucket[h] = en; } } D_RW(hashmap)->buckets = buckets_new; TX_FREE(buckets_old); } TX_ONABORT { fprintf(stderr, "%s: transaction aborted: %s\n", __func__, pmemobj_errormsg()); /* * We don't need to do anything here, because everything is * consistent. The only thing affected is performance. */ } TX_END } /* * hm_tx_insert -- inserts specified value into the hashmap, * returns: * - 0 if successful, * - 1 if value already existed, * - -1 if something bad happened */ int hm_tx_insert(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key, PMEMoid value) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); int num = 0; for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) { if (D_RO(var)->key == key) return 1; num++; } int ret = 0; TX_BEGIN(pop) { TX_ADD_FIELD(D_RO(hashmap)->buckets, bucket[h]); TX_ADD_FIELD(hashmap, count); TOID(struct entry) e = TX_NEW(struct entry); D_RW(e)->key = key; D_RW(e)->value = value; D_RW(e)->next = D_RO(buckets)->bucket[h]; D_RW(buckets)->bucket[h] = e; D_RW(hashmap)->count++; num++; } TX_ONABORT { fprintf(stderr, "transaction aborted: %s\n", pmemobj_errormsg()); ret = -1; } TX_END if (ret) return ret; if (num > MAX_HASHSET_THRESHOLD || (num > MIN_HASHSET_THRESHOLD && D_RO(hashmap)->count > 2 * D_RO(buckets)->nbuckets)) hm_tx_rebuild(pop, hashmap, D_RO(buckets)->nbuckets * 2); return 0; } /* * hm_tx_remove -- removes specified value from the hashmap, * returns: * - key's value if successful, * - OID_NULL if value didn't exist or if something bad happened */ PMEMoid hm_tx_remove(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var, prev = TOID_NULL(struct entry); uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); prev = var, var = D_RO(var)->next) { if (D_RO(var)->key == key) break; } if (TOID_IS_NULL(var)) return OID_NULL; int ret = 0; PMEMoid retoid = D_RO(var)->value; TX_BEGIN(pop) { if (TOID_IS_NULL(prev)) TX_ADD_FIELD(D_RO(hashmap)->buckets, bucket[h]); else TX_ADD_FIELD(prev, next); TX_ADD_FIELD(hashmap, count); if (TOID_IS_NULL(prev)) D_RW(buckets)->bucket[h] = D_RO(var)->next; else D_RW(prev)->next = D_RO(var)->next; D_RW(hashmap)->count--; TX_FREE(var); } TX_ONABORT { fprintf(stderr, "transaction aborted: %s\n", pmemobj_errormsg()); ret = -1; } TX_END if (ret) return OID_NULL; if (D_RO(hashmap)->count < D_RO(buckets)->nbuckets) hm_tx_rebuild(pop, hashmap, D_RO(buckets)->nbuckets / 2); return retoid; } /* * hm_tx_foreach -- prints all values from the hashmap */ int hm_tx_foreach(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; int ret = 0; for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) { if (TOID_IS_NULL(D_RO(buckets)->bucket[i])) continue; for (var = D_RO(buckets)->bucket[i]; !TOID_IS_NULL(var); var = D_RO(var)->next) { ret = cb(D_RO(var)->key, D_RO(var)->value, arg); if (ret) break; } } return ret; } /* * hm_tx_debug -- prints complete hashmap state */ static void hm_tx_debug(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, FILE *out) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; fprintf(out, "a: %u b: %u p: %" PRIu64 "\n", D_RO(hashmap)->hash_fun_a, D_RO(hashmap)->hash_fun_b, D_RO(hashmap)->hash_fun_p); fprintf(out, "count: %" PRIu64 ", buckets: %zu\n", D_RO(hashmap)->count, D_RO(buckets)->nbuckets); for (size_t i = 0; i < D_RO(buckets)->nbuckets; ++i) { if (TOID_IS_NULL(D_RO(buckets)->bucket[i])) continue; int num = 0; fprintf(out, "%zu: ", i); for (var = D_RO(buckets)->bucket[i]; !TOID_IS_NULL(var); var = D_RO(var)->next) { fprintf(out, "%" PRIu64 " ", D_RO(var)->key); num++; } fprintf(out, "(%d)\n", num); } } /* * hm_tx_get -- checks whether specified value is in the hashmap */ PMEMoid hm_tx_get(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) if (D_RO(var)->key == key) return D_RO(var)->value; return OID_NULL; } /* * hm_tx_lookup -- checks whether specified value exists */ int hm_tx_lookup(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, uint64_t key) { TOID(struct buckets) buckets = D_RO(hashmap)->buckets; TOID(struct entry) var; uint64_t h = hash(&hashmap, &buckets, key); for (var = D_RO(buckets)->bucket[h]; !TOID_IS_NULL(var); var = D_RO(var)->next) if (D_RO(var)->key == key) return 1; return 0; } /* * hm_tx_count -- returns number of elements */ size_t hm_tx_count(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { return D_RO(hashmap)->count; } /* * hm_tx_init -- recovers hashmap state, called after pmemobj_open */ int hm_tx_init(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { srand(D_RO(hashmap)->seed); return 0; } /* * hm_tx_create -- allocates new hashmap */ int hm_tx_create(PMEMobjpool *pop, TOID(struct hashmap_tx) *map, void *arg) { struct hashmap_args *args = (struct hashmap_args *)arg; int ret = 0; TX_BEGIN(pop) { TX_ADD_DIRECT(map); *map = TX_ZNEW(struct hashmap_tx); uint32_t seed = args ? args->seed : 0; create_hashmap(pop, *map, seed); } TX_ONABORT { ret = -1; } TX_END return ret; } /* * hm_tx_check -- checks if specified persistent object is an * instance of hashmap */ int hm_tx_check(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap) { return TOID_IS_NULL(hashmap) || !TOID_VALID(hashmap); } /* * hm_tx_cmd -- execute cmd for hashmap */ int hm_tx_cmd(PMEMobjpool *pop, TOID(struct hashmap_tx) hashmap, unsigned cmd, uint64_t arg) { switch (cmd) { case HASHMAP_CMD_REBUILD: hm_tx_rebuild(pop, hashmap, arg); return 0; case HASHMAP_CMD_DEBUG: if (!arg) return -EINVAL; hm_tx_debug(pop, hashmap, (FILE *)arg); return 0; default: return -EINVAL; } }
9,692
22.078571
80
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_skiplist.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016, Intel Corporation */ /* * map_skiplist.c -- common interface for maps */ #include <map.h> #include <skiplist_map.h> #include "map_skiplist.h" /* * map_skiplist_check -- wrapper for skiplist_map_check */ static int map_skiplist_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_check(pop, skiplist_map); } /* * map_skiplist_create -- wrapper for skiplist_map_new */ static int map_skiplist_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct skiplist_map_node) *skiplist_map = (TOID(struct skiplist_map_node) *)map; return skiplist_map_create(pop, skiplist_map, arg); } /* * map_skiplist_destroy -- wrapper for skiplist_map_delete */ static int map_skiplist_destroy(PMEMobjpool *pop, TOID(struct map) *map) { TOID(struct skiplist_map_node) *skiplist_map = (TOID(struct skiplist_map_node) *)map; return skiplist_map_destroy(pop, skiplist_map); } /* * map_skiplist_insert -- wrapper for skiplist_map_insert */ static int map_skiplist_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_insert(pop, skiplist_map, key, value); } /* * map_skiplist_insert_new -- wrapper for skiplist_map_insert_new */ static int map_skiplist_insert_new(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_insert_new(pop, skiplist_map, key, size, type_num, constructor, arg); } /* * map_skiplist_remove -- wrapper for skiplist_map_remove */ static PMEMoid map_skiplist_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_remove(pop, skiplist_map, key); } /* * map_skiplist_remove_free -- wrapper for skiplist_map_remove_free */ static int map_skiplist_remove_free(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_remove_free(pop, skiplist_map, key); } /* * map_skiplist_clear -- wrapper for skiplist_map_clear */ static int map_skiplist_clear(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_clear(pop, skiplist_map); } /* * map_skiplist_get -- wrapper for skiplist_map_get */ static PMEMoid map_skiplist_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_get(pop, skiplist_map, key); } /* * map_skiplist_lookup -- wrapper for skiplist_map_lookup */ static int map_skiplist_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_lookup(pop, skiplist_map, key); } /* * map_skiplist_foreach -- wrapper for skiplist_map_foreach */ static int map_skiplist_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_foreach(pop, skiplist_map, cb, arg); } /* * map_skiplist_is_empty -- wrapper for skiplist_map_is_empty */ static int map_skiplist_is_empty(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct skiplist_map_node) skiplist_map; TOID_ASSIGN(skiplist_map, map.oid); return skiplist_map_is_empty(pop, skiplist_map); } struct map_ops skiplist_map_ops = { /* .check = */ map_skiplist_check, /* .create = */ map_skiplist_create, /* .destroy = */ map_skiplist_destroy, /* .init = */ NULL, /* .insert = */ map_skiplist_insert, /* .insert_new = */ map_skiplist_insert_new, /* .remove = */ map_skiplist_remove, /* .remove_free = */ map_skiplist_remove_free, /* .clear = */ map_skiplist_clear, /* .get = */ map_skiplist_get, /* .lookup = */ map_skiplist_lookup, /* .foreach = */ map_skiplist_foreach, /* .is_empty = */ map_skiplist_is_empty, /* .count = */ NULL, /* .cmd = */ NULL, };
4,488
23.664835
78
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_tx.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map_hashmap_tx.h -- common interface for maps */ #ifndef MAP_HASHMAP_TX_H #define MAP_HASHMAP_TX_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops hashmap_tx_ops; #define MAP_HASHMAP_TX (&hashmap_tx_ops) #ifdef __cplusplus } #endif #endif /* MAP_HASHMAP_TX_H */
393
14.153846
48
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_rbtree.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map_rbtree.h -- common interface for maps */ #ifndef MAP_RBTREE_H #define MAP_RBTREE_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops rbtree_map_ops; #define MAP_RBTREE (&rbtree_map_ops) #ifdef __cplusplus } #endif #endif /* MAP_RBTREE_H */
373
13.384615
44
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_ctree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map_ctree.c -- common interface for maps */ #include <map.h> #include <ctree_map.h> #include "map_ctree.h" /* * map_ctree_check -- wrapper for ctree_map_check */ static int map_ctree_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_check(pop, ctree_map); } /* * map_ctree_create -- wrapper for ctree_map_create */ static int map_ctree_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct ctree_map) *ctree_map = (TOID(struct ctree_map) *)map; return ctree_map_create(pop, ctree_map, arg); } /* * map_ctree_destroy -- wrapper for ctree_map_destroy */ static int map_ctree_destroy(PMEMobjpool *pop, TOID(struct map) *map) { TOID(struct ctree_map) *ctree_map = (TOID(struct ctree_map) *)map; return ctree_map_destroy(pop, ctree_map); } /* * map_ctree_insert -- wrapper for ctree_map_insert */ static int map_ctree_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_insert(pop, ctree_map, key, value); } /* * map_ctree_insert_new -- wrapper for ctree_map_insert_new */ static int map_ctree_insert_new(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_insert_new(pop, ctree_map, key, size, type_num, constructor, arg); } /* * map_ctree_remove -- wrapper for ctree_map_remove */ static PMEMoid map_ctree_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_remove(pop, ctree_map, key); } /* * map_ctree_remove_free -- wrapper for ctree_map_remove_free */ static int map_ctree_remove_free(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_remove_free(pop, ctree_map, key); } /* * map_ctree_clear -- wrapper for ctree_map_clear */ static int map_ctree_clear(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_clear(pop, ctree_map); } /* * map_ctree_get -- wrapper for ctree_map_get */ static PMEMoid map_ctree_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_get(pop, ctree_map, key); } /* * map_ctree_lookup -- wrapper for ctree_map_lookup */ static int map_ctree_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_lookup(pop, ctree_map, key); } /* * map_ctree_foreach -- wrapper for ctree_map_foreach */ static int map_ctree_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_foreach(pop, ctree_map, cb, arg); } /* * map_ctree_is_empty -- wrapper for ctree_map_is_empty */ static int map_ctree_is_empty(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct ctree_map) ctree_map; TOID_ASSIGN(ctree_map, map.oid); return ctree_map_is_empty(pop, ctree_map); } struct map_ops ctree_map_ops = { /* .check = */ map_ctree_check, /* .create = */ map_ctree_create, /* .destroy = */ map_ctree_destroy, /* .init = */ NULL, /* .insert = */ map_ctree_insert, /* .insert_new = */ map_ctree_insert_new, /* .remove = */ map_ctree_remove, /* .remove_free = */ map_ctree_remove_free, /* .clear = */ map_ctree_clear, /* .get = */ map_ctree_get, /* .lookup = */ map_ctree_lookup, /* .foreach = */ map_ctree_foreach, /* .is_empty = */ map_ctree_is_empty, /* .count = */ NULL, /* .cmd = */ NULL, };
4,091
21.483516
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_btree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map_btree.c -- common interface for maps */ #include <map.h> #include <btree_map.h> #include "map_btree.h" /* * map_btree_check -- wrapper for btree_map_check */ static int map_btree_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_check(pop, btree_map); } /* * map_btree_create -- wrapper for btree_map_create */ static int map_btree_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct btree_map) *btree_map = (TOID(struct btree_map) *)map; return btree_map_create(pop, btree_map, arg); } /* * map_btree_destroy -- wrapper for btree_map_destroy */ static int map_btree_destroy(PMEMobjpool *pop, TOID(struct map) *map) { TOID(struct btree_map) *btree_map = (TOID(struct btree_map) *)map; return btree_map_destroy(pop, btree_map); } /* * map_btree_insert -- wrapper for btree_map_insert */ static int map_btree_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_insert(pop, btree_map, key, value); } /* * map_btree_insert_new -- wrapper for btree_map_insert_new */ static int map_btree_insert_new(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_insert_new(pop, btree_map, key, size, type_num, constructor, arg); } /* * map_btree_remove -- wrapper for btree_map_remove */ static PMEMoid map_btree_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_remove(pop, btree_map, key); } /* * map_btree_remove_free -- wrapper for btree_map_remove_free */ static int map_btree_remove_free(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_remove_free(pop, btree_map, key); } /* * map_btree_clear -- wrapper for btree_map_clear */ static int map_btree_clear(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_clear(pop, btree_map); } /* * map_btree_get -- wrapper for btree_map_get */ static PMEMoid map_btree_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_get(pop, btree_map, key); } /* * map_btree_lookup -- wrapper for btree_map_lookup */ static int map_btree_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_lookup(pop, btree_map, key); } /* * map_btree_foreach -- wrapper for btree_map_foreach */ static int map_btree_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_foreach(pop, btree_map, cb, arg); } /* * map_btree_is_empty -- wrapper for btree_map_is_empty */ static int map_btree_is_empty(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct btree_map) btree_map; TOID_ASSIGN(btree_map, map.oid); return btree_map_is_empty(pop, btree_map); } struct map_ops btree_map_ops = { /* .check = */ map_btree_check, /* .create = */ map_btree_create, /* .destroy = */ map_btree_destroy, /* .init = */ NULL, /* .insert = */ map_btree_insert, /* .insert_new = */ map_btree_insert_new, /* .remove = */ map_btree_remove, /* .remove_free = */ map_btree_remove_free, /* .clear = */ map_btree_clear, /* .get = */ map_btree_get, /* .lookup = */ map_btree_lookup, /* .foreach = */ map_btree_foreach, /* .is_empty = */ map_btree_is_empty, /* .count = */ NULL, /* .cmd = */ NULL, };
4,091
21.483516
75
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map.c -- common interface for maps */ #include <stdlib.h> #include <stdio.h> #include <libpmemobj.h> #include "map.h" #define ABORT_NOT_IMPLEMENTED(mapc, func)\ if ((mapc)->ops->func == NULL) {\ fprintf(stderr, "error: '%s'"\ " function not implemented\n", #func);\ exit(1);\ } /* * map_ctx_init -- initialize map context */ struct map_ctx * map_ctx_init(const struct map_ops *ops, PMEMobjpool *pop) { if (!ops) return NULL; struct map_ctx *mapc = (struct map_ctx *)calloc(1, sizeof(*mapc)); if (!mapc) return NULL; mapc->ops = ops; mapc->pop = pop; return mapc; } /* * map_ctx_free -- free map context */ void map_ctx_free(struct map_ctx *mapc) { free(mapc); } /* * map_create -- create new map */ int map_create(struct map_ctx *mapc, TOID(struct map) *map, void *arg) { ABORT_NOT_IMPLEMENTED(mapc, create); return mapc->ops->create(mapc->pop, map, arg); } /* * map_destroy -- free the map */ int map_destroy(struct map_ctx *mapc, TOID(struct map) *map) { ABORT_NOT_IMPLEMENTED(mapc, destroy); return mapc->ops->destroy(mapc->pop, map); } /* * map_init -- initialize map */ int map_init(struct map_ctx *mapc, TOID(struct map) map) { ABORT_NOT_IMPLEMENTED(mapc, init); return mapc->ops->init(mapc->pop, map); } /* * map_check -- check if persistent object is a valid map object */ int map_check(struct map_ctx *mapc, TOID(struct map) map) { ABORT_NOT_IMPLEMENTED(mapc, check); return mapc->ops->check(mapc->pop, map); } /* * map_insert -- insert key value pair */ int map_insert(struct map_ctx *mapc, TOID(struct map) map, uint64_t key, PMEMoid value) { ABORT_NOT_IMPLEMENTED(mapc, insert); return mapc->ops->insert(mapc->pop, map, key, value); } /* * map_insert_new -- allocate and insert key value pair */ int map_insert_new(struct map_ctx *mapc, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { ABORT_NOT_IMPLEMENTED(mapc, insert_new); return mapc->ops->insert_new(mapc->pop, map, key, size, type_num, constructor, arg); } /* * map_remove -- remove key value pair */ PMEMoid map_remove(struct map_ctx *mapc, TOID(struct map) map, uint64_t key) { ABORT_NOT_IMPLEMENTED(mapc, remove); return mapc->ops->remove(mapc->pop, map, key); } /* * map_remove_free -- remove and free key value pair */ int map_remove_free(struct map_ctx *mapc, TOID(struct map) map, uint64_t key) { ABORT_NOT_IMPLEMENTED(mapc, remove_free); return mapc->ops->remove_free(mapc->pop, map, key); } /* * map_clear -- remove all key value pairs from map */ int map_clear(struct map_ctx *mapc, TOID(struct map) map) { ABORT_NOT_IMPLEMENTED(mapc, clear); return mapc->ops->clear(mapc->pop, map); } /* * map_get -- get value of specified key */ PMEMoid map_get(struct map_ctx *mapc, TOID(struct map) map, uint64_t key) { ABORT_NOT_IMPLEMENTED(mapc, get); return mapc->ops->get(mapc->pop, map, key); } /* * map_lookup -- check if specified key exists in map */ int map_lookup(struct map_ctx *mapc, TOID(struct map) map, uint64_t key) { ABORT_NOT_IMPLEMENTED(mapc, lookup); return mapc->ops->lookup(mapc->pop, map, key); } /* * map_foreach -- iterate through all key value pairs in a map */ int map_foreach(struct map_ctx *mapc, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { ABORT_NOT_IMPLEMENTED(mapc, foreach); return mapc->ops->foreach(mapc->pop, map, cb, arg); } /* * map_is_empty -- check if map is empty */ int map_is_empty(struct map_ctx *mapc, TOID(struct map) map) { ABORT_NOT_IMPLEMENTED(mapc, is_empty); return mapc->ops->is_empty(mapc->pop, map); } /* * map_count -- get number of key value pairs in map */ size_t map_count(struct map_ctx *mapc, TOID(struct map) map) { ABORT_NOT_IMPLEMENTED(mapc, count); return mapc->ops->count(mapc->pop, map); } /* * map_cmd -- execute command specific for map type */ int map_cmd(struct map_ctx *mapc, TOID(struct map) map, unsigned cmd, uint64_t arg) { ABORT_NOT_IMPLEMENTED(mapc, cmd); return mapc->ops->cmd(mapc->pop, map, cmd, arg); }
4,200
19.593137
79
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_hashmap_atomic.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map_hashmap_atomic.c -- common interface for maps */ #include <map.h> #include <hashmap_atomic.h> #include "map_hashmap_atomic.h" /* * map_hm_atomic_check -- wrapper for hm_atomic_check */ static int map_hm_atomic_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_check(pop, hashmap_atomic); } /* * map_hm_atomic_count -- wrapper for hm_atomic_count */ static size_t map_hm_atomic_count(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_count(pop, hashmap_atomic); } /* * map_hm_atomic_init -- wrapper for hm_atomic_init */ static int map_hm_atomic_init(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_init(pop, hashmap_atomic); } /* * map_hm_atomic_new -- wrapper for hm_atomic_create */ static int map_hm_atomic_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct hashmap_atomic) *hashmap_atomic = (TOID(struct hashmap_atomic) *)map; return hm_atomic_create(pop, hashmap_atomic, arg); } /* * map_hm_atomic_insert -- wrapper for hm_atomic_insert */ static int map_hm_atomic_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_insert(pop, hashmap_atomic, key, value); } /* * map_hm_atomic_remove -- wrapper for hm_atomic_remove */ static PMEMoid map_hm_atomic_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_remove(pop, hashmap_atomic, key); } /* * map_hm_atomic_get -- wrapper for hm_atomic_get */ static PMEMoid map_hm_atomic_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_get(pop, hashmap_atomic, key); } /* * map_hm_atomic_lookup -- wrapper for hm_atomic_lookup */ static int map_hm_atomic_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_lookup(pop, hashmap_atomic, key); } /* * map_hm_atomic_foreach -- wrapper for hm_atomic_foreach */ static int map_hm_atomic_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_foreach(pop, hashmap_atomic, cb, arg); } /* * map_hm_atomic_cmd -- wrapper for hm_atomic_cmd */ static int map_hm_atomic_cmd(PMEMobjpool *pop, TOID(struct map) map, unsigned cmd, uint64_t arg) { TOID(struct hashmap_atomic) hashmap_atomic; TOID_ASSIGN(hashmap_atomic, map.oid); return hm_atomic_cmd(pop, hashmap_atomic, cmd, arg); } struct map_ops hashmap_atomic_ops = { /* .check = */ map_hm_atomic_check, /* .create = */ map_hm_atomic_create, /* .destroy = */ NULL, /* .init = */ map_hm_atomic_init, /* .insert = */ map_hm_atomic_insert, /* .insert_new = */ NULL, /* .remove = */ map_hm_atomic_remove, /* .remove_free = */ NULL, /* .clear = */ NULL, /* .get = */ map_hm_atomic_get, /* .lookup = */ map_hm_atomic_lookup, /* .foreach = */ map_hm_atomic_foreach, /* .is_empty = */ NULL, /* .count = */ map_hm_atomic_count, /* .cmd = */ map_hm_atomic_cmd, };
3,693
22.987013
74
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/kv_protocol.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2016, Intel Corporation */ /* * kv_protocol.h -- kv store text protocol */ #ifndef KV_PROTOCOL_H #define KV_PROTOCOL_H #include <stdint.h> #define MAX_KEY_LEN 255 /* * All client messages must start with a valid message token and be terminated * by a newline character ('\n'). The message parser is case-sensitive. * * Server responds with newline terminated string literals. * If invalid message token is received RESP_MSG_UNKNOWN is sent. */ enum kv_cmsg { /* * INSERT client message * Syntax: INSERT [key] [value]\n * * The key is limited to 255 characters, the size of a value is limited * by the pmemobj maximum allocation size (~16 gigabytes). * * Operation adds a new key value pair to the map. * Returns RESP_MSG_SUCCESS if successful or RESP_MSG_FAIL otherwise. */ CMSG_INSERT, /* * REMOVE client message * Syntax: REMOVE [key]\n * * Operation removes a key value pair from the map. * Returns RESP_MSG_SUCCESS if successful or RESP_MSG_FAIL otherwise. */ CMSG_REMOVE, /* * GET client message * Syntax: GET [key]\n * * Operation retrieves a key value pair from the map. * Returns the value if found or RESP_MSG_NULL otherwise. */ CMSG_GET, /* * BYE client message * Syntax: BYE\n * * Operation terminates the client connection. * No return value. */ CMSG_BYE, /* * KILL client message * Syntax: KILL\n * * Operation terminates the client connection and gracefully shutdowns * the server. * No return value. */ CMSG_KILL, MAX_CMSG }; enum resp_messages { RESP_MSG_SUCCESS, RESP_MSG_FAIL, RESP_MSG_NULL, RESP_MSG_UNKNOWN, MAX_RESP_MSG }; static const char *resp_msg[MAX_RESP_MSG] = { [RESP_MSG_SUCCESS] = "SUCCESS\n", [RESP_MSG_FAIL] = "FAIL\n", [RESP_MSG_NULL] = "NULL\n", [RESP_MSG_UNKNOWN] = "UNKNOWN\n" }; static const char *kv_cmsg_token[MAX_CMSG] = { [CMSG_INSERT] = "INSERT", [CMSG_REMOVE] = "REMOVE", [CMSG_GET] = "GET", [CMSG_BYE] = "BYE", [CMSG_KILL] = "KILL" }; #endif /* KV_PROTOCOL_H */
2,082
19.623762
78
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_ctree.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2018, Intel Corporation */ /* * map_ctree.h -- common interface for maps */ #ifndef MAP_CTREE_H #define MAP_CTREE_H #include "map.h" #ifdef __cplusplus extern "C" { #endif extern struct map_ops ctree_map_ops; #define MAP_CTREE (&ctree_map_ops) #ifdef __cplusplus } #endif #endif /* MAP_CTREE_H */
366
13.115385
44
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/map/map_rbtree.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * map_rbtree.c -- common interface for maps */ #include <map.h> #include <rbtree_map.h> #include "map_rbtree.h" /* * map_rbtree_check -- wrapper for rbtree_map_check */ static int map_rbtree_check(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_check(pop, rbtree_map); } /* * map_rbtree_create -- wrapper for rbtree_map_new */ static int map_rbtree_create(PMEMobjpool *pop, TOID(struct map) *map, void *arg) { TOID(struct rbtree_map) *rbtree_map = (TOID(struct rbtree_map) *)map; return rbtree_map_create(pop, rbtree_map, arg); } /* * map_rbtree_destroy -- wrapper for rbtree_map_delete */ static int map_rbtree_destroy(PMEMobjpool *pop, TOID(struct map) *map) { TOID(struct rbtree_map) *rbtree_map = (TOID(struct rbtree_map) *)map; return rbtree_map_destroy(pop, rbtree_map); } /* * map_rbtree_insert -- wrapper for rbtree_map_insert */ static int map_rbtree_insert(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, PMEMoid value) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_insert(pop, rbtree_map, key, value); } /* * map_rbtree_insert_new -- wrapper for rbtree_map_insert_new */ static int map_rbtree_insert_new(PMEMobjpool *pop, TOID(struct map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_insert_new(pop, rbtree_map, key, size, type_num, constructor, arg); } /* * map_rbtree_remove -- wrapper for rbtree_map_remove */ static PMEMoid map_rbtree_remove(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_remove(pop, rbtree_map, key); } /* * map_rbtree_remove_free -- wrapper for rbtree_map_remove_free */ static int map_rbtree_remove_free(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_remove_free(pop, rbtree_map, key); } /* * map_rbtree_clear -- wrapper for rbtree_map_clear */ static int map_rbtree_clear(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_clear(pop, rbtree_map); } /* * map_rbtree_get -- wrapper for rbtree_map_get */ static PMEMoid map_rbtree_get(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_get(pop, rbtree_map, key); } /* * map_rbtree_lookup -- wrapper for rbtree_map_lookup */ static int map_rbtree_lookup(PMEMobjpool *pop, TOID(struct map) map, uint64_t key) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_lookup(pop, rbtree_map, key); } /* * map_rbtree_foreach -- wrapper for rbtree_map_foreach */ static int map_rbtree_foreach(PMEMobjpool *pop, TOID(struct map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_foreach(pop, rbtree_map, cb, arg); } /* * map_rbtree_is_empty -- wrapper for rbtree_map_is_empty */ static int map_rbtree_is_empty(PMEMobjpool *pop, TOID(struct map) map) { TOID(struct rbtree_map) rbtree_map; TOID_ASSIGN(rbtree_map, map.oid); return rbtree_map_is_empty(pop, rbtree_map); } struct map_ops rbtree_map_ops = { /* .check = */ map_rbtree_check, /* .create = */ map_rbtree_create, /* .destroy = */ map_rbtree_destroy, /* .init = */ NULL, /* .insert = */ map_rbtree_insert, /* .insert_new = */ map_rbtree_insert_new, /* .remove = */ map_rbtree_remove, /* .remove_free = */ map_rbtree_remove_free, /* .clear = */ map_rbtree_clear, /* .get = */ map_rbtree_get, /* .lookup = */ map_rbtree_lookup, /* .foreach = */ map_rbtree_foreach, /* .is_empty = */ map_rbtree_is_empty, /* .count = */ NULL, /* .cmd = */ NULL, };
4,199
22.076923
76
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx/writer.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * writer.c -- example from introduction part 2 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_create(argv[1], LAYOUT_NAME, PMEMOBJ_MIN_POOL, 0666); if (pop == NULL) { perror("pmemobj_create"); return 1; } PMEMoid root = pmemobj_root(pop, sizeof(struct my_root)); struct my_root *rootp = pmemobj_direct(root); char buf[MAX_BUF_LEN] = {0}; if (scanf("%9s", buf) == EOF) { fprintf(stderr, "EOF\n"); return 1; } TX_BEGIN(pop) { pmemobj_tx_add_range(root, 0, sizeof(struct my_root)); memcpy(rootp->buf, buf, strlen(buf)); } TX_END pmemobj_close(pop); return 0; }
866
17.0625
58
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx/reader.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * reader.c -- example from introduction part 2 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_open(argv[1], LAYOUT_NAME); if (pop == NULL) { perror("pmemobj_open"); return 1; } PMEMoid root = pmemobj_root(pop, sizeof(struct my_root)); struct my_root *rootp = pmemobj_direct(root); printf("%s\n", rootp->buf); pmemobj_close(pop); return 0; }
631
16.081081
58
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store_tx/layout.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * layout.h -- example from introduction part 2 */ #define LAYOUT_NAME "intro_2" #define MAX_BUF_LEN 10 struct my_root { char buf[MAX_BUF_LEN]; };
241
16.285714
47
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store/writer.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * writer.c -- example from introduction part 1 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_create(argv[1], LAYOUT_NAME, PMEMOBJ_MIN_POOL, 0666); if (pop == NULL) { perror("pmemobj_create"); return 1; } PMEMoid root = pmemobj_root(pop, sizeof(struct my_root)); struct my_root *rootp = pmemobj_direct(root); char buf[MAX_BUF_LEN] = {0}; if (scanf("%9s", buf) == EOF) { fprintf(stderr, "EOF\n"); return 1; } rootp->len = strlen(buf); pmemobj_persist(pop, &rootp->len, sizeof(rootp->len)); pmemobj_memcpy_persist(pop, rootp->buf, buf, rootp->len); pmemobj_close(pop); return 0; }
885
17.458333
58
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store/reader.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * reader.c -- example from introduction part 1 */ #include <stdio.h> #include <string.h> #include <libpmemobj.h> #include "layout.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s file-name\n", argv[0]); return 1; } PMEMobjpool *pop = pmemobj_open(argv[1], LAYOUT_NAME); if (pop == NULL) { perror("pmemobj_open"); return 1; } PMEMoid root = pmemobj_root(pop, sizeof(struct my_root)); struct my_root *rootp = pmemobj_direct(root); if (rootp->len == strlen(rootp->buf)) printf("%s\n", rootp->buf); pmemobj_close(pop); return 0; }
671
16.684211
58
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/string_store/layout.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * layout.h -- example from introduction part 1 */ #define LAYOUT_NAME "intro_1" #define MAX_BUF_LEN 10 struct my_root { size_t len; char buf[MAX_BUF_LEN]; };
254
16
47
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/tree_map/ctree_map.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2019, Intel Corporation */ /* * ctree_map.c -- Crit-bit trie implementation */ #include <ex_common.h> #include <assert.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include "ctree_map.h" #define BIT_IS_SET(n, i) (!!((n) & (1ULL << (i)))) #include <x86intrin.h> 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; } TOID_DECLARE(struct tree_map_node, CTREE_MAP_TYPE_OFFSET + 1); static void setpage(void * addr){ uint64_t pageNo = ((uint64_t)addr)/4096; unsigned long * pageStart = (unsigned long *)(pageNo*4096); mprotect(pageStart, 4096, PROT_READ); return; } struct tree_map_entry { uint64_t key; PMEMoid slot; }; struct tree_map_node { int diff; /* most significant differing bit */ struct tree_map_entry entries[2]; }; struct ctree_map { struct tree_map_entry root; }; /* * find_crit_bit -- (internal) finds the most significant differing bit */ static int find_crit_bit(uint64_t lhs, uint64_t rhs) { return find_last_set_64(lhs ^ rhs); } /* * ctree_map_create -- allocates a new crit-bit tree instance */ int ctree_map_create(PMEMobjpool *pop, TOID(struct ctree_map) *map, void *arg) { int ret = 0; TX_BEGIN(pop) { pmemobj_tx_add_range_direct(map, sizeof(*map)); *map = TX_ZNEW(struct ctree_map); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * ctree_map_clear_node -- (internal) clears this node and its children */ static void ctree_map_clear_node(PMEMoid p) { if (OID_IS_NULL(p)) return; if (OID_INSTANCEOF(p, struct tree_map_node)) { TOID(struct tree_map_node) node; TOID_ASSIGN(node, p); ctree_map_clear_node(D_RW(node)->entries[0].slot); ctree_map_clear_node(D_RW(node)->entries[1].slot); } pmemobj_tx_free(p); } /* * ctree_map_clear -- removes all elements from the map */ int ctree_map_clear(PMEMobjpool *pop, TOID(struct ctree_map) map) { TX_BEGIN(pop) { ctree_map_clear_node(D_RW(map)->root.slot); TX_ADD_FIELD(map, root); D_RW(map)->root.slot = OID_NULL; } TX_END return 0; } /* * ctree_map_destroy -- cleanups and frees crit-bit tree instance */ int ctree_map_destroy(PMEMobjpool *pop, TOID(struct ctree_map) *map) { int ret = 0; TX_BEGIN(pop) { ctree_map_clear(pop, *map); pmemobj_tx_add_range_direct(map, sizeof(*map)); TX_FREE(*map); *map = TOID_NULL(struct ctree_map); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * ctree_map_insert_leaf -- (internal) inserts a new leaf at the position */ static void ctree_map_insert_leaf(struct tree_map_entry *p, struct tree_map_entry e, int diff) { TOID(struct tree_map_node) new_node = TX_NEW(struct tree_map_node); D_RW(new_node)->diff = diff; int d = BIT_IS_SET(e.key, D_RO(new_node)->diff); /* insert the leaf at the direction based on the critical bit */ D_RW(new_node)->entries[d] = e; /* find the appropriate position in the tree to insert the node */ TOID(struct tree_map_node) node; while (OID_INSTANCEOF(p->slot, struct tree_map_node)) { TOID_ASSIGN(node, p->slot); /* the critical bits have to be sorted */ if (D_RO(node)->diff < D_RO(new_node)->diff) break; p = &D_RW(node)->entries[BIT_IS_SET(e.key, D_RO(node)->diff)]; } pmemobj_tx_add_range_direct(p, sizeof(*p)); /* insert the found destination in the other slot */ D_RW(new_node)->entries[!d] = *p; p->key = 0; p->slot = new_node.oid; } /* * ctree_map_insert_new -- allocates a new object and inserts it into the tree */ int ctree_map_insert_new(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { int ret = 0; TX_BEGIN(pop) { PMEMoid n = pmemobj_tx_alloc(size, type_num); constructor(pop, pmemobj_direct(n), arg); ctree_map_insert(pop, map, key, n); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * ctree_map_insert -- inserts a new key-value pair into the map */ #ifdef GET_NDP_BREAKDOWN uint64_t ulogCycles; uint64_t waitCycles; uint64_t ulogcount; #endif int ctree_map_insert(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key, PMEMoid value) { int ret = 0; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; //ulogcount = 0; //uint64_t maxulogcount=0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif struct tree_map_entry *p = &D_RW(map)->root; /* descend the path until a best matching key is found */ TOID(struct tree_map_node) node; while (!OID_IS_NULL(p->slot) && OID_INSTANCEOF(p->slot, struct tree_map_node)) { TOID_ASSIGN(node, p->slot); p = &D_RW(node)->entries[BIT_IS_SET(key, D_RW(node)->diff)]; } struct tree_map_entry e = {key, value}; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif //uint64_t startCycles1,endCycles1; TX_BEGIN(pop) { if (p->key == 0 || p->key == key) { pmemobj_tx_add_range_direct(p, sizeof(*p)); *p = e; } else { ctree_map_insert_leaf(&D_RW(map)->root, e, find_crit_bit(p->key, key)); } } TX_ONABORT { ret = 1; } TX_END //if( maxulogcount < ulogcount) // maxulogcount = ulogcount; //ulogcount = 0; #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("ctree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree tx cmd issue total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree tx total wait time = %f\n", (((double)waitCycles)/2000000000)); //printf("maxulogs = %ld\n", maxulogcount); #endif return ret; } /* * ctree_map_get_leaf -- (internal) searches for a leaf of the key */ static struct tree_map_entry * ctree_map_get_leaf(TOID(struct ctree_map) map, uint64_t key, struct tree_map_entry **parent) { struct tree_map_entry *n = &D_RW(map)->root; struct tree_map_entry *p = NULL; TOID(struct tree_map_node) node; while (!OID_IS_NULL(n->slot) && OID_INSTANCEOF(n->slot, struct tree_map_node)) { TOID_ASSIGN(node, n->slot); p = n; n = &D_RW(node)->entries[BIT_IS_SET(key, D_RW(node)->diff)]; } if (n->key == key) { if (parent) *parent = p; return n; } return NULL; } /* * ctree_map_remove_free -- removes and frees an object from the tree */ int ctree_map_remove_free(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key) { int ret = 0; TX_BEGIN(pop) { PMEMoid val = ctree_map_remove(pop, map, key); pmemobj_tx_free(val); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * ctree_map_remove -- removes key-value pair from the map */ PMEMoid ctree_map_remove(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key) { PMEMoid ret; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ startCycles = getCycle(); #endif struct tree_map_entry *parent = NULL; struct tree_map_entry *leaf = ctree_map_get_leaf(map, key, &parent); if (leaf == NULL) return OID_NULL; ret = leaf->slot; if (parent == NULL) { /* root */ TX_BEGIN(pop) { pmemobj_tx_add_range_direct(leaf, sizeof(*leaf)); leaf->key = 0; leaf->slot = OID_NULL; } TX_END } else { /* * In this situation: * parent * / \ * LEFT RIGHT * there's no point in leaving the parent internal node * so it's swapped with the remaining node and then also freed. */ #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { struct tree_map_entry *dest = parent; TOID(struct tree_map_node) node; TOID_ASSIGN(node, parent->slot); pmemobj_tx_add_range_direct(dest, sizeof(*dest)); *dest = D_RW(node)->entries[ D_RO(node)->entries[0].key == leaf->key]; TX_FREE(node); } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("btree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree ulog total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree total wait time = %f\n", (((double)waitCycles)/2000000000)); #endif } return ret; } /* * ctree_map_get -- searches for a value of the key */ PMEMoid ctree_map_get(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key) { struct tree_map_entry *entry = ctree_map_get_leaf(map, key, NULL); return entry ? entry->slot : OID_NULL; } /* * ctree_map_lookup -- searches if a key exists */ int ctree_map_lookup(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key) { struct tree_map_entry *entry = ctree_map_get_leaf(map, key, NULL); return entry != NULL; } /* * ctree_map_foreach_node -- (internal) recursively traverses tree */ static int ctree_map_foreach_node(struct tree_map_entry e, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { int ret = 0; if (OID_INSTANCEOF(e.slot, struct tree_map_node)) { TOID(struct tree_map_node) node; TOID_ASSIGN(node, e.slot); if (ctree_map_foreach_node(D_RO(node)->entries[0], cb, arg) == 0) ctree_map_foreach_node(D_RO(node)->entries[1], cb, arg); } else { /* leaf */ ret = cb(e.key, e.slot, arg); } return ret; } /* * ctree_map_foreach -- initiates recursive traversal */ int ctree_map_foreach(PMEMobjpool *pop, TOID(struct ctree_map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg) { if (OID_IS_NULL(D_RO(map)->root.slot)) return 0; return ctree_map_foreach_node(D_RO(map)->root, cb, arg); } /* * ctree_map_is_empty -- checks whether the tree map is empty */ int ctree_map_is_empty(PMEMobjpool *pop, TOID(struct ctree_map) map) { return D_RO(map)->root.key == 0; } /* * ctree_map_check -- check if given persistent object is a tree map */ int ctree_map_check(PMEMobjpool *pop, TOID(struct ctree_map) map) { return TOID_IS_NULL(map) || !TOID_VALID(map); }
10,423
22.011038
83
c
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/tree_map/ctree_map.h
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2015-2017, Intel Corporation */ /* * ctree_map.h -- TreeMap sorted collection implementation */ #ifndef CTREE_MAP_H #define CTREE_MAP_H #include <libpmemobj.h> #ifndef CTREE_MAP_TYPE_OFFSET #define CTREE_MAP_TYPE_OFFSET 1008 #endif struct ctree_map; TOID_DECLARE(struct ctree_map, CTREE_MAP_TYPE_OFFSET + 0); int ctree_map_check(PMEMobjpool *pop, TOID(struct ctree_map) map); int ctree_map_create(PMEMobjpool *pop, TOID(struct ctree_map) *map, void *arg); int ctree_map_destroy(PMEMobjpool *pop, TOID(struct ctree_map) *map); int ctree_map_insert(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key, PMEMoid value); int ctree_map_insert_new(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg); PMEMoid ctree_map_remove(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key); int ctree_map_remove_free(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key); int ctree_map_clear(PMEMobjpool *pop, TOID(struct ctree_map) map); PMEMoid ctree_map_get(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key); int ctree_map_lookup(PMEMobjpool *pop, TOID(struct ctree_map) map, uint64_t key); int ctree_map_foreach(PMEMobjpool *pop, TOID(struct ctree_map) map, int (*cb)(uint64_t key, PMEMoid value, void *arg), void *arg); int ctree_map_is_empty(PMEMobjpool *pop, TOID(struct ctree_map) map); #endif /* CTREE_MAP_H */
1,523
34.44186
79
h
null
NearPMSW-main/nearpm/shadow/pmdk-sd/src/examples/libpmemobj/tree_map/rtree_map.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2016-2019, Intel Corporation */ /* * rtree_map.c -- implementation of rtree */ #include <ex_common.h> #include <assert.h> #include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include "rtree_map.h" #include <x86intrin.h> 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; } TOID_DECLARE(struct tree_map_node, RTREE_MAP_TYPE_OFFSET + 1); /* Good values: 0x10 an 0x100, but implementation is bound to 0x100 */ #ifndef ALPHABET_SIZE #define ALPHABET_SIZE 0x100 #endif struct tree_map_node { TOID(struct tree_map_node) slots[ALPHABET_SIZE]; unsigned has_value; PMEMoid value; uint64_t key_size; unsigned char key[]; }; struct rtree_map { TOID(struct tree_map_node) root; }; /* * rtree_map_create -- allocates a new rtree instance */ int rtree_map_create(PMEMobjpool *pop, TOID(struct rtree_map) *map, void *arg) { int ret = 0; TX_BEGIN(pop) { TX_ADD_DIRECT(map); *map = TX_ZNEW(struct rtree_map); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * rtree_map_clear_node -- (internal) removes all elements from the node */ static void rtree_map_clear_node(TOID(struct tree_map_node) node) { for (unsigned i = 0; i < ALPHABET_SIZE; i++) { rtree_map_clear_node(D_RO(node)->slots[i]); } pmemobj_tx_add_range(node.oid, 0, sizeof(struct tree_map_node) + D_RO(node)->key_size); TX_FREE(node); } /* * rtree_map_clear -- removes all elements from the map */ int rtree_map_clear(PMEMobjpool *pop, TOID(struct rtree_map) map) { int ret = 0; TX_BEGIN(pop) { rtree_map_clear_node(D_RO(map)->root); TX_ADD_FIELD(map, root); D_RW(map)->root = TOID_NULL(struct tree_map_node); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * rtree_map_destroy -- cleanups and frees rtree instance */ int rtree_map_destroy(PMEMobjpool *pop, TOID(struct rtree_map) *map) { int ret = 0; TX_BEGIN(pop) { rtree_map_clear(pop, *map); TX_ADD_DIRECT(map); TX_FREE(*map); *map = TOID_NULL(struct rtree_map); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * rtree_new_node -- (internal) inserts a node into an empty map */ static TOID(struct tree_map_node) rtree_new_node(const unsigned char *key, uint64_t key_size, PMEMoid value, unsigned has_value) { TOID(struct tree_map_node) node; node = TX_ZALLOC(struct tree_map_node, sizeof(struct tree_map_node) + key_size); /* * !!! Here should be: D_RO(node)->value * ... because we don't change map */ D_RW(node)->value = value; D_RW(node)->has_value = has_value; D_RW(node)->key_size = key_size; memcpy(D_RW(node)->key, key, key_size); return node; } /* * rtree_map_insert_empty -- (internal) inserts a node into an empty map */ static void rtree_map_insert_empty(TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size, PMEMoid value) { TX_ADD_FIELD(map, root); D_RW(map)->root = rtree_new_node(key, key_size, value, 1); } /* * key_comm_len -- (internal) calculate the len of common part of keys */ static unsigned key_comm_len(TOID(struct tree_map_node) node, const unsigned char *key, uint64_t key_size) { unsigned i; for (i = 0; i < MIN(key_size, D_RO(node)->key_size) && key[i] == D_RO(node)->key[i]; i++) ; return i; } /* * rtree_map_insert_value -- (internal) inserts a pair into a tree */ static void rtree_map_insert_value(TOID(struct tree_map_node) *node, const unsigned char *key, uint64_t key_size, PMEMoid value) { unsigned i; if (TOID_IS_NULL(*node)) { TX_ADD_DIRECT(node); *node = rtree_new_node(key, key_size, value, 1); return; } i = key_comm_len(*node, key, key_size); if (i != D_RO(*node)->key_size) { /* Node does not exist. Let's add. */ TOID(struct tree_map_node) orig_node = *node; TX_ADD_DIRECT(node); if (i != key_size) { *node = rtree_new_node(D_RO(orig_node)->key, i, OID_NULL, 0); } else { *node = rtree_new_node(D_RO(orig_node)->key, i, value, 1); } D_RW(*node)->slots[D_RO(orig_node)->key[i]] = orig_node; TX_ADD_FIELD(orig_node, key_size); D_RW(orig_node)->key_size -= i; pmemobj_tx_add_range_direct(D_RW(orig_node)->key, D_RO(orig_node)->key_size); memmove(D_RW(orig_node)->key, D_RO(orig_node)->key + i, D_RO(orig_node)->key_size); if (i != key_size) { D_RW(*node)->slots[key[i]] = rtree_new_node(key + i, key_size - i, value, 1); } return; } if (i == key_size) { if (OID_IS_NULL(D_RO(*node)->value) || D_RO(*node)->has_value) { /* Just replace old value with new */ TX_ADD_FIELD(*node, value); TX_ADD_FIELD(*node, has_value); D_RW(*node)->value = value; D_RW(*node)->has_value = 1; } else { /* * Ignore. By the fact current value should be * removed in advance, or handled in a different way. */ } } else { /* Recurse deeply */ return rtree_map_insert_value(&D_RW(*node)->slots[key[i]], key + i, key_size - i, value); } } /* * rtree_map_is_empty -- checks whether the tree map is empty */ int rtree_map_is_empty(PMEMobjpool *pop, TOID(struct rtree_map) map) { return TOID_IS_NULL(D_RO(map)->root); } /* * rtree_map_insert -- inserts a new key-value pair into the map */ #ifdef GET_NDP_BREAKDOWN uint64_t ulogCycles; uint64_t waitCycles; uint64_t resetCycles; #endif int rtree_map_insert(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size, PMEMoid value) { int ret = 0; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ startCycles = getCycle(); #endif TX_BEGIN(pop) { if (rtree_map_is_empty(pop, map)) { rtree_map_insert_empty(map, key, key_size, value); } else { rtree_map_insert_value(&D_RW(map)->root, key, key_size, value); } } TX_ONABORT { ret = 1; } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("ctree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree tx cmd issue total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree tx total wait time = %f\n", (((double)waitCycles)/2000000000)); #endif return ret; } /* * rtree_map_insert_new -- allocates a new object and inserts it into the tree */ int rtree_map_insert_new(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size, size_t size, unsigned type_num, void (*constructor)(PMEMobjpool *pop, void *ptr, void *arg), void *arg) { int ret = 0; TX_BEGIN(pop) { PMEMoid n = pmemobj_tx_alloc(size, type_num); constructor(pop, pmemobj_direct(n), arg); rtree_map_insert(pop, map, key, key_size, n); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * is_leaf -- (internal) check a node for zero qty of children */ static bool is_leaf(TOID(struct tree_map_node) node) { unsigned j; for (j = 0; j < ALPHABET_SIZE && TOID_IS_NULL(D_RO(node)->slots[j]); j++) ; return (j == ALPHABET_SIZE); } /* * has_only_one_child -- (internal) check a node for qty of children */ static bool has_only_one_child(TOID(struct tree_map_node) node, unsigned *child_idx) { unsigned j, child_qty; for (j = 0, child_qty = 0; j < ALPHABET_SIZE; j++) if (!TOID_IS_NULL(D_RO(node)->slots[j])) { child_qty++; *child_idx = j; } return (1 == child_qty); } /* * remove_extra_node -- (internal) remove unneeded extra node */ static void remove_extra_node(TOID(struct tree_map_node) *node) { unsigned child_idx = UINT_MAX; TOID(struct tree_map_node) tmp, tmp_child; /* Our node has child with only one child. */ tmp = *node; has_only_one_child(tmp, &child_idx); assert(child_idx != UINT_MAX); tmp_child = D_RO(tmp)->slots[child_idx]; /* * That child's incoming label is appended to the ours incoming label * and the child is removed. */ uint64_t new_key_size = D_RO(tmp)->key_size + D_RO(tmp_child)->key_size; unsigned char *new_key = (unsigned char *)malloc(new_key_size); assert(new_key != NULL); memcpy(new_key, D_RO(tmp)->key, D_RO(tmp)->key_size); memcpy(new_key + D_RO(tmp)->key_size, D_RO(tmp_child)->key, D_RO(tmp_child)->key_size); TX_ADD_DIRECT(node); *node = rtree_new_node(new_key, new_key_size, D_RO(tmp_child)->value, D_RO(tmp_child)->has_value); free(new_key); TX_FREE(tmp); memcpy(D_RW(*node)->slots, D_RO(tmp_child)->slots, sizeof(D_RO(tmp_child)->slots)); TX_FREE(tmp_child); } /* * rtree_map_remove_node -- (internal) removes node from tree */ static PMEMoid rtree_map_remove_node(TOID(struct rtree_map) map, TOID(struct tree_map_node) *node, const unsigned char *key, uint64_t key_size, bool *check_for_child) { bool c4c; unsigned i, child_idx; PMEMoid ret = OID_NULL; *check_for_child = false; if (TOID_IS_NULL(*node)) return OID_NULL; i = key_comm_len(*node, key, key_size); if (i != D_RO(*node)->key_size) /* Node does not exist */ return OID_NULL; if (i == key_size) { if (0 == D_RO(*node)->has_value) return OID_NULL; /* Node is found */ ret = D_RO(*node)->value; /* delete node from tree */ TX_ADD_FIELD((*node), value); TX_ADD_FIELD((*node), has_value); D_RW(*node)->value = OID_NULL; D_RW(*node)->has_value = 0; if (is_leaf(*node)) { pmemobj_tx_add_range(node->oid, 0, sizeof(*node) + D_RO(*node)->key_size); TX_FREE(*node); TX_ADD_DIRECT(node); (*node) = TOID_NULL(struct tree_map_node); } return ret; } /* Recurse deeply */ ret = rtree_map_remove_node(map, &D_RW(*node)->slots[key[i]], key + i, key_size - i, &c4c); if (c4c) { /* Our node has child with only one child. Remove. */ remove_extra_node(&D_RW(*node)->slots[key[i]]); return ret; } if (has_only_one_child(*node, &child_idx) && (0 == D_RO(*node)->has_value)) { *check_for_child = true; } return ret; } /* * rtree_map_remove -- removes key-value pair from the map */ PMEMoid rtree_map_remove(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size) { PMEMoid ret; #ifdef GET_NDP_BREAKDOWN ulogCycles = 0; waitCycles = 0; #endif #ifdef GET_NDP_PERFORMENCE uint64_t btreetxCycles = 0; uint64_t endCycles, startCycles; for(int i=0;i<RUN_COUNT;i++){ #endif ret = OID_NULL; bool check_for_child; if (TOID_IS_NULL(map)) return OID_NULL; #ifdef GET_NDP_PERFORMENCE startCycles = getCycle(); #endif TX_BEGIN(pop) { ret = rtree_map_remove_node(map, &D_RW(map)->root, key, key_size, &check_for_child); if (check_for_child) { /* Our root node has only one child. Remove. */ remove_extra_node(&D_RW(map)->root); } } TX_END #ifdef GET_NDP_PERFORMENCE endCycles = getCycle(); btreetxCycles += endCycles - startCycles; } double totTime = ((double)btreetxCycles)/2000000000; printf("ctree TX/s = %f\nctree tx total time = %f\n",RUN_COUNT/totTime,totTime); #endif #ifdef GET_NDP_BREAKDOWN printf("ctree tx cmd issue total time = %f\n", (((double)ulogCycles)/2000000000)); printf("ctree tx total wait time = %f\n", (((double)waitCycles)/2000000000)); #endif return ret; } /* * rtree_map_remove_free -- removes and frees an object from the tree */ int rtree_map_remove_free(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size) { int ret = 0; if (TOID_IS_NULL(map)) return 1; TX_BEGIN(pop) { pmemobj_tx_free(rtree_map_remove(pop, map, key, key_size)); } TX_ONABORT { ret = 1; } TX_END return ret; } /* * rtree_map_get_in_node -- (internal) searches for a value in the node */ static PMEMoid rtree_map_get_in_node(TOID(struct tree_map_node) node, const unsigned char *key, uint64_t key_size) { unsigned i; if (TOID_IS_NULL(node)) return OID_NULL; i = key_comm_len(node, key, key_size); if (i != D_RO(node)->key_size) /* Node does not exist */ return OID_NULL; if (i == key_size) { /* Node is found */ return D_RO(node)->value; } else { /* Recurse deeply */ return rtree_map_get_in_node(D_RO(node)->slots[key[i]], key + i, key_size - i); } } /* * rtree_map_get -- searches for a value of the key */ PMEMoid rtree_map_get(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size) { if (TOID_IS_NULL(D_RO(map)->root)) return OID_NULL; return rtree_map_get_in_node(D_RO(map)->root, key, key_size); } /* * rtree_map_lookup_in_node -- (internal) searches for key if exists */ static int rtree_map_lookup_in_node(TOID(struct tree_map_node) node, const unsigned char *key, uint64_t key_size) { unsigned i; if (TOID_IS_NULL(node)) return 0; i = key_comm_len(node, key, key_size); if (i != D_RO(node)->key_size) /* Node does not exist */ return 0; if (i == key_size) { /* Node is found */ return 1; } /* Recurse deeply */ return rtree_map_lookup_in_node(D_RO(node)->slots[key[i]], key + i, key_size - i); } /* * rtree_map_lookup -- searches if key exists */ int rtree_map_lookup(PMEMobjpool *pop, TOID(struct rtree_map) map, const unsigned char *key, uint64_t key_size) { if (TOID_IS_NULL(D_RO(map)->root)) return 0; return rtree_map_lookup_in_node(D_RO(map)->root, key, key_size); } /* * rtree_map_foreach_node -- (internal) recursively traverses tree */ static int rtree_map_foreach_node(const TOID(struct tree_map_node) node, int (*cb)(const unsigned char *key, uint64_t key_size, PMEMoid, void *arg), void *arg) { unsigned i; if (TOID_IS_NULL(node)) return 0; for (i = 0; i < ALPHABET_SIZE; i++) { if (rtree_map_foreach_node(D_RO(node)->slots[i], cb, arg) != 0) return 1; } if (NULL != cb) { if (cb(D_RO(node)->key, D_RO(node)->key_size, D_RO(node)->value, arg) != 0) return 1; } return 0; } /* * rtree_map_foreach -- initiates recursive traversal */ int rtree_map_foreach(PMEMobjpool *pop, TOID(struct rtree_map) map, int (*cb)(const unsigned char *key, uint64_t key_size, PMEMoid value, void *arg), void *arg) { return rtree_map_foreach_node(D_RO(map)->root, cb, arg); } /* * ctree_map_check -- check if given persistent object is a tree map */ int rtree_map_check(PMEMobjpool *pop, TOID(struct rtree_map) map) { return TOID_IS_NULL(map) || !TOID_VALID(map); }
14,705
21.081081
83
c