repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/ctl.c
/* * Copyright 2016-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ctl.c -- implementation of the interface for examination and modification of * the library's internal state */ #include "ctl.h" #include "os.h" #define CTL_MAX_ENTRIES 100 #define MAX_CONFIG_FILE_LEN (1 << 20) /* 1 megabyte */ #define CTL_STRING_QUERY_SEPARATOR ";" #define CTL_NAME_VALUE_SEPARATOR "=" #define CTL_QUERY_NODE_SEPARATOR "." #define CTL_VALUE_ARG_SEPARATOR "," static int ctl_global_first_free = 0; static struct ctl_node CTL_NODE(global)[CTL_MAX_ENTRIES]; /* * This is the top level node of the ctl tree structure. Each node can contain * children and leaf nodes. * * Internal nodes simply create a new path in the tree whereas child nodes are * the ones providing the read/write functionality by the means of callbacks. * * Each tree node must be NULL-terminated, CTL_NODE_END macro is provided for * convience. */ struct ctl { struct ctl_node root[CTL_MAX_ENTRIES]; int first_free; }; /* * ctl_find_node -- (internal) searches for a matching entry point in the * provided nodes * * The caller is responsible for freeing all of the allocated indexes, * regardless of the return value. */ static struct ctl_node * ctl_find_node(struct ctl_node *nodes, const char *name, struct ctl_indexes *indexes) { LOG(3, "nodes %p name %s indexes %p", nodes, name, indexes); struct ctl_node *n = NULL; char *sptr = NULL; char *parse_str = Strdup(name); if (parse_str == NULL) return NULL; char *node_name = strtok_r(parse_str, CTL_QUERY_NODE_SEPARATOR, &sptr); /* * Go through the string and separate tokens that correspond to nodes * in the main ctl tree. */ while (node_name != NULL) { char *endptr; /* * Ignore errno from strtol: FreeBSD returns EINVAL if no * conversion is performed. Linux does not, but endptr * check is valid in both cases. */ int tmp_errno = errno; long index_value = strtol(node_name, &endptr, 0); errno = tmp_errno; struct ctl_index *index_entry = NULL; if (endptr != node_name) { /* a valid index */ index_entry = Malloc(sizeof(*index_entry)); if (index_entry == NULL) goto error; index_entry->value = index_value; SLIST_INSERT_HEAD(indexes, index_entry, entry); } for (n = &nodes[0]; n->name != NULL; ++n) { if (index_entry && n->type == CTL_NODE_INDEXED) break; else if (strcmp(n->name, node_name) == 0) break; } if (n->name == NULL) goto error; if (index_entry) index_entry->name = n->name; nodes = n->children; node_name = strtok_r(NULL, CTL_QUERY_NODE_SEPARATOR, &sptr); } Free(parse_str); return n; error: Free(parse_str); return NULL; } /* * ctl_delete_indexes -- * (internal) removes and frees all entires on the index list */ static void ctl_delete_indexes(struct ctl_indexes *indexes) { while (!SLIST_EMPTY(indexes)) { struct ctl_index *index = SLIST_FIRST(indexes); SLIST_REMOVE_HEAD(indexes, entry); Free(index); } } /* * ctl_parse_args -- (internal) parses a string argument based on the node * structure */ static void * ctl_parse_args(struct ctl_argument *arg_proto, char *arg) { ASSERTne(arg, NULL); char *dest_arg = Malloc(arg_proto->dest_size); if (dest_arg == NULL) return NULL; char *sptr = NULL; char *arg_sep = strtok_r(arg, CTL_VALUE_ARG_SEPARATOR, &sptr); for (struct ctl_argument_parser *p = arg_proto->parsers; p->parser != NULL; ++p) { ASSERT(p->dest_offset + p->dest_size <= arg_proto->dest_size); if (arg_sep == NULL) goto error_parsing; if (p->parser(arg_sep, dest_arg + p->dest_offset, p->dest_size) != 0) goto error_parsing; arg_sep = strtok_r(NULL, CTL_VALUE_ARG_SEPARATOR, &sptr); } return dest_arg; error_parsing: Free(dest_arg); return NULL; } /* * ctl_query_get_real_args -- (internal) returns a pointer with actual argument * structure as required by the node callback */ static void * ctl_query_get_real_args(struct ctl_node *n, void *write_arg, enum ctl_query_source source) { void *real_arg = NULL; switch (source) { case CTL_QUERY_CONFIG_INPUT: real_arg = ctl_parse_args(n->arg, write_arg); break; case CTL_QUERY_PROGRAMMATIC: real_arg = write_arg; break; default: ASSERT(0); break; } return real_arg; } /* * ctl_query_cleanup_real_args -- (internal) cleanups relevant argument * structures allocated as a result of the get_real_args call */ static void ctl_query_cleanup_real_args(struct ctl_node *n, void *real_arg, enum ctl_query_source source) { switch (source) { case CTL_QUERY_CONFIG_INPUT: Free(real_arg); break; case CTL_QUERY_PROGRAMMATIC: break; default: ASSERT(0); break; } } /* * ctl_exec_query_read -- (internal) calls the read callback of a node */ static int ctl_exec_query_read(void *ctx, struct ctl_node *n, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { if (arg == NULL) { ERR("read queries require non-NULL argument"); errno = EINVAL; return -1; } return n->cb[CTL_QUERY_READ](ctx, source, arg, indexes); } /* * ctl_exec_query_write -- (internal) calls the write callback of a node */ static int ctl_exec_query_write(void *ctx, struct ctl_node *n, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { if (arg == NULL) { ERR("write queries require non-NULL argument"); errno = EINVAL; return -1; } void *real_arg = ctl_query_get_real_args(n, arg, source); if (real_arg == NULL) { errno = EINVAL; ERR("invalid arguments"); return -1; } int ret = n->cb[CTL_QUERY_WRITE](ctx, source, real_arg, indexes); ctl_query_cleanup_real_args(n, real_arg, source); return ret; } /* * ctl_exec_query_runnable -- (internal) calls the run callback of a node */ static int ctl_exec_query_runnable(void *ctx, struct ctl_node *n, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { return n->cb[CTL_QUERY_RUNNABLE](ctx, source, arg, indexes); } static int (*ctl_exec_query[MAX_CTL_QUERY_TYPE])(void *ctx, struct ctl_node *n, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) = { ctl_exec_query_read, ctl_exec_query_write, ctl_exec_query_runnable, }; /* * ctl_query -- (internal) parses the name and calls the appropriate methods * from the ctl tree */ int ctl_query(struct ctl *ctl, void *ctx, enum ctl_query_source source, const char *name, enum ctl_query_type type, void *arg) { LOG(3, "ctl %p ctx %p source %d name %s type %d arg %p", ctl, ctx, source, name, type, arg); if (name == NULL) { ERR("invalid query"); errno = EINVAL; return -1; } /* * All of the indexes are put on this list so that the handlers can * easily retrieve the index values. The list is cleared once the ctl * query has been handled. */ struct ctl_indexes indexes; SLIST_INIT(&indexes); int ret = -1; struct ctl_node *n = ctl_find_node(CTL_NODE(global), name, &indexes); if (n == NULL && ctl) { ctl_delete_indexes(&indexes); n = ctl_find_node(ctl->root, name, &indexes); } if (n == NULL || n->type != CTL_NODE_LEAF || n->cb[type] == NULL) { ERR("invalid query entry point %s", name); errno = EINVAL; goto out; } ret = ctl_exec_query[type](ctx, n, source, arg, &indexes); out: ctl_delete_indexes(&indexes); return ret; } /* * ctl_register_module_node -- adds a new node to the CTL tree root. */ void ctl_register_module_node(struct ctl *c, const char *name, struct ctl_node *n) { struct ctl_node *nnode = c == NULL ? &CTL_NODE(global)[ctl_global_first_free++] : &c->root[c->first_free++]; nnode->children = n; nnode->type = CTL_NODE_NAMED; nnode->name = name; } /* * ctl_parse_query -- (internal) splits an entire query string * into name and value */ static int ctl_parse_query(char *qbuf, char **name, char **value) { if (qbuf == NULL) return -1; char *sptr; *name = strtok_r(qbuf, CTL_NAME_VALUE_SEPARATOR, &sptr); if (*name == NULL) return -1; *value = strtok_r(NULL, CTL_NAME_VALUE_SEPARATOR, &sptr); if (*value == NULL) return -1; /* the value itself mustn't include CTL_NAME_VALUE_SEPARATOR */ char *extra = strtok_r(NULL, CTL_NAME_VALUE_SEPARATOR, &sptr); if (extra != NULL) return -1; return 0; } /* * ctl_load_config -- executes the entire query collection from a provider */ static int ctl_load_config(struct ctl *ctl, void *ctx, char *buf) { int r = 0; char *sptr = NULL; /* for internal use of strtok */ char *name; char *value; ASSERTne(buf, NULL); char *qbuf = strtok_r(buf, CTL_STRING_QUERY_SEPARATOR, &sptr); while (qbuf != NULL) { r = ctl_parse_query(qbuf, &name, &value); if (r != 0) { ERR("failed to parse query %s", qbuf); return -1; } r = ctl_query(ctl, ctx, CTL_QUERY_CONFIG_INPUT, name, CTL_QUERY_WRITE, value); if (r < 0 && ctx != NULL) return -1; qbuf = strtok_r(NULL, CTL_STRING_QUERY_SEPARATOR, &sptr); } return 0; } /* * ctl_load_config_from_string -- loads obj configuration from string */ int ctl_load_config_from_string(struct ctl *ctl, void *ctx, const char *cfg_string) { LOG(3, "ctl %p ctx %p cfg_string \"%s\"", ctl, ctx, cfg_string); char *buf = Strdup(cfg_string); if (buf == NULL) { ERR("!Strdup"); return -1; } int ret = ctl_load_config(ctl, ctx, buf); Free(buf); return ret; } /* * ctl_load_config_from_file -- loads obj configuration from file * * This function opens up the config file, allocates a buffer of size equal to * the size of the file, reads its content and sanitizes it for ctl_load_config. */ int ctl_load_config_from_file(struct ctl *ctl, void *ctx, const char *cfg_file) { LOG(3, "ctl %p ctx %p cfg_file \"%s\"", ctl, ctx, cfg_file); int ret = -1; FILE *fp = os_fopen(cfg_file, "r"); if (fp == NULL) return ret; int err; if ((err = fseek(fp, 0, SEEK_END)) != 0) goto error_file_parse; long fsize = ftell(fp); if (fsize == -1) goto error_file_parse; if (fsize > MAX_CONFIG_FILE_LEN) { ERR("Config file too large"); goto error_file_parse; } if ((err = fseek(fp, 0, SEEK_SET)) != 0) goto error_file_parse; char *buf = Zalloc((size_t)fsize + 1); /* +1 for NULL-termination */ if (buf == NULL) { ERR("!Zalloc"); goto error_file_parse; } size_t bufpos = 0; int c; int is_comment_section = 0; while ((c = fgetc(fp)) != EOF) { if (c == '#') is_comment_section = 1; else if (c == '\n') is_comment_section = 0; else if (!is_comment_section && !isspace(c)) buf[bufpos++] = (char)c; } ret = ctl_load_config(ctl, ctx, buf); Free(buf); error_file_parse: (void) fclose(fp); return ret; } /* * ctl_new -- allocates and initalizes ctl data structures */ struct ctl * ctl_new(void) { struct ctl *c = Zalloc(sizeof(struct ctl)); if (c == NULL) { ERR("!Zalloc"); return NULL; } c->first_free = 0; return c; } /* * ctl_delete -- deletes ctl */ void ctl_delete(struct ctl *c) { Free(c); } /* * ctl_parse_ll -- (internal) parses and returns a long long signed integer */ static long long ctl_parse_ll(const char *str) { char *endptr; int olderrno = errno; errno = 0; long long val = strtoll(str, &endptr, 0); if (endptr == str || errno != 0) return LLONG_MIN; errno = olderrno; return val; } /* * ctl_arg_boolean -- checks whether the provided argument contains * either a 1 or y or Y. */ int ctl_arg_boolean(const void *arg, void *dest, size_t dest_size) { int *intp = dest; char in = ((char *)arg)[0]; if (tolower(in) == 'y' || in == '1') { *intp = 1; return 0; } else if (tolower(in) == 'n' || in == '0') { *intp = 0; return 0; } return -1; } /* * ctl_arg_integer -- parses signed integer argument */ int ctl_arg_integer(const void *arg, void *dest, size_t dest_size) { long long val = ctl_parse_ll(arg); if (val == LLONG_MIN) return -1; switch (dest_size) { case sizeof(int): if (val > INT_MAX || val < INT_MIN) return -1; *(int *)dest = (int)val; break; case sizeof(long long): *(long long *)dest = val; break; case sizeof(uint8_t): if (val > UINT8_MAX || val < 0) return -1; *(uint8_t *)dest = (uint8_t)val; break; default: ERR("invalid destination size %zu", dest_size); errno = EINVAL; return -1; } return 0; } /* * ctl_arg_string -- verifies length and copies a string argument into a zeroed * buffer */ int ctl_arg_string(const void *arg, void *dest, size_t dest_size) { /* check if the incoming string is longer or equal to dest_size */ if (strnlen(arg, dest_size) == dest_size) return -1; strncpy(dest, arg, dest_size); return 0; }
14,069
22.217822
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/pool_hdr.c
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * pool_hdr.c -- pool header utilities */ #include <errno.h> #include <stdio.h> #include <string.h> #include <endian.h> #include "out.h" #include "pool_hdr.h" /* Determine ISA for which PMDK is currently compiled */ #if defined(__x86_64) || defined(_M_X64) /* x86 -- 64 bit */ #define PMDK_MACHINE PMDK_MACHINE_X86_64 #define PMDK_MACHINE_CLASS PMDK_MACHINE_CLASS_64 #elif defined(__aarch64__) /* 64 bit ARM not supported yet */ #define PMDK_MACHINE PMDK_MACHINE_AARCH64 #define PMDK_MACHINE_CLASS PMDK_MACHINE_CLASS_64 #else /* add appropriate definitions here when porting PMDK to another ISA */ #error unable to recognize ISA at compile time #endif /* * arch_machine -- (internal) determine endianness */ static uint8_t arch_data(void) { uint16_t word = (PMDK_DATA_BE << 8) + PMDK_DATA_LE; return ((uint8_t *)&word)[0]; } /* * util_get_arch_flags -- get architecture identification flags */ void util_get_arch_flags(struct arch_flags *arch_flags) { memset(arch_flags, 0, sizeof(*arch_flags)); arch_flags->machine = PMDK_MACHINE; arch_flags->machine_class = PMDK_MACHINE_CLASS; arch_flags->data = arch_data(); arch_flags->alignment_desc = alignment_desc(); } /* * util_convert2le_hdr -- convert pool_hdr into little-endian byte order */ void util_convert2le_hdr(struct pool_hdr *hdrp) { hdrp->major = htole32(hdrp->major); hdrp->features.compat = htole32(hdrp->features.compat); hdrp->features.incompat = htole32(hdrp->features.incompat); hdrp->features.ro_compat = htole32(hdrp->features.ro_compat); hdrp->arch_flags.alignment_desc = htole64(hdrp->arch_flags.alignment_desc); hdrp->arch_flags.machine = htole16(hdrp->arch_flags.machine); hdrp->crtime = htole64(hdrp->crtime); hdrp->checksum = htole64(hdrp->checksum); } /* * util_convert2h_hdr_nocheck -- convert pool_hdr into host byte order */ void util_convert2h_hdr_nocheck(struct pool_hdr *hdrp) { hdrp->major = le32toh(hdrp->major); hdrp->features.compat = le32toh(hdrp->features.compat); hdrp->features.incompat = le32toh(hdrp->features.incompat); hdrp->features.ro_compat = le32toh(hdrp->features.ro_compat); hdrp->crtime = le64toh(hdrp->crtime); hdrp->arch_flags.machine = le16toh(hdrp->arch_flags.machine); hdrp->arch_flags.alignment_desc = le64toh(hdrp->arch_flags.alignment_desc); hdrp->checksum = le64toh(hdrp->checksum); } /* * util_arch_flags_check -- validates arch_flags */ int util_check_arch_flags(const struct arch_flags *arch_flags) { struct arch_flags cur_af; int ret = 0; util_get_arch_flags(&cur_af); if (!util_is_zeroed(&arch_flags->reserved, sizeof(arch_flags->reserved))) { ERR("invalid reserved values"); ret = -1; } if (arch_flags->machine != cur_af.machine) { ERR("invalid machine value"); ret = -1; } if (arch_flags->data != cur_af.data) { ERR("invalid data value"); ret = -1; } if (arch_flags->machine_class != cur_af.machine_class) { ERR("invalid machine_class value"); ret = -1; } if (arch_flags->alignment_desc != cur_af.alignment_desc) { ERR("invalid alignment_desc value"); ret = -1; } return ret; } /* * util_get_unknown_features -- filter out unknown features flags */ features_t util_get_unknown_features(features_t features, features_t known) { features_t unknown; unknown.compat = util_get_not_masked_bits( features.compat, known.compat); unknown.incompat = util_get_not_masked_bits( features.incompat, known.incompat); unknown.ro_compat = util_get_not_masked_bits( features.ro_compat, known.ro_compat); return unknown; } /* * util_feature_check -- check features masks */ int util_feature_check(struct pool_hdr *hdrp, features_t known) { LOG(3, "hdrp %p features {incompat %#x ro_compat %#x compat %#x}", hdrp, known.incompat, known.ro_compat, known.compat); features_t unknown = util_get_unknown_features(hdrp->features, known); /* check incompatible ("must support") features */ if (unknown.incompat) { ERR("unsafe to continue due to unknown incompat "\ "features: %#x", unknown.incompat); errno = EINVAL; return -1; } /* check RO-compatible features (force RO if unsupported) */ if (unknown.ro_compat) { ERR("switching to read-only mode due to unknown ro_compat "\ "features: %#x", unknown.ro_compat); return 0; } /* check compatible ("may") features */ if (unknown.compat) { LOG(3, "ignoring unknown compat features: %#x", unknown.compat); } return 1; } /* * util_feature_cmp -- compares features with reference * * returns 1 if features and reference match and 0 otherwise */ int util_feature_cmp(features_t features, features_t ref) { LOG(3, "features {incompat %#x ro_compat %#x compat %#x}" "ref {incompat %#x ro_compat %#x compat %#x}", features.incompat, features.ro_compat, features.compat, ref.incompat, ref.ro_compat, ref.compat); return features.compat == ref.compat && features.incompat == ref.incompat && features.ro_compat == ref.ro_compat; } /* * util_feature_is_zero -- check if features flags are zeroed * * returns 1 if features is zeroed and 0 otherwise */ int util_feature_is_zero(features_t features) { const uint32_t bits = features.compat | features.incompat | features.ro_compat; return bits ? 0 : 1; } /* * util_feature_is_set -- check if feature flag is set in features * * returns 1 if feature flag is set and 0 otherwise */ int util_feature_is_set(features_t features, features_t flag) { uint32_t bits = 0; bits |= features.compat & flag.compat; bits |= features.incompat & flag.incompat; bits |= features.ro_compat & flag.ro_compat; return bits ? 1 : 0; } /* * util_feature_enable -- enable feature */ void util_feature_enable(features_t *features, features_t new_feature) { #define FEATURE_ENABLE(flags, X) \ (flags) |= (X) FEATURE_ENABLE(features->compat, new_feature.compat); FEATURE_ENABLE(features->incompat, new_feature.incompat); FEATURE_ENABLE(features->ro_compat, new_feature.ro_compat); #undef FEATURE_ENABLE } /* * util_feature_disable -- (internal) disable feature */ void util_feature_disable(features_t *features, features_t old_feature) { #define FEATURE_DISABLE(flags, X) \ (flags) &= ~(X) FEATURE_DISABLE(features->compat, old_feature.compat); FEATURE_DISABLE(features->incompat, old_feature.incompat); FEATURE_DISABLE(features->ro_compat, old_feature.ro_compat); #undef FEATURE_DISABLE } static const features_t feature_2_pmempool_feature_map[] = { FEAT_INCOMPAT(SINGLEHDR), /* PMEMPOOL_FEAT_SINGLEHDR */ FEAT_INCOMPAT(CKSUM_2K), /* PMEMPOOL_FEAT_CKSUM_2K */ FEAT_INCOMPAT(SDS), /* PMEMPOOL_FEAT_SHUTDOWN_STATE */ FEAT_COMPAT(CHECK_BAD_BLOCKS), /* PMEMPOOL_FEAT_CHECK_BAD_BLOCKS */ }; #define FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE \ ARRAY_SIZE(feature_2_pmempool_feature_map) static const char *str_2_pmempool_feature_map[] = { "SINGLEHDR", "CKSUM_2K", "SHUTDOWN_STATE", "CHECK_BAD_BLOCKS", }; #define PMEMPOOL_FEATURE_2_STR_MAP_SIZE ARRAY_SIZE(str_2_pmempool_feature_map) /* * util_str2feature -- convert string to feat_flags value */ features_t util_str2feature(const char *str) { /* all features have to be named in incompat_features_str array */ COMPILE_ERROR_ON(FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE != PMEMPOOL_FEATURE_2_STR_MAP_SIZE); for (uint32_t f = 0; f < PMEMPOOL_FEATURE_2_STR_MAP_SIZE; ++f) { if (strcmp(str, str_2_pmempool_feature_map[f]) == 0) { return feature_2_pmempool_feature_map[f]; } } return features_zero; } /* * util_feature2pmempool_feature -- convert feature to pmempool_feature */ uint32_t util_feature2pmempool_feature(features_t feat) { for (uint32_t pf = 0; pf < FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE; ++pf) { const features_t *record = &feature_2_pmempool_feature_map[pf]; if (util_feature_cmp(feat, *record)) { return pf; } } return UINT32_MAX; } /* * util_str2pmempool_feature -- convert string to uint32_t enum pmempool_feature * equivalent */ uint32_t util_str2pmempool_feature(const char *str) { features_t fval = util_str2feature(str); if (util_feature_is_zero(fval)) return UINT32_MAX; return util_feature2pmempool_feature(fval); } /* * util_feature2str -- convert uint32_t feature to string */ const char * util_feature2str(features_t features, features_t *found) { for (uint32_t i = 0; i < FEAT_2_PMEMPOOL_FEATURE_MAP_SIZE; ++i) { const features_t *record = &feature_2_pmempool_feature_map[i]; if (util_feature_is_set(features, *record)) { if (found) memcpy(found, record, sizeof(features_t)); return str_2_pmempool_feature_map[i]; } } return NULL; }
10,132
26.312668
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/uuid_windows.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * uuid_windows.c -- pool set utilities with OS-specific implementation */ #include "uuid.h" #include "out.h" /* * util_uuid_generate -- generate a uuid */ int util_uuid_generate(uuid_t uuid) { HRESULT res = CoCreateGuid((GUID *)(uuid)); if (res != S_OK) { ERR("CoCreateGuid"); return -1; } return 0; }
1,921
35.264151
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/shutdown_state.h
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * shutdown_state.h -- unsafe shudown detection */ #ifndef PMDK_SHUTDOWN_STATE_H #define PMDK_SHUTDOWN_STATE_H 1 #include <stdint.h> #ifdef __cplusplus extern "C" { #endif struct pool_replica; struct shutdown_state { uint64_t usc; uint64_t uuid; /* UID checksum */ uint8_t dirty; uint8_t reserved[39]; uint64_t checksum; }; int shutdown_state_init(struct shutdown_state *sds, struct pool_replica *rep); int shutdown_state_add_part(struct shutdown_state *sds, const char *path, struct pool_replica *rep); void shutdown_state_set_dirty(struct shutdown_state *sds, struct pool_replica *rep); void shutdown_state_clear_dirty(struct shutdown_state *sds, struct pool_replica *rep); int shutdown_state_check(struct shutdown_state *curr_sds, struct shutdown_state *pool_sds, struct pool_replica *rep); #ifdef __cplusplus } #endif #endif /* shutdown_state.h */
2,475
33.873239
78
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/uuid.h
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * uuid.h -- internal definitions for uuid module */ #ifndef PMDK_UUID_H #define PMDK_UUID_H 1 #include <stdint.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /* * Structure for binary version of uuid. From RFC4122, * https://tools.ietf.org/html/rfc4122 */ struct uuid { uint32_t time_low; uint16_t time_mid; uint16_t time_hi_and_ver; uint8_t clock_seq_hi; uint8_t clock_seq_low; uint8_t node[6]; }; #define POOL_HDR_UUID_LEN 16 /* uuid byte length */ #define POOL_HDR_UUID_STR_LEN 37 /* uuid string length */ #define POOL_HDR_UUID_GEN_FILE "/proc/sys/kernel/random/uuid" typedef unsigned char uuid_t[POOL_HDR_UUID_LEN]; /* 16 byte binary uuid value */ int util_uuid_generate(uuid_t uuid); int util_uuid_to_string(const uuid_t u, char *buf); int util_uuid_from_string(const char uuid[POOL_HDR_UUID_STR_LEN], struct uuid *ud); /* * uuidcmp -- compare two uuids */ static inline int uuidcmp(const uuid_t uuid1, const uuid_t uuid2) { return memcmp(uuid1, uuid2, POOL_HDR_UUID_LEN); } #ifdef __cplusplus } #endif #endif
2,660
30.305882
80
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/badblock.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * badblock.c - common part of implementation of bad blocks API */ #define _GNU_SOURCE #include <fcntl.h> #include <inttypes.h> #include <errno.h> #include "file.h" #include "os.h" #include "out.h" #include "extent.h" #include "os_badblock.h" #include "badblock.h" /* * badblocks_new -- zalloc bad blocks structure */ struct badblocks * badblocks_new(void) { LOG(3, " "); struct badblocks *bbs = Zalloc(sizeof(struct badblocks)); if (bbs == NULL) { ERR("!Zalloc"); } return bbs; } /* * badblocks_delete -- free bad blocks structure */ void badblocks_delete(struct badblocks *bbs) { LOG(3, "badblocks %p", bbs); if (bbs == NULL) return; Free(bbs->bbv); Free(bbs); } /* helper structure for badblocks_check_file_cb() */ struct check_file_cb { int n_files_bbs; /* number of files with bad blocks */ int create; /* poolset is just being created */ }; /* * badblocks_check_file_cb -- (internal) callback checking bad blocks * in the given file */ static int badblocks_check_file_cb(struct part_file *pf, void *arg) { LOG(3, "part_file %p arg %p", pf, arg); struct check_file_cb *pcfcb = arg; if (pf->is_remote) { /* * Remote replicas are checked for bad blocks * while opening in util_pool_open_remote(). */ return 0; } int exists = util_file_exists(pf->part->path); if (exists < 0) return -1; if (!exists) /* the part does not exist, so it has no bad blocks */ return 0; int ret = os_badblocks_check_file(pf->part->path); if (ret < 0) { ERR("checking the pool file for bad blocks failed -- '%s'", pf->part->path); return -1; } if (ret > 0) { ERR("part file contains bad blocks -- '%s'", pf->part->path); pcfcb->n_files_bbs++; pf->part->has_bad_blocks = 1; } return 0; } /* * badblocks_check_poolset -- checks if the pool set contains bad blocks * * Return value: * -1 error * 0 pool set does not contain bad blocks * 1 pool set contains bad blocks */ int badblocks_check_poolset(struct pool_set *set, int create) { LOG(3, "set %p create %i", set, create); struct check_file_cb cfcb; cfcb.n_files_bbs = 0; cfcb.create = create; if (util_poolset_foreach_part_struct(set, badblocks_check_file_cb, &cfcb)) { return -1; } if (cfcb.n_files_bbs) { LOG(1, "%i pool file(s) contain bad blocks", cfcb.n_files_bbs); set->has_bad_blocks = 1; } return (cfcb.n_files_bbs > 0); } /* * badblocks_clear_poolset_cb -- (internal) callback clearing bad blocks * in the given file */ static int badblocks_clear_poolset_cb(struct part_file *pf, void *arg) { LOG(3, "part_file %p arg %p", pf, arg); int *create = arg; if (pf->is_remote) { /* XXX not supported yet */ LOG(1, "WARNING: clearing bad blocks in remote replicas is not supported yet -- '%s:%s'", pf->remote->node_addr, pf->remote->pool_desc); return 0; } if (*create) { /* * Poolset is just being created - check if file exists * and if we can read it. */ int exists = util_file_exists(pf->part->path); if (exists < 0) return -1; if (!exists) return 0; } int ret = os_badblocks_clear_all(pf->part->path); if (ret < 0) { ERR("clearing bad blocks in the pool file failed -- '%s'", pf->part->path); errno = EIO; return -1; } pf->part->has_bad_blocks = 0; return 0; } /* * badblocks_clear_poolset -- clears bad blocks in the pool set */ int badblocks_clear_poolset(struct pool_set *set, int create) { LOG(3, "set %p create %i", set, create); if (util_poolset_foreach_part_struct(set, badblocks_clear_poolset_cb, &create)) { return -1; } set->has_bad_blocks = 0; return 0; } /* * badblocks_recovery_file_alloc -- allocate name of bad block recovery file, * the allocated name has to be freed * using Free() */ char * badblocks_recovery_file_alloc(const char *file, unsigned rep, unsigned part) { LOG(3, "file %s rep %u part %u", file, rep, part); char bbs_suffix[32]; char *path; sprintf(bbs_suffix, "_r%u_p%u_badblocks.txt", rep, part); size_t len_file = strlen(file); size_t len_bbs_suffix = strlen(bbs_suffix); size_t len_path = len_file + len_bbs_suffix; path = Zalloc(len_path + 1); if (path == NULL) { ERR("!Zalloc"); return NULL; } strncpy(path, file, len_file); strncat(path, bbs_suffix, len_bbs_suffix); return path; } /* * badblocks_recovery_file_exists -- check if any bad block recovery file exists * * Returns: * 0 when there are no bad block recovery files and * 1 when there is at least one bad block recovery file. */ int badblocks_recovery_file_exists(struct pool_set *set) { LOG(3, "set %p", set); int recovery_file_exists = 0; for (unsigned r = 0; r < set->nreplicas; ++r) { struct pool_replica *rep = set->replica[r]; /* XXX: not supported yet */ if (rep->remote) continue; for (unsigned p = 0; p < rep->nparts; ++p) { const char *path = PART(rep, p)->path; int exists = util_file_exists(path); if (exists < 0) return -1; if (!exists) { /* part file does not exist - skip it */ continue; } char *rec_file = badblocks_recovery_file_alloc(set->path, r, p); if (rec_file == NULL) { LOG(1, "allocating name of bad block recovery file failed"); return -1; } exists = util_file_exists(rec_file); if (exists < 0) { Free(rec_file); return -1; } if (exists) { LOG(3, "bad block recovery file exists: %s", rec_file); recovery_file_exists = 1; } Free(rec_file); if (recovery_file_exists) return 1; } } return 0; }
7,257
21.968354
85
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/uuid.c
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * uuid.c -- uuid utilities */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "uuid.h" #include "out.h" /* * util_uuid_to_string -- generate a string form of the uuid */ int util_uuid_to_string(const uuid_t u, char *buf) { int len; /* size that is returned from sprintf call */ if (buf == NULL) { LOG(2, "invalid buffer for uuid string"); return -1; } if (u == NULL) { LOG(2, "invalid uuid structure"); return -1; } struct uuid *uuid = (struct uuid *)u; len = snprintf(buf, POOL_HDR_UUID_STR_LEN, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid->time_low, uuid->time_mid, uuid->time_hi_and_ver, uuid->clock_seq_hi, uuid->clock_seq_low, uuid->node[0], uuid->node[1], uuid->node[2], uuid->node[3], uuid->node[4], uuid->node[5]); if (len != POOL_HDR_UUID_STR_LEN - 1) { LOG(2, "snprintf(uuid): %d", len); return -1; } return 0; } /* * util_uuid_from_string -- generate a binary form of the uuid * * uuid string read from /proc/sys/kernel/random/uuid. UUID string * format example: * f81d4fae-7dec-11d0-a765-00a0c91e6bf6 */ int util_uuid_from_string(const char *uuid, struct uuid *ud) { if (strlen(uuid) != 36) { LOG(2, "invalid uuid string"); return -1; } if (uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' || uuid[23] != '-') { LOG(2, "invalid uuid string"); return -1; } int n = sscanf(uuid, "%08x-%04hx-%04hx-%02hhx%02hhx-" "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", &ud->time_low, &ud->time_mid, &ud->time_hi_and_ver, &ud->clock_seq_hi, &ud->clock_seq_low, &ud->node[0], &ud->node[1], &ud->node[2], &ud->node[3], &ud->node[4], &ud->node[5]); if (n != 11) { LOG(2, "sscanf(uuid)"); return -1; } return 0; }
3,333
28.504425
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/queue.h
/* * Source: glibc 2.24 (git://sourceware.org/glibc.git /misc/sys/queue.h) * * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ /* * This file defines five types of data structures: singly-linked lists, * lists, simple queues, tail queues, and circular queues. * * A singly-linked list is headed by a single forward pointer. The * elements are singly linked for minimum space and pointer manipulation * overhead at the expense of O(n) removal for arbitrary elements. New * elements can be added to the list after an existing element or at the * head of the list. Elements being removed from the head of the list * should use the explicit macro for this purpose for optimum * efficiency. A singly-linked list may only be traversed in the forward * direction. Singly-linked lists are ideal for applications with large * datasets and few or no removals or for implementing a LIFO queue. * * A list is headed by a single forward pointer (or an array of forward * pointers for a hash table header). The elements are doubly linked * so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before * or after an existing element or at the head of the list. A list * may only be traversed in the forward direction. * * A simple queue is headed by a pair of pointers, one the head of the * list and the other to the tail of the list. The elements are singly * linked to save space, so elements can only be removed from the * head of the list. New elements can be added to the list after * an existing element, at the head of the list, or at the end of the * list. A simple queue may only be traversed in the forward direction. * * A tail queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or * after an existing element, at the head of the list, or at the end of * the list. A tail queue may be traversed in either direction. * * A circle queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the list. * A circle queue may be traversed in either direction, but has a more * complex end of list detection. * * For details on the use of these macros, see the queue(3) manual page. */ /* * XXX This is a workaround for a bug in the llvm's static analyzer. For more * info see https://github.com/pmem/issues/issues/309. */ #ifdef __clang_analyzer__ static void custom_assert(void) { abort(); } #define ANALYZER_ASSERT(x) (__builtin_expect(!(x), 0) ? (void)0 : custom_assert()) #else #define ANALYZER_ASSERT(x) do {} while (0) #endif /* * List definitions. */ #define LIST_HEAD(name, type) \ struct name { \ struct type *lh_first; /* first element */ \ } #define LIST_HEAD_INITIALIZER(head) \ { NULL } #ifdef __cplusplus #define _CAST_AND_ASSIGN(x, y) x = (__typeof__(x))y; #else #define _CAST_AND_ASSIGN(x, y) x = (void *)(y); #endif #define LIST_ENTRY(type) \ struct { \ struct type *le_next; /* next element */ \ struct type **le_prev; /* address of previous next element */ \ } /* * List functions. */ #define LIST_INIT(head) do { \ (head)->lh_first = NULL; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_AFTER(listelm, elm, field) do { \ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ (listelm)->field.le_next->field.le_prev = \ &(elm)->field.le_next; \ (listelm)->field.le_next = (elm); \ (elm)->field.le_prev = &(listelm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.le_prev = (listelm)->field.le_prev; \ (elm)->field.le_next = (listelm); \ *(listelm)->field.le_prev = (elm); \ (listelm)->field.le_prev = &(elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.le_next = (head)->lh_first) != NULL) \ (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ (head)->lh_first = (elm); \ (elm)->field.le_prev = &(head)->lh_first; \ } while (/*CONSTCOND*/0) #define LIST_REMOVE(elm, field) do { \ ANALYZER_ASSERT((elm) != NULL); \ if ((elm)->field.le_next != NULL) \ (elm)->field.le_next->field.le_prev = \ (elm)->field.le_prev; \ *(elm)->field.le_prev = (elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_FOREACH(var, head, field) \ for ((var) = ((head)->lh_first); \ (var); \ (var) = ((var)->field.le_next)) /* * List access methods. */ #define LIST_EMPTY(head) ((head)->lh_first == NULL) #define LIST_FIRST(head) ((head)->lh_first) #define LIST_NEXT(elm, field) ((elm)->field.le_next) /* * Singly-linked List definitions. */ #define SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ } #define SLIST_HEAD_INITIALIZER(head) \ { NULL } #define SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } /* * Singly-linked List functions. */ #define SLIST_INIT(head) do { \ (head)->slh_first = NULL; \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ (elm)->field.sle_next = (slistelm)->field.sle_next; \ (slistelm)->field.sle_next = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_HEAD(head, elm, field) do { \ (elm)->field.sle_next = (head)->slh_first; \ (head)->slh_first = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE_HEAD(head, field) do { \ (head)->slh_first = (head)->slh_first->field.sle_next; \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE(head, elm, type, field) do { \ if ((head)->slh_first == (elm)) { \ SLIST_REMOVE_HEAD((head), field); \ } \ else { \ struct type *curelm = (head)->slh_first; \ while(curelm->field.sle_next != (elm)) \ curelm = curelm->field.sle_next; \ curelm->field.sle_next = \ curelm->field.sle_next->field.sle_next; \ } \ } while (/*CONSTCOND*/0) #define SLIST_FOREACH(var, head, field) \ for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) /* * Singly-linked List access methods. */ #define SLIST_EMPTY(head) ((head)->slh_first == NULL) #define SLIST_FIRST(head) ((head)->slh_first) #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) /* * Singly-linked Tail queue declarations. */ #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first; /* first element */ \ struct type **stqh_last; /* addr of last next element */ \ } #define STAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).stqh_first } #define STAILQ_ENTRY(type) \ struct { \ struct type *stqe_next; /* next element */ \ } /* * Singly-linked Tail queue functions. */ #define STAILQ_INIT(head) do { \ (head)->stqh_first = NULL; \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \ (head)->stqh_last = &(elm)->field.stqe_next; \ (head)->stqh_first = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.stqe_next = NULL; \ *(head)->stqh_last = (elm); \ (head)->stqh_last = &(elm)->field.stqe_next; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\ (head)->stqh_last = &(elm)->field.stqe_next; \ (listelm)->field.stqe_next = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE_HEAD(head, field) do { \ if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE(head, elm, type, field) do { \ if ((head)->stqh_first == (elm)) { \ STAILQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->stqh_first; \ while (curelm->field.stqe_next != (elm)) \ curelm = curelm->field.stqe_next; \ if ((curelm->field.stqe_next = \ curelm->field.stqe_next->field.stqe_next) == NULL) \ (head)->stqh_last = &(curelm)->field.stqe_next; \ } \ } while (/*CONSTCOND*/0) #define STAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->stqh_first); \ (var); \ (var) = ((var)->field.stqe_next)) #define STAILQ_CONCAT(head1, head2) do { \ if (!STAILQ_EMPTY((head2))) { \ *(head1)->stqh_last = (head2)->stqh_first; \ (head1)->stqh_last = (head2)->stqh_last; \ STAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Singly-linked Tail queue access methods. */ #define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) #define STAILQ_FIRST(head) ((head)->stqh_first) #define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) /* * Simple queue definitions. */ #define SIMPLEQ_HEAD(name, type) \ struct name { \ struct type *sqh_first; /* first element */ \ struct type **sqh_last; /* addr of last next element */ \ } #define SIMPLEQ_HEAD_INITIALIZER(head) \ { NULL, &(head).sqh_first } #define SIMPLEQ_ENTRY(type) \ struct { \ struct type *sqe_next; /* next element */ \ } /* * Simple queue functions. */ #define SIMPLEQ_INIT(head) do { \ (head)->sqh_first = NULL; \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ (head)->sqh_last = &(elm)->field.sqe_next; \ (head)->sqh_first = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.sqe_next = NULL; \ *(head)->sqh_last = (elm); \ (head)->sqh_last = &(elm)->field.sqe_next; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ (head)->sqh_last = &(elm)->field.sqe_next; \ (listelm)->field.sqe_next = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE(head, elm, type, field) do { \ if ((head)->sqh_first == (elm)) { \ SIMPLEQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->sqh_first; \ while (curelm->field.sqe_next != (elm)) \ curelm = curelm->field.sqe_next; \ if ((curelm->field.sqe_next = \ curelm->field.sqe_next->field.sqe_next) == NULL) \ (head)->sqh_last = &(curelm)->field.sqe_next; \ } \ } while (/*CONSTCOND*/0) #define SIMPLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->sqh_first); \ (var); \ (var) = ((var)->field.sqe_next)) /* * Simple queue access methods. */ #define SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) #define SIMPLEQ_FIRST(head) ((head)->sqh_first) #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) /* * Tail queue definitions. */ #define _TAILQ_HEAD(name, type, qual) \ struct name { \ qual type *tqh_first; /* first element */ \ qual type *qual *tqh_last; /* addr of last next element */ \ } #define TAILQ_HEAD(name, type) _TAILQ_HEAD(name, struct type,) #define TAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).tqh_first } #define _TAILQ_ENTRY(type, qual) \ struct { \ qual type *tqe_next; /* next element */ \ qual type *qual *tqe_prev; /* address of previous next element */\ } #define TAILQ_ENTRY(type) _TAILQ_ENTRY(struct type,) /* * Tail queue functions. */ #define TAILQ_INIT(head) do { \ (head)->tqh_first = NULL; \ (head)->tqh_last = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ (head)->tqh_first->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (head)->tqh_first = (elm); \ (elm)->field.tqe_prev = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.tqe_next = NULL; \ (elm)->field.tqe_prev = (head)->tqh_last; \ *(head)->tqh_last = (elm); \ (head)->tqh_last = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ (elm)->field.tqe_next->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (listelm)->field.tqe_next = (elm); \ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ (elm)->field.tqe_next = (listelm); \ *(listelm)->field.tqe_prev = (elm); \ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_REMOVE(head, elm, field) do { \ ANALYZER_ASSERT((elm) != NULL); \ if (((elm)->field.tqe_next) != NULL) \ (elm)->field.tqe_next->field.tqe_prev = \ (elm)->field.tqe_prev; \ else \ (head)->tqh_last = (elm)->field.tqe_prev; \ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->tqh_first); \ (var); \ (var) = ((var)->field.tqe_next)) #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \ (var); \ (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) #define TAILQ_CONCAT(head1, head2, field) do { \ if (!TAILQ_EMPTY(head2)) { \ *(head1)->tqh_last = (head2)->tqh_first; \ (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ (head1)->tqh_last = (head2)->tqh_last; \ TAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Tail queue access methods. */ #define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) #define TAILQ_FIRST(head) ((head)->tqh_first) #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) #define TAILQ_LAST(head, headname) \ (*(((struct headname *)((head)->tqh_last))->tqh_last)) #define TAILQ_PREV(elm, headname, field) \ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) /* * Circular queue definitions. */ #define CIRCLEQ_HEAD(name, type) \ struct name { \ struct type *cqh_first; /* first element */ \ struct type *cqh_last; /* last element */ \ } #define CIRCLEQ_HEAD_INITIALIZER(head) \ { (void *)&(head), (void *)&(head) } #define CIRCLEQ_ENTRY(type) \ struct { \ struct type *cqe_next; /* next element */ \ struct type *cqe_prev; /* previous element */ \ } /* * Circular queue functions. */ #define CIRCLEQ_INIT(head) do { \ _CAST_AND_ASSIGN((head)->cqh_first, (head)); \ _CAST_AND_ASSIGN((head)->cqh_last, (head)); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm)->field.cqe_next; \ (elm)->field.cqe_prev = (listelm); \ if ((listelm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (listelm)->field.cqe_next->field.cqe_prev = (elm); \ (listelm)->field.cqe_next = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm); \ (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ if ((listelm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (listelm)->field.cqe_prev->field.cqe_next = (elm); \ (listelm)->field.cqe_prev = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \ (elm)->field.cqe_next = (head)->cqh_first; \ (elm)->field.cqe_prev = (void *)(head); \ if ((head)->cqh_last == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (head)->cqh_first->field.cqe_prev = (elm); \ (head)->cqh_first = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \ _CAST_AND_ASSIGN((elm)->field.cqe_next, (head)); \ (elm)->field.cqe_prev = (head)->cqh_last; \ if ((head)->cqh_first == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (head)->cqh_last->field.cqe_next = (elm); \ (head)->cqh_last = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_REMOVE(head, elm, field) do { \ if ((elm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm)->field.cqe_prev; \ else \ (elm)->field.cqe_next->field.cqe_prev = \ (elm)->field.cqe_prev; \ if ((elm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm)->field.cqe_next; \ else \ (elm)->field.cqe_prev->field.cqe_next = \ (elm)->field.cqe_next; \ } while (/*CONSTCOND*/0) #define CIRCLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->cqh_first); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_next)) #define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ for ((var) = ((head)->cqh_last); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_prev)) /* * Circular queue access methods. */ #define CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head)) #define CIRCLEQ_FIRST(head) ((head)->cqh_first) #define CIRCLEQ_LAST(head) ((head)->cqh_last) #define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) #define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) #define CIRCLEQ_LOOP_NEXT(head, elm, field) \ (((elm)->field.cqe_next == (void *)(head)) \ ? ((head)->cqh_first) \ : ((elm)->field.cqe_next)) #define CIRCLEQ_LOOP_PREV(head, elm, field) \ (((elm)->field.cqe_prev == (void *)(head)) \ ? ((head)->cqh_last) \ : ((elm)->field.cqe_prev)) /* * Sorted queue functions. */ #define SORTEDQ_HEAD(name, type) CIRCLEQ_HEAD(name, type) #define SORTEDQ_HEAD_INITIALIZER(head) CIRCLEQ_HEAD_INITIALIZER(head) #define SORTEDQ_ENTRY(type) CIRCLEQ_ENTRY(type) #define SORTEDQ_INIT(head) CIRCLEQ_INIT(head) #define SORTEDQ_INSERT(head, elm, field, type, comparer) { \ type *_elm_it; \ for (_elm_it = (head)->cqh_first; \ ((_elm_it != (void *)(head)) && \ (comparer(_elm_it, (elm)) < 0)); \ _elm_it = _elm_it->field.cqe_next) \ /*NOTHING*/; \ if (_elm_it == (void *)(head)) \ CIRCLEQ_INSERT_TAIL(head, elm, field); \ else \ CIRCLEQ_INSERT_BEFORE(head, _elm_it, elm, field); \ } #define SORTEDQ_REMOVE(head, elm, field) CIRCLEQ_REMOVE(head, elm, field) #define SORTEDQ_FOREACH(var, head, field) CIRCLEQ_FOREACH(var, head, field) #define SORTEDQ_FOREACH_REVERSE(var, head, field) \ CIRCLEQ_FOREACH_REVERSE(var, head, field) /* * Sorted queue access methods. */ #define SORTEDQ_EMPTY(head) CIRCLEQ_EMPTY(head) #define SORTEDQ_FIRST(head) CIRCLEQ_FIRST(head) #define SORTEDQ_LAST(head) CIRCLEQ_LAST(head) #define SORTEDQ_NEXT(elm, field) CIRCLEQ_NEXT(elm, field) #define SORTEDQ_PREV(elm, field) CIRCLEQ_PREV(elm, field) #endif /* sys/queue.h */
21,518
32.888189
82
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/set.h
/* * Copyright 2014-2018, Intel Corporation * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * set.h -- internal definitions for set module */ #ifndef PMDK_SET_H #define PMDK_SET_H 1 #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <sys/types.h> #include "out.h" #include "vec.h" #include "pool_hdr.h" #include "librpmem.h" #ifdef __cplusplus extern "C" { #endif /* * pool sets & replicas */ #define POOLSET_HDR_SIG "PMEMPOOLSET" #define POOLSET_HDR_SIG_LEN 11 /* does NOT include '\0' */ #define POOLSET_REPLICA_SIG "REPLICA" #define POOLSET_REPLICA_SIG_LEN 7 /* does NOT include '\0' */ #define POOLSET_OPTION_SIG "OPTION" #define POOLSET_OPTION_SIG_LEN 6 /* does NOT include '\0' */ /* pool set option flags */ enum pool_set_option_flag { OPTION_UNKNOWN = 0x0, OPTION_SINGLEHDR = 0x1, /* pool headers only in the first part */ OPTION_NOHDRS = 0x2, /* no pool headers, remote replicas only */ }; struct pool_set_option { const char *name; enum pool_set_option_flag flag; }; #define POOL_LOCAL 0 #define POOL_REMOTE 1 #define REPLICAS_DISABLED 0 #define REPLICAS_ENABLED 1 /* util_pool_open flags */ #define POOL_OPEN_COW 1 /* copy-on-write mode */ #define POOL_OPEN_IGNORE_SDS 2 /* ignore shutdown state */ #define POOL_OPEN_IGNORE_BAD_BLOCKS 4 /* ignore bad blocks */ #define POOL_OPEN_CHECK_BAD_BLOCKS 8 /* check bad blocks */ enum del_parts_mode { DO_NOT_DELETE_PARTS, /* do not delete part files */ DELETE_CREATED_PARTS, /* delete only newly created parts files */ DELETE_ALL_PARTS /* force delete all parts files */ }; struct pool_set_part { /* populated by a pool set file parser */ const char *path; size_t filesize; /* aligned to page size */ int fd; int flags; /* stores flags used when opening the file */ /* valid only if fd >= 0 */ int is_dev_dax; /* indicates if the part is on device dax */ size_t alignment; /* internal alignment (Device DAX only) */ int created; /* indicates newly created (zeroed) file */ /* util_poolset_open/create */ void *remote_hdr; /* allocated header for remote replica */ void *hdr; /* base address of header */ size_t hdrsize; /* size of the header mapping */ int hdr_map_sync; /* header mapped with MAP_SYNC */ void *addr; /* base address of the mapping */ size_t size; /* size of the mapping - page aligned */ int map_sync; /* part has been mapped with MAP_SYNC flag */ int rdonly; /* is set based on compat features, affects */ /* the whole poolset */ uuid_t uuid; int has_bad_blocks; /* part file contains bad blocks */ int sds_dirty_modified; /* sds dirty flag was set */ }; struct pool_set_directory { const char *path; size_t resvsize; /* size of the address space reservation */ }; struct remote_replica { void *rpp; /* RPMEMpool opaque handle */ char *node_addr; /* address of a remote node */ /* poolset descriptor is a pool set file name on a remote node */ char *pool_desc; /* descriptor of a poolset */ }; struct pool_replica { unsigned nparts; unsigned nallocated; unsigned nhdrs; /* should be 0, 1 or nparts */ size_t repsize; /* total size of all the parts (mappings) */ size_t resvsize; /* min size of the address space reservation */ int is_pmem; /* true if all the parts are in PMEM */ void *mapaddr; /* base address (libpmemcto only) */ struct remote_replica *remote; /* not NULL if the replica */ /* is a remote one */ VEC(, struct pool_set_directory) directory; struct pool_set_part part[]; }; struct pool_set { char *path; /* path of the poolset file */ unsigned nreplicas; uuid_t uuid; int rdonly; int zeroed; /* true if all the parts are new files */ size_t poolsize; /* the smallest replica size */ int has_bad_blocks; /* pool set contains bad blocks */ int remote; /* true if contains a remote replica */ unsigned options; /* enabled pool set options */ int directory_based; size_t resvsize; unsigned next_id; unsigned next_directory_id; int ignore_sds; /* don't use shutdown state */ struct pool_replica *replica[]; }; struct part_file { int is_remote; /* * Pointer to the part file structure - * - not-NULL only for a local part file */ struct pool_set_part *part; /* * Pointer to the replica structure - * - not-NULL only for a remote replica */ struct remote_replica *remote; }; struct pool_attr { char signature[POOL_HDR_SIG_LEN]; /* pool signature */ uint32_t major; /* format major version number */ features_t features; /* features flags */ unsigned char poolset_uuid[POOL_HDR_UUID_LEN]; /* pool uuid */ unsigned char first_part_uuid[POOL_HDR_UUID_LEN]; /* first part uuid */ unsigned char prev_repl_uuid[POOL_HDR_UUID_LEN]; /* prev replica uuid */ unsigned char next_repl_uuid[POOL_HDR_UUID_LEN]; /* next replica uuid */ unsigned char arch_flags[POOL_HDR_ARCH_LEN]; /* arch flags */ }; /* get index of the (r)th replica */ static inline unsigned REPidx(const struct pool_set *set, unsigned r) { ASSERTne(set->nreplicas, 0); return (set->nreplicas + r) % set->nreplicas; } /* get index of the (r + 1)th replica */ static inline unsigned REPNidx(const struct pool_set *set, unsigned r) { ASSERTne(set->nreplicas, 0); return (set->nreplicas + r + 1) % set->nreplicas; } /* get index of the (r - 1)th replica */ static inline unsigned REPPidx(const struct pool_set *set, unsigned r) { ASSERTne(set->nreplicas, 0); return (set->nreplicas + r - 1) % set->nreplicas; } /* get index of the (r)th part */ static inline unsigned PARTidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nparts, 0); return (rep->nparts + p) % rep->nparts; } /* get index of the (r + 1)th part */ static inline unsigned PARTNidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nparts, 0); return (rep->nparts + p + 1) % rep->nparts; } /* get index of the (r - 1)th part */ static inline unsigned PARTPidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nparts, 0); return (rep->nparts + p - 1) % rep->nparts; } /* get index of the (r)th part */ static inline unsigned HDRidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nhdrs, 0); return (rep->nhdrs + p) % rep->nhdrs; } /* get index of the (r + 1)th part */ static inline unsigned HDRNidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nhdrs, 0); return (rep->nhdrs + p + 1) % rep->nhdrs; } /* get index of the (r - 1)th part */ static inline unsigned HDRPidx(const struct pool_replica *rep, unsigned p) { ASSERTne(rep->nhdrs, 0); return (rep->nhdrs + p - 1) % rep->nhdrs; } /* get (r)th replica */ static inline struct pool_replica * REP(const struct pool_set *set, unsigned r) { return set->replica[REPidx(set, r)]; } /* get (r + 1)th replica */ static inline struct pool_replica * REPN(const struct pool_set *set, unsigned r) { return set->replica[REPNidx(set, r)]; } /* get (r - 1)th replica */ static inline struct pool_replica * REPP(const struct pool_set *set, unsigned r) { return set->replica[REPPidx(set, r)]; } /* get (p)th part */ static inline struct pool_set_part * PART(struct pool_replica *rep, unsigned p) { return &rep->part[PARTidx(rep, p)]; } /* get (p + 1)th part */ static inline struct pool_set_part * PARTN(struct pool_replica *rep, unsigned p) { return &rep->part[PARTNidx(rep, p)]; } /* get (p - 1)th part */ static inline struct pool_set_part * PARTP(struct pool_replica *rep, unsigned p) { return &rep->part[PARTPidx(rep, p)]; } /* get (p)th header */ static inline struct pool_hdr * HDR(struct pool_replica *rep, unsigned p) { return (struct pool_hdr *)(rep->part[HDRidx(rep, p)].hdr); } /* get (p + 1)th header */ static inline struct pool_hdr * HDRN(struct pool_replica *rep, unsigned p) { return (struct pool_hdr *)(rep->part[HDRNidx(rep, p)].hdr); } /* get (p - 1)th header */ static inline struct pool_hdr * HDRP(struct pool_replica *rep, unsigned p) { return (struct pool_hdr *)(rep->part[HDRPidx(rep, p)].hdr); } extern int Prefault_at_open; extern int Prefault_at_create; int util_poolset_parse(struct pool_set **setp, const char *path, int fd); int util_poolset_read(struct pool_set **setp, const char *path); int util_poolset_create_set(struct pool_set **setp, const char *path, size_t poolsize, size_t minsize, int ignore_sds); int util_poolset_open(struct pool_set *set); void util_poolset_close(struct pool_set *set, enum del_parts_mode del); void util_poolset_free(struct pool_set *set); int util_poolset_chmod(struct pool_set *set, mode_t mode); void util_poolset_fdclose(struct pool_set *set); void util_poolset_fdclose_always(struct pool_set *set); int util_is_poolset_file(const char *path); int util_poolset_foreach_part_struct(struct pool_set *set, int (*cb)(struct part_file *pf, void *arg), void *arg); int util_poolset_foreach_part(const char *path, int (*cb)(struct part_file *pf, void *arg), void *arg); size_t util_poolset_size(const char *path); int util_replica_deep_common(const void *addr, size_t len, struct pool_set *set, unsigned replica_id, int flush); int util_replica_deep_persist(const void *addr, size_t len, struct pool_set *set, unsigned replica_id); int util_replica_deep_drain(const void *addr, size_t len, struct pool_set *set, unsigned replica_id); int util_pool_create(struct pool_set **setp, const char *path, size_t poolsize, size_t minsize, size_t minpartsize, const struct pool_attr *attr, unsigned *nlanes, int can_have_rep); int util_pool_create_uuids(struct pool_set **setp, const char *path, size_t poolsize, size_t minsize, size_t minpartsize, const struct pool_attr *attr, unsigned *nlanes, int can_have_rep, int remote); int util_part_open(struct pool_set_part *part, size_t minsize, int create); void util_part_fdclose(struct pool_set_part *part); int util_replica_open(struct pool_set *set, unsigned repidx, int flags); int util_replica_set_attr(struct pool_replica *rep, const struct rpmem_pool_attr *rattr); void util_pool_hdr2attr(struct pool_attr *attr, struct pool_hdr *hdr); void util_pool_attr2hdr(struct pool_hdr *hdr, const struct pool_attr *attr); int util_replica_close(struct pool_set *set, unsigned repidx); int util_map_part(struct pool_set_part *part, void *addr, size_t size, size_t offset, int flags, int rdonly); int util_unmap_part(struct pool_set_part *part); int util_unmap_parts(struct pool_replica *rep, unsigned start_index, unsigned end_index); int util_header_create(struct pool_set *set, unsigned repidx, unsigned partidx, const struct pool_attr *attr, int overwrite); int util_map_hdr(struct pool_set_part *part, int flags, int rdonly); int util_unmap_hdr(struct pool_set_part *part); int util_pool_has_device_dax(struct pool_set *set); int util_pool_open_nocheck(struct pool_set *set, unsigned flags); int util_pool_open(struct pool_set **setp, const char *path, size_t minpartsize, const struct pool_attr *attr, unsigned *nlanes, void *addr, unsigned flags); int util_pool_open_remote(struct pool_set **setp, const char *path, int cow, size_t minpartsize, struct rpmem_pool_attr *rattr); void *util_pool_extend(struct pool_set *set, size_t *size, size_t minpartsize); void util_remote_init(void); void util_remote_fini(void); int util_update_remote_header(struct pool_set *set, unsigned repn); void util_remote_init_lock(void); void util_remote_destroy_lock(void); int util_pool_close_remote(RPMEMpool *rpp); void util_remote_unload(void); void util_replica_fdclose(struct pool_replica *rep); int util_poolset_remote_open(struct pool_replica *rep, unsigned repidx, size_t minsize, int create, void *pool_addr, size_t pool_size, unsigned *nlanes); int util_remote_load(void); int util_replica_open_remote(struct pool_set *set, unsigned repidx, int flags); int util_poolset_remote_replica_open(struct pool_set *set, unsigned repidx, size_t minsize, int create, unsigned *nlanes); int util_replica_close_local(struct pool_replica *rep, unsigned repn, enum del_parts_mode del); int util_replica_close_remote(struct pool_replica *rep, unsigned repn, enum del_parts_mode del); extern int (*Rpmem_persist)(RPMEMpool *rpp, size_t offset, size_t length, unsigned lane, unsigned flags); extern int (*Rpmem_deep_persist)(RPMEMpool *rpp, size_t offset, size_t length, unsigned lane); extern int (*Rpmem_read)(RPMEMpool *rpp, void *buff, size_t offset, size_t length, unsigned lane); extern int (*Rpmem_close)(RPMEMpool *rpp); extern int (*Rpmem_remove)(const char *target, const char *pool_set_name, int flags); extern int (*Rpmem_set_attr)(RPMEMpool *rpp, const struct rpmem_pool_attr *rattr); #ifdef __cplusplus } #endif #endif
14,162
31.261959
80
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_dimm_windows.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_dimm_windows.c -- implementation of DIMMs API based on winapi */ #include "out.h" #include "os.h" #include "os_dimm.h" #include "util.h" #define GUID_SIZE sizeof("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") /* * os_dimm_volume -- returns volume handle */ static HANDLE os_dimm_volume_handle(const char *path) { wchar_t mount[MAX_PATH]; wchar_t volume[MAX_PATH]; wchar_t *wpath = util_toUTF16(path); if (wpath == NULL) return INVALID_HANDLE_VALUE; if (!GetVolumePathNameW(wpath, mount, MAX_PATH)) { ERR("!GetVolumePathNameW"); util_free_UTF16(wpath); return INVALID_HANDLE_VALUE; } util_free_UTF16(wpath); /* get volume name - "\\?\Volume{VOLUME_GUID}\" */ if (!GetVolumeNameForVolumeMountPointW(mount, volume, MAX_PATH) || wcslen(volume) == 0 || volume[wcslen(volume) - 1] != L'\\') { ERR("!GetVolumeNameForVolumeMountPointW"); return INVALID_HANDLE_VALUE; } /* * Remove trailing \\ as "CreateFile processes a volume GUID path with * an appended backslash as the root directory of the volume." */ volume[wcslen(volume) - 1] = L'\0'; HANDLE h = CreateFileW(volume, /* path to the file */ /* request access to send ioctl to the file */ FILE_READ_ATTRIBUTES, /* do not block access to the file */ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, /* security attributes */ OPEN_EXISTING, /* open only if it exists */ FILE_ATTRIBUTE_NORMAL, /* no attributes */ NULL); /* used only for new files */ if (h == INVALID_HANDLE_VALUE) ERR("!CreateFileW"); return h; } /* * os_dimm_uid -- returns a file uid based on dimm guid */ int os_dimm_uid(const char *path, char *uid, size_t *len) { LOG(3, "path %s, uid %p, len %lu", path, uid, *len); if (uid == NULL) { *len = GUID_SIZE; } else { ASSERT(*len >= GUID_SIZE); HANDLE vHandle = os_dimm_volume_handle(path); if (vHandle == INVALID_HANDLE_VALUE) return -1; STORAGE_DEVICE_NUMBER_EX sdn; sdn.DeviceNumber = -1; DWORD dwBytesReturned = 0; if (!DeviceIoControl(vHandle, IOCTL_STORAGE_GET_DEVICE_NUMBER_EX, NULL, 0, &sdn, sizeof(sdn), &dwBytesReturned, NULL)) { /* * IOCTL_STORAGE_GET_DEVICE_NUMBER_EX is not supported * on this server */ memset(uid, 0, *len); CloseHandle(vHandle); return 0; } GUID guid = sdn.DeviceGuid; snprintf(uid, GUID_SIZE, "%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); CloseHandle(vHandle); } return 0; } /* * os_dimm_usc -- returns unsafe shutdown count */ int os_dimm_usc(const char *path, uint64_t *usc) { LOG(3, "path %s, usc %p", path, usc); *usc = 0; HANDLE vHandle = os_dimm_volume_handle(path); if (vHandle == INVALID_HANDLE_VALUE) return -1; STORAGE_PROPERTY_QUERY prop; DWORD dwSize; prop.PropertyId = StorageDeviceUnsafeShutdownCount; prop.QueryType = PropertyExistsQuery; prop.AdditionalParameters[0] = 0; STORAGE_DEVICE_UNSAFE_SHUTDOWN_COUNT ret; BOOL bResult = DeviceIoControl(vHandle, IOCTL_STORAGE_QUERY_PROPERTY, &prop, sizeof(prop), &ret, sizeof(ret), (LPDWORD)&dwSize, (LPOVERLAPPED)NULL); if (!bResult) { CloseHandle(vHandle); return 0; /* STORAGE_PROPERTY_QUERY not supported */ } prop.QueryType = PropertyStandardQuery; bResult = DeviceIoControl(vHandle, IOCTL_STORAGE_QUERY_PROPERTY, &prop, sizeof(prop), &ret, sizeof(ret), (LPDWORD)&dwSize, (LPOVERLAPPED)NULL); CloseHandle(vHandle); if (!bResult) return -1; *usc = ret.UnsafeShutdownCount; return 0; } /* * os_dimm_files_namespace_badblocks -- fake os_dimm_files_namespace_badblocks() */ int os_dimm_files_namespace_badblocks(const char *path, struct badblocks *bbs) { LOG(3, "path %s", path); os_stat_t st; if (os_stat(path, &st)) { ERR("!stat %s", path); return -1; } return 0; } /* * os_dimm_devdax_clear_badblocks -- fake bad block clearing routine */ int os_dimm_devdax_clear_badblocks(const char *path, struct badblocks *bbs) { LOG(3, "path %s badblocks %p", path, bbs); return 0; } /* * os_dimm_devdax_clear_badblocks_all -- fake bad block clearing routine */ int os_dimm_devdax_clear_badblocks_all(const char *path) { LOG(3, "path %s", path); return 0; }
5,931
26.086758
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/dlsym.h
/* * Copyright 2016-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * dlsym.h -- dynamic linking utilities with library-specific implementation */ #ifndef PMDK_DLSYM_H #define PMDK_DLSYM_H 1 #include "out.h" #if defined(USE_LIBDL) && !defined(_WIN32) #include <dlfcn.h> /* * util_dlopen -- calls real dlopen() */ static inline void * util_dlopen(const char *filename) { LOG(3, "filename %s", filename); return dlopen(filename, RTLD_NOW); } /* * util_dlerror -- calls real dlerror() */ static inline char * util_dlerror(void) { return dlerror(); } /* * util_dlsym -- calls real dlsym() */ static inline void * util_dlsym(void *handle, const char *symbol) { LOG(3, "handle %p symbol %s", handle, symbol); return dlsym(handle, symbol); } /* * util_dlclose -- calls real dlclose() */ static inline int util_dlclose(void *handle) { LOG(3, "handle %p", handle); return dlclose(handle); } #else /* empty functions */ /* * util_dlopen -- empty function */ static inline void * util_dlopen(const char *filename) { errno = ENOSYS; return NULL; } /* * util_dlerror -- empty function */ static inline char * util_dlerror(void) { errno = ENOSYS; return NULL; } /* * util_dlsym -- empty function */ static inline void * util_dlsym(void *handle, const char *symbol) { errno = ENOSYS; return NULL; } /* * util_dlclose -- empty function */ static inline int util_dlclose(void *handle) { errno = ENOSYS; return 0; } #endif #endif
3,000
21.56391
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/shutdown_state.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * shutdown_state.c -- unsafe shudown detection */ #include <string.h> #include <stdbool.h> #include <endian.h> #include "shutdown_state.h" #include "os_dimm.h" #include "out.h" #include "util.h" #include "os_deep.h" #include "set.h" #define FLUSH_SDS(sds, rep) \ if ((rep) != NULL) os_part_deep_common(rep, 0, sds, sizeof(*(sds)), 1) /* * shutdown_state_checksum -- (internal) counts SDS checksum and flush it */ static void shutdown_state_checksum(struct shutdown_state *sds, struct pool_replica *rep) { LOG(3, "sds %p", sds); util_checksum(sds, sizeof(*sds), &sds->checksum, 1, 0); FLUSH_SDS(sds, rep); } /* * shutdown_state_init -- initializes shutdown_state struct */ int shutdown_state_init(struct shutdown_state *sds, struct pool_replica *rep) { /* check if we didn't change size of shutdown_state accidentally */ COMPILE_ERROR_ON(sizeof(struct shutdown_state) != 64); LOG(3, "sds %p", sds); memset(sds, 0, sizeof(*sds)); shutdown_state_checksum(sds, rep); return 0; } /* * shutdown_state_add_part -- adds file uuid and usc to shutdown_state struct * * if path does not exist it will fail which does NOT mean shutdown failure */ int shutdown_state_add_part(struct shutdown_state *sds, const char *path, struct pool_replica *rep) { LOG(3, "sds %p, path %s", sds, path); size_t len = 0; char *uid; uint64_t usc; if (os_dimm_usc(path, &usc)) { ERR("cannot read unsafe shutdown count of %s", path); return 1; } if (os_dimm_uid(path, NULL, &len)) { ERR("cannot read uuid of %s", path); return 1; } len += 4 - len % 4; uid = Zalloc(len); if (uid == NULL) { ERR("!Zalloc"); return 1; } if (os_dimm_uid(path, uid, &len)) { ERR("cannot read uuid of %s", path); Free(uid); return 1; } sds->usc = htole64(le64toh(sds->usc) + usc); uint64_t tmp; util_checksum(uid, len, &tmp, 1, 0); sds->uuid = htole64(le64toh(sds->uuid) + tmp); FLUSH_SDS(sds, rep); Free(uid); shutdown_state_checksum(sds, rep); return 0; } /* * shutdown_state_set_dirty -- sets dirty pool flag */ void shutdown_state_set_dirty(struct shutdown_state *sds, struct pool_replica *rep) { LOG(3, "sds %p", sds); sds->dirty = 1; rep->part[0].sds_dirty_modified = 1; FLUSH_SDS(sds, rep); shutdown_state_checksum(sds, rep); } /* * shutdown_state_clear_dirty -- clears dirty pool flag */ void shutdown_state_clear_dirty(struct shutdown_state *sds, struct pool_replica *rep) { LOG(3, "sds %p", sds); struct pool_set_part part = rep->part[0]; /* * If a dirty flag was set in previous program execution it should be * preserved as it stores information about potential ADR failure. */ if (part.sds_dirty_modified != 1) return; sds->dirty = 0; part.sds_dirty_modified = 0; FLUSH_SDS(sds, rep); shutdown_state_checksum(sds, rep); } /* * shutdown_state_reinit -- (internal) reinitializes shutdown_state struct */ static void shutdown_state_reinit(struct shutdown_state *curr_sds, struct shutdown_state *pool_sds, struct pool_replica *rep) { LOG(3, "curr_sds %p, pool_sds %p", curr_sds, pool_sds); shutdown_state_init(pool_sds, rep); pool_sds->uuid = htole64(curr_sds->uuid); pool_sds->usc = htole64(curr_sds->usc); pool_sds->dirty = 0; FLUSH_SDS(pool_sds, rep); shutdown_state_checksum(pool_sds, rep); } /* * shutdown_state_check -- compares and fixes shutdown state */ int shutdown_state_check(struct shutdown_state *curr_sds, struct shutdown_state *pool_sds, struct pool_replica *rep) { LOG(3, "curr_sds %p, pool_sds %p", curr_sds, pool_sds); if (util_is_zeroed(pool_sds, sizeof(*pool_sds)) && !util_is_zeroed(curr_sds, sizeof(*curr_sds))) { shutdown_state_reinit(curr_sds, pool_sds, rep); return 0; } bool is_uuid_usc_correct = le64toh(pool_sds->usc) == le64toh(curr_sds->usc) && le64toh(pool_sds->uuid) == le64toh(curr_sds->uuid); bool is_checksum_correct = util_checksum(pool_sds, sizeof(*pool_sds), &pool_sds->checksum, 0, 0); int dirty = pool_sds->dirty; if (!is_checksum_correct) { /* the program was killed during opening or closing the pool */ LOG(2, "incorrect checksum - SDS will be reinitialized"); shutdown_state_reinit(curr_sds, pool_sds, rep); return 0; } if (is_uuid_usc_correct) { if (dirty == 0) return 0; /* * the program was killed when the pool was opened * but there wasn't an ADR failure */ LOG(2, "the pool was not closed - SDS will be reinitialized"); shutdown_state_reinit(curr_sds, pool_sds, rep); return 0; } if (dirty == 0) { /* an ADR failure but the pool was closed */ LOG(2, "an ADR failure was detected but the pool was closed - SDS will be reinitialized"); shutdown_state_reinit(curr_sds, pool_sds, rep); return 0; } /* an ADR failure - the pool might be corrupted */ ERR("an ADR failure was detected, the pool might be corrupted"); return 1; }
6,440
25.615702
86
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_thread_windows.c
/* * Copyright 2015-2018, Intel Corporation * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_thread_windows.c -- (imperfect) POSIX-like threads for Windows * * Loosely inspired by: * http://locklessinc.com/articles/pthreads_on_windows/ */ #include <time.h> #include <synchapi.h> #include <sys/types.h> #include <sys/timeb.h> #include "os_thread.h" #include "util.h" #include "out.h" typedef struct { unsigned attr; CRITICAL_SECTION lock; } internal_os_mutex_t; typedef struct { unsigned attr; char is_write; SRWLOCK lock; } internal_os_rwlock_t; typedef struct { unsigned attr; CONDITION_VARIABLE cond; } internal_os_cond_t; typedef long long internal_os_once_t; typedef struct { HANDLE handle; } internal_semaphore_t; typedef struct { GROUP_AFFINITY affinity; } internal_os_cpu_set_t; typedef struct { HANDLE thread_handle; void *arg; void *(*start_routine)(void *); void *result; } internal_os_thread_t; /* number of useconds between 1970-01-01T00:00:00Z and 1601-01-01T00:00:00Z */ #define DELTA_WIN2UNIX (11644473600000000ull) #define TIMED_LOCK(action, ts) {\ if ((action) == TRUE)\ return 0;\ unsigned long long et = (ts)->tv_sec * 1000000000 + (ts)->tv_nsec;\ while (1) {\ FILETIME _t;\ GetSystemTimeAsFileTime(&_t);\ ULARGE_INTEGER _UI = {\ .HighPart = _t.dwHighDateTime,\ .LowPart = _t.dwLowDateTime,\ };\ if (100 * _UI.QuadPart - 1000 * DELTA_WIN2UNIX >= et)\ return ETIMEDOUT;\ if ((action) == TRUE)\ return 0;\ Sleep(1);\ }\ return ETIMEDOUT;\ } /* * os_mutex_init -- initializes mutex */ int os_mutex_init(os_mutex_t *__restrict mutex) { COMPILE_ERROR_ON(sizeof(os_mutex_t) < sizeof(internal_os_mutex_t)); internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; InitializeCriticalSection(&mutex_internal->lock); return 0; } /* * os_mutex_destroy -- destroys mutex */ int os_mutex_destroy(os_mutex_t *__restrict mutex) { internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; DeleteCriticalSection(&mutex_internal->lock); return 0; } /* * os_mutex_lock -- locks mutex */ _Use_decl_annotations_ int os_mutex_lock(os_mutex_t *__restrict mutex) { internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; EnterCriticalSection(&mutex_internal->lock); if (mutex_internal->lock.RecursionCount > 1) { LeaveCriticalSection(&mutex_internal->lock); FATAL("deadlock detected"); } return 0; } /* * os_mutex_trylock -- tries lock mutex */ _Use_decl_annotations_ int os_mutex_trylock(os_mutex_t *__restrict mutex) { internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; if (TryEnterCriticalSection(&mutex_internal->lock) == FALSE) return EBUSY; if (mutex_internal->lock.RecursionCount > 1) { LeaveCriticalSection(&mutex_internal->lock); return EBUSY; } return 0; } /* * os_mutex_timedlock -- tries lock mutex with timeout */ int os_mutex_timedlock(os_mutex_t *__restrict mutex, const struct timespec *abstime) { TIMED_LOCK((os_mutex_trylock(mutex) == 0), abstime); } /* * os_mutex_unlock -- unlocks mutex */ int os_mutex_unlock(os_mutex_t *__restrict mutex) { internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; LeaveCriticalSection(&mutex_internal->lock); return 0; } /* * os_rwlock_init -- initializes rwlock */ int os_rwlock_init(os_rwlock_t *__restrict rwlock) { COMPILE_ERROR_ON(sizeof(os_rwlock_t) < sizeof(internal_os_rwlock_t)); internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; InitializeSRWLock(&rwlock_internal->lock); return 0; } /* * os_rwlock_destroy -- destroys rwlock */ int os_rwlock_destroy(os_rwlock_t *__restrict rwlock) { /* do nothing */ UNREFERENCED_PARAMETER(rwlock); return 0; } /* * os_rwlock_rdlock -- get shared lock */ int os_rwlock_rdlock(os_rwlock_t *__restrict rwlock) { internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; AcquireSRWLockShared(&rwlock_internal->lock); rwlock_internal->is_write = 0; return 0; } /* * os_rwlock_wrlock -- get exclusive lock */ int os_rwlock_wrlock(os_rwlock_t *__restrict rwlock) { internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; AcquireSRWLockExclusive(&rwlock_internal->lock); rwlock_internal->is_write = 1; return 0; } /* * os_rwlock_tryrdlock -- tries get shared lock */ int os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock) { internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; if (TryAcquireSRWLockShared(&rwlock_internal->lock) == FALSE) { return EBUSY; } else { rwlock_internal->is_write = 0; return 0; } } /* * os_rwlock_trywrlock -- tries get exclusive lock */ _Use_decl_annotations_ int os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock) { internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; if (TryAcquireSRWLockExclusive(&rwlock_internal->lock) == FALSE) { return EBUSY; } else { rwlock_internal->is_write = 1; return 0; } } /* * os_rwlock_timedrdlock -- gets shared lock with timeout */ int os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock, const struct timespec *abstime) { TIMED_LOCK((os_rwlock_tryrdlock(rwlock) == 0), abstime); } /* * os_rwlock_timedwrlock -- gets exclusive lock with timeout */ int os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock, const struct timespec *abstime) { TIMED_LOCK((os_rwlock_trywrlock(rwlock) == 0), abstime); } /* * os_rwlock_unlock -- unlocks rwlock */ _Use_decl_annotations_ int os_rwlock_unlock(os_rwlock_t *__restrict rwlock) { internal_os_rwlock_t *rwlock_internal = (internal_os_rwlock_t *)rwlock; if (rwlock_internal->is_write) ReleaseSRWLockExclusive(&rwlock_internal->lock); else ReleaseSRWLockShared(&rwlock_internal->lock); return 0; } /* * os_cond_init -- initializes condition variable */ int os_cond_init(os_cond_t *__restrict cond) { COMPILE_ERROR_ON(sizeof(os_cond_t) < sizeof(internal_os_cond_t)); internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond; InitializeConditionVariable(&cond_internal->cond); return 0; } /* * os_cond_destroy -- destroys condition variable */ int os_cond_destroy(os_cond_t *__restrict cond) { /* do nothing */ UNREFERENCED_PARAMETER(cond); return 0; } /* * os_cond_broadcast -- broadcast condition variable */ int os_cond_broadcast(os_cond_t *__restrict cond) { internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond; WakeAllConditionVariable(&cond_internal->cond); return 0; } /* * os_cond_wait -- signal condition variable */ int os_cond_signal(os_cond_t *__restrict cond) { internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond; WakeConditionVariable(&cond_internal->cond); return 0; } /* * get_rel_wait -- (internal) convert timespec to windows timeout */ static DWORD get_rel_wait(const struct timespec *abstime) { struct __timeb64 t; _ftime64_s(&t); time_t now_ms = t.time * 1000 + t.millitm; time_t ms = (time_t)(abstime->tv_sec * 1000 + abstime->tv_nsec / 1000000); DWORD rel_wait = (DWORD)(ms - now_ms); return rel_wait < 0 ? 0 : rel_wait; } /* * os_cond_timedwait -- waits on condition variable with timeout */ int os_cond_timedwait(os_cond_t *__restrict cond, os_mutex_t *__restrict mutex, const struct timespec *abstime) { internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond; internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; BOOL ret; SetLastError(0); ret = SleepConditionVariableCS(&cond_internal->cond, &mutex_internal->lock, get_rel_wait(abstime)); if (ret == FALSE) return (GetLastError() == ERROR_TIMEOUT) ? ETIMEDOUT : EINVAL; return 0; } /* * os_cond_wait -- waits on condition variable */ int os_cond_wait(os_cond_t *__restrict cond, os_mutex_t *__restrict mutex) { internal_os_cond_t *cond_internal = (internal_os_cond_t *)cond; internal_os_mutex_t *mutex_internal = (internal_os_mutex_t *)mutex; /* XXX - return error code based on GetLastError() */ BOOL ret; ret = SleepConditionVariableCS(&cond_internal->cond, &mutex_internal->lock, INFINITE); return (ret == FALSE) ? EINVAL : 0; } /* * os_once -- once-only function call */ int os_once(os_once_t *once, void (*func)(void)) { internal_os_once_t *once_internal = (internal_os_once_t *)once; internal_os_once_t tmp; while ((tmp = *once_internal) != 2) { if (tmp == 1) continue; /* another thread is already calling func() */ /* try to be the first one... */ if (!util_bool_compare_and_swap64(once_internal, tmp, 1)) continue; /* sorry, another thread was faster */ func(); if (!util_bool_compare_and_swap64(once_internal, 1, 2)) { ERR("error setting once"); return -1; } } return 0; } /* * os_tls_key_create -- creates a new tls key */ int os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *)) { *key = FlsAlloc(destructor); if (*key == TLS_OUT_OF_INDEXES) return EAGAIN; return 0; } /* * os_tls_key_delete -- deletes key from tls */ int os_tls_key_delete(os_tls_key_t key) { if (!FlsFree(key)) return EINVAL; return 0; } /* * os_tls_set -- sets a value in tls */ int os_tls_set(os_tls_key_t key, const void *value) { if (!FlsSetValue(key, (LPVOID)value)) return ENOENT; return 0; } /* * os_tls_get -- gets a value from tls */ void * os_tls_get(os_tls_key_t key) { return FlsGetValue(key); } /* threading */ /* * os_thread_start_routine_wrapper is a start routine for _beginthreadex() and * it helps: * * - wrap the os_thread_create's start function */ static unsigned __stdcall os_thread_start_routine_wrapper(void *arg) { internal_os_thread_t *thread_info = (internal_os_thread_t *)arg; thread_info->result = thread_info->start_routine(thread_info->arg); return 0; } /* * os_thread_create -- starts a new thread */ int os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr, void *(*start_routine)(void *), void *arg) { COMPILE_ERROR_ON(sizeof(os_thread_t) < sizeof(internal_os_thread_t)); internal_os_thread_t *thread_info = (internal_os_thread_t *)thread; thread_info->start_routine = start_routine; thread_info->arg = arg; thread_info->thread_handle = (HANDLE)_beginthreadex(NULL, 0, os_thread_start_routine_wrapper, thread_info, CREATE_SUSPENDED, NULL); if (thread_info->thread_handle == 0) { free(thread_info); return errno; } if (ResumeThread(thread_info->thread_handle) == -1) { free(thread_info); return EAGAIN; } return 0; } /* * os_thread_join -- joins a thread */ int os_thread_join(os_thread_t *thread, void **result) { internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread; WaitForSingleObject(internal_thread->thread_handle, INFINITE); CloseHandle(internal_thread->thread_handle); if (result != NULL) *result = internal_thread->result; return 0; } /* * os_thread_self -- returns handle to calling thread */ void os_thread_self(os_thread_t *thread) { internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread; internal_thread->thread_handle = GetCurrentThread(); } /* * os_cpu_zero -- clears cpu set */ void os_cpu_zero(os_cpu_set_t *set) { internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set; memset(&internal_set->affinity, 0, sizeof(internal_set->affinity)); } /* * os_cpu_set -- adds cpu to set */ void os_cpu_set(size_t cpu, os_cpu_set_t *set) { internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set; int sum = 0; int group_max = GetActiveProcessorGroupCount(); int group = 0; while (group < group_max) { sum += GetActiveProcessorCount(group); if (sum > cpu) { /* * XXX: can't set affinity to two different cpu groups */ if (internal_set->affinity.Group != group) { internal_set->affinity.Mask = 0; internal_set->affinity.Group = group; } cpu -= sum - GetActiveProcessorCount(group); internal_set->affinity.Mask |= 1LL << cpu; return; } group++; } FATAL("os_cpu_set cpu out of bounds"); } /* * os_thread_setaffinity_np -- sets affinity of the thread */ int os_thread_setaffinity_np(os_thread_t *thread, size_t set_size, const os_cpu_set_t *set) { internal_os_cpu_set_t *internal_set = (internal_os_cpu_set_t *)set; internal_os_thread_t *internal_thread = (internal_os_thread_t *)thread; int ret = SetThreadGroupAffinity(internal_thread->thread_handle, &internal_set->affinity, NULL); return ret != 0 ? 0 : EINVAL; } /* * os_semaphore_init -- initializes a new semaphore instance */ int os_semaphore_init(os_semaphore_t *sem, unsigned value) { internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem; internal_sem->handle = CreateSemaphore(NULL, value, LONG_MAX, NULL); return internal_sem->handle != 0 ? 0 : -1; } /* * os_semaphore_destroy -- destroys a semaphore instance */ int os_semaphore_destroy(os_semaphore_t *sem) { internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem; BOOL ret = CloseHandle(internal_sem->handle); return ret ? 0 : -1; } /* * os_semaphore_wait -- decreases the value of the semaphore */ int os_semaphore_wait(os_semaphore_t *sem) { internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem; DWORD ret = WaitForSingleObject(internal_sem->handle, INFINITE); return ret == WAIT_OBJECT_0 ? 0 : -1; } /* * os_semaphore_trywait -- tries to decrease the value of the semaphore */ int os_semaphore_trywait(os_semaphore_t *sem) { internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem; DWORD ret = WaitForSingleObject(internal_sem->handle, 0); if (ret == WAIT_TIMEOUT) errno = EAGAIN; return ret == WAIT_OBJECT_0 ? 0 : -1; } /* * os_semaphore_post -- increases the value of the semaphore */ int os_semaphore_post(os_semaphore_t *sem) { internal_semaphore_t *internal_sem = (internal_semaphore_t *)sem; BOOL ret = ReleaseSemaphore(internal_sem->handle, 1, NULL); return ret ? 0 : -1; }
15,381
22.412481
78
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/out.c
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * out.c -- support for logging, tracing, and assertion output * * Macros like LOG(), OUT, ASSERT(), etc. end up here. */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <unistd.h> #include <limits.h> #include <string.h> #include <errno.h> #include "out.h" #include "os.h" #include "os_thread.h" #include "valgrind_internal.h" #include "util.h" /* XXX - modify Linux makefiles to generate srcversion.h and remove #ifdef */ #ifdef _WIN32 #include "srcversion.h" #endif static const char *Log_prefix; static int Log_level; static FILE *Out_fp; static unsigned Log_alignment; #ifndef NO_LIBPTHREAD #define MAXPRINT 8192 /* maximum expected log line */ #else #define MAXPRINT 256 /* maximum expected log line for libpmem */ #endif struct errormsg { char msg[MAXPRINT]; #ifdef _WIN32 wchar_t wmsg[MAXPRINT]; #endif }; #ifndef NO_LIBPTHREAD static os_once_t Last_errormsg_key_once = OS_ONCE_INIT; static os_tls_key_t Last_errormsg_key; static void _Last_errormsg_key_alloc(void) { int pth_ret = os_tls_key_create(&Last_errormsg_key, free); if (pth_ret) FATAL("!os_thread_key_create"); VALGRIND_ANNOTATE_HAPPENS_BEFORE(&Last_errormsg_key_once); } static void Last_errormsg_key_alloc(void) { os_once(&Last_errormsg_key_once, _Last_errormsg_key_alloc); /* * Workaround Helgrind's bug: * https://bugs.kde.org/show_bug.cgi?id=337735 */ VALGRIND_ANNOTATE_HAPPENS_AFTER(&Last_errormsg_key_once); } static inline void Last_errormsg_fini(void) { void *p = os_tls_get(Last_errormsg_key); if (p) { free(p); (void) os_tls_set(Last_errormsg_key, NULL); } (void) os_tls_key_delete(Last_errormsg_key); } static inline struct errormsg * Last_errormsg_get(void) { Last_errormsg_key_alloc(); struct errormsg *errormsg = os_tls_get(Last_errormsg_key); if (errormsg == NULL) { errormsg = malloc(sizeof(struct errormsg)); if (errormsg == NULL) FATAL("!malloc"); /* make sure it contains empty string initially */ errormsg->msg[0] = '\0'; int ret = os_tls_set(Last_errormsg_key, errormsg); if (ret) FATAL("!os_tls_set"); } return errormsg; } #else /* * We don't want libpmem to depend on libpthread. Instead of using pthread * API to dynamically allocate thread-specific error message buffer, we put * it into TLS. However, keeping a pretty large static buffer (8K) in TLS * may lead to some issues, so the maximum message length is reduced. * Fortunately, it looks like the longest error message in libpmem should * not be longer than about 90 chars (in case of pmem_check_version()). */ static __thread struct errormsg Last_errormsg; static inline void Last_errormsg_key_alloc(void) { } static inline void Last_errormsg_fini(void) { } static inline const struct errormsg * Last_errormsg_get(void) { return &Last_errormsg.msg[0]; } #endif /* NO_LIBPTHREAD */ /* * out_init -- initialize the log * * This is called from the library initialization code. */ void out_init(const char *log_prefix, const char *log_level_var, const char *log_file_var, int major_version, int minor_version) { static int once; /* only need to initialize the out module once */ if (once) return; once++; Log_prefix = log_prefix; #ifdef DEBUG char *log_level; char *log_file; if ((log_level = os_getenv(log_level_var)) != NULL) { Log_level = atoi(log_level); if (Log_level < 0) { Log_level = 0; } } if ((log_file = os_getenv(log_file_var)) != NULL && log_file[0] != '\0') { /* reserve more than enough space for a PID + '\0' */ char log_file_pid[PATH_MAX]; size_t len = strlen(log_file); if (len > 0 && log_file[len - 1] == '-') { int ret = snprintf(log_file_pid, PATH_MAX, "%s%d", log_file, getpid()); if (ret < 0 || ret >= PATH_MAX) { ERR("snprintf: %d", ret); abort(); } log_file = log_file_pid; } if ((Out_fp = os_fopen(log_file, "w")) == NULL) { char buff[UTIL_MAX_ERR_MSG]; util_strerror(errno, buff, UTIL_MAX_ERR_MSG); fprintf(stderr, "Error (%s): %s=%s: %s\n", log_prefix, log_file_var, log_file, buff); abort(); } } #endif /* DEBUG */ char *log_alignment = os_getenv("PMDK_LOG_ALIGN"); if (log_alignment) { int align = atoi(log_alignment); if (align > 0) Log_alignment = (unsigned)align; } if (Out_fp == NULL) Out_fp = stderr; else setlinebuf(Out_fp); #ifdef DEBUG static char namepath[PATH_MAX]; LOG(1, "pid %d: program: %s", getpid(), util_getexecname(namepath, PATH_MAX)); #endif LOG(1, "%s version %d.%d", log_prefix, major_version, minor_version); static __attribute__((used)) const char *version_msg = "src version: " SRCVERSION; LOG(1, "%s", version_msg); #if VG_PMEMCHECK_ENABLED /* * Attribute "used" to prevent compiler from optimizing out the variable * when LOG expands to no code (!DEBUG) */ static __attribute__((used)) const char *pmemcheck_msg = "compiled with support for Valgrind pmemcheck"; LOG(1, "%s", pmemcheck_msg); #endif /* VG_PMEMCHECK_ENABLED */ #if VG_HELGRIND_ENABLED static __attribute__((used)) const char *helgrind_msg = "compiled with support for Valgrind helgrind"; LOG(1, "%s", helgrind_msg); #endif /* VG_HELGRIND_ENABLED */ #if VG_MEMCHECK_ENABLED static __attribute__((used)) const char *memcheck_msg = "compiled with support for Valgrind memcheck"; LOG(1, "%s", memcheck_msg); #endif /* VG_MEMCHECK_ENABLED */ #if VG_DRD_ENABLED static __attribute__((used)) const char *drd_msg = "compiled with support for Valgrind drd"; LOG(1, "%s", drd_msg); #endif /* VG_DRD_ENABLED */ #if SDS_ENABLED static __attribute__((used)) const char *shutdown_state_msg = "compiled with support for shutdown state"; LOG(1, "%s", shutdown_state_msg); #endif Last_errormsg_key_alloc(); } /* * out_fini -- close the log file * * This is called to close log file before process stop. */ void out_fini(void) { if (Out_fp != NULL && Out_fp != stderr) { fclose(Out_fp); Out_fp = stderr; } Last_errormsg_fini(); } /* * out_print_func -- default print_func, goes to stderr or Out_fp */ static void out_print_func(const char *s) { /* to suppress drd false-positive */ /* XXX: confirm real nature of this issue: pmem/issues#863 */ #ifdef SUPPRESS_FPUTS_DRD_ERROR VALGRIND_ANNOTATE_IGNORE_READS_BEGIN(); VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN(); #endif fputs(s, Out_fp); #ifdef SUPPRESS_FPUTS_DRD_ERROR VALGRIND_ANNOTATE_IGNORE_READS_END(); VALGRIND_ANNOTATE_IGNORE_WRITES_END(); #endif } /* * calling Print(s) calls the current print_func... */ typedef void (*Print_func)(const char *s); typedef int (*Vsnprintf_func)(char *str, size_t size, const char *format, va_list ap); static Print_func Print = out_print_func; static Vsnprintf_func Vsnprintf = vsnprintf; /* * out_set_print_func -- allow override of print_func used by out module */ void out_set_print_func(void (*print_func)(const char *s)) { LOG(3, "print %p", print_func); Print = (print_func == NULL) ? out_print_func : print_func; } /* * out_set_vsnprintf_func -- allow override of vsnprintf_func used by out module */ void out_set_vsnprintf_func(int (*vsnprintf_func)(char *str, size_t size, const char *format, va_list ap)) { LOG(3, "vsnprintf %p", vsnprintf_func); Vsnprintf = (vsnprintf_func == NULL) ? vsnprintf : vsnprintf_func; } /* * out_snprintf -- (internal) custom snprintf implementation */ FORMAT_PRINTF(3, 4) static int out_snprintf(char *str, size_t size, const char *format, ...) { int ret; va_list ap; va_start(ap, format); ret = Vsnprintf(str, size, format, ap); va_end(ap); return (ret); } /* * out_common -- common output code, all output goes through here */ static void out_common(const char *file, int line, const char *func, int level, const char *suffix, const char *fmt, va_list ap) { int oerrno = errno; char buf[MAXPRINT]; unsigned cc = 0; int ret; const char *sep = ""; char errstr[UTIL_MAX_ERR_MSG] = ""; if (file) { char *f = strrchr(file, OS_DIR_SEPARATOR); if (f) file = f + 1; ret = out_snprintf(&buf[cc], MAXPRINT - cc, "<%s>: <%d> [%s:%d %s] ", Log_prefix, level, file, line, func); if (ret < 0) { Print("out_snprintf failed"); goto end; } cc += (unsigned)ret; if (cc < Log_alignment) { memset(buf + cc, ' ', Log_alignment - cc); cc = Log_alignment; } } if (fmt) { if (*fmt == '!') { fmt++; sep = ": "; util_strerror(errno, errstr, UTIL_MAX_ERR_MSG); } ret = Vsnprintf(&buf[cc], MAXPRINT - cc, fmt, ap); if (ret < 0) { Print("Vsnprintf failed"); goto end; } cc += (unsigned)ret; } out_snprintf(&buf[cc], MAXPRINT - cc, "%s%s%s", sep, errstr, suffix); Print(buf); end: errno = oerrno; } /* * out_error -- common error output code, all error messages go through here */ static void out_error(const char *file, int line, const char *func, const char *suffix, const char *fmt, va_list ap) { int oerrno = errno; unsigned cc = 0; int ret; const char *sep = ""; char errstr[UTIL_MAX_ERR_MSG] = ""; char *errormsg = (char *)out_get_errormsg(); if (fmt) { if (*fmt == '!') { fmt++; sep = ": "; util_strerror(errno, errstr, UTIL_MAX_ERR_MSG); } ret = Vsnprintf(&errormsg[cc], MAXPRINT, fmt, ap); if (ret < 0) { strcpy(errormsg, "Vsnprintf failed"); goto end; } cc += (unsigned)ret; out_snprintf(&errormsg[cc], MAXPRINT - cc, "%s%s", sep, errstr); } #ifdef DEBUG if (Log_level >= 1) { char buf[MAXPRINT]; cc = 0; if (file) { char *f = strrchr(file, OS_DIR_SEPARATOR); if (f) file = f + 1; ret = out_snprintf(&buf[cc], MAXPRINT, "<%s>: <1> [%s:%d %s] ", Log_prefix, file, line, func); if (ret < 0) { Print("out_snprintf failed"); goto end; } cc += (unsigned)ret; if (cc < Log_alignment) { memset(buf + cc, ' ', Log_alignment - cc); cc = Log_alignment; } } out_snprintf(&buf[cc], MAXPRINT - cc, "%s%s", errormsg, suffix); Print(buf); } #endif end: errno = oerrno; } /* * out -- output a line, newline added automatically */ void out(const char *fmt, ...) { va_list ap; va_start(ap, fmt); out_common(NULL, 0, NULL, 0, "\n", fmt, ap); va_end(ap); } /* * out_nonl -- output a line, no newline added automatically */ void out_nonl(int level, const char *fmt, ...) { va_list ap; if (Log_level < level) return; va_start(ap, fmt); out_common(NULL, 0, NULL, level, "", fmt, ap); va_end(ap); } /* * out_log -- output a log line if Log_level >= level */ void out_log(const char *file, int line, const char *func, int level, const char *fmt, ...) { va_list ap; if (Log_level < level) return; va_start(ap, fmt); out_common(file, line, func, level, "\n", fmt, ap); va_end(ap); } /* * out_fatal -- output a fatal error & die (i.e. assertion failure) */ void out_fatal(const char *file, int line, const char *func, const char *fmt, ...) { va_list ap; va_start(ap, fmt); out_common(file, line, func, 1, "\n", fmt, ap); va_end(ap); abort(); } /* * out_err -- output an error message */ void out_err(const char *file, int line, const char *func, const char *fmt, ...) { va_list ap; va_start(ap, fmt); out_error(file, line, func, "\n", fmt, ap); va_end(ap); } /* * out_get_errormsg -- get the last error message */ const char * out_get_errormsg(void) { const struct errormsg *errormsg = Last_errormsg_get(); return &errormsg->msg[0]; } #ifdef _WIN32 /* * out_get_errormsgW -- get the last error message in wchar_t */ const wchar_t * out_get_errormsgW(void) { struct errormsg *errormsg = Last_errormsg_get(); const char *utf8 = &errormsg->msg[0]; wchar_t *utf16 = &errormsg->wmsg[0]; if (util_toUTF16_buff(utf8, utf16, sizeof(errormsg->wmsg)) != 0) FATAL("!Failed to convert string"); return (const wchar_t *)utf16; } #endif
13,370
21.817406
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/sys_util.h
/* * Copyright 2016-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * sys_util.h -- internal utility wrappers around system functions */ #ifndef PMDK_SYS_UTIL_H #define PMDK_SYS_UTIL_H 1 #include <errno.h> #include "os_thread.h" #ifdef __cplusplus extern "C" { #endif /* * util_mutex_init -- os_mutex_init variant that never fails from * caller perspective. If os_mutex_init failed, this function aborts * the program. */ static inline void util_mutex_init(os_mutex_t *m) { int tmp = os_mutex_init(m); if (tmp) { errno = tmp; FATAL("!os_mutex_init"); } } /* * util_mutex_destroy -- os_mutex_destroy variant that never fails from * caller perspective. If os_mutex_destroy failed, this function aborts * the program. */ static inline void util_mutex_destroy(os_mutex_t *m) { int tmp = os_mutex_destroy(m); if (tmp) { errno = tmp; FATAL("!os_mutex_destroy"); } } /* * util_mutex_lock -- os_mutex_lock variant that never fails from * caller perspective. If os_mutex_lock failed, this function aborts * the program. */ static inline void util_mutex_lock(os_mutex_t *m) { int tmp = os_mutex_lock(m); if (tmp) { errno = tmp; FATAL("!os_mutex_lock"); } } /* * util_mutex_trylock -- os_mutex_trylock variant that never fails from * caller perspective (other than EBUSY). If util_mutex_trylock failed, this * function aborts the program. * Returns 0 if locked successfully, otherwise returns EBUSY. */ static inline int util_mutex_trylock(os_mutex_t *m) { int tmp = os_mutex_trylock(m); if (tmp && tmp != EBUSY) { errno = tmp; FATAL("!os_mutex_trylock"); } return tmp; } /* * util_mutex_unlock -- os_mutex_unlock variant that never fails from * caller perspective. If os_mutex_unlock failed, this function aborts * the program. */ static inline void util_mutex_unlock(os_mutex_t *m) { int tmp = os_mutex_unlock(m); if (tmp) { errno = tmp; FATAL("!os_mutex_unlock"); } } /* * util_rwlock_init -- os_rwlock_init variant that never fails from * caller perspective. If os_rwlock_init failed, this function aborts * the program. */ static inline void util_rwlock_init(os_rwlock_t *m) { int tmp = os_rwlock_init(m); if (tmp) { errno = tmp; FATAL("!os_rwlock_init"); } } /* * util_rwlock_rdlock -- os_rwlock_rdlock variant that never fails from * caller perspective. If os_rwlock_rdlock failed, this function aborts * the program. */ static inline void util_rwlock_rdlock(os_rwlock_t *m) { int tmp = os_rwlock_rdlock(m); if (tmp) { errno = tmp; FATAL("!os_rwlock_rdlock"); } } /* * util_rwlock_wrlock -- os_rwlock_wrlock variant that never fails from * caller perspective. If os_rwlock_wrlock failed, this function aborts * the program. */ static inline void util_rwlock_wrlock(os_rwlock_t *m) { int tmp = os_rwlock_wrlock(m); if (tmp) { errno = tmp; FATAL("!os_rwlock_wrlock"); } } /* * util_rwlock_unlock -- os_rwlock_unlock variant that never fails from * caller perspective. If os_rwlock_unlock failed, this function aborts * the program. */ static inline void util_rwlock_unlock(os_rwlock_t *m) { int tmp = os_rwlock_unlock(m); if (tmp) { errno = tmp; FATAL("!os_rwlock_unlock"); } } /* * util_rwlock_destroy -- os_rwlock_destroy variant that never fails from * caller perspective. If os_rwlock_destroy failed, this function aborts * the program. */ static inline void util_rwlock_destroy(os_rwlock_t *m) { int tmp = os_rwlock_destroy(m); if (tmp) { errno = tmp; FATAL("!os_rwlock_destroy"); } } /* * util_spin_init -- os_spin_init variant that logs on fail and sets errno. */ static inline int util_spin_init(os_spinlock_t *lock, int pshared) { int tmp = os_spin_init(lock, pshared); if (tmp) { errno = tmp; ERR("!os_spin_init"); } return tmp; } /* * util_spin_destroy -- os_spin_destroy variant that never fails from * caller perspective. If os_spin_destroy failed, this function aborts * the program. */ static inline void util_spin_destroy(os_spinlock_t *lock) { int tmp = os_spin_destroy(lock); if (tmp) { errno = tmp; FATAL("!os_spin_destroy"); } } /* * util_spin_lock -- os_spin_lock variant that never fails from caller * perspective. If os_spin_lock failed, this function aborts the program. */ static inline void util_spin_lock(os_spinlock_t *lock) { int tmp = os_spin_lock(lock); if (tmp) { errno = tmp; FATAL("!os_spin_lock"); } } /* * util_spin_unlock -- os_spin_unlock variant that never fails * from caller perspective. If os_spin_unlock failed, * this function aborts the program. */ static inline void util_spin_unlock(os_spinlock_t *lock) { int tmp = os_spin_unlock(lock); if (tmp) { errno = tmp; FATAL("!os_spin_unlock"); } } /* * util_semaphore_init -- os_semaphore_init variant that never fails * from caller perspective. If os_semaphore_init failed, * this function aborts the program. */ static inline void util_semaphore_init(os_semaphore_t *sem, unsigned value) { if (os_semaphore_init(sem, value)) FATAL("!os_semaphore_init"); } /* * util_semaphore_destroy -- deletes a semaphore instance */ static inline void util_semaphore_destroy(os_semaphore_t *sem) { if (os_semaphore_destroy(sem) != 0) FATAL("!os_semaphore_destroy"); } /* * util_semaphore_wait -- decreases the value of the semaphore */ static inline void util_semaphore_wait(os_semaphore_t *sem) { errno = 0; int ret; do { ret = os_semaphore_wait(sem); } while (errno == EINTR); /* signal interrupt */ if (ret != 0) FATAL("!os_semaphore_wait"); } /* * util_semaphore_trywait -- tries to decrease the value of the semaphore */ static inline int util_semaphore_trywait(os_semaphore_t *sem) { errno = 0; int ret; do { ret = os_semaphore_trywait(sem); } while (errno == EINTR); /* signal interrupt */ if (ret != 0 && errno != EAGAIN) FATAL("!os_semaphore_trywait"); return ret; } /* * util_semaphore_post -- increases the value of the semaphore */ static inline void util_semaphore_post(os_semaphore_t *sem) { if (os_semaphore_post(sem) != 0) FATAL("!os_semaphore_post"); } #ifdef __cplusplus } #endif #endif
7,640
22.154545
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os.h
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os.h -- os abstaction layer */ #ifndef PMDK_OS_H #define PMDK_OS_H 1 #include <sys/stat.h> #include <stdio.h> #include <unistd.h> #include "errno_freebsd.h" #ifdef __cplusplus extern "C" { #endif #ifndef _WIN32 #define OS_DIR_SEPARATOR '/' #define OS_DIR_SEP_STR "/" #else #define OS_DIR_SEPARATOR '\\' #define OS_DIR_SEP_STR "\\" #endif #ifndef _WIN32 /* madvise() */ #ifdef __FreeBSD__ #define os_madvise minherit #define MADV_DONTFORK INHERIT_NONE #else #define os_madvise madvise #endif /* dlopen() */ #ifdef __FreeBSD__ #define RTLD_DEEPBIND 0 /* XXX */ #endif /* major(), minor() */ #ifdef __FreeBSD__ #define os_major (unsigned)major #define os_minor (unsigned)minor #else #define os_major major #define os_minor minor #endif #endif /* #ifndef _WIN32 */ struct iovec; /* os_flock */ #define OS_LOCK_SH 1 #define OS_LOCK_EX 2 #define OS_LOCK_NB 4 #define OS_LOCK_UN 8 #ifndef _WIN32 typedef struct stat os_stat_t; #define os_fstat fstat #define os_lseek lseek #else typedef struct _stat64 os_stat_t; #define os_fstat _fstat64 #define os_lseek _lseeki64 #endif #define os_close close #define os_fclose fclose #ifndef _WIN32 typedef off_t os_off_t; #else /* XXX: os_off_t defined in platform.h */ #endif int os_open(const char *pathname, int flags, ...); int os_fsync(int fd); int os_fsync_dir(const char *dir_name); int os_stat(const char *pathname, os_stat_t *buf); int os_unlink(const char *pathname); int os_access(const char *pathname, int mode); FILE *os_fopen(const char *pathname, const char *mode); FILE *os_fdopen(int fd, const char *mode); int os_chmod(const char *pathname, mode_t mode); int os_mkstemp(char *temp); int os_posix_fallocate(int fd, os_off_t offset, os_off_t len); int os_ftruncate(int fd, os_off_t length); int os_flock(int fd, int operation); ssize_t os_writev(int fd, const struct iovec *iov, int iovcnt); int os_clock_gettime(int id, struct timespec *ts); unsigned os_rand_r(unsigned *seedp); int os_unsetenv(const char *name); int os_setenv(const char *name, const char *value, int overwrite); char *os_getenv(const char *name); const char *os_strsignal(int sig); int os_execv(const char *path, char *const argv[]); /* * XXX: missing APis (used in ut_file.c) * * rename * read * write */ #ifdef __cplusplus } #endif #endif /* os.h */
3,902
25.917241
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/mmap.h
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * mmap.h -- internal definitions for mmap module */ #ifndef PMDK_MMAP_H #define PMDK_MMAP_H 1 #include <stddef.h> #include <stdint.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include "out.h" #include "queue.h" #include "os.h" #ifdef __cplusplus extern "C" { #endif extern int Mmap_no_random; extern void *Mmap_hint; extern char *Mmap_mapfile; void *util_map_sync(void *addr, size_t len, int proto, int flags, int fd, os_off_t offset, int *map_sync); void *util_map(int fd, size_t len, int flags, int rdonly, size_t req_align, int *map_sync); int util_unmap(void *addr, size_t len); void *util_map_tmpfile(const char *dir, size_t size, size_t req_align); #ifdef __FreeBSD__ #define MAP_NORESERVE 0 #define OS_MAPFILE "/proc/curproc/map" #else #define OS_MAPFILE "/proc/self/maps" #endif #ifndef MAP_SYNC #define MAP_SYNC 0x80000 #endif #ifndef MAP_SHARED_VALIDATE #define MAP_SHARED_VALIDATE 0x03 #endif /* * macros for micromanaging range protections for the debug version */ #ifdef DEBUG #define RANGE(addr, len, is_dev_dax, type) do {\ if (!is_dev_dax) ASSERT(util_range_##type(addr, len) >= 0);\ } while (0) #else #define RANGE(addr, len, is_dev_dax, type) do {} while (0) #endif #define RANGE_RO(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, ro) #define RANGE_RW(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, rw) #define RANGE_NONE(addr, len, is_dev_dax) RANGE(addr, len, is_dev_dax, none) /* pmem mapping type */ enum pmem_map_type { PMEM_DEV_DAX, /* device dax */ PMEM_MAP_SYNC, /* mapping with MAP_SYNC flag on dax fs */ MAX_PMEM_TYPE }; /* * this structure tracks the file mappings outstanding per file handle */ struct map_tracker { SORTEDQ_ENTRY(map_tracker) entry; uintptr_t base_addr; uintptr_t end_addr; int region_id; enum pmem_map_type type; #ifdef _WIN32 /* Windows-specific data */ HANDLE FileHandle; HANDLE FileMappingHandle; DWORD Access; os_off_t Offset; size_t FileLen; #endif }; void util_mmap_init(void); void util_mmap_fini(void); int util_range_ro(void *addr, size_t len); int util_range_rw(void *addr, size_t len); int util_range_none(void *addr, size_t len); char *util_map_hint_unused(void *minaddr, size_t len, size_t align); char *util_map_hint(size_t len, size_t req_align); #define MEGABYTE ((uintptr_t)1 << 20) #define GIGABYTE ((uintptr_t)1 << 30) /* * util_map_hint_align -- choose the desired mapping alignment * * The smallest supported alignment is 2 megabytes because of the object * alignment requirements. Changing this value to 4 kilobytes constitues a * layout change. * * Use 1GB page alignment only if the mapping length is at least * twice as big as the page size. */ static inline size_t util_map_hint_align(size_t len, size_t req_align) { size_t align = 2 * MEGABYTE; if (req_align) align = req_align; else if (len >= 2 * GIGABYTE) align = GIGABYTE; return align; } int util_range_register(const void *addr, size_t len, const char *path, enum pmem_map_type type); int util_range_unregister(const void *addr, size_t len); struct map_tracker *util_range_find(uintptr_t addr, size_t len); int util_range_is_pmem(const void *addr, size_t len); #ifdef __cplusplus } #endif #endif
4,854
27.063584
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_auto_flush_windows.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_auto_flush_windows.c -- Windows abstraction layer for auto flush detection */ #include <windows.h> #include <inttypes.h> #include "out.h" #include "os.h" #include "endian.h" #include "os_auto_flush_windows.h" /* * is_nfit_available -- (internal) check if platform supports NFIT table. */ static int is_nfit_available() { LOG(3, "is_nfit_available()"); DWORD signatures_size; char *signatures = NULL; int is_nfit = 0; DWORD offset = 0; signatures_size = EnumSystemFirmwareTables(ACPI_SIGNATURE, NULL, 0); if (signatures_size == 0) { ERR("!EnumSystemFirmwareTables"); return -1; } signatures = (char *)Malloc(signatures_size + 1); if (signatures == NULL) { ERR("!malloc"); return -1; } int ret = EnumSystemFirmwareTables(ACPI_SIGNATURE, signatures, signatures_size); signatures[signatures_size] = '\0'; if (ret != signatures_size) { ERR("!EnumSystemFirmwareTables"); goto err; } while (offset <= signatures_size) { int nfit_sig = strncmp(signatures + offset, NFIT_STR_SIGNATURE, NFIT_SIGNATURE_LEN); if (nfit_sig == 0) { is_nfit = 1; break; } offset += NFIT_SIGNATURE_LEN; } Free(signatures); return is_nfit; err: Free(signatures); return -1; } /* * is_auto_flush_cap_set -- (internal) check if specific * capabilities bits are set. * * ACPI 6.2A Specification: * Bit[0] - CPU Cache Flush to NVDIMM Durability on * Power Loss Capable. If set to 1, indicates that platform * ensures the entire CPU store data path is flushed to * persistent memory on system power loss. * Bit[1] - Memory Controller Flush to NVDIMM Durability on Power Loss Capable. * If set to 1, indicates that platform provides mechanisms to automatically * flush outstanding write data from the memory controller to persistent memory * in the event of platform power loss. Note: If bit 0 is set to 1 then this bit * shall be set to 1 as well. */ static int is_auto_flush_cap_set(uint32_t capabilities) { LOG(3, "is_auto_flush_cap_set capabilities 0x%" PRIx32, capabilities); int CPU_cache_flush = CHECK_BIT(capabilities, 0); int memory_controller_flush = CHECK_BIT(capabilities, 1); LOG(15, "CPU_cache_flush %d, memory_controller_flush %d", CPU_cache_flush, memory_controller_flush); if (memory_controller_flush == 1 && CPU_cache_flush == 1) return 1; return 0; } /* * parse_nfit_buffer -- (internal) parse nfit buffer * if platform_capabilities struct is available return pcs structure. */ static struct platform_capabilities parse_nfit_buffer(const unsigned char *nfit_buffer, unsigned long buffer_size) { LOG(3, "parse_nfit_buffer nfit_buffer %s, buffer_size %lu", nfit_buffer, buffer_size); uint16_t type; uint16_t length; size_t offset = sizeof(struct nfit_header); struct platform_capabilities pcs = {0}; while (offset < buffer_size) { type = *(nfit_buffer + offset); length = *(nfit_buffer + offset + 2); if (type == PCS_TYPE_NUMBER) { if (length == sizeof(struct platform_capabilities)) { memmove(&pcs, nfit_buffer + offset, length); return pcs; } } offset += length; } return pcs; } /* * os_auto_flush -- check if platform supports auto flush. */ int os_auto_flush(void) { LOG(3, NULL); DWORD nfit_buffer_size = 0; DWORD nfit_written = 0; PVOID nfit_buffer = NULL; struct nfit_header *nfit_data; struct platform_capabilities *pc = NULL; int eADR = 0; int is_nfit = is_nfit_available(); if (is_nfit == 0) { LOG(15, "ACPI NFIT table not available"); return 0; } if (is_nfit < 0 || is_nfit != 1) { LOG(1, "!is_nfit_available"); return -1; } /* get the entire nfit size */ nfit_buffer_size = GetSystemFirmwareTable( (DWORD)ACPI_SIGNATURE, (DWORD)NFIT_REV_SIGNATURE, NULL, 0); if (nfit_buffer_size == 0) { ERR("!GetSystemFirmwareTable"); return -1; } /* reserve buffer */ nfit_buffer = (unsigned char *)Malloc(nfit_buffer_size); if (nfit_buffer == NULL) { ERR("!malloc"); goto err; } /* write actual nfit to buffer */ nfit_written = GetSystemFirmwareTable( (DWORD)ACPI_SIGNATURE, (DWORD)NFIT_REV_SIGNATURE, nfit_buffer, nfit_buffer_size); if (nfit_written == 0) { ERR("!GetSystemFirmwareTable"); goto err; } if (nfit_buffer_size != nfit_written) { errno = ERROR_INVALID_DATA; ERR("!GetSystemFirmwareTable invalid data"); goto err; } nfit_data = (struct nfit_header *)nfit_buffer; int nfit_sig = strncmp(nfit_data->signature, NFIT_STR_SIGNATURE, NFIT_SIGNATURE_LEN); if (nfit_sig != 0) { ERR("!NFIT buffer has invalid data"); goto err; } struct platform_capabilities pcs = parse_nfit_buffer( nfit_buffer, nfit_buffer_size); eADR = is_auto_flush_cap_set(pcs.capabilities); Free(nfit_buffer); return eADR; err: Free(nfit_buffer); return -1; }
6,369
27.311111
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_dimm.h
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_dimm.h -- DIMMs API based on the ndctl library */ #ifndef PMDK_OS_DIMM_H #define PMDK_OS_DIMM_H 1 #include <string.h> #include <stdint.h> #include "os_badblock.h" #ifdef __cplusplus extern "C" { #endif int os_dimm_uid(const char *path, char *uid, size_t *len); int os_dimm_usc(const char *path, uint64_t *usc); int os_dimm_files_namespace_badblocks(const char *path, struct badblocks *bbs); int os_dimm_devdax_clear_badblocks_all(const char *path); int os_dimm_devdax_clear_badblocks(const char *path, struct badblocks *bbs); #ifdef __cplusplus } #endif #endif
2,180
35.35
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/fs_windows.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * fs_windows.c -- file system traversal windows implementation */ #include <windows.h> #include "util.h" #include "out.h" #include "vec.h" #include "fs.h" struct fs { size_t dirlen; WIN32_FIND_DATAW ffd; HANDLE hFind; int first_done; const char *dir; struct fs_entry entry; }; /* * fs_new -- creates fs traversal instance */ struct fs * fs_new(const char *path) { size_t pathlen = strlen(path); char *search_path = Malloc(strlen(path) + sizeof("\\*\0")); if (search_path == NULL) goto error_spath_alloc; strcpy(search_path, path); strcpy(search_path + pathlen, "\\*\0"); wchar_t *pathw = util_toUTF16(search_path); if (pathw == NULL) goto error_path_alloc; struct fs *f = Zalloc(sizeof(*f)); if (f == NULL) goto error_fs_alloc; f->first_done = 0; f->hFind = FindFirstFileW(pathw, &f->ffd); if (f->hFind == INVALID_HANDLE_VALUE) goto error_fff; f->dir = path; f->dirlen = pathlen; util_free_UTF16(pathw); Free(search_path); return f; error_fff: Free(f); error_fs_alloc: util_free_UTF16(pathw); error_path_alloc: Free(search_path); error_spath_alloc: return NULL; } /* * fs_read -- reads an entry from the fs path */ struct fs_entry * fs_read(struct fs *f) { util_free_UTF8((char *)f->entry.name); Free((char *)f->entry.path); f->entry.name = NULL; f->entry.path = NULL; if (f->first_done) { if (FindNextFileW(f->hFind, &f->ffd) == 0) return NULL; } else { f->first_done = 1; } if (f->ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) f->entry.type = FS_ENTRY_DIRECTORY; else f->entry.type = FS_ENTRY_FILE; f->entry.name = util_toUTF8(f->ffd.cFileName); if (f->entry.name == NULL) return NULL; f->entry.namelen = strnlen(f->entry.name, MAX_PATH); f->entry.pathlen = f->dirlen + f->entry.namelen + 1; char *path = Zalloc(f->entry.pathlen + 1); if (path == NULL) { util_free_UTF8((char *)f->entry.name); return NULL; } strcpy(path, f->dir); path[f->dirlen] = '\\'; strcpy(path + f->dirlen + 1, f->entry.name); f->entry.path = path; f->entry.level = 1; return &f->entry; } /* * fs_delete -- deletes a fs traversal instance */ void fs_delete(struct fs *f) { util_free_UTF8((char *)f->entry.name); Free((char *)f->entry.path); FindClose(f->hFind); Free(f); }
3,862
24.248366
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/badblock_windows.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * badblock_windows.c - implementation of the windows bad block API */ #include "out.h" #include "os_badblock.h" /* * os_badblocks_check_file -- check if the file contains bad blocks * * Return value: * -1 : an error * 0 : no bad blocks * 1 : bad blocks detected */ int os_badblocks_check_file(const char *file) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_count -- returns number of bad blocks in the file * or -1 in case of an error */ long os_badblocks_count(const char *file) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_get -- returns list of bad blocks in the file */ int os_badblocks_get(const char *file, struct badblocks *bbs) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_clear -- clears the given bad blocks in a file * (regular file or dax device) */ int os_badblocks_clear(const char *file, struct badblocks *bbs) { LOG(3, "file %s badblocks %p", file, bbs); return 0; } /* * os_badblocks_clear_all -- clears all bad blocks in a file * (regular file or dax device) */ int os_badblocks_clear_all(const char *file) { LOG(3, "file %s", file); return 0; }
2,812
26.578431
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/util.h
/* * Copyright 2014-2018, Intel Corporation * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * util.h -- internal definitions for util module */ #ifndef PMDK_UTIL_H #define PMDK_UTIL_H 1 #include <string.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <ctype.h> #ifdef _MSC_VER #include <intrin.h> /* popcnt, bitscan */ #endif #include <sys/param.h> #ifdef __cplusplus extern "C" { #endif extern unsigned long long Pagesize; extern unsigned long long Mmap_align; #define CACHELINE_SIZE 64ULL #define PAGE_ALIGNED_DOWN_SIZE(size) ((size) & ~(Pagesize - 1)) #define PAGE_ALIGNED_UP_SIZE(size)\ PAGE_ALIGNED_DOWN_SIZE((size) + (Pagesize - 1)) #define IS_PAGE_ALIGNED(size) (((size) & (Pagesize - 1)) == 0) #define PAGE_ALIGN_UP(addr) ((void *)PAGE_ALIGNED_UP_SIZE((uintptr_t)(addr))) #define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1)) #define ALIGN_DOWN(size, align) ((size) & ~((align) - 1)) #define ADDR_SUM(vp, lp) ((void *)((char *)(vp) + (lp))) #define util_alignof(t) offsetof(struct {char _util_c; t _util_m; }, _util_m) #define FORMAT_PRINTF(a, b) __attribute__((__format__(__printf__, (a), (b)))) /* * overridable names for malloc & friends used by this library */ typedef void *(*Malloc_func)(size_t size); typedef void (*Free_func)(void *ptr); typedef void *(*Realloc_func)(void *ptr, size_t size); typedef char *(*Strdup_func)(const char *s); extern Malloc_func Malloc; extern Free_func Free; extern Realloc_func Realloc; extern Strdup_func Strdup; extern void *Zalloc(size_t sz); void util_init(void); int util_is_zeroed(const void *addr, size_t len); int util_checksum(void *addr, size_t len, uint64_t *csump, int insert, size_t skip_off); uint64_t util_checksum_seq(const void *addr, size_t len, uint64_t csum); int util_parse_size(const char *str, size_t *sizep); char *util_fgets(char *buffer, int max, FILE *stream); char *util_getexecname(char *path, size_t pathlen); char *util_part_realpath(const char *path); int util_compare_file_inodes(const char *path1, const char *path2); void *util_aligned_malloc(size_t alignment, size_t size); void util_aligned_free(void *ptr); struct tm *util_localtime(const time_t *timep); int util_safe_strcpy(char *dst, const char *src, size_t max_length); #ifdef _WIN32 char *util_toUTF8(const wchar_t *wstr); wchar_t *util_toUTF16(const char *wstr); void util_free_UTF8(char *str); void util_free_UTF16(wchar_t *str); int util_toUTF16_buff(const char *in, wchar_t *out, size_t out_size); int util_toUTF8_buff(const wchar_t *in, char *out, size_t out_size); #endif #define UTIL_MAX_ERR_MSG 128 void util_strerror(int errnum, char *buff, size_t bufflen); void util_set_alloc_funcs( void *(*malloc_func)(size_t size), void (*free_func)(void *ptr), void *(*realloc_func)(void *ptr, size_t size), char *(*strdup_func)(const char *s)); /* * Macro calculates number of elements in given table */ #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif #ifdef _MSC_VER #define force_inline inline __forceinline #define NORETURN __declspec(noreturn) #else #define force_inline __attribute__((always_inline)) inline #define NORETURN __attribute__((noreturn)) #endif #define util_get_not_masked_bits(x, mask) ((x) & ~(mask)) /* * util_setbit -- setbit macro substitution which properly deals with types */ static inline void util_setbit(uint8_t *b, uint32_t i) { b[i / 8] = (uint8_t)(b[i / 8] | (uint8_t)(1 << (i % 8))); } /* * util_clrbit -- clrbit macro substitution which properly deals with types */ static inline void util_clrbit(uint8_t *b, uint32_t i) { b[i / 8] = (uint8_t)(b[i / 8] & (uint8_t)(~(1 << (i % 8)))); } #define util_isset(a, i) isset(a, i) #define util_isclr(a, i) isclr(a, i) #define util_flag_isset(a, f) ((a) & (f)) #define util_flag_isclr(a, f) (((a) & (f)) == 0) /* * util_is_pow2 -- returns !0 when there's only 1 bit set in v, 0 otherwise */ static force_inline int util_is_pow2(uint64_t v) { return v && !(v & (v - 1)); } /* * util_div_ceil -- divides a by b and rounds up the result */ static force_inline unsigned util_div_ceil(unsigned a, unsigned b) { return (unsigned)(((unsigned long)a + b - 1) / b); } /* * util_bool_compare_and_swap -- perform an atomic compare and swap * util_fetch_and_* -- perform an operation atomically, return old value * util_synchronize -- issue a full memory barrier * util_popcount -- count number of set bits * util_lssb_index -- return index of least significant set bit, * undefined on zero * util_mssb_index -- return index of most significant set bit * undefined on zero * * XXX assertions needed on (value != 0) in both versions of bitscans * */ #ifndef _MSC_VER /* * ISO C11 -- 7.17.1.4 * memory_order - an enumerated type whose enumerators identify memory ordering * constraints. */ typedef enum { memory_order_relaxed = __ATOMIC_RELAXED, memory_order_consume = __ATOMIC_CONSUME, memory_order_acquire = __ATOMIC_ACQUIRE, memory_order_release = __ATOMIC_RELEASE, memory_order_acq_rel = __ATOMIC_ACQ_REL, memory_order_seq_cst = __ATOMIC_SEQ_CST } memory_order; /* * ISO C11 -- 7.17.7.2 The atomic_load generic functions * Integer width specific versions as supplement for: * * * #include <stdatomic.h> * C atomic_load(volatile A *object); * C atomic_load_explicit(volatile A *object, memory_order order); * * The atomic_load interface doesn't return the loaded value, but instead * copies it to a specified address -- see comments at the MSVC version. * * Also, instead of generic functions, two versions are available: * for 32 bit fundamental integers, and for 64 bit ones. */ #define util_atomic_load_explicit32 __atomic_load #define util_atomic_load_explicit64 __atomic_load /* * ISO C11 -- 7.17.7.1 The atomic_store generic functions * Integer width specific versions as supplement for: * * #include <stdatomic.h> * void atomic_store(volatile A *object, C desired); * void atomic_store_explicit(volatile A *object, C desired, * memory_order order); */ #define util_atomic_store_explicit32 __atomic_store_n #define util_atomic_store_explicit64 __atomic_store_n /* * https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html * https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html * https://clang.llvm.org/docs/LanguageExtensions.html#builtin-functions */ #define util_bool_compare_and_swap32 __sync_bool_compare_and_swap #define util_bool_compare_and_swap64 __sync_bool_compare_and_swap #define util_fetch_and_add32 __sync_fetch_and_add #define util_fetch_and_add64 __sync_fetch_and_add #define util_fetch_and_sub32 __sync_fetch_and_sub #define util_fetch_and_sub64 __sync_fetch_and_sub #define util_fetch_and_and32 __sync_fetch_and_and #define util_fetch_and_and64 __sync_fetch_and_and #define util_fetch_and_or32 __sync_fetch_and_or #define util_fetch_and_or64 __sync_fetch_and_or #define util_synchronize __sync_synchronize #define util_popcount(value) ((unsigned char)__builtin_popcount(value)) #define util_popcount64(value) ((unsigned char)__builtin_popcountll(value)) #define util_lssb_index(value) ((unsigned char)__builtin_ctz(value)) #define util_lssb_index64(value) ((unsigned char)__builtin_ctzll(value)) #define util_mssb_index(value) ((unsigned char)(31 - __builtin_clz(value))) #define util_mssb_index64(value) ((unsigned char)(63 - __builtin_clzll(value))) #else /* ISO C11 -- 7.17.1.4 */ typedef enum { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; /* * ISO C11 -- 7.17.7.2 The atomic_load generic functions * Integer width specific versions as supplement for: * * * #include <stdatomic.h> * C atomic_load(volatile A *object); * C atomic_load_explicit(volatile A *object, memory_order order); * * The atomic_load interface doesn't return the loaded value, but instead * copies it to a specified address. * The MSVC specific implementation needs to trigger a barrier (at least * compiler barrier) after the load from the volatile value. The actual load * from the volatile value itself is expected to be atomic. * * The actual isnterface here: * #include <util.h> * void util_atomic_load32(volatile A *object, A *destination); * void util_atomic_load64(volatile A *object, A *destination); * void util_atomic_load_explicit32(volatile A *object, A *destination, * memory_order order); * void util_atomic_load_explicit64(volatile A *object, A *destination, * memory_order order); */ #ifndef _M_X64 #error MSVC ports of util_atomic_ only work on X86_64 #endif #if _MSC_VER >= 2000 #error util_atomic_ utility functions not tested with this version of VC++ #error These utility functions are not future proof, as they are not #error based on publicly available documentation. #endif #define util_atomic_load_explicit(object, dest, order)\ do {\ COMPILE_ERROR_ON(order != memory_order_seq_cst &&\ order != memory_order_consume &&\ order != memory_order_acquire &&\ order != memory_order_relaxed);\ *dest = *object;\ if (order == memory_order_seq_cst ||\ order == memory_order_consume ||\ order == memory_order_acquire)\ _ReadWriteBarrier();\ } while (0) #define util_atomic_load_explicit32 util_atomic_load_explicit #define util_atomic_load_explicit64 util_atomic_load_explicit /* ISO C11 -- 7.17.7.1 The atomic_store generic functions */ #define util_atomic_store_explicit64(object, desired, order)\ do {\ COMPILE_ERROR_ON(order != memory_order_seq_cst &&\ order != memory_order_release &&\ order != memory_order_relaxed);\ if (order == memory_order_seq_cst) {\ _InterlockedExchange64(\ (volatile long long *)object, desired);\ } else {\ if (order == memory_order_release)\ _ReadWriteBarrier();\ *object = desired;\ }\ } while (0) #define util_atomic_store_explicit32(object, desired, order)\ do {\ COMPILE_ERROR_ON(order != memory_order_seq_cst &&\ order != memory_order_release &&\ order != memory_order_relaxed);\ if (order == memory_order_seq_cst) {\ _InterlockedExchange(\ (volatile long *)object, desired);\ } else {\ if (order == memory_order_release)\ _ReadWriteBarrier();\ *object = desired;\ }\ } while (0) /* * https://msdn.microsoft.com/en-us/library/hh977022.aspx */ static __inline int bool_compare_and_swap32_VC(volatile LONG *ptr, LONG oldval, LONG newval) { LONG old = InterlockedCompareExchange(ptr, newval, oldval); return (old == oldval); } static __inline int bool_compare_and_swap64_VC(volatile LONG64 *ptr, LONG64 oldval, LONG64 newval) { LONG64 old = InterlockedCompareExchange64(ptr, newval, oldval); return (old == oldval); } #define util_bool_compare_and_swap32(p, o, n)\ bool_compare_and_swap32_VC((LONG *)(p), (LONG)(o), (LONG)(n)) #define util_bool_compare_and_swap64(p, o, n)\ bool_compare_and_swap64_VC((LONG64 *)(p), (LONG64)(o), (LONG64)(n)) #define util_fetch_and_add32(ptr, value)\ InterlockedExchangeAdd((LONG *)(ptr), value) #define util_fetch_and_add64(ptr, value)\ InterlockedExchangeAdd64((LONG64 *)(ptr), value) #define util_fetch_and_sub32(ptr, value)\ InterlockedExchangeSubtract((LONG *)(ptr), value) #define util_fetch_and_sub64(ptr, value)\ InterlockedExchangeAdd64((LONG64 *)(ptr), -((LONG64)(value))) #define util_fetch_and_and32(ptr, value)\ InterlockedAnd((LONG *)(ptr), value) #define util_fetch_and_and64(ptr, value)\ InterlockedAnd64((LONG64 *)(ptr), value) #define util_fetch_and_or32(ptr, value)\ InterlockedOr((LONG *)(ptr), value) #define util_fetch_and_or64(ptr, value)\ InterlockedOr64((LONG64 *)(ptr), value) static __inline void util_synchronize(void) { MemoryBarrier(); } #define util_popcount(value) (unsigned char)__popcnt(value) #define util_popcount64(value) (unsigned char)__popcnt64(value) static __inline unsigned char util_lssb_index(int value) { unsigned long ret; _BitScanForward(&ret, value); return (unsigned char)ret; } static __inline unsigned char util_lssb_index64(long long value) { unsigned long ret; _BitScanForward64(&ret, value); return (unsigned char)ret; } static __inline unsigned char util_mssb_index(int value) { unsigned long ret; _BitScanReverse(&ret, value); return (unsigned char)ret; } static __inline unsigned char util_mssb_index64(long long value) { unsigned long ret; _BitScanReverse64(&ret, value); return (unsigned char)ret; } #endif /* ISO C11 -- 7.17.7 Operations on atomic types */ #define util_atomic_load32(object, dest)\ util_atomic_load_explicit32(object, dest, memory_order_seqcst) #define util_atomic_load64(object, dest)\ util_atomic_load_explicit64(object, dest, memory_order_seqcst) #define util_atomic_store32(object, desired)\ util_atomic_store_explicit32(object, desired, memory_order_seqcst) #define util_atomic_store64(object, desired)\ util_atomic_store_explicit64(object, desired, memory_order_seqcst) /* * util_get_printable_ascii -- convert non-printable ascii to dot '.' */ static inline char util_get_printable_ascii(char c) { return isprint((unsigned char)c) ? c : '.'; } char *util_concat_str(const char *s1, const char *s2); #if !defined(likely) #if defined(__GNUC__) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else #define likely(x) (!!(x)) #define unlikely(x) (!!(x)) #endif #endif #if defined(__CHECKER__) #define COMPILE_ERROR_ON(cond) #define ASSERT_COMPILE_ERROR_ON(cond) #elif defined(_MSC_VER) #define COMPILE_ERROR_ON(cond) C_ASSERT(!(cond)) /* XXX - can't be done with C_ASSERT() unless we have __builtin_constant_p() */ #define ASSERT_COMPILE_ERROR_ON(cond) do {} while (0) #else #define COMPILE_ERROR_ON(cond) ((void)sizeof(char[(cond) ? -1 : 1])) #define ASSERT_COMPILE_ERROR_ON(cond) COMPILE_ERROR_ON(cond) #endif #ifndef _MSC_VER #define ATTR_CONSTRUCTOR __attribute__((constructor)) static #define ATTR_DESTRUCTOR __attribute__((destructor)) static #else #define ATTR_CONSTRUCTOR #define ATTR_DESTRUCTOR #endif #ifndef _MSC_VER #define CONSTRUCTOR(fun) ATTR_CONSTRUCTOR #else #ifdef __cplusplus #define CONSTRUCTOR(fun) \ void fun(); \ struct _##fun { \ _##fun() { \ fun(); \ } \ }; static _##fun foo; \ static #else #define CONSTRUCTOR(fun) \ MSVC_CONSTR(fun) \ static #endif #endif #ifdef __GNUC__ #define CHECK_FUNC_COMPATIBLE(func1, func2)\ COMPILE_ERROR_ON(!__builtin_types_compatible_p(typeof(func1),\ typeof(func2))) #else #define CHECK_FUNC_COMPATIBLE(func1, func2) do {} while (0) #endif /* __GNUC__ */ #ifdef __cplusplus } #endif #endif /* util.h */
16,304
29.880682
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/valgrind_internal.h
/* * Copyright 2015-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * valgrind_internal.h -- internal definitions for valgrind macros */ #ifndef PMDK_VALGRIND_INTERNAL_H #define PMDK_VALGRIND_INTERNAL_H 1 #ifndef _WIN32 #ifndef VALGRIND_ENABLED #define VALGRIND_ENABLED 1 #endif #endif #if VALGRIND_ENABLED #define VG_PMEMCHECK_ENABLED 1 #define VG_HELGRIND_ENABLED 1 #define VG_MEMCHECK_ENABLED 1 #define VG_DRD_ENABLED 1 #endif #if VG_PMEMCHECK_ENABLED || VG_HELGRIND_ENABLED || VG_MEMCHECK_ENABLED || \ VG_DRD_ENABLED #define ANY_VG_TOOL_ENABLED 1 #else #define ANY_VG_TOOL_ENABLED 0 #endif #if ANY_VG_TOOL_ENABLED extern unsigned _On_valgrind; #define On_valgrind __builtin_expect(_On_valgrind, 0) #include "valgrind/valgrind.h" #else #define On_valgrind (0) #endif #if VG_HELGRIND_ENABLED #include "valgrind/helgrind.h" #endif #if VG_DRD_ENABLED #include "valgrind/drd.h" #endif #if VG_HELGRIND_ENABLED || VG_DRD_ENABLED #define VALGRIND_ANNOTATE_HAPPENS_BEFORE(obj) do {\ if (On_valgrind) \ ANNOTATE_HAPPENS_BEFORE((obj));\ } while (0) #define VALGRIND_ANNOTATE_HAPPENS_AFTER(obj) do {\ if (On_valgrind) \ ANNOTATE_HAPPENS_AFTER((obj));\ } while (0) #define VALGRIND_ANNOTATE_NEW_MEMORY(addr, size) do {\ if (On_valgrind) \ ANNOTATE_NEW_MEMORY((addr), (size));\ } while (0) #define VALGRIND_ANNOTATE_IGNORE_READS_BEGIN() do {\ if (On_valgrind) \ ANNOTATE_IGNORE_READS_BEGIN();\ } while (0) #define VALGRIND_ANNOTATE_IGNORE_READS_END() do {\ if (On_valgrind) \ ANNOTATE_IGNORE_READS_END();\ } while (0) #define VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN() do {\ if (On_valgrind) \ ANNOTATE_IGNORE_WRITES_BEGIN();\ } while (0) #define VALGRIND_ANNOTATE_IGNORE_WRITES_END() do {\ if (On_valgrind) \ ANNOTATE_IGNORE_WRITES_END();\ } while (0) #else #define VALGRIND_ANNOTATE_HAPPENS_BEFORE(obj) do { (void)(obj); } while (0) #define VALGRIND_ANNOTATE_HAPPENS_AFTER(obj) do { (void)(obj); } while (0) #define VALGRIND_ANNOTATE_NEW_MEMORY(addr, size) do {\ (void) (addr);\ (void) (size);\ } while (0) #define VALGRIND_ANNOTATE_IGNORE_READS_BEGIN() do {} while (0) #define VALGRIND_ANNOTATE_IGNORE_READS_END() do {} while (0) #define VALGRIND_ANNOTATE_IGNORE_WRITES_BEGIN() do {} while (0) #define VALGRIND_ANNOTATE_IGNORE_WRITES_END() do {} while (0) #endif #if VG_PMEMCHECK_ENABLED #include "valgrind/pmemcheck.h" extern void util_emit_log(const char *lib, const char *func, int order); extern int _Pmreorder_emit; #define Pmreorder_emit __builtin_expect(_Pmreorder_emit, 0) #define VALGRIND_REGISTER_PMEM_MAPPING(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_REGISTER_PMEM_MAPPING((addr), (len));\ } while (0) #define VALGRIND_REGISTER_PMEM_FILE(desc, base_addr, size, offset) do {\ if (On_valgrind)\ VALGRIND_PMC_REGISTER_PMEM_FILE((desc), (base_addr), (size), \ (offset));\ } while (0) #define VALGRIND_REMOVE_PMEM_MAPPING(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_REMOVE_PMEM_MAPPING((addr), (len));\ } while (0) #define VALGRIND_CHECK_IS_PMEM_MAPPING(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_CHECK_IS_PMEM_MAPPING((addr), (len));\ } while (0) #define VALGRIND_PRINT_PMEM_MAPPINGS do {\ if (On_valgrind)\ VALGRIND_PMC_PRINT_PMEM_MAPPINGS;\ } while (0) #define VALGRIND_DO_FLUSH(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_DO_FLUSH((addr), (len));\ } while (0) #define VALGRIND_DO_FENCE do {\ if (On_valgrind)\ VALGRIND_PMC_DO_FENCE;\ } while (0) #define VALGRIND_DO_PERSIST(addr, len) do {\ if (On_valgrind) {\ VALGRIND_PMC_DO_FLUSH((addr), (len));\ VALGRIND_PMC_DO_FENCE;\ }\ } while (0) #define VALGRIND_SET_CLEAN(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_SET_CLEAN(addr, len);\ } while (0) #define VALGRIND_WRITE_STATS do {\ if (On_valgrind)\ VALGRIND_PMC_WRITE_STATS;\ } while (0) #define VALGRIND_LOG_STORES do {\ if (On_valgrind)\ VALGRIND_PMC_LOG_STORES;\ } while (0) #define VALGRIND_NO_LOG_STORES do {\ if (On_valgrind)\ VALGRIND_PMC_NO_LOG_STORES;\ } while (0) #define VALGRIND_ADD_LOG_REGION(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_ADD_LOG_REGION((addr), (len));\ } while (0) #define VALGRIND_REMOVE_LOG_REGION(addr, len) do {\ if (On_valgrind)\ \ VALGRIND_PMC_REMOVE_LOG_REGION((addr), (len));\ } while (0) #define VALGRIND_EMIT_LOG(emit_log) do {\ if (On_valgrind)\ VALGRIND_PMC_EMIT_LOG((emit_log));\ } while (0) #define VALGRIND_START_TX do {\ if (On_valgrind)\ VALGRIND_PMC_START_TX;\ } while (0) #define VALGRIND_START_TX_N(txn) do {\ if (On_valgrind)\ VALGRIND_PMC_START_TX_N(txn);\ } while (0) #define VALGRIND_END_TX do {\ if (On_valgrind)\ VALGRIND_PMC_END_TX;\ } while (0) #define VALGRIND_END_TX_N(txn) do {\ if (On_valgrind)\ VALGRIND_PMC_END_TX_N(txn);\ } while (0) #define VALGRIND_ADD_TO_TX(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_ADD_TO_TX(addr, len);\ } while (0) #define VALGRIND_ADD_TO_TX_N(txn, addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_ADD_TO_TX_N(txn, addr, len);\ } while (0) #define VALGRIND_REMOVE_FROM_TX(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_REMOVE_FROM_TX(addr, len);\ } while (0) #define VALGRIND_REMOVE_FROM_TX_N(txn, addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_REMOVE_FROM_TX_N(txn, addr, len);\ } while (0) #define VALGRIND_ADD_TO_GLOBAL_TX_IGNORE(addr, len) do {\ if (On_valgrind)\ VALGRIND_PMC_ADD_TO_GLOBAL_TX_IGNORE(addr, len);\ } while (0) /* * Logs library and function name with proper suffix * to pmemcheck store log file. */ #define PMEMOBJ_API_START()\ if (Pmreorder_emit)\ util_emit_log("libpmemobj", __func__, 0); #define PMEMOBJ_API_END()\ if (Pmreorder_emit)\ util_emit_log("libpmemobj", __func__, 1); #else #define Pmreorder_emit (0) #define VALGRIND_REGISTER_PMEM_MAPPING(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_REGISTER_PMEM_FILE(desc, base_addr, size, offset) do {\ (void) (desc);\ (void) (base_addr);\ (void) (size);\ (void) (offset);\ } while (0) #define VALGRIND_REMOVE_PMEM_MAPPING(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_CHECK_IS_PMEM_MAPPING(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_PRINT_PMEM_MAPPINGS do {} while (0) #define VALGRIND_DO_FLUSH(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_DO_FENCE do {} while (0) #define VALGRIND_DO_PERSIST(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_SET_CLEAN(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_WRITE_STATS do {} while (0) #define VALGRIND_LOG_STORES do {} while (0) #define VALGRIND_NO_LOG_STORES do {} while (0) #define VALGRIND_ADD_LOG_REGION(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_REMOVE_LOG_REGION(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_EMIT_LOG(emit_log) do {\ (void) (emit_log);\ } while (0) #define VALGRIND_START_TX do {} while (0) #define VALGRIND_START_TX_N(txn) do { (void) (txn); } while (0) #define VALGRIND_END_TX do {} while (0) #define VALGRIND_END_TX_N(txn) do {\ (void) (txn);\ } while (0) #define VALGRIND_ADD_TO_TX(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_ADD_TO_TX_N(txn, addr, len) do {\ (void) (txn);\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_REMOVE_FROM_TX(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_REMOVE_FROM_TX_N(txn, addr, len) do {\ (void) (txn);\ (void) (addr);\ (void) (len);\ } while (0) #define VALGRIND_ADD_TO_GLOBAL_TX_IGNORE(addr, len) do {\ (void) (addr);\ (void) (len);\ } while (0) #define PMEMOBJ_API_START() do {} while (0) #define PMEMOBJ_API_END() do {} while (0) #endif #if VG_MEMCHECK_ENABLED #include "valgrind/memcheck.h" #define VALGRIND_DO_DISABLE_ERROR_REPORTING do {\ if (On_valgrind)\ VALGRIND_DISABLE_ERROR_REPORTING;\ } while (0) #define VALGRIND_DO_ENABLE_ERROR_REPORTING do {\ if (On_valgrind)\ VALGRIND_ENABLE_ERROR_REPORTING;\ } while (0) #define VALGRIND_DO_CREATE_MEMPOOL(heap, rzB, is_zeroed) do {\ if (On_valgrind)\ VALGRIND_CREATE_MEMPOOL(heap, rzB, is_zeroed);\ } while (0) #define VALGRIND_DO_DESTROY_MEMPOOL(heap) do {\ if (On_valgrind)\ VALGRIND_DESTROY_MEMPOOL(heap);\ } while (0) #define VALGRIND_DO_MEMPOOL_ALLOC(heap, addr, size) do {\ if (On_valgrind)\ VALGRIND_MEMPOOL_ALLOC(heap, addr, size);\ } while (0) #define VALGRIND_DO_MEMPOOL_FREE(heap, addr) do {\ if (On_valgrind)\ VALGRIND_MEMPOOL_FREE(heap, addr);\ } while (0) #define VALGRIND_DO_MEMPOOL_CHANGE(heap, addrA, addrB, size) do {\ if (On_valgrind)\ VALGRIND_MEMPOOL_CHANGE(heap, addrA, addrB, size);\ } while (0) #define VALGRIND_DO_MAKE_MEM_DEFINED(addr, len) do {\ if (On_valgrind)\ VALGRIND_MAKE_MEM_DEFINED(addr, len);\ } while (0) #define VALGRIND_DO_MAKE_MEM_UNDEFINED(addr, len) do {\ if (On_valgrind)\ VALGRIND_MAKE_MEM_UNDEFINED(addr, len);\ } while (0) #define VALGRIND_DO_MAKE_MEM_NOACCESS(addr, len) do {\ if (On_valgrind)\ VALGRIND_MAKE_MEM_NOACCESS(addr, len);\ } while (0) #define VALGRIND_DO_CHECK_MEM_IS_ADDRESSABLE(addr, len) do {\ if (On_valgrind)\ VALGRIND_CHECK_MEM_IS_ADDRESSABLE(addr, len);\ } while (0) #else #define VALGRIND_DO_DISABLE_ERROR_REPORTING do {} while (0) #define VALGRIND_DO_ENABLE_ERROR_REPORTING do {} while (0) #define VALGRIND_DO_CREATE_MEMPOOL(heap, rzB, is_zeroed)\ do { (void) (heap); (void) (rzB); (void) (is_zeroed); } while (0) #define VALGRIND_DO_DESTROY_MEMPOOL(heap)\ do { (void) (heap); } while (0) #define VALGRIND_DO_MEMPOOL_ALLOC(heap, addr, size)\ do { (void) (heap); (void) (addr); (void) (size); } while (0) #define VALGRIND_DO_MEMPOOL_FREE(heap, addr)\ do { (void) (heap); (void) (addr); } while (0) #define VALGRIND_DO_MEMPOOL_CHANGE(heap, addrA, addrB, size)\ do {\ (void) (heap); (void) (addrA); (void) (addrB); (void) (size);\ } while (0) #define VALGRIND_DO_MAKE_MEM_DEFINED(addr, len)\ do { (void) (addr); (void) (len); } while (0) #define VALGRIND_DO_MAKE_MEM_UNDEFINED(addr, len)\ do { (void) (addr); (void) (len); } while (0) #define VALGRIND_DO_MAKE_MEM_NOACCESS(addr, len)\ do { (void) (addr); (void) (len); } while (0) #define VALGRIND_DO_CHECK_MEM_IS_ADDRESSABLE(addr, len)\ do { (void) (addr); (void) (len); } while (0) #endif #endif
11,923
23.738589
75
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_posix.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_posix.c -- abstraction layer for basic Posix functions */ #define _GNU_SOURCE #include <fcntl.h> #include <stdarg.h> #include <sys/file.h> #ifdef __FreeBSD__ #include <sys/mount.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <errno.h> #include "util.h" #include "out.h" #include "os.h" /* * os_open -- open abstraction layer */ int os_open(const char *pathname, int flags, ...) { int mode_required = (flags & O_CREAT) == O_CREAT; #ifdef O_TMPFILE mode_required |= (flags & O_TMPFILE) == O_TMPFILE; #endif if (mode_required) { va_list arg; va_start(arg, flags); /* Clang requires int due to auto-promotion */ int mode = va_arg(arg, int); va_end(arg); return open(pathname, flags, (mode_t)mode); } else { return open(pathname, flags); } } /* * os_fsync -- fsync abstraction layer */ int os_fsync(int fd) { return fsync(fd); } /* * os_fsync_dir -- fsync the directory */ int os_fsync_dir(const char *dir_name) { int fd = os_open(dir_name, O_RDONLY | O_DIRECTORY); if (fd < 0) return -1; int ret = os_fsync(fd); os_close(fd); return ret; } /* * os_stat -- stat abstraction layer */ int os_stat(const char *pathname, os_stat_t *buf) { return stat(pathname, buf); } /* * os_unlink -- unlink abstraction layer */ int os_unlink(const char *pathname) { return unlink(pathname); } /* * os_access -- access abstraction layer */ int os_access(const char *pathname, int mode) { return access(pathname, mode); } /* * os_fopen -- fopen abstraction layer */ FILE * os_fopen(const char *pathname, const char *mode) { return fopen(pathname, mode); } /* * os_fdopen -- fdopen abstraction layer */ FILE * os_fdopen(int fd, const char *mode) { return fdopen(fd, mode); } /* * os_chmod -- chmod abstraction layer */ int os_chmod(const char *pathname, mode_t mode) { return chmod(pathname, mode); } /* * os_mkstemp -- mkstemp abstraction layer */ int os_mkstemp(char *temp) { return mkstemp(temp); } /* * os_posix_fallocate -- posix_fallocate abstraction layer */ int os_posix_fallocate(int fd, os_off_t offset, off_t len) { #ifdef __FreeBSD__ struct stat fbuf; struct statfs fsbuf; /* * XXX Workaround for https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=223287 * * FreeBSD implements posix_fallocate with a simple block allocation/zero * loop. If the requested size is unreasonably large, this can result in * an uninterruptable system call that will suck up all the space in the * file system and could take hours to fail. To avoid this, make a crude * check to see if the requested allocation is larger than the available * space in the file system (minus any blocks already allocated to the * file), and if so, immediately return ENOSPC. We do the check only if * the offset is 0; otherwise, trying to figure out how many additional * blocks are required is too complicated. * * This workaround is here mostly to fail "absurdly" large requests for * testing purposes; however, it is coded to allow normal (albeit slow) * operation if the space can actually be allocated. Because of the way * PMDK uses posix_fallocate, supporting Linux-style fallocate in * FreeBSD should be considered. */ if (offset == 0) { if (fstatfs(fd, &fsbuf) == -1 || fstat(fd, &fbuf) == -1) return errno; size_t reqd_blocks = (((size_t)len + (fsbuf.f_bsize - 1)) / fsbuf.f_bsize) - (size_t)fbuf.st_blocks; if (reqd_blocks > (size_t)fsbuf.f_bavail) return ENOSPC; } #endif return posix_fallocate(fd, offset, len); } /* * os_ftruncate -- ftruncate abstraction layer */ int os_ftruncate(int fd, os_off_t length) { return ftruncate(fd, length); } /* * os_flock -- flock abstraction layer */ int os_flock(int fd, int operation) { int opt = 0; if (operation & OS_LOCK_EX) opt |= LOCK_EX; if (operation & OS_LOCK_SH) opt |= LOCK_SH; if (operation & OS_LOCK_UN) opt |= LOCK_UN; if (operation & OS_LOCK_NB) opt |= LOCK_NB; return flock(fd, opt); } /* * os_writev -- writev abstraction layer */ ssize_t os_writev(int fd, const struct iovec *iov, int iovcnt) { return writev(fd, iov, iovcnt); } /* * os_clock_gettime -- clock_gettime abstraction layer */ int os_clock_gettime(int id, struct timespec *ts) { return clock_gettime(id, ts); } /* * os_rand_r -- rand_r abstraction layer */ unsigned os_rand_r(unsigned *seedp) { return (unsigned)rand_r(seedp); } /* * os_unsetenv -- unsetenv abstraction layer */ int os_unsetenv(const char *name) { return unsetenv(name); } /* * os_setenv -- setenv abstraction layer */ int os_setenv(const char *name, const char *value, int overwrite) { return setenv(name, value, overwrite); } /* * secure_getenv -- provide GNU secure_getenv for FreeBSD */ #ifndef __USE_GNU static char * secure_getenv(const char *name) { if (issetugid() != 0) return NULL; return getenv(name); } #endif /* * os_getenv -- getenv abstraction layer */ char * os_getenv(const char *name) { return secure_getenv(name); } /* * os_strsignal -- strsignal abstraction layer */ const char * os_strsignal(int sig) { return strsignal(sig); } int os_execv(const char *path, char *const argv[]) { return execv(path, argv); }
6,879
20.234568
78
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/vecq.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * vecq.h -- vector queue (FIFO) interface */ #ifndef PMDK_VECQ_H #define PMDK_VECQ_H 1 #include <stddef.h> #include "util.h" #include "out.h" #ifdef __cplusplus extern "C" { #endif #define VECQ_INIT_SIZE (64) #define VECQ(name, type)\ struct name {\ type *buffer;\ size_t capacity;\ size_t front;\ size_t back;\ } #define VECQ_INIT(vec) do {\ (vec)->buffer = NULL;\ (vec)->capacity = 0;\ (vec)->front = 0;\ (vec)->back = 0;\ } while (0) #define VECQ_REINIT(vec) do {\ VALGRIND_ANNOTATE_NEW_MEMORY((vec), sizeof(*vec));\ VALGRIND_ANNOTATE_NEW_MEMORY((vec)->buffer,\ (sizeof(*(vec)->buffer) * ((vec)->capacity)));\ (vec)->front = 0;\ (vec)->back = 0;\ } while (0) #define VECQ_FRONT_POS(vec)\ ((vec)->front & ((vec)->capacity - 1)) #define VECQ_BACK_POS(vec)\ ((vec)->back & ((vec)->capacity - 1)) #define VECQ_FRONT(vec)\ (vec)->buffer[VECQ_FRONT_POS(vec)] #define VECQ_BACK(vec)\ (vec)->buffer[VECQ_BACK_POS(vec)] #define VECQ_DEQUEUE(vec)\ ((vec)->buffer[(((vec)->front++) & ((vec)->capacity - 1))]) #define VECQ_SIZE(vec)\ ((vec)->back - (vec)->front) static inline int vecq_grow(void *vec, size_t s) { VECQ(vvec, void) *vecp = (struct vvec *)vec; size_t ncapacity = vecp->capacity == 0 ? VECQ_INIT_SIZE : vecp->capacity * 2; void *tbuf = Realloc(vecp->buffer, s * ncapacity); if (tbuf == NULL) { ERR("!Realloc"); return -1; } vecp->buffer = tbuf; vecp->capacity = ncapacity; return 0; } #define VECQ_GROW(vec)\ vecq_grow((void *)vec, sizeof(*(vec)->buffer)) #define VECQ_INSERT(vec, element)\ (VECQ_BACK(vec) = element, (vec)->back += 1, 0) #define VECQ_ENQUEUE(vec, element)\ ((vec)->capacity == VECQ_SIZE(vec) ?\ (VECQ_GROW(vec) == 0 ? VECQ_INSERT(vec, element) : -1) :\ VECQ_INSERT(vec, element)) #define VECQ_CAPACITY(vec)\ ((vec)->capacity) #define VECQ_FOREACH(el, vec)\ for (size_t _vec_i = 0;\ _vec_i < VECQ_SIZE(vec) &&\ (((el) = (vec)->buffer[_vec_i & ((vec)->capacity - 1)]), 1);\ ++_vec_i) #define VECQ_FOREACH_REVERSE(el, vec)\ for (size_t _vec_i = VECQ_SIZE(vec);\ _vec_i > 0 &&\ (((el) = (vec)->buffer[(_vec_i - 1) & ((vec)->capacity - 1)]), 1);\ --_vec_i) #define VECQ_CLEAR(vec) do {\ (vec)->front = 0;\ (vec)->back = 0;\ } while (0) #define VECQ_DELETE(vec) do {\ Free((vec)->buffer);\ (vec)->buffer = NULL;\ (vec)->capacity = 0;\ (vec)->front = 0;\ (vec)->back = 0;\ } while (0) #ifdef __cplusplus } #endif #endif /* PMDK_VECQ_H */
4,023
25.473684
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_deep_linux.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_deep_linux.c -- Linux abstraction layer */ #define _GNU_SOURCE #include <inttypes.h> #include <fcntl.h> #include <sys/stat.h> #include "out.h" #include "os.h" #include "mmap.h" #include "file.h" #include "libpmem.h" #include "os_deep.h" /* * os_deep_flush_write -- (internal) perform write to deep_flush file * on given region_id */ static int os_deep_flush_write(int region_id) { LOG(3, "region_id %d", region_id); char deep_flush_path[PATH_MAX]; int deep_flush_fd; snprintf(deep_flush_path, PATH_MAX, "/sys/bus/nd/devices/region%d/deep_flush", region_id); if ((deep_flush_fd = os_open(deep_flush_path, O_WRONLY)) < 0) { LOG(1, "!os_open(\"%s\", O_WRONLY)", deep_flush_path); return -1; } if (write(deep_flush_fd, "1", 1) != 1) { LOG(1, "!write(%d, \"1\")", deep_flush_fd); int oerrno = errno; os_close(deep_flush_fd); errno = oerrno; return -1; } os_close(deep_flush_fd); return 0; } /* * os_deep_type -- (internal) perform deep operation based on a pmem * mapping type */ static int os_deep_type(const struct map_tracker *mt, void *addr, size_t len) { LOG(15, "mt %p addr %p len %zu", mt, addr, len); switch (mt->type) { case PMEM_DEV_DAX: pmem_drain(); if (os_deep_flush_write(mt->region_id) < 0) { if (errno == ENOENT) { errno = ENOTSUP; LOG(1, "!deep_flush not supported"); } else { LOG(2, "cannot write to deep_flush" "in region %d", mt->region_id); } return -1; } return 0; case PMEM_MAP_SYNC: return pmem_msync(addr, len); default: ASSERT(0); return -1; } } /* * os_range_deep_common -- perform deep action of given address range */ int os_range_deep_common(uintptr_t addr, size_t len) { LOG(3, "addr 0x%016" PRIxPTR " len %zu", addr, len); while (len != 0) { const struct map_tracker *mt = util_range_find(addr, len); /* no more overlapping track regions or NOT a device DAX */ if (mt == NULL) { LOG(15, "pmem_msync addr %p, len %lu", (void *)addr, len); return pmem_msync((void *)addr, len); } /* * For range that intersects with the found mapping * write to (Device DAX) deep_flush file. * Call msync for the non-intersecting part. */ if (mt->base_addr > addr) { size_t curr_len = mt->base_addr - addr; if (curr_len > len) curr_len = len; if (pmem_msync((void *)addr, curr_len) != 0) return -1; len -= curr_len; if (len == 0) return 0; addr = mt->base_addr; } size_t mt_in_len = mt->end_addr - addr; size_t persist_len = MIN(len, mt_in_len); if (os_deep_type(mt, (void *)addr, persist_len)) return -1; if (mt->end_addr >= addr + len) return 0; len -= mt_in_len; addr = mt->end_addr; } return 0; } /* * os_part_deep_common -- common function to handle both * deep_persist and deep_drain part flush cases. */ int os_part_deep_common(struct pool_replica *rep, unsigned partidx, void *addr, size_t len, int flush) { LOG(3, "part %p part %d addr %p len %lu flush %d", rep, partidx, addr, len, flush); if (!rep->is_pmem) { /* * In case of part on non-pmem call msync on the range * to deep flush the data. Deep drain is empty as all * data is msynced to persistence. */ if (!flush) return 0; if (pmem_msync(addr, len)) { LOG(1, "pmem_msync(%p, %lu)", addr, len); return -1; } return 0; } struct pool_set_part part = rep->part[partidx]; /* Call deep flush if it was requested */ if (flush) { LOG(15, "pmem_deep_flush addr %p, len %lu", addr, len); pmem_deep_flush(addr, len); } /* * Before deep drain call normal drain to ensure that data * is at least in WPQ. */ pmem_drain(); if (part.is_dev_dax) { /* * During deep_drain for part on device DAX search for * device region id, and perform WPQ flush on found * device DAX region. */ int region_id = util_ddax_region_find(part.path); if (region_id < 0) { if (errno == ENOENT) { errno = ENOTSUP; LOG(1, "!deep_flush not supported"); } else { LOG(1, "invalid dax_region id %d", region_id); } return -1; } if (os_deep_flush_write(region_id)) { LOG(1, "ddax_deep_flush_write(%d)", region_id); return -1; } } else { /* * For deep_drain on normal pmem it is enough to * call msync on one page. */ if (pmem_msync(addr, MIN(Pagesize, len))) { LOG(1, "pmem_msync(%p, %lu)", addr, len); return -1; } } return 0; }
6,006
24.561702
75
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/ctl_global.c
/* * Copyright 2016-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ctl_global.c -- implementation of the global CTL namespace */ #include "ctl.h" #include "set.h" #include "out.h" #include "ctl_global.h" static int CTL_READ_HANDLER(at_create)(void *ctx, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { int *arg_out = arg; *arg_out = Prefault_at_create; return 0; } static int CTL_WRITE_HANDLER(at_create)(void *ctx, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { int arg_in = *(int *)arg; Prefault_at_create = arg_in; return 0; } static int CTL_READ_HANDLER(at_open)(void *ctx, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { int *arg_out = arg; *arg_out = Prefault_at_open; return 0; } static int CTL_WRITE_HANDLER(at_open)(void *ctx, enum ctl_query_source source, void *arg, struct ctl_indexes *indexes) { int arg_in = *(int *)arg; Prefault_at_open = arg_in; return 0; } static struct ctl_argument CTL_ARG(at_create) = CTL_ARG_BOOLEAN; static struct ctl_argument CTL_ARG(at_open) = CTL_ARG_BOOLEAN; static const struct ctl_node CTL_NODE(prefault)[] = { CTL_LEAF_RW(at_create), CTL_LEAF_RW(at_open), CTL_NODE_END }; void ctl_global_register(void) { CTL_REGISTER_MODULE(NULL, prefault); }
2,839
27.686869
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_dimm_ndctl.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_dimm_ndctl.c -- implementation of DIMMs API based on the ndctl library */ #define _GNU_SOURCE #include <sys/types.h> #include <libgen.h> #include <limits.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ndctl/libndctl.h> #include <ndctl/libdaxctl.h> /* XXX: workaround for missing PAGE_SIZE - should be fixed in linux/ndctl.h */ #include <sys/user.h> #include <linux/ndctl.h> #include "out.h" #include "os.h" #include "os_dimm.h" #include "os_badblock.h" #include "badblock.h" #include "vec.h" /* * http://pmem.io/documents/NVDIMM_DSM_Interface-V1.6.pdf * Table 3-2 SMART amd Health Data - Validity flags * Bit[5] – If set to 1, indicates that Unsafe Shutdown Count * field is valid */ #define USC_VALID_FLAG (1 << 5) #define FOREACH_BUS_REGION_NAMESPACE(ctx, bus, region, ndns) \ ndctl_bus_foreach(ctx, bus) \ ndctl_region_foreach(bus, region) \ ndctl_namespace_foreach(region, ndns) \ /* * os_dimm_match_device -- (internal) returns 1 if the device matches * with the given file, 0 if it doesn't match, * and -1 in case of error. */ static int os_dimm_match_device(const os_stat_t *st, const char *devname) { LOG(3, "st %p devname %s", st, devname); if (*devname == '\0') return 0; char path[PATH_MAX]; os_stat_t stat; int ret; if ((ret = snprintf(path, PATH_MAX, "/dev/%s", devname)) < 0) { ERR("snprintf: %d", ret); return -1; } if (os_stat(path, &stat)) { ERR("!stat %s", path); return -1; } dev_t dev = S_ISCHR(st->st_mode) ? st->st_rdev : st->st_dev; if (dev == stat.st_rdev) { LOG(4, "found matching device: %s", path); return 1; } LOG(10, "skipping not matching device: %s", path); return 0; } /* * os_dimm_region_namespace -- (internal) returns the region * (and optionally the namespace) * where the given file is located */ static int os_dimm_region_namespace(struct ndctl_ctx *ctx, const os_stat_t *st, struct ndctl_region **pregion, struct ndctl_namespace **pndns) { LOG(3, "ctx %p stat %p pregion %p pnamespace %p", ctx, st, pregion, pndns); struct ndctl_bus *bus; struct ndctl_region *region; struct ndctl_namespace *ndns; ASSERTne(pregion, NULL); *pregion = NULL; if (pndns) *pndns = NULL; FOREACH_BUS_REGION_NAMESPACE(ctx, bus, region, ndns) { struct ndctl_btt *btt; struct ndctl_dax *dax = NULL; struct ndctl_pfn *pfn; const char *devname; if ((dax = ndctl_namespace_get_dax(ndns))) { struct daxctl_region *dax_region; dax_region = ndctl_dax_get_daxctl_region(dax); if (!dax_region) { ERR("!cannot find dax region"); return -1; } struct daxctl_dev *dev; daxctl_dev_foreach(dax_region, dev) { devname = daxctl_dev_get_devname(dev); int ret = os_dimm_match_device(st, devname); if (ret < 0) return ret; if (ret) { *pregion = region; if (pndns) *pndns = ndns; return 0; } } } else { if ((btt = ndctl_namespace_get_btt(ndns))) { devname = ndctl_btt_get_block_device(btt); } else if ((pfn = ndctl_namespace_get_pfn(ndns))) { devname = ndctl_pfn_get_block_device(pfn); } else { devname = ndctl_namespace_get_block_device(ndns); } int ret = os_dimm_match_device(st, devname); if (ret < 0) return ret; if (ret) { *pregion = region; if (pndns) *pndns = ndns; return 0; } } } LOG(10, "did not found any matching device"); return 0; } /* * os_dimm_interleave_set -- (internal) returns set of dimms * where the pool file is located */ static struct ndctl_interleave_set * os_dimm_interleave_set(struct ndctl_ctx *ctx, const os_stat_t *st) { LOG(3, "ctx %p stat %p", ctx, st); struct ndctl_region *region = NULL; if (os_dimm_region_namespace(ctx, st, &region, NULL)) return NULL; return region ? ndctl_region_get_interleave_set(region) : NULL; } /* * os_dimm_uid -- returns a file uid based on dimms uids * * if uid == null then function will return required buffer size */ int os_dimm_uid(const char *path, char *uid, size_t *buff_len) { LOG(3, "path %s, uid %p, len %lu", path, uid, *buff_len); os_stat_t st; struct ndctl_ctx *ctx; struct ndctl_interleave_set *set; struct ndctl_dimm *dimm; int ret = 0; if (os_stat(path, &st)) { ERR("!stat %s", path); return -1; } if (ndctl_new(&ctx)) { ERR("!ndctl_new"); return -1; } if (uid == NULL) { *buff_len = 1; /* '\0' */ } set = os_dimm_interleave_set(ctx, &st); if (set == NULL) goto end; if (uid == NULL) { ndctl_dimm_foreach_in_interleave_set(set, dimm) { *buff_len += strlen(ndctl_dimm_get_unique_id(dimm)); } goto end; } size_t len = 1; ndctl_dimm_foreach_in_interleave_set(set, dimm) { const char *dimm_uid = ndctl_dimm_get_unique_id(dimm); len += strlen(dimm_uid); if (len > *buff_len) { ret = -1; goto end; } strncat(uid, dimm_uid, *buff_len); } end: ndctl_unref(ctx); return ret; } /* * os_dimm_usc -- returns unsafe shutdown count */ int os_dimm_usc(const char *path, uint64_t *usc) { LOG(3, "path %s, uid %p", path, usc); os_stat_t st; struct ndctl_ctx *ctx; int ret = -1; *usc = 0; if (os_stat(path, &st)) { ERR("!stat %s", path); return -1; } if (ndctl_new(&ctx)) { ERR("!ndctl_new"); return -1; } struct ndctl_interleave_set *iset = os_dimm_interleave_set(ctx, &st); if (iset == NULL) goto out; struct ndctl_dimm *dimm; ndctl_dimm_foreach_in_interleave_set(iset, dimm) { struct ndctl_cmd *cmd = ndctl_dimm_cmd_new_smart(dimm); if (cmd == NULL) { ERR("!ndctl_dimm_cmd_new_smart"); goto err; } if (ndctl_cmd_submit(cmd)) { ERR("!ndctl_cmd_submit"); goto err; } if (!(ndctl_cmd_smart_get_flags(cmd) & USC_VALID_FLAG)) { /* dimm doesn't support unsafe shutdown count */ continue; } *usc += ndctl_cmd_smart_get_shutdown_count(cmd); } out: ret = 0; err: ndctl_unref(ctx); return ret; } /* * os_dimm_get_namespace_bounds -- (internal) returns the bounds * (offset and size) of the given namespace * relative to the beginning of its region */ static int os_dimm_get_namespace_bounds(struct ndctl_region *region, struct ndctl_namespace *ndns, unsigned long long *ns_offset, unsigned long long *ns_size) { LOG(3, "region %p namespace %p ns_offset %p ns_size %p", region, ndns, ns_offset, ns_size); struct ndctl_pfn *pfn = ndctl_namespace_get_pfn(ndns); struct ndctl_dax *dax = ndctl_namespace_get_dax(ndns); ASSERTne(ns_offset, NULL); ASSERTne(ns_size, NULL); if (pfn) { *ns_offset = ndctl_pfn_get_resource(pfn); if (*ns_offset == ULLONG_MAX) { ERR("!(pfn) cannot read offset of the namespace"); return -1; } *ns_size = ndctl_pfn_get_size(pfn); if (*ns_size == ULLONG_MAX) { ERR("!(pfn) cannot read size of the namespace"); return -1; } LOG(10, "(pfn) ns_offset 0x%llx ns_size %llu", *ns_offset, *ns_size); } else if (dax) { *ns_offset = ndctl_dax_get_resource(dax); if (*ns_offset == ULLONG_MAX) { ERR("!(dax) cannot read offset of the namespace"); return -1; } *ns_size = ndctl_dax_get_size(dax); if (*ns_size == ULLONG_MAX) { ERR("!(dax) cannot read size of the namespace"); return -1; } LOG(10, "(dax) ns_offset 0x%llx ns_size %llu", *ns_offset, *ns_size); } else { /* raw or btt */ *ns_offset = ndctl_namespace_get_resource(ndns); if (*ns_offset == ULLONG_MAX) { ERR("!(raw/btt) cannot read offset of the namespace"); return -1; } *ns_size = ndctl_namespace_get_size(ndns); if (*ns_size == ULLONG_MAX) { ERR("!(raw/btt) cannot read size of the namespace"); return -1; } LOG(10, "(raw/btt) ns_offset 0x%llx ns_size %llu", *ns_offset, *ns_size); } unsigned long long region_offset = ndctl_region_get_resource(region); if (region_offset == ULLONG_MAX) { ERR("!cannot read offset of the region"); return -1; } LOG(10, "region_offset 0x%llx", region_offset); *ns_offset -= region_offset; return 0; } /* * os_dimm_namespace_get_badblocks -- (internal) returns bad blocks * in the given namespace */ static int os_dimm_namespace_get_badblocks(struct ndctl_region *region, struct ndctl_namespace *ndns, struct badblocks *bbs) { LOG(3, "region %p, namespace %p", region, ndns); ASSERTne(bbs, NULL); unsigned long long ns_beg, ns_size, ns_end; unsigned long long bb_beg, bb_end; unsigned long long beg, end; VEC(bbsvec, struct bad_block) bbv = VEC_INITIALIZER; bbs->ns_resource = 0; bbs->bb_cnt = 0; bbs->bbv = NULL; if (os_dimm_get_namespace_bounds(region, ndns, &ns_beg, &ns_size)) { LOG(1, "cannot read namespace's bounds"); return -1; } ns_end = ns_beg + ns_size - 1; LOG(10, "namespace: begin %llu, end %llu size %llu (in 512B sectors)", B2SEC(ns_beg), B2SEC(ns_end + 1) - 1, B2SEC(ns_size)); struct badblock *bb; ndctl_region_badblock_foreach(region, bb) { /* * libndctl returns offset and length of a bad block * both expressed in 512B sectors and offset is relative * to the beginning of the region. */ bb_beg = SEC2B(bb->offset); bb_end = bb_beg + SEC2B(bb->len) - 1; LOG(10, "region bad block: begin %llu end %llu length %u (in 512B sectors)", bb->offset, bb->offset + bb->len - 1, bb->len); if (bb_beg > ns_end || ns_beg > bb_end) continue; beg = (bb_beg > ns_beg) ? bb_beg : ns_beg; end = (bb_end < ns_end) ? bb_end : ns_end; /* * Form a new bad block structure with offset and length * expressed in bytes and offset relative to the beginning * of the namespace. */ struct bad_block bbn; bbn.offset = beg - ns_beg; bbn.length = (unsigned)(end - beg + 1); bbn.nhealthy = NO_HEALTHY_REPLICA; /* unknown healthy replica */ /* add the new bad block to the vector */ if (VEC_PUSH_BACK(&bbv, bbn)) { VEC_DELETE(&bbv); return -1; } LOG(4, "namespace bad block: begin %llu end %llu length %llu (in 512B sectors)", B2SEC(beg - ns_beg), B2SEC(end - ns_beg), B2SEC(end - beg) + 1); } bbs->bb_cnt = (unsigned)VEC_SIZE(&bbv); bbs->bbv = VEC_ARR(&bbv); bbs->ns_resource = ns_beg + ndctl_region_get_resource(region); LOG(4, "number of bad blocks detected: %u", bbs->bb_cnt); return 0; } /* * os_dimm_files_namespace_bus -- (internal) returns bus where the given * file is located */ static int os_dimm_files_namespace_bus(struct ndctl_ctx *ctx, const char *path, struct ndctl_bus **pbus) { LOG(3, "ctx %p path %s pbus %p", ctx, path, pbus); ASSERTne(pbus, NULL); struct ndctl_region *region; struct ndctl_namespace *ndns; os_stat_t st; if (os_stat(path, &st)) { ERR("!stat %s", path); return -1; } int rv = os_dimm_region_namespace(ctx, &st, &region, &ndns); if (rv) { LOG(1, "getting region and namespace failed"); return -1; } if (!region) { ERR("region unknown"); return -1; } *pbus = ndctl_region_get_bus(region); return 0; } /* * os_dimm_files_namespace_badblocks_bus -- (internal) returns badblocks * in the namespace where the given * file is located * (optionally returns also the bus) */ static int os_dimm_files_namespace_badblocks_bus(struct ndctl_ctx *ctx, const char *path, struct ndctl_bus **pbus, struct badblocks *bbs) { LOG(3, "ctx %p path %s pbus %p badblocks %p", ctx, path, pbus, bbs); struct ndctl_region *region; struct ndctl_namespace *ndns; os_stat_t st; if (os_stat(path, &st)) { ERR("!stat %s", path); return -1; } int rv = os_dimm_region_namespace(ctx, &st, &region, &ndns); if (rv) { LOG(1, "getting region and namespace failed"); return -1; } memset(bbs, 0, sizeof(*bbs)); if (region == NULL || ndns == NULL) return 0; if (pbus) *pbus = ndctl_region_get_bus(region); return os_dimm_namespace_get_badblocks(region, ndns, bbs); } /* * os_dimm_files_namespace_badblocks -- returns badblocks in the namespace * where the given file is located */ int os_dimm_files_namespace_badblocks(const char *path, struct badblocks *bbs) { LOG(3, "path %s", path); struct ndctl_ctx *ctx; if (ndctl_new(&ctx)) { ERR("!ndctl_new"); return -1; } int ret = os_dimm_files_namespace_badblocks_bus(ctx, path, NULL, bbs); ndctl_unref(ctx); return ret; } /* * os_dimm_devdax_clear_one_badblock -- (internal) clear one bad block * in the dax device */ static int os_dimm_devdax_clear_one_badblock(struct ndctl_bus *bus, unsigned long long address, unsigned long long length) { LOG(3, "bus %p address 0x%llx length %llu (bytes)", bus, address, length); int ret = 0; struct ndctl_cmd *cmd_ars_cap = ndctl_bus_cmd_new_ars_cap(bus, address, length); if (cmd_ars_cap == NULL) { ERR("failed to create cmd (bus '%s')", ndctl_bus_get_provider(bus)); return -1; } if ((ret = ndctl_cmd_submit(cmd_ars_cap)) < 0) { ERR("failed to submit cmd (bus '%s')", ndctl_bus_get_provider(bus)); goto out_ars_cap; } struct ndctl_cmd *cmd_ars_start = ndctl_bus_cmd_new_ars_start(cmd_ars_cap, ND_ARS_PERSISTENT); if (cmd_ars_start == NULL) { ERR("ndctl_bus_cmd_new_ars_start() failed"); goto out_ars_cap; } if ((ret = ndctl_cmd_submit(cmd_ars_start)) < 0) { ERR("failed to submit cmd (bus '%s')", ndctl_bus_get_provider(bus)); goto out_ars_start; } struct ndctl_cmd *cmd_ars_status; do { cmd_ars_status = ndctl_bus_cmd_new_ars_status(cmd_ars_cap); if (cmd_ars_status == NULL) { ERR("ndctl_bus_cmd_new_ars_status() failed"); goto out_ars_start; } if ((ret = ndctl_cmd_submit(cmd_ars_status)) < 0) { ERR("failed to submit cmd (bus '%s')", ndctl_bus_get_provider(bus)); goto out_ars_status; } } while (ndctl_cmd_ars_in_progress(cmd_ars_status)); struct ndctl_range range; ndctl_cmd_ars_cap_get_range(cmd_ars_cap, &range); struct ndctl_cmd *cmd_clear_error = ndctl_bus_cmd_new_clear_error( range.address, range.length, cmd_ars_cap); if ((ret = ndctl_cmd_submit(cmd_clear_error)) < 0) { ERR("failed to submit cmd (bus '%s')", ndctl_bus_get_provider(bus)); goto out_clear_error; } size_t cleared = ndctl_cmd_clear_error_get_cleared(cmd_clear_error); LOG(4, "cleared %zu out of %llu bad blocks", cleared, length); ret = cleared == length ? 0 : -1; out_clear_error: ndctl_cmd_unref(cmd_clear_error); out_ars_status: ndctl_cmd_unref(cmd_ars_status); out_ars_start: ndctl_cmd_unref(cmd_ars_start); out_ars_cap: ndctl_cmd_unref(cmd_ars_cap); return ret; } /* * os_dimm_devdax_clear_badblocks -- clear the given bad blocks in the dax * device (or all of them if 'pbbs' is not set) */ int os_dimm_devdax_clear_badblocks(const char *path, struct badblocks *pbbs) { LOG(3, "path %s badblocks %p", path, pbbs); struct ndctl_ctx *ctx; struct ndctl_bus *bus; int ret = -1; if (ndctl_new(&ctx)) { ERR("!ndctl_new"); return -1; } struct badblocks *bbs = badblocks_new(); if (bbs == NULL) goto exit_free_all; if (pbbs) { ret = os_dimm_files_namespace_bus(ctx, path, &bus); if (ret) { LOG(1, "getting bad blocks' bus failed -- %s", path); goto exit_free_all; } badblocks_delete(bbs); bbs = pbbs; } else { ret = os_dimm_files_namespace_badblocks_bus(ctx, path, &bus, bbs); if (ret) { LOG(1, "getting bad blocks for the file failed -- %s", path); goto exit_free_all; } } if (bbs->bb_cnt == 0 || bbs->bbv == NULL) /* OK - no bad blocks found */ goto exit_free_all; LOG(4, "clearing %u bad block(s)...", bbs->bb_cnt); unsigned b; for (b = 0; b < bbs->bb_cnt; b++) { LOG(4, "clearing bad block: offset %llu length %u (in 512B sectors)", B2SEC(bbs->bbv[b].offset), B2SEC(bbs->bbv[b].length)); ret = os_dimm_devdax_clear_one_badblock(bus, bbs->bbv[b].offset + bbs->ns_resource, bbs->bbv[b].length); if (ret) { LOG(1, "failed to clear bad block: offset %llu length %u (in 512B sectors)", B2SEC(bbs->bbv[b].offset), B2SEC(bbs->bbv[b].length)); goto exit_free_all; } } exit_free_all: if (!pbbs) badblocks_delete(bbs); ndctl_unref(ctx); return ret; } /* * os_dimm_devdax_clear_badblocks_all -- clear all bad blocks in the dax device */ int os_dimm_devdax_clear_badblocks_all(const char *path) { LOG(3, "path %s", path); return os_dimm_devdax_clear_badblocks(path, NULL); }
18,252
23.272606
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/fs.h
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * fs.h -- file system traversal abstraction layer */ #ifndef PMDK_FS_H #define PMDK_FS_H 1 #include <unistd.h> #ifdef __cplusplus extern "C" { #endif struct fs; enum fs_entry_type { FS_ENTRY_FILE, FS_ENTRY_DIRECTORY, FS_ENTRY_SYMLINK, FS_ENTRY_OTHER, MAX_FS_ENTRY_TYPES }; struct fs_entry { enum fs_entry_type type; const char *name; size_t namelen; const char *path; size_t pathlen; /* the depth of the traversal */ /* XXX long on FreeBSD. Linux uses short. No harm in it being bigger */ long level; }; struct fs *fs_new(const char *path); void fs_delete(struct fs *f); /* this call invalidates the previous entry */ struct fs_entry *fs_read(struct fs *f); #ifdef __cplusplus } #endif #endif /* PMDK_FS_H */
2,342
27.925926
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/vec.h
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * vec.h -- vector interface */ #ifndef PMDK_VEC_H #define PMDK_VEC_H 1 #include <stddef.h> #include "valgrind_internal.h" #include "util.h" #include "out.h" #ifdef __cplusplus extern "C" { #endif #define VEC_INIT_SIZE (64) #define VEC(name, type)\ struct name {\ type *buffer;\ size_t size;\ size_t capacity;\ } #define VEC_INITIALIZER {NULL, 0, 0} #define VEC_INIT(vec) do {\ (vec)->buffer = NULL;\ (vec)->size = 0;\ (vec)->capacity = 0;\ } while (0) #define VEC_MOVE(vecl, vecr) do {\ (vecl)->buffer = (vecr)->buffer;\ (vecl)->size = (vecr)->size;\ (vecl)->capacity = (vecr)->capacity;\ (vecr)->buffer = NULL;\ (vecr)->size = 0;\ (vecr)->capacity = 0;\ } while (0) #define VEC_REINIT(vec) do {\ VALGRIND_ANNOTATE_NEW_MEMORY((vec), sizeof(*vec));\ VALGRIND_ANNOTATE_NEW_MEMORY((vec)->buffer,\ (sizeof(*(vec)->buffer) * ((vec)->capacity)));\ (vec)->size = 0;\ } while (0) static inline int vec_reserve(void *vec, size_t ncapacity, size_t s) { size_t ncap = ncapacity == 0 ? VEC_INIT_SIZE : ncapacity; VEC(vvec, void) *vecp = (struct vvec *)vec; void *tbuf = Realloc(vecp->buffer, s * ncap); if (tbuf == NULL) { ERR("!Realloc"); return -1; } vecp->buffer = tbuf; vecp->capacity = ncap; return 0; } #define VEC_RESERVE(vec, ncapacity)\ (((vec)->size == 0 || (ncapacity) > (vec)->size) ?\ vec_reserve((void *)vec, ncapacity, sizeof(*(vec)->buffer)) :\ 0) #define VEC_POP_BACK(vec) do {\ (vec)->size -= 1;\ } while (0) #define VEC_FRONT(vec)\ (vec)->buffer[0] #define VEC_BACK(vec)\ (vec)->buffer[(vec)->size - 1] #define VEC_ERASE_BY_POS(vec, pos) do {\ if ((pos) != ((vec)->size - 1))\ (vec)->buffer[(pos)] = VEC_BACK(vec);\ VEC_POP_BACK(vec);\ } while (0) #define VEC_ERASE_BY_PTR(vec, element) do {\ if ((element) != &VEC_BACK(vec))\ *(element) = VEC_BACK(vec);\ VEC_POP_BACK(vec);\ } while (0) #define VEC_INSERT(vec, element)\ ((vec)->buffer[(vec)->size - 1] = (element), 0) #define VEC_INC_SIZE(vec)\ (((vec)->size++), 0) #define VEC_INC_BACK(vec)\ ((vec)->capacity == (vec)->size ?\ (VEC_RESERVE((vec), ((vec)->capacity * 2)) == 0 ?\ VEC_INC_SIZE(vec) : -1) :\ VEC_INC_SIZE(vec)) #define VEC_PUSH_BACK(vec, element)\ (VEC_INC_BACK(vec) == 0? VEC_INSERT(vec, element) : -1) #define VEC_FOREACH(el, vec)\ for (size_t _vec_i = 0;\ _vec_i < (vec)->size && (((el) = (vec)->buffer[_vec_i]), 1);\ ++_vec_i) #define VEC_FOREACH_REVERSE(el, vec)\ for (size_t _vec_i = ((vec)->size);\ _vec_i != 0 && (((el) = (vec)->buffer[_vec_i - 1]), 1);\ --_vec_i) #define VEC_FOREACH_BY_POS(elpos, vec)\ for ((elpos) = 0; (elpos) < (vec)->size; ++(elpos)) #define VEC_FOREACH_BY_PTR(el, vec)\ for (size_t _vec_i = 0;\ _vec_i < (vec)->size && (((el) = &(vec)->buffer[_vec_i]), 1);\ ++_vec_i) #define VEC_SIZE(vec)\ ((vec)->size) #define VEC_CAPACITY(vec)\ ((vec)->capacity) #define VEC_ARR(vec)\ ((vec)->buffer) #define VEC_GET(vec, id)\ (&(vec)->buffer[id]) #define VEC_CLEAR(vec) do {\ (vec)->size = 0;\ } while (0) #define VEC_DELETE(vec) do {\ Free((vec)->buffer);\ (vec)->buffer = NULL;\ (vec)->size = 0;\ (vec)->capacity = 0;\ } while (0) #ifdef __cplusplus } #endif #endif /* PMDK_VEC_H */
4,773
24.666667
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/badblock.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * badblock.h - common part of bad blocks API */ #ifndef PMDK_BADBLOCK_POOLSET_H #define PMDK_BADBLOCK_POOLSET_H 1 #include "set.h" #ifdef __cplusplus extern "C" { #endif struct badblocks *badblocks_new(void); void badblocks_delete(struct badblocks *bbs); int badblocks_check_poolset(struct pool_set *set, int create); int badblocks_clear_poolset(struct pool_set *set, int create); char *badblocks_recovery_file_alloc(const char *file, unsigned rep, unsigned part); int badblocks_recovery_file_exists(struct pool_set *set); #ifdef __cplusplus } #endif #endif /* PMDK_BADBLOCK_POOLSET_H */
2,203
35.131148
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_auto_flush_linux.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_auto_flush_linux.c -- Linux abstraction layer for auto flush detection */ #define _GNU_SOURCE #include <inttypes.h> #include <fcntl.h> #include <sys/stat.h> #include <string.h> #include "out.h" #include "os.h" #include "fs.h" #include "os_auto_flush.h" #define BUS_DEVICE_PATH "/sys/bus/nd/devices" #define PERSISTENCE_DOMAIN "persistence_domain" #define DOMAIN_VALUE_LEN 32 /* * check_cpu_cache -- (internal) check if file contains "cpu_cache" entry */ static int check_cpu_cache(const char *domain_path) { LOG(3, "domain_path: %s", domain_path); char domain_value[DOMAIN_VALUE_LEN]; int domain_fd; int cpu_cache = 0; if ((domain_fd = os_open(domain_path, O_RDONLY)) < 0) { LOG(1, "!open(\"%s\", O_RDONLY)", domain_path); goto end; } ssize_t len = read(domain_fd, domain_value, DOMAIN_VALUE_LEN); if (len == -1) { ERR("!read(%d, %p, %d)", domain_fd, domain_value, DOMAIN_VALUE_LEN); cpu_cache = -1; goto end; } else if (domain_value[len - 1] != '\n') { ERR("!read(%d, %p, %d) invalid format", domain_fd, domain_value, DOMAIN_VALUE_LEN); cpu_cache = -1; goto end; } LOG(15, "detected persistent_domain: %s", domain_value); if (strncmp(domain_value, "cpu_cache", strlen("cpu_cache")) == 0) { LOG(15, "cpu_cache in persistent_domain: %s", domain_path); cpu_cache = 1; } else { LOG(15, "cpu_cache not in persistent_domain: %s", domain_path); cpu_cache = 0; } end: if (domain_fd >= 0) os_close(domain_fd); return cpu_cache; } /* * check_domain_in_region -- (internal) check if region * contains persistence_domain file */ static int check_domain_in_region(const char *region_path) { LOG(3, "region_path: %s", region_path); struct fs *reg = NULL; struct fs_entry *reg_entry; char domain_path[PATH_MAX]; int cpu_cache = 0; reg = fs_new(region_path); if (reg == NULL) { ERR("!fs_new: \"%s\"", region_path); cpu_cache = -1; goto end; } while ((reg_entry = fs_read(reg)) != NULL) { /* * persistence_domain has to be a file type entry * and it has to be first level child for region; * there is no need to run into deeper levels */ if (reg_entry->type != FS_ENTRY_FILE || strcmp(reg_entry->name, PERSISTENCE_DOMAIN) != 0 || reg_entry->level != 1) continue; int ret = snprintf(domain_path, PATH_MAX, "%s/"PERSISTENCE_DOMAIN, region_path); if (ret < 0) { ERR("snprintf(%p, %d," "%s/"PERSISTENCE_DOMAIN", %s): %d", domain_path, PATH_MAX, region_path, region_path, ret); cpu_cache = -1; goto end; } cpu_cache = check_cpu_cache(domain_path); } end: if (reg) fs_delete(reg); return cpu_cache; } /* * os_auto_flush -- check if platform supports auto flush for all regions * * Traverse "/sys/bus/nd/devices" path to find all the nvdimm regions, * then for each region checks if "persistence_domain" file exists and * contains "cpu_cache" string. * If for any region "persistence_domain" entry does not exists, or its * context is not as expected, assume eADR is not available on this platform. */ int os_auto_flush(void) { LOG(15, NULL); char *device_path; int cpu_cache = 0; device_path = BUS_DEVICE_PATH; os_stat_t sdev; if (os_stat(device_path, &sdev) != 0 || S_ISDIR(sdev.st_mode) == 0) { LOG(3, "eADR not supported"); return cpu_cache; } struct fs *dev = fs_new(device_path); if (dev == NULL) { ERR("!fs_new: \"%s\"", device_path); return -1; } struct fs_entry *dev_entry; while ((dev_entry = fs_read(dev)) != NULL) { /* * Skip if not a symlink, because we expect that * region on sysfs path is a symlink. * Skip if depth is different than 1, bacause region * we are interested in should be the first level * child for device. */ if ((dev_entry->type != FS_ENTRY_SYMLINK) || !strstr(dev_entry->name, "region") || dev_entry->level != 1) continue; LOG(15, "Start traversing region: %s", dev_entry->path); cpu_cache = check_domain_in_region(dev_entry->path); if (cpu_cache != 1) goto end; } end: fs_delete(dev); return cpu_cache; }
5,669
26
77
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_auto_flush_windows.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PMDK_OS_AUTO_FLUSH_WINDOWS_H #define PMDK_OS_AUTO_FLUSH_WINDOWS_H 1 #define ACPI_SIGNATURE 0x41435049 /* hex value of ACPI signature */ #define NFIT_REV_SIGNATURE 0x5449464e /* hex value of htonl(NFIT) signature */ #define NFIT_STR_SIGNATURE "NFIT" #define NFIT_SIGNATURE_LEN 4 #define NFIT_OEM_ID_LEN 6 #define NFIT_OEM_TABLE_ID_LEN 8 #define NFIT_MAX_STRUCTURES 8 #define PCS_RESERVED 3 #define PCS_RESERVED_2 4 #define PCS_TYPE_NUMBER 7 /* check if bit on 'bit' position in number 'num' is set */ #define CHECK_BIT(num, bit) (((num) >> (bit)) & 1) /* * sets alignment of members of structure */ #pragma pack(1) struct platform_capabilities { uint16_t type; uint16_t length; uint8_t highest_valid; uint8_t reserved[PCS_RESERVED]; uint32_t capabilities; uint8_t reserved2[PCS_RESERVED_2]; }; struct nfit_header { uint8_t signature[NFIT_SIGNATURE_LEN]; uint32_t length; uint8_t revision; uint8_t checksum; uint8_t oem_id[NFIT_OEM_ID_LEN]; uint8_t oem_table_id[NFIT_OEM_TABLE_ID_LEN]; uint32_t oem_revision; uint8_t creator_id[4]; uint32_t creator_revision; uint32_t reserved; }; #pragma pack() #endif
2,730
32.716049
78
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/file_windows.c
/* * Copyright 2015-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * file_windows.c -- Windows emulation of Linux-specific system calls */ /* * XXX - The initial approach to PMDK for Windows port was to minimize the * amount of changes required in the core part of the library, and to avoid * preprocessor conditionals, if possible. For that reason, some of the * Linux system calls that have no equivalents on Windows have been emulated * using Windows API. * Note that it was not a goal to fully emulate POSIX-compliant behavior * of mentioned functions. They are used only internally, so current * implementation is just good enough to satisfy PMDK needs and to make it * work on Windows. */ #include <windows.h> #include <sys/stat.h> #include <sys/file.h> #include "file.h" #include "out.h" #include "os.h" /* * util_tmpfile -- create a temporary file */ int util_tmpfile(const char *dir, const char *templ, int flags) { LOG(3, "dir \"%s\" template \"%s\" flags %x", dir, templ, flags); /* only O_EXCL is allowed here */ ASSERT(flags == 0 || flags == O_EXCL); int oerrno; int fd = -1; size_t len = strlen(dir) + strlen(templ) + 1; char *fullname = Malloc(sizeof(*fullname) * len); if (fullname == NULL) { ERR("!Malloc"); return -1; } int ret = _snprintf(fullname, len, "%s%s", dir, templ); if (ret < 0 || ret >= len) { ERR("snprintf: %d", ret); goto err; } LOG(4, "fullname \"%s\"", fullname); /* * XXX - block signals and modify file creation mask for the time * of mkstmep() execution. Restore previous settings once the file * is created. */ fd = os_mkstemp(fullname); if (fd < 0) { ERR("!os_mkstemp"); goto err; } /* * There is no point to use unlink() here. First, because it does not * work on open files. Second, because the file is created with * O_TEMPORARY flag, and it looks like such temp files cannot be open * from another process, even though they are visible on * the filesystem. */ Free(fullname); return fd; err: Free(fullname); oerrno = errno; if (fd != -1) (void) os_close(fd); errno = oerrno; return -1; } /* * util_is_absolute_path -- check if the path is absolute */ int util_is_absolute_path(const char *path) { LOG(3, "path \"%s\"", path); if (path == NULL || path[0] == '\0') return 0; if (path[0] == '\\' || path[1] == ':') return 1; return 0; } /* * util_file_mkdir -- creates new dir */ int util_file_mkdir(const char *path, mode_t mode) { /* * On windows we cannot create read only dir so mode * parameter is useless. */ UNREFERENCED_PARAMETER(mode); LOG(3, "path: %s mode: %d", path, mode); return _mkdir(path); } /* * util_file_dir_open -- open a directory */ int util_file_dir_open(struct dir_handle *handle, const char *path) { /* init handle */ handle->handle = NULL; handle->path = path; return 0; } /* * util_file_dir_next - read next file in directory */ int util_file_dir_next(struct dir_handle *handle, struct file_info *info) { WIN32_FIND_DATAA data; if (handle->handle == NULL) { handle->handle = FindFirstFileA(handle->path, &data); if (handle->handle == NULL) return 1; } else { if (FindNextFileA(handle->handle, &data) == 0) return 1; } info->filename[NAME_MAX] = '\0'; strncpy(info->filename, data.cFileName, NAME_MAX + 1); if (info->filename[NAME_MAX] != '\0') return -1; /* filename truncated */ info->is_dir = data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY; return 0; } /* * util_file_dir_close -- close a directory */ int util_file_dir_close(struct dir_handle *handle) { return FindClose(handle->handle); } /* * util_file_dir_close -- remove directory */ int util_file_dir_remove(const char *path) { return RemoveDirectoryA(path) == 0 ? -1 : 0; } /* * util_file_device_dax_alignment -- returns internal Device DAX alignment */ size_t util_file_device_dax_alignment(const char *path) { LOG(3, "path \"%s\"", path); return 0; } /* * util_ddax_region_find -- returns DEV dax region id that contains file */ int util_ddax_region_find(const char *path) { LOG(3, "path \"%s\"", path); return -1; }
5,660
24.16
76
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_auto_flush.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_auto_flush.h -- abstraction layer for auto flush detection functionality */ #ifndef PMDK_OS_AUTO_FLUSH_H #define PMDK_OS_AUTO_FLUSH_H 1 #ifdef __cplusplus extern "C" { #endif int os_auto_flush(void); #ifdef __cplusplus } #endif #endif
1,847
35.235294
78
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/fs_posix.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * fs_posix.c -- file system traversal Posix implementation */ #include <fts.h> #include "util.h" #include "out.h" #include "vec.h" #include "fs.h" struct fs { FTS *ft; struct fs_entry entry; }; /* * fs_new -- creates fs traversal instance */ struct fs * fs_new(const char *path) { struct fs *f = Zalloc(sizeof(*f)); if (f == NULL) goto error_fs_alloc; const char *paths[2] = {path, NULL}; f->ft = fts_open((char * const *)paths, FTS_COMFOLLOW | FTS_XDEV, NULL); if (f->ft == NULL) goto error_fts_open; return f; error_fts_open: Free(f); error_fs_alloc: return NULL; } /* * fs_read -- reads an entry from the fs path */ struct fs_entry * fs_read(struct fs *f) { FTSENT *entry = fts_read(f->ft); if (entry == NULL) return NULL; switch (entry->fts_info) { case FTS_D: f->entry.type = FS_ENTRY_DIRECTORY; break; case FTS_F: f->entry.type = FS_ENTRY_FILE; break; case FTS_SL: f->entry.type = FS_ENTRY_SYMLINK; break; default: f->entry.type = FS_ENTRY_OTHER; break; } f->entry.name = entry->fts_name; f->entry.namelen = entry->fts_namelen; f->entry.path = entry->fts_path; f->entry.pathlen = entry->fts_pathlen; f->entry.level = entry->fts_level; return &f->entry; } /* * fs_delete -- deletes a fs traversal instance */ void fs_delete(struct fs *f) { fts_close(f->ft); Free(f); }
2,946
24.850877
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/errno_freebsd.h
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * errno_freebsd.h -- map Linux errno's to something close on FreeBSD */ #ifndef PMDK_ERRNO_FREEBSD_H #define PMDK_ERRNO_FREEBSD_H 1 #ifdef __FreeBSD__ #define EBADFD EBADF #define ELIBACC EINVAL #define EMEDIUMTYPE EOPNOTSUPP #define ENOMEDIUM ENODEV #define EREMOTEIO EIO #endif #endif /* PMDK_ERRNO_FREEBSD_H */
1,919
38.183673
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/mmap.c
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * mmap.c -- mmap utilities */ #include <errno.h> #include <inttypes.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include "file.h" #include "queue.h" #include "mmap.h" #include "sys_util.h" #include "os.h" int Mmap_no_random; void *Mmap_hint; static os_rwlock_t Mmap_list_lock; static SORTEDQ_HEAD(map_list_head, map_tracker) Mmap_list = SORTEDQ_HEAD_INITIALIZER(Mmap_list); /* * util_mmap_init -- initialize the mmap utils * * This is called from the library initialization code. */ void util_mmap_init(void) { LOG(3, NULL); util_rwlock_init(&Mmap_list_lock); /* * For testing, allow overriding the default mmap() hint address. * If hint address is defined, it also disables address randomization. */ char *e = os_getenv("PMEM_MMAP_HINT"); if (e) { char *endp; errno = 0; unsigned long long val = strtoull(e, &endp, 16); if (errno || endp == e) { LOG(2, "Invalid PMEM_MMAP_HINT"); } else if (os_access(OS_MAPFILE, R_OK)) { LOG(2, "No /proc, PMEM_MMAP_HINT ignored"); } else { Mmap_hint = (void *)val; Mmap_no_random = 1; LOG(3, "PMEM_MMAP_HINT set to %p", Mmap_hint); } } } /* * util_mmap_fini -- clean up the mmap utils * * This is called before process stop. */ void util_mmap_fini(void) { LOG(3, NULL); util_rwlock_destroy(&Mmap_list_lock); } /* * util_map -- memory map a file * * This is just a convenience function that calls mmap() with the * appropriate arguments and includes our trace points. */ void * util_map(int fd, size_t len, int flags, int rdonly, size_t req_align, int *map_sync) { LOG(3, "fd %d len %zu flags %d rdonly %d req_align %zu map_sync %p", fd, len, flags, rdonly, req_align, map_sync); void *base; void *addr = util_map_hint(len, req_align); if (addr == MAP_FAILED) { ERR("cannot find a contiguous region of given size"); return NULL; } if (req_align) ASSERTeq((uintptr_t)addr % req_align, 0); int proto = rdonly ? PROT_READ : PROT_READ|PROT_WRITE; base = util_map_sync(addr, len, proto, flags, fd, 0, map_sync); if (base == MAP_FAILED) { ERR("!mmap %zu bytes", len); return NULL; } LOG(3, "mapped at %p", base); return base; } /* * util_unmap -- unmap a file * * This is just a convenience function that calls munmap() with the * appropriate arguments and includes our trace points. */ int util_unmap(void *addr, size_t len) { LOG(3, "addr %p len %zu", addr, len); /* * XXX Workaround for https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=169608 */ #ifdef __FreeBSD__ if (!IS_PAGE_ALIGNED((uintptr_t)addr)) { errno = EINVAL; ERR("!munmap"); return -1; } #endif int retval = munmap(addr, len); if (retval < 0) ERR("!munmap"); return retval; } /* * util_map_tmpfile -- reserve space in an unlinked file and memory-map it * * size must be multiple of page size. */ void * util_map_tmpfile(const char *dir, size_t size, size_t req_align) { int oerrno; if (((os_off_t)size) < 0) { ERR("invalid size (%zu) for os_off_t", size); errno = EFBIG; return NULL; } int fd = util_tmpfile(dir, OS_DIR_SEP_STR "vmem.XXXXXX", O_EXCL); if (fd == -1) { LOG(2, "cannot create temporary file in dir %s", dir); goto err; } if ((errno = os_posix_fallocate(fd, 0, (os_off_t)size)) != 0) { ERR("!posix_fallocate"); goto err; } void *base; if ((base = util_map(fd, size, MAP_SHARED, 0, req_align, NULL)) == NULL) { LOG(2, "cannot mmap temporary file"); goto err; } (void) os_close(fd); return base; err: oerrno = errno; if (fd != -1) (void) os_close(fd); errno = oerrno; return NULL; } /* * util_range_ro -- set a memory range read-only */ int util_range_ro(void *addr, size_t len) { LOG(3, "addr %p len %zu", addr, len); uintptr_t uptr; int retval; /* * mprotect requires addr to be a multiple of pagesize, so * adjust addr and len to represent the full 4k chunks * covering the given range. */ /* increase len by the amount we gain when we round addr down */ len += (uintptr_t)addr & (Pagesize - 1); /* round addr down to page boundary */ uptr = (uintptr_t)addr & ~(Pagesize - 1); if ((retval = mprotect((void *)uptr, len, PROT_READ)) < 0) ERR("!mprotect: PROT_READ"); return retval; } /* * util_range_rw -- set a memory range read-write */ int util_range_rw(void *addr, size_t len) { LOG(3, "addr %p len %zu", addr, len); uintptr_t uptr; int retval; /* * mprotect requires addr to be a multiple of pagesize, so * adjust addr and len to represent the full 4k chunks * covering the given range. */ /* increase len by the amount we gain when we round addr down */ len += (uintptr_t)addr & (Pagesize - 1); /* round addr down to page boundary */ uptr = (uintptr_t)addr & ~(Pagesize - 1); if ((retval = mprotect((void *)uptr, len, PROT_READ|PROT_WRITE)) < 0) ERR("!mprotect: PROT_READ|PROT_WRITE"); return retval; } /* * util_range_none -- set a memory range for no access allowed */ int util_range_none(void *addr, size_t len) { LOG(3, "addr %p len %zu", addr, len); uintptr_t uptr; int retval; /* * mprotect requires addr to be a multiple of pagesize, so * adjust addr and len to represent the full 4k chunks * covering the given range. */ /* increase len by the amount we gain when we round addr down */ len += (uintptr_t)addr & (Pagesize - 1); /* round addr down to page boundary */ uptr = (uintptr_t)addr & ~(Pagesize - 1); if ((retval = mprotect((void *)uptr, len, PROT_NONE)) < 0) ERR("!mprotect: PROT_NONE"); return retval; } /* * util_range_comparer -- (internal) compares the two mapping trackers */ static intptr_t util_range_comparer(struct map_tracker *a, struct map_tracker *b) { return ((intptr_t)a->base_addr - (intptr_t)b->base_addr); } /* * util_range_find_unlocked -- (internal) find the map tracker * for given address range * * Returns the first entry at least partially overlapping given range. * It's up to the caller to check whether the entry exactly matches the range, * or if the range spans multiple entries. */ static struct map_tracker * util_range_find_unlocked(uintptr_t addr, size_t len) { LOG(10, "addr 0x%016" PRIxPTR " len %zu", addr, len); uintptr_t end = addr + len; struct map_tracker *mt; SORTEDQ_FOREACH(mt, &Mmap_list, entry) { if (addr < mt->end_addr && (addr >= mt->base_addr || end > mt->base_addr)) goto out; /* break if there is no chance to find matching entry */ if (addr < mt->base_addr) break; } mt = NULL; out: return mt; } /* * util_range_find -- find the map tracker for given address range * the same as util_range_find_unlocked but locked */ struct map_tracker * util_range_find(uintptr_t addr, size_t len) { LOG(10, "addr 0x%016" PRIxPTR " len %zu", addr, len); util_rwlock_rdlock(&Mmap_list_lock); struct map_tracker *mt = util_range_find_unlocked(addr, len); util_rwlock_unlock(&Mmap_list_lock); return mt; } /* * util_range_register -- add a memory range into a map tracking list */ int util_range_register(const void *addr, size_t len, const char *path, enum pmem_map_type type) { LOG(3, "addr %p len %zu path %s type %d", addr, len, path, type); /* check if not tracked already */ if (util_range_find((uintptr_t)addr, len) != NULL) { ERR( "duplicated persistent memory range; presumably unmapped with munmap() instead of pmem_unmap(): addr %p len %zu", addr, len); errno = ENOMEM; return -1; } struct map_tracker *mt; mt = Malloc(sizeof(struct map_tracker)); if (mt == NULL) { ERR("!Malloc"); return -1; } mt->base_addr = (uintptr_t)addr; mt->end_addr = mt->base_addr + len; mt->type = type; if (type == PMEM_DEV_DAX) mt->region_id = util_ddax_region_find(path); util_rwlock_wrlock(&Mmap_list_lock); SORTEDQ_INSERT(&Mmap_list, mt, entry, struct map_tracker, util_range_comparer); util_rwlock_unlock(&Mmap_list_lock); return 0; } /* * util_range_split -- (internal) remove or split a map tracking entry */ static int util_range_split(struct map_tracker *mt, const void *addrp, const void *endp) { LOG(3, "begin %p end %p", addrp, endp); uintptr_t addr = (uintptr_t)addrp; uintptr_t end = (uintptr_t)endp; ASSERTne(mt, NULL); if (addr == end || addr % Mmap_align != 0 || end % Mmap_align != 0) { ERR( "invalid munmap length, must be non-zero and page aligned"); return -1; } struct map_tracker *mtb = NULL; struct map_tracker *mte = NULL; /* * 1) b e b e * xxxxxxxxxxxxx => xxx.......xxxx - mtb+mte * 2) b e b e * xxxxxxxxxxxxx => xxxxxxx....... - mtb * 3) b e b e * xxxxxxxxxxxxx => ........xxxxxx - mte * 4) b e b e * xxxxxxxxxxxxx => .............. - <none> */ if (addr > mt->base_addr) { /* case #1/2 */ /* new mapping at the beginning */ mtb = Malloc(sizeof(struct map_tracker)); if (mtb == NULL) { ERR("!Malloc"); goto err; } mtb->base_addr = mt->base_addr; mtb->end_addr = addr; mtb->region_id = mt->region_id; mtb->type = mt->type; } if (end < mt->end_addr) { /* case #1/3 */ /* new mapping at the end */ mte = Malloc(sizeof(struct map_tracker)); if (mte == NULL) { ERR("!Malloc"); goto err; } mte->base_addr = end; mte->end_addr = mt->end_addr; mte->region_id = mt->region_id; mte->type = mt->type; } SORTEDQ_REMOVE(&Mmap_list, mt, entry); if (mtb) { SORTEDQ_INSERT(&Mmap_list, mtb, entry, struct map_tracker, util_range_comparer); } if (mte) { SORTEDQ_INSERT(&Mmap_list, mte, entry, struct map_tracker, util_range_comparer); } /* free entry for the original mapping */ Free(mt); return 0; err: Free(mtb); Free(mte); return -1; } /* * util_range_unregister -- remove a memory range * from map tracking list * * Remove the region between [begin,end]. If it's in a middle of the existing * mapping, it results in two new map trackers. */ int util_range_unregister(const void *addr, size_t len) { LOG(3, "addr %p len %zu", addr, len); int ret = 0; util_rwlock_wrlock(&Mmap_list_lock); /* * Changes in the map tracker list must match the underlying behavior. * * $ man 2 mmap: * The address addr must be a multiple of the page size (but length * need not be). All pages containing a part of the indicated range * are unmapped. * * This means that we must align the length to the page size. */ len = PAGE_ALIGNED_UP_SIZE(len); void *end = (char *)addr + len; /* XXX optimize the loop */ struct map_tracker *mt; while ((mt = util_range_find_unlocked((uintptr_t)addr, len)) != NULL) { if (util_range_split(mt, addr, end) != 0) { ret = -1; break; } } util_rwlock_unlock(&Mmap_list_lock); return ret; } /* * util_range_is_pmem -- return true if entire range * is persistent memory */ int util_range_is_pmem(const void *addrp, size_t len) { LOG(10, "addr %p len %zu", addrp, len); uintptr_t addr = (uintptr_t)addrp; int retval = 1; util_rwlock_rdlock(&Mmap_list_lock); do { struct map_tracker *mt = util_range_find(addr, len); if (mt == NULL) { LOG(4, "address not found 0x%016" PRIxPTR, addr); retval = 0; break; } LOG(10, "range found - begin 0x%016" PRIxPTR " end 0x%016" PRIxPTR, mt->base_addr, mt->end_addr); if (mt->base_addr > addr) { LOG(10, "base address doesn't match: " "0x%" PRIxPTR " > 0x%" PRIxPTR, mt->base_addr, addr); retval = 0; break; } uintptr_t map_len = mt->end_addr - addr; if (map_len > len) map_len = len; len -= map_len; addr += map_len; } while (len > 0); util_rwlock_unlock(&Mmap_list_lock); return retval; }
13,289
22.315789
115
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_thread.h
/* * Copyright 2015-2018, Intel Corporation * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_thread.h -- os thread abstraction layer */ #ifndef OS_THREAD_H #define OS_THREAD_H 1 #include <stdint.h> #include <time.h> #ifdef __cplusplus extern "C" { #endif typedef union { long long align; char padding[44]; /* linux: 40 windows: 44 */ } os_mutex_t; typedef union { long long align; char padding[56]; /* linux: 56 windows: 13 */ } os_rwlock_t; typedef union { long long align; char padding[48]; /* linux: 48 windows: 12 */ } os_cond_t; typedef union { long long align; char padding[32]; /* linux: 8 windows: 32 */ } os_thread_t; typedef union { long long align; /* linux: long windows: 8 FreeBSD: 12 */ char padding[16]; /* 16 to be safe */ } os_once_t; #define OS_ONCE_INIT { .padding = {0} } typedef unsigned os_tls_key_t; typedef union { long long align; char padding[56]; /* linux: 56 windows: 8 */ } os_semaphore_t; typedef union { long long align; char padding[56]; /* linux: 56 windows: 8 */ } os_thread_attr_t; typedef union { long long align; char padding[512]; } os_cpu_set_t; #ifdef __FreeBSD__ #define cpu_set_t cpuset_t typedef uintptr_t os_spinlock_t; #else typedef volatile int os_spinlock_t; /* XXX: not implemented on windows */ #endif void os_cpu_zero(os_cpu_set_t *set); void os_cpu_set(size_t cpu, os_cpu_set_t *set); #ifndef _WIN32 #define _When_(...) #endif int os_once(os_once_t *o, void (*func)(void)); int os_tls_key_create(os_tls_key_t *key, void (*destructor)(void *)); int os_tls_key_delete(os_tls_key_t key); int os_tls_set(os_tls_key_t key, const void *value); void *os_tls_get(os_tls_key_t key); int os_mutex_init(os_mutex_t *__restrict mutex); int os_mutex_destroy(os_mutex_t *__restrict mutex); _When_(return == 0, _Acquires_lock_(mutex->lock)) int os_mutex_lock(os_mutex_t *__restrict mutex); _When_(return == 0, _Acquires_lock_(mutex->lock)) int os_mutex_trylock(os_mutex_t *__restrict mutex); int os_mutex_unlock(os_mutex_t *__restrict mutex); /* XXX - non POSIX */ int os_mutex_timedlock(os_mutex_t *__restrict mutex, const struct timespec *abstime); int os_rwlock_init(os_rwlock_t *__restrict rwlock); int os_rwlock_destroy(os_rwlock_t *__restrict rwlock); int os_rwlock_rdlock(os_rwlock_t *__restrict rwlock); int os_rwlock_wrlock(os_rwlock_t *__restrict rwlock); int os_rwlock_tryrdlock(os_rwlock_t *__restrict rwlock); _When_(return == 0, _Acquires_exclusive_lock_(rwlock->lock)) int os_rwlock_trywrlock(os_rwlock_t *__restrict rwlock); _When_(rwlock->is_write != 0, _Requires_exclusive_lock_held_(rwlock->lock)) _When_(rwlock->is_write == 0, _Requires_shared_lock_held_(rwlock->lock)) int os_rwlock_unlock(os_rwlock_t *__restrict rwlock); int os_rwlock_timedrdlock(os_rwlock_t *__restrict rwlock, const struct timespec *abstime); int os_rwlock_timedwrlock(os_rwlock_t *__restrict rwlock, const struct timespec *abstime); int os_spin_init(os_spinlock_t *lock, int pshared); int os_spin_destroy(os_spinlock_t *lock); int os_spin_lock(os_spinlock_t *lock); int os_spin_unlock(os_spinlock_t *lock); int os_spin_trylock(os_spinlock_t *lock); int os_cond_init(os_cond_t *__restrict cond); int os_cond_destroy(os_cond_t *__restrict cond); int os_cond_broadcast(os_cond_t *__restrict cond); int os_cond_signal(os_cond_t *__restrict cond); int os_cond_timedwait(os_cond_t *__restrict cond, os_mutex_t *__restrict mutex, const struct timespec *abstime); int os_cond_wait(os_cond_t *__restrict cond, os_mutex_t *__restrict mutex); /* threading */ int os_thread_create(os_thread_t *thread, const os_thread_attr_t *attr, void *(*start_routine)(void *), void *arg); int os_thread_join(os_thread_t *thread, void **result); void os_thread_self(os_thread_t *thread); /* thread affinity */ int os_thread_setaffinity_np(os_thread_t *thread, size_t set_size, const os_cpu_set_t *set); int os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)); int os_semaphore_init(os_semaphore_t *sem, unsigned value); int os_semaphore_destroy(os_semaphore_t *sem); int os_semaphore_wait(os_semaphore_t *sem); int os_semaphore_trywait(os_semaphore_t *sem); int os_semaphore_post(os_semaphore_t *sem); #ifdef __cplusplus } #endif #endif /* OS_THREAD_H */
5,833
31.054945
75
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/uuid_linux.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * uuid_linux.c -- pool set utilities with OS-specific implementation */ #include <fcntl.h> #include <unistd.h> #include <stdint.h> #include "uuid.h" #include "os.h" #include "out.h" /* * util_uuid_generate -- generate a uuid * * This function reads the uuid string from /proc/sys/kernel/random/uuid * It converts this string into the binary uuid format as specified in * https://www.ietf.org/rfc/rfc4122.txt */ int util_uuid_generate(uuid_t uuid) { char uu[POOL_HDR_UUID_STR_LEN]; int fd = os_open(POOL_HDR_UUID_GEN_FILE, O_RDONLY); if (fd < 0) { /* Fatal error */ LOG(2, "!open(uuid)"); return -1; } ssize_t num = read(fd, uu, POOL_HDR_UUID_STR_LEN); if (num < POOL_HDR_UUID_STR_LEN) { /* Fatal error */ LOG(2, "!read(uuid)"); os_close(fd); return -1; } os_close(fd); uu[POOL_HDR_UUID_STR_LEN - 1] = '\0'; int ret = util_uuid_from_string(uu, (struct uuid *)uuid); if (ret < 0) return ret; return 0; }
2,550
31.291139
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_badblock.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_badblock.h -- linux bad block API */ #ifndef PMDK_BADBLOCK_H #define PMDK_BADBLOCK_H 1 #include <stdint.h> #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif #define B2SEC(n) ((n) >> 9) /* convert bytes to sectors */ #define SEC2B(n) ((n) << 9) /* convert sectors to bytes */ #define NO_HEALTHY_REPLICA ((int)(-1)) /* * 'struct badblock' is already defined in ndctl/libndctl.h, * so we cannot use this name. * * libndctl returns offset relative to the beginning of the region, * but in this structure we save offset relative to the beginning of: * - namespace (before os_badblocks_get()) * and * - file (before sync_recalc_badblocks()) * and * - pool (after sync_recalc_badblocks()) */ struct bad_block { /* * offset in bytes relative to the beginning of * - namespace (before os_badblocks_get()) * and * - file (before sync_recalc_badblocks()) * and * - pool (after sync_recalc_badblocks()) */ unsigned long long offset; /* length in bytes */ unsigned length; /* number of healthy replica to fix this bad block */ int nhealthy; }; struct badblocks { unsigned long long ns_resource; /* address of the namespace */ unsigned bb_cnt; /* number of bad blocks */ struct bad_block *bbv; /* array of bad blocks */ }; long os_badblocks_count(const char *path); int os_badblocks_get(const char *file, struct badblocks *bbs); int os_badblocks_clear(const char *path, struct badblocks *bbs); int os_badblocks_clear_all(const char *file); int os_badblocks_check_file(const char *path); #ifdef __cplusplus } #endif #endif /* PMDK_BADBLOCK_H */
3,200
31.333333
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/extent.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * extent.h -- fs extent query API */ #ifndef PMDK_EXTENT_H #define PMDK_EXTENT_H 1 #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif struct extent { uint64_t offset_physical; uint64_t offset_logical; uint64_t length; }; struct extents { uint64_t blksize; uint32_t extents_count; struct extent *extents; }; long os_extents_count(const char *path, struct extents *exts); int os_extents_get(const char *path, struct extents *exts); #ifdef __cplusplus } #endif #endif /* PMDK_EXTENT_H */
2,129
30.791045
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/out.h
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * out.h -- definitions for "out" module */ #ifndef PMDK_OUT_H #define PMDK_OUT_H 1 #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include "util.h" #ifdef __cplusplus extern "C" { #endif /* * Suppress errors which are after appropriate ASSERT* macro for nondebug * builds. */ #if !defined(DEBUG) && (defined(__clang_analyzer__) || defined(__COVERITY__)) #define OUT_FATAL_DISCARD_NORETURN __attribute__((noreturn)) #else #define OUT_FATAL_DISCARD_NORETURN #endif #ifndef EVALUATE_DBG_EXPRESSIONS #if defined(DEBUG) || defined(__clang_analyzer__) || defined(__COVERITY__) #define EVALUATE_DBG_EXPRESSIONS 1 #else #define EVALUATE_DBG_EXPRESSIONS 0 #endif #endif #ifdef DEBUG #define OUT_LOG out_log #define OUT_NONL out_nonl #define OUT_FATAL out_fatal #define OUT_FATAL_ABORT out_fatal #else static __attribute__((always_inline)) inline void out_log_discard(const char *file, int line, const char *func, int level, const char *fmt, ...) { (void) file; (void) line; (void) func; (void) level; (void) fmt; } static __attribute__((always_inline)) inline void out_nonl_discard(int level, const char *fmt, ...) { (void) level; (void) fmt; } static __attribute__((always_inline)) OUT_FATAL_DISCARD_NORETURN inline void out_fatal_discard(const char *file, int line, const char *func, const char *fmt, ...) { (void) file; (void) line; (void) func; (void) fmt; } static __attribute__((always_inline)) NORETURN inline void out_fatal_abort(const char *file, int line, const char *func, const char *fmt, ...) { (void) file; (void) line; (void) func; (void) fmt; abort(); } #define OUT_LOG out_log_discard #define OUT_NONL out_nonl_discard #define OUT_FATAL out_fatal_discard #define OUT_FATAL_ABORT out_fatal_abort #endif /* produce debug/trace output */ #define LOG(level, ...) do { \ if (!EVALUATE_DBG_EXPRESSIONS) break;\ OUT_LOG(__FILE__, __LINE__, __func__, level, __VA_ARGS__);\ } while (0) /* produce debug/trace output without prefix and new line */ #define LOG_NONL(level, ...) do { \ if (!EVALUATE_DBG_EXPRESSIONS) break; \ OUT_NONL(level, __VA_ARGS__); \ } while (0) /* produce output and exit */ #define FATAL(...)\ OUT_FATAL_ABORT(__FILE__, __LINE__, __func__, __VA_ARGS__) /* assert a condition is true at runtime */ #define ASSERT_rt(cnd) do { \ if (!EVALUATE_DBG_EXPRESSIONS || (cnd)) break; \ OUT_FATAL(__FILE__, __LINE__, __func__, "assertion failure: %s", #cnd);\ } while (0) /* assertion with extra info printed if assertion fails at runtime */ #define ASSERTinfo_rt(cnd, info) do { \ if (!EVALUATE_DBG_EXPRESSIONS || (cnd)) break; \ OUT_FATAL(__FILE__, __LINE__, __func__, \ "assertion failure: %s (%s = %s)", #cnd, #info, info);\ } while (0) /* assert two integer values are equal at runtime */ #define ASSERTeq_rt(lhs, rhs) do { \ if (!EVALUATE_DBG_EXPRESSIONS || ((lhs) == (rhs))) break; \ OUT_FATAL(__FILE__, __LINE__, __func__,\ "assertion failure: %s (0x%llx) == %s (0x%llx)", #lhs,\ (unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)); \ } while (0) /* assert two integer values are not equal at runtime */ #define ASSERTne_rt(lhs, rhs) do { \ if (!EVALUATE_DBG_EXPRESSIONS || ((lhs) != (rhs))) break; \ OUT_FATAL(__FILE__, __LINE__, __func__,\ "assertion failure: %s (0x%llx) != %s (0x%llx)", #lhs,\ (unsigned long long)(lhs), #rhs, (unsigned long long)(rhs)); \ } while (0) /* assert a condition is true */ #define ASSERT(cnd)\ do {\ /*\ * Detect useless asserts on always true expression. Please use\ * COMPILE_ERROR_ON(!cnd) or ASSERT_rt(cnd) in such cases.\ */\ if (__builtin_constant_p(cnd))\ ASSERT_COMPILE_ERROR_ON(cnd);\ ASSERT_rt(cnd);\ } while (0) /* assertion with extra info printed if assertion fails */ #define ASSERTinfo(cnd, info)\ do {\ /* See comment in ASSERT. */\ if (__builtin_constant_p(cnd))\ ASSERT_COMPILE_ERROR_ON(cnd);\ ASSERTinfo_rt(cnd, info);\ } while (0) /* assert two integer values are equal */ #define ASSERTeq(lhs, rhs)\ do {\ /* See comment in ASSERT. */\ if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\ ASSERT_COMPILE_ERROR_ON((lhs) == (rhs));\ ASSERTeq_rt(lhs, rhs);\ } while (0) /* assert two integer values are not equal */ #define ASSERTne(lhs, rhs)\ do {\ /* See comment in ASSERT. */\ if (__builtin_constant_p(lhs) && __builtin_constant_p(rhs))\ ASSERT_COMPILE_ERROR_ON((lhs) != (rhs));\ ASSERTne_rt(lhs, rhs);\ } while (0) #define ERR(...)\ out_err(__FILE__, __LINE__, __func__, __VA_ARGS__) void out_init(const char *log_prefix, const char *log_level_var, const char *log_file_var, int major_version, int minor_version); void out_fini(void); void out(const char *fmt, ...) FORMAT_PRINTF(1, 2); void out_nonl(int level, const char *fmt, ...) FORMAT_PRINTF(2, 3); void out_log(const char *file, int line, const char *func, int level, const char *fmt, ...) FORMAT_PRINTF(5, 6); void out_err(const char *file, int line, const char *func, const char *fmt, ...) FORMAT_PRINTF(4, 5); void NORETURN out_fatal(const char *file, int line, const char *func, const char *fmt, ...) FORMAT_PRINTF(4, 5); void out_set_print_func(void (*print_func)(const char *s)); void out_set_vsnprintf_func(int (*vsnprintf_func)(char *str, size_t size, const char *format, va_list ap)); #ifdef _WIN32 #ifndef PMDK_UTF8_API #define out_get_errormsg out_get_errormsgW #else #define out_get_errormsg out_get_errormsgU #endif #endif #ifndef _WIN32 const char *out_get_errormsg(void); #else const char *out_get_errormsgU(void); const wchar_t *out_get_errormsgW(void); #endif #ifdef __cplusplus } #endif #endif
7,218
28.226721
77
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/util_windows.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * util_windows.c -- misc utilities with OS-specific implementation */ #include <string.h> #include <tchar.h> #include <errno.h> #include "util.h" #include "out.h" #include "file.h" /* Windows CRT doesn't support all errors, add unmapped here */ #define ENOTSUP_STR "Operation not supported" #define ECANCELED_STR "Operation canceled" #define ENOERROR 0 #define ENOERROR_STR "Success" #define UNMAPPED_STR "Unmapped error" /* * util_strerror -- return string describing error number * * XXX: There are many other POSIX error codes that are not recognized by * strerror_s(), so eventually we may want to implement this in a similar * fashion as strsignal(). */ void util_strerror(int errnum, char *buff, size_t bufflen) { switch (errnum) { case ENOERROR: strcpy_s(buff, bufflen, ENOERROR_STR); break; case ENOTSUP: strcpy_s(buff, bufflen, ENOTSUP_STR); break; case ECANCELED: strcpy_s(buff, bufflen, ECANCELED_STR); break; default: if (strerror_s(buff, bufflen, errnum)) strcpy_s(buff, bufflen, UNMAPPED_STR); } } /* * util_part_realpath -- get canonicalized absolute pathname for a part file * * On Windows, paths cannot be symlinks and paths used in a poolset have to * be absolute (checked when parsing a poolset file), so we just return * the path. */ char * util_part_realpath(const char *path) { return strdup(path); } /* * util_compare_file_inodes -- compare device and inodes of two files */ int util_compare_file_inodes(const char *path1, const char *path2) { return strcmp(path1, path2) != 0; } /* * util_aligned_malloc -- allocate aligned memory */ void * util_aligned_malloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); } /* * util_aligned_free -- free allocated memory in util_aligned_malloc */ void util_aligned_free(void *ptr) { _aligned_free(ptr); } /* * util_toUTF8 -- allocating conversion from wide char string to UTF8 */ char * util_toUTF8(const wchar_t *wstr) { int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1, NULL, 0, NULL, NULL); if (size == 0) goto err; char *str = Malloc(size * sizeof(char)); if (str == NULL) goto out; if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr, -1, str, size, NULL, NULL) == 0) { Free(str); goto err; } out: return str; err: errno = EINVAL; return NULL; } /* * util_free_UTF8 -- free UTF8 string */ void util_free_UTF8(char *str) { Free(str); } /* * util_toUTF16 -- allocating conversion from UTF8 to wide char string */ wchar_t * util_toUTF16(const char *str) { int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str, -1, NULL, 0); if (size == 0) goto err; wchar_t *wstr = Malloc(size * sizeof(wchar_t)); if (wstr == NULL) goto out; if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str, -1, wstr, size) == 0) { Free(wstr); goto err; } out: return wstr; err: errno = EINVAL; return NULL; } /* * util_free_UTF16 -- free wide char string */ void util_free_UTF16(wchar_t *wstr) { Free(wstr); } /* * util_toUTF16_buff -- non-allocating conversion from UTF8 to wide char string * * The user responsible for supplying a large enough out buffer. */ int util_toUTF16_buff(const char *in, wchar_t *out, size_t out_size) { ASSERT(out != NULL); int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, in, -1, NULL, 0); if (size == 0 || out_size < size) goto err; if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, in, -1, out, size) == 0) goto err; return 0; err: errno = EINVAL; return -1; } /* * util_toUTF8_buff -- non-allocating conversion from wide char string to UTF8 * * The user responsible for supplying a large enough out buffer. */ int util_toUTF8_buff(const wchar_t *in, char *out, size_t out_size) { ASSERT(out != NULL); int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, in, -1, NULL, 0, NULL, NULL); if (size == 0 || out_size < size) goto err; if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, in, -1, out, size, NULL, NULL) == 0) goto err; return 0; err: errno = EINVAL; return -1; } /* * util_getexecname -- return name of current executable */ char * util_getexecname(char *path, size_t pathlen) { ssize_t cc; if ((cc = GetModuleFileNameA(NULL, path, (DWORD)pathlen)) == 0) strcpy(path, "unknown"); else path[cc] = '\0'; return path; }
5,980
22.454902
79
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/extent_freebsd.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. */ /* * extent_freebsd.c - implementation of the FreeBSD fs extent query API * XXX THIS IS CURRENTLY A DUMMY MODULE. */ #include <string.h> #include <fcntl.h> #include <sys/ioctl.h> #include "file.h" #include "out.h" #include "extent.h" /* * os_extents_count -- get number of extents of the given file * (and optionally read its block size) */ long os_extents_count(const char *path, struct extents *exts) { LOG(3, "path %s extents %p", path, exts); return -1; } /* * os_extents_get -- get extents of the given file * (and optionally read its block size) */ int os_extents_get(const char *path, struct extents *exts) { LOG(3, "path %s extents %p", path, exts); return -1; }
2,325
32.710145
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/mmap_posix.c
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * mmap_posix.c -- memory-mapped files for Posix */ #include <stdio.h> #include <sys/mman.h> #include <sys/param.h> #include "mmap.h" #include "out.h" #include "os.h" #define PROCMAXLEN 2048 /* maximum expected line length in /proc files */ char *Mmap_mapfile = OS_MAPFILE; /* Should be modified only for testing */ #ifdef __FreeBSD__ static const char * const sscanf_os = "%p %p"; #else static const char * const sscanf_os = "%p-%p"; #endif /* * util_map_hint_unused -- use /proc to determine a hint address for mmap() * * This is a helper function for util_map_hint(). * It opens up /proc/self/maps and looks for the first unused address * in the process address space that is: * - greater or equal 'minaddr' argument, * - large enough to hold range of given length, * - aligned to the specified unit. * * Asking for aligned address like this will allow the DAX code to use large * mappings. It is not an error if mmap() ignores the hint and chooses * different address. */ char * util_map_hint_unused(void *minaddr, size_t len, size_t align) { LOG(3, "minaddr %p len %zu align %zu", minaddr, len, align); ASSERT(align > 0); FILE *fp; if ((fp = os_fopen(Mmap_mapfile, "r")) == NULL) { ERR("!%s", Mmap_mapfile); return MAP_FAILED; } char line[PROCMAXLEN]; /* for fgets() */ char *lo = NULL; /* beginning of current range in maps file */ char *hi = NULL; /* end of current range in maps file */ char *raddr = minaddr; /* ignore regions below 'minaddr' */ if (raddr == NULL) raddr += Pagesize; raddr = (char *)roundup((uintptr_t)raddr, align); while (fgets(line, PROCMAXLEN, fp) != NULL) { /* check for range line */ if (sscanf(line, sscanf_os, &lo, &hi) == 2) { LOG(4, "%p-%p", lo, hi); if (lo > raddr) { if ((uintptr_t)(lo - raddr) >= len) { LOG(4, "unused region of size %zu " "found at %p", lo - raddr, raddr); break; } else { LOG(4, "region is too small: %zu < %zu", lo - raddr, len); } } if (hi > raddr) { raddr = (char *)roundup((uintptr_t)hi, align); LOG(4, "nearest aligned addr %p", raddr); } if (raddr == NULL) { LOG(4, "end of address space reached"); break; } } } /* * Check for a case when this is the last unused range in the address * space, but is not large enough. (very unlikely) */ if ((raddr != NULL) && (UINTPTR_MAX - (uintptr_t)raddr < len)) { LOG(4, "end of address space reached"); raddr = MAP_FAILED; } fclose(fp); LOG(3, "returning %p", raddr); return raddr; } /* * util_map_hint -- determine hint address for mmap() * * If PMEM_MMAP_HINT environment variable is not set, we let the system to pick * the randomized mapping address. Otherwise, a user-defined hint address * is used. * * ALSR in 64-bit Linux kernel uses 28-bit of randomness for mmap * (bit positions 12-39), which means the base mapping address is randomized * within [0..1024GB] range, with 4KB granularity. Assuming additional * 1GB alignment, it results in 1024 possible locations. * * Configuring the hint address via PMEM_MMAP_HINT environment variable * disables address randomization. In such case, the function will search for * the first unused, properly aligned region of given size, above the specified * address. */ char * util_map_hint(size_t len, size_t req_align) { LOG(3, "len %zu req_align %zu", len, req_align); char *hint_addr = MAP_FAILED; /* choose the desired alignment based on the requested length */ size_t align = util_map_hint_align(len, req_align); if (Mmap_no_random) { LOG(4, "user-defined hint %p", Mmap_hint); hint_addr = util_map_hint_unused(Mmap_hint, len, align); } else { /* * Create dummy mapping to find an unused region of given size. * Request for increased size for later address alignment. * Use MAP_PRIVATE with read-only access to simulate * zero cost for overcommit accounting. Note: MAP_NORESERVE * flag is ignored if overcommit is disabled (mode 2). */ char *addr = mmap(NULL, len + align, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (addr != MAP_FAILED) { LOG(4, "system choice %p", addr); hint_addr = (char *)roundup((uintptr_t)addr, align); munmap(addr, len + align); } } LOG(4, "hint %p", hint_addr); return hint_addr; } /* * util_map_sync -- memory map given file into memory, if MAP_SHARED flag is * provided it attempts to use MAP_SYNC flag. Otherwise it fallbacks to * mmap(2). */ void * util_map_sync(void *addr, size_t len, int proto, int flags, int fd, os_off_t offset, int *map_sync) { LOG(15, "addr %p len %zu proto %x flags %x fd %d offset %ld " "map_sync %p", addr, len, proto, flags, fd, offset, map_sync); if (map_sync) *map_sync = 0; /* if map_sync is NULL do not even try to mmap with MAP_SYNC flag */ if (!map_sync || flags & MAP_PRIVATE) return mmap(addr, len, proto, flags, fd, offset); /* MAP_SHARED */ void *ret = mmap(addr, len, proto, flags | MAP_SHARED_VALIDATE | MAP_SYNC, fd, offset); if (ret != MAP_FAILED) { LOG(4, "mmap with MAP_SYNC succeeded"); *map_sync = 1; return ret; } if (errno == EINVAL || errno == ENOTSUP) { LOG(4, "mmap with MAP_SYNC not supported"); return mmap(addr, len, proto, flags, fd, offset); } /* other error */ return MAP_FAILED; }
6,914
30.289593
79
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/badblock_freebsd.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * badblock_freebsd.c - implementation of the FreeBSD bad block API */ #include "out.h" #include "os_badblock.h" /* * os_badblocks_check_file -- check if the file contains bad blocks * * Return value: * -1 : an error * 0 : no bad blocks * 1 : bad blocks detected */ int os_badblocks_check_file(const char *file) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_count -- returns number of bad blocks in the file * or -1 in case of an error */ long os_badblocks_count(const char *file) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_get -- returns list of bad blocks in the file */ int os_badblocks_get(const char *file, struct badblocks *bbs) { LOG(3, "file %s", file); return 0; } /* * os_badblocks_clear -- clears the given bad blocks in a file * (regular file or dax device) */ int os_badblocks_clear(const char *file, struct badblocks *bbs) { LOG(3, "file %s badblocks %p", file, bbs); return 0; } /* * os_badblocks_clear_all -- clears all bad blocks in a file * (regular file or dax device) */ int os_badblocks_clear_all(const char *file) { LOG(3, "file %s", file); return 0; }
2,812
26.578431
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/pool_hdr.h
/* * Copyright 2014-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * pool_hdr.h -- internal definitions for pool header module */ #ifndef PMDK_POOL_HDR_H #define PMDK_POOL_HDR_H 1 #include <stddef.h> #include <stdint.h> #include <unistd.h> #include "uuid.h" #include "shutdown_state.h" #ifdef __cplusplus extern "C" { #endif /* * Number of bits per type in alignment descriptor */ #define ALIGNMENT_DESC_BITS 4 /* * architecture identification flags * * These flags allow to unambiguously determine the architecture * on which the pool was created. * * The alignment_desc field contains information about alignment * of the following basic types: * - char * - short * - int * - long * - long long * - size_t * - os_off_t * - float * - double * - long double * - void * * * The alignment of each type is computed as an offset of field * of specific type in the following structure: * struct { * char byte; * type field; * }; * * The value is decremented by 1 and masked by 4 bits. * Multiple alignments are stored on consecutive 4 bits of each * type in the order specified above. * * The values used in the machine, and machine_class fields are in * principle independent of operating systems, and object formats. * In practice they happen to match constants used in ELF object headers. */ struct arch_flags { uint64_t alignment_desc; /* alignment descriptor */ uint8_t machine_class; /* address size -- 64 bit or 32 bit */ uint8_t data; /* data encoding -- LE or BE */ uint8_t reserved[4]; uint16_t machine; /* required architecture */ }; #define POOL_HDR_ARCH_LEN sizeof(struct arch_flags) /* possible values of the machine class field in the above struct */ #define PMDK_MACHINE_CLASS_64 2 /* 64 bit pointers, 64 bit size_t */ /* possible values of the machine field in the above struct */ #define PMDK_MACHINE_X86_64 62 #define PMDK_MACHINE_AARCH64 183 /* possible values of the data field in the above struct */ #define PMDK_DATA_LE 1 /* 2's complement, little endian */ #define PMDK_DATA_BE 2 /* 2's complement, big endian */ /* * features flags */ typedef struct { uint32_t compat; /* mask: compatible "may" features */ uint32_t incompat; /* mask: "must support" features */ uint32_t ro_compat; /* mask: force RO if unsupported */ } features_t; /* * header used at the beginning of all types of memory pools * * for pools build on persistent memory, the integer types * below are stored in little-endian byte order. */ #define POOL_HDR_SIG_LEN 8 struct pool_hdr { char signature[POOL_HDR_SIG_LEN]; uint32_t major; /* format major version number */ features_t features; /* features flags */ uuid_t poolset_uuid; /* pool set UUID */ uuid_t uuid; /* UUID of this file */ uuid_t prev_part_uuid; /* prev part */ uuid_t next_part_uuid; /* next part */ uuid_t prev_repl_uuid; /* prev replica */ uuid_t next_repl_uuid; /* next replica */ uint64_t crtime; /* when created (seconds since epoch) */ struct arch_flags arch_flags; /* architecture identification flags */ unsigned char unused[1904]; /* must be zero */ /* not checksumed */ unsigned char unused2[1976]; /* must be zero */ struct shutdown_state sds; /* shutdown status */ uint64_t checksum; /* checksum of above fields */ }; #define POOL_HDR_SIZE (sizeof(struct pool_hdr)) #define POOL_DESC_SIZE 4096 void util_convert2le_hdr(struct pool_hdr *hdrp); void util_convert2h_hdr_nocheck(struct pool_hdr *hdrp); void util_get_arch_flags(struct arch_flags *arch_flags); int util_check_arch_flags(const struct arch_flags *arch_flags); features_t util_get_unknown_features(features_t features, features_t known); int util_feature_check(struct pool_hdr *hdrp, features_t features); int util_feature_cmp(features_t features, features_t ref); int util_feature_is_zero(features_t features); int util_feature_is_set(features_t features, features_t flag); void util_feature_enable(features_t *features, features_t new_feature); void util_feature_disable(features_t *features, features_t new_feature); const char *util_feature2str(features_t feature, features_t *found); features_t util_str2feature(const char *str); uint32_t util_str2pmempool_feature(const char *str); uint32_t util_feature2pmempool_feature(features_t feat); /* * set of macros for determining the alignment descriptor */ #define DESC_MASK ((1 << ALIGNMENT_DESC_BITS) - 1) #define alignment_of(t) offsetof(struct { char c; t x; }, x) #define alignment_desc_of(t) (((uint64_t)alignment_of(t) - 1) & DESC_MASK) #define alignment_desc()\ (alignment_desc_of(char) << 0 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(short) << 1 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(int) << 2 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(long) << 3 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(long long) << 4 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(size_t) << 5 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(off_t) << 6 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(float) << 7 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(double) << 8 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(long double) << 9 * ALIGNMENT_DESC_BITS) |\ (alignment_desc_of(void *) << 10 * ALIGNMENT_DESC_BITS) #define POOL_FEAT_ZERO 0x0000U static const features_t features_zero = {POOL_FEAT_ZERO, POOL_FEAT_ZERO, POOL_FEAT_ZERO}; /* * compat features */ #define POOL_FEAT_CHECK_BAD_BLOCKS 0x0001U /* check bad blocks in a pool */ #define POOL_FEAT_COMPAT_ALL \ (POOL_FEAT_CHECK_BAD_BLOCKS) #define FEAT_COMPAT(X) \ {POOL_FEAT_##X, POOL_FEAT_ZERO, POOL_FEAT_ZERO} /* * incompat features */ #define POOL_FEAT_SINGLEHDR 0x0001U /* pool header only in the first part */ #define POOL_FEAT_CKSUM_2K 0x0002U /* only first 2K of hdr checksummed */ #define POOL_FEAT_SDS 0x0004U /* check shutdown state */ #define POOL_FEAT_INCOMPAT_ALL \ (POOL_FEAT_SINGLEHDR | POOL_FEAT_CKSUM_2K | POOL_FEAT_SDS) /* * incompat features effective values (if applicable) */ #ifdef SDS_ENABLED #define POOL_E_FEAT_SDS POOL_FEAT_SDS #else #define POOL_E_FEAT_SDS 0x0000U /* empty */ #endif #define POOL_FEAT_COMPAT_VALID \ (POOL_FEAT_CHECK_BAD_BLOCKS) #define POOL_FEAT_INCOMPAT_VALID \ (POOL_FEAT_SINGLEHDR | POOL_FEAT_CKSUM_2K | POOL_E_FEAT_SDS) #ifdef _WIN32 #define POOL_FEAT_INCOMPAT_DEFAULT \ (POOL_FEAT_CKSUM_2K | POOL_E_FEAT_SDS) #else /* * shutdown state support on Linux requires root access * so it is disabled by default */ #define POOL_FEAT_INCOMPAT_DEFAULT \ (POOL_FEAT_CKSUM_2K) #endif #define FEAT_INCOMPAT(X) \ {POOL_FEAT_ZERO, POOL_FEAT_##X, POOL_FEAT_ZERO} #define POOL_FEAT_VALID \ {POOL_FEAT_COMPAT_VALID, POOL_FEAT_INCOMPAT_VALID, POOL_FEAT_ZERO} /* * defines the first not checksummed field - all fields after this will be * ignored during checksum calculations. */ #define POOL_HDR_CSUM_2K_END_OFF offsetof(struct pool_hdr, unused2) #define POOL_HDR_CSUM_4K_END_OFF offsetof(struct pool_hdr, checksum) /* * pick the first not checksummed field. 2K variant is used if * POOL_FEAT_CKSUM_2K incompat feature is set. */ #define POOL_HDR_CSUM_END_OFF(hdrp) \ ((hdrp)->features.incompat & POOL_FEAT_CKSUM_2K) \ ? POOL_HDR_CSUM_2K_END_OFF : POOL_HDR_CSUM_4K_END_OFF /* ignore shutdown state if incompat feature is disabled */ #define IGNORE_SDS(hdrp) \ (((hdrp) != NULL) && (((hdrp)->features.incompat & POOL_FEAT_SDS) == 0)) #ifdef __cplusplus } #endif #endif
8,929
31.830882
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/os_deep_windows.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * os_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); 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; }
3,086
28.970874
75
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/extent_linux.c
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * extent_linux.c - implementation of the linux fs extent query API */ #include <string.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/fs.h> #include <linux/fiemap.h> #include "file.h" #include "out.h" #include "extent.h" /* * os_extents_common -- (internal) common part of getting extents * of the given file * * Returns: number of extents the file consists of or -1 in case of an error. * Sets: file descriptor, struct fiemap and struct extents. */ static long os_extents_common(const char *path, struct extents *exts, int *pfd, struct fiemap **pfmap) { LOG(3, "path %s exts %p pfd %p pfmap %p", path, exts, pfd, pfmap); int fd = open(path, O_RDONLY); if (fd == -1) { ERR("!open %s", path); return -1; } enum file_type type = util_fd_get_type(fd); if (type < 0) goto error_close; struct stat st; if (fstat(fd, &st) < 0) { ERR("!fstat %d", fd); goto error_close; } if (exts->extents_count == 0) { LOG(10, "%s: block size: %li", path, (long int)st.st_blksize); exts->blksize = (uint64_t)st.st_blksize; } /* devdax does not have any extents */ if (type == TYPE_DEVDAX) { close(fd); return 0; } struct fiemap *fmap = Zalloc(sizeof(struct fiemap)); if (fmap == NULL) { ERR("!malloc"); goto error_close; } fmap->fm_start = 0; fmap->fm_length = (size_t)st.st_size; fmap->fm_flags = 0; fmap->fm_extent_count = 0; if (ioctl(fd, FS_IOC_FIEMAP, fmap) != 0) { ERR("!ioctl %d", fd); goto error_free; } if (exts->extents_count == 0) { exts->extents_count = fmap->fm_mapped_extents; LOG(4, "%s: number of extents: %u", path, exts->extents_count); } else if (exts->extents_count != fmap->fm_mapped_extents) { ERR("number of extents differs (was: %u, is: %u)", exts->extents_count, fmap->fm_mapped_extents); goto error_free; } *pfd = fd; *pfmap = fmap; return exts->extents_count; error_free: Free(fmap); error_close: close(fd); return -1; } /* * os_extents_count -- get number of extents of the given file * (and optionally read its block size) */ long os_extents_count(const char *path, struct extents *exts) { LOG(3, "path %s extents %p", path, exts); struct fiemap *fmap = NULL; int fd = -1; ASSERTne(exts, NULL); memset(exts, 0, sizeof(*exts)); long ret = os_extents_common(path, exts, &fd, &fmap); Free(fmap); if (fd != -1) close(fd); return ret; } /* * os_extents_get -- get extents of the given file * (and optionally read its block size) */ int os_extents_get(const char *path, struct extents *exts) { LOG(3, "path %s extents %p", path, exts); struct fiemap *fmap = NULL; int fd = -1; int ret = -1; ASSERTne(exts, NULL); if (exts->extents_count == 0) return 0; ASSERTne(exts->extents, NULL); if (os_extents_common(path, exts, &fd, &fmap) <= 0) goto error_free; struct fiemap *newfmap = Realloc(fmap, sizeof(struct fiemap) + fmap->fm_mapped_extents * sizeof(struct fiemap_extent)); if (newfmap == NULL) { ERR("!Realloc"); goto error_free; } fmap = newfmap; fmap->fm_extent_count = fmap->fm_mapped_extents; memset(fmap->fm_extents, 0, fmap->fm_mapped_extents * sizeof(struct fiemap_extent)); if (ioctl(fd, FS_IOC_FIEMAP, fmap) != 0) { ERR("!ioctl %d", fd); goto error_free; } unsigned e; for (e = 0; e < fmap->fm_extent_count; e++) { exts->extents[e].offset_physical = fmap->fm_extents[e].fe_physical; exts->extents[e].offset_logical = fmap->fm_extents[e].fe_logical; exts->extents[e].length = fmap->fm_extents[e].fe_length; } ret = 0; error_free: Free(fmap); if (fd != -1) close(fd); return ret; }
5,272
23.755869
77
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/mmap_windows.c
/* * 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,921
31.813333
76
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/valgrind/memcheck.h
/* ---------------------------------------------------------------- Notice that the following BSD-style license applies to this one file (memcheck.h) only. The rest of Valgrind is licensed under the terms of the GNU General Public License, version 2, unless otherwise indicated. See the COPYING file in the source distribution for details. ---------------------------------------------------------------- This file is part of MemCheck, a heavyweight Valgrind tool for detecting memory errors. Copyright (C) 2000-2017 Julian Seward. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------- Notice that the above BSD-style license applies to this one file (memcheck.h) only. The entire rest of Valgrind is licensed under the terms of the GNU General Public License, version 2. See the COPYING file in the source distribution for details. ---------------------------------------------------------------- */ #ifndef __MEMCHECK_H #define __MEMCHECK_H /* This file is for inclusion into client (your!) code. You can use these macros to manipulate and query memory permissions inside your own programs. See comment near the top of valgrind.h on how to use them. */ #include "valgrind.h" /* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! This enum comprises an ABI exported by Valgrind to programs which use client requests. DO NOT CHANGE THE ORDER OF THESE ENTRIES, NOR DELETE ANY -- add new ones at the end. */ typedef enum { VG_USERREQ__MAKE_MEM_NOACCESS = VG_USERREQ_TOOL_BASE('M','C'), VG_USERREQ__MAKE_MEM_UNDEFINED, VG_USERREQ__MAKE_MEM_DEFINED, VG_USERREQ__DISCARD, VG_USERREQ__CHECK_MEM_IS_ADDRESSABLE, VG_USERREQ__CHECK_MEM_IS_DEFINED, VG_USERREQ__DO_LEAK_CHECK, VG_USERREQ__COUNT_LEAKS, VG_USERREQ__GET_VBITS, VG_USERREQ__SET_VBITS, VG_USERREQ__CREATE_BLOCK, VG_USERREQ__MAKE_MEM_DEFINED_IF_ADDRESSABLE, /* Not next to VG_USERREQ__COUNT_LEAKS because it was added later. */ VG_USERREQ__COUNT_LEAK_BLOCKS, VG_USERREQ__ENABLE_ADDR_ERROR_REPORTING_IN_RANGE, VG_USERREQ__DISABLE_ADDR_ERROR_REPORTING_IN_RANGE, VG_USERREQ__CHECK_MEM_IS_UNADDRESSABLE, VG_USERREQ__CHECK_MEM_IS_UNDEFINED, /* This is just for memcheck's internal use - don't use it */ _VG_USERREQ__MEMCHECK_RECORD_OVERLAP_ERROR = VG_USERREQ_TOOL_BASE('M','C') + 256 } Vg_MemCheckClientRequest; /* Client-code macros to manipulate the state of memory. */ /* Mark memory at _qzz_addr as unaddressable for _qzz_len bytes. */ #define VALGRIND_MAKE_MEM_NOACCESS(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__MAKE_MEM_NOACCESS, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Similarly, mark memory at _qzz_addr as addressable but undefined for _qzz_len bytes. */ #define VALGRIND_MAKE_MEM_UNDEFINED(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__MAKE_MEM_UNDEFINED, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Similarly, mark memory at _qzz_addr as addressable and defined for _qzz_len bytes. */ #define VALGRIND_MAKE_MEM_DEFINED(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__MAKE_MEM_DEFINED, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Similar to VALGRIND_MAKE_MEM_DEFINED except that addressability is not altered: bytes which are addressable are marked as defined, but those which are not addressable are left unchanged. */ #define VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__MAKE_MEM_DEFINED_IF_ADDRESSABLE, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Create a block-description handle. The description is an ascii string which is included in any messages pertaining to addresses within the specified memory range. Has no other effect on the properties of the memory range. */ #define VALGRIND_CREATE_BLOCK(_qzz_addr,_qzz_len, _qzz_desc) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__CREATE_BLOCK, \ (_qzz_addr), (_qzz_len), (_qzz_desc), \ 0, 0) /* Discard a block-description-handle. Returns 1 for an invalid handle, 0 for a valid handle. */ #define VALGRIND_DISCARD(_qzz_blkindex) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__DISCARD, \ 0, (_qzz_blkindex), 0, 0, 0) /* Client-code macros to check the state of memory. */ /* Check that memory at _qzz_addr is addressable for _qzz_len bytes. If suitable addressibility is not established, Valgrind prints an error message and returns the address of the first offending byte. Otherwise it returns zero. */ #define VALGRIND_CHECK_MEM_IS_ADDRESSABLE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__CHECK_MEM_IS_ADDRESSABLE, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Check that memory at _qzz_addr is addressable and defined for _qzz_len bytes. If suitable addressibility and definedness are not established, Valgrind prints an error message and returns the address of the first offending byte. Otherwise it returns zero. */ #define VALGRIND_CHECK_MEM_IS_DEFINED(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__CHECK_MEM_IS_DEFINED, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Use this macro to force the definedness and addressibility of an lvalue to be checked. If suitable addressibility and definedness are not established, Valgrind prints an error message and returns the address of the first offending byte. Otherwise it returns zero. */ #define VALGRIND_CHECK_VALUE_IS_DEFINED(__lvalue) \ VALGRIND_CHECK_MEM_IS_DEFINED( \ (volatile unsigned char *)&(__lvalue), \ (unsigned long)(sizeof (__lvalue))) /* Check that memory at _qzz_addr is unaddressable for _qzz_len bytes. If any byte in this range is addressable, Valgrind returns the address of the first offending byte. Otherwise it returns zero. */ #define VALGRIND_CHECK_MEM_IS_UNADDRESSABLE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__CHECK_MEM_IS_UNADDRESSABLE,\ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Check that memory at _qzz_addr is undefined for _qzz_len bytes. If any byte in this range is defined or unaddressable, Valgrind returns the address of the first offending byte. Otherwise it returns zero. */ #define VALGRIND_CHECK_MEM_IS_UNDEFINED(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__CHECK_MEM_IS_UNDEFINED, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /* Do a full memory leak check (like --leak-check=full) mid-execution. */ #define VALGRIND_DO_LEAK_CHECK \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \ 0, 0, 0, 0, 0) /* Same as VALGRIND_DO_LEAK_CHECK but only showing the entries for which there was an increase in leaked bytes or leaked nr of blocks since the previous leak search. */ #define VALGRIND_DO_ADDED_LEAK_CHECK \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \ 0, 1, 0, 0, 0) /* Same as VALGRIND_DO_ADDED_LEAK_CHECK but showing entries with increased or decreased leaked bytes/blocks since previous leak search. */ #define VALGRIND_DO_CHANGED_LEAK_CHECK \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \ 0, 2, 0, 0, 0) /* Do a summary memory leak check (like --leak-check=summary) mid-execution. */ #define VALGRIND_DO_QUICK_LEAK_CHECK \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DO_LEAK_CHECK, \ 1, 0, 0, 0, 0) /* Return number of leaked, dubious, reachable and suppressed bytes found by all previous leak checks. They must be lvalues. */ #define VALGRIND_COUNT_LEAKS(leaked, dubious, reachable, suppressed) \ /* For safety on 64-bit platforms we assign the results to private unsigned long variables, then assign these to the lvalues the user specified, which works no matter what type 'leaked', 'dubious', etc are. We also initialise '_qzz_leaked', etc because VG_USERREQ__COUNT_LEAKS doesn't mark the values returned as defined. */ \ { \ unsigned long _qzz_leaked = 0, _qzz_dubious = 0; \ unsigned long _qzz_reachable = 0, _qzz_suppressed = 0; \ VALGRIND_DO_CLIENT_REQUEST_STMT( \ VG_USERREQ__COUNT_LEAKS, \ &_qzz_leaked, &_qzz_dubious, \ &_qzz_reachable, &_qzz_suppressed, 0); \ leaked = _qzz_leaked; \ dubious = _qzz_dubious; \ reachable = _qzz_reachable; \ suppressed = _qzz_suppressed; \ } /* Return number of leaked, dubious, reachable and suppressed bytes found by all previous leak checks. They must be lvalues. */ #define VALGRIND_COUNT_LEAK_BLOCKS(leaked, dubious, reachable, suppressed) \ /* For safety on 64-bit platforms we assign the results to private unsigned long variables, then assign these to the lvalues the user specified, which works no matter what type 'leaked', 'dubious', etc are. We also initialise '_qzz_leaked', etc because VG_USERREQ__COUNT_LEAKS doesn't mark the values returned as defined. */ \ { \ unsigned long _qzz_leaked = 0, _qzz_dubious = 0; \ unsigned long _qzz_reachable = 0, _qzz_suppressed = 0; \ VALGRIND_DO_CLIENT_REQUEST_STMT( \ VG_USERREQ__COUNT_LEAK_BLOCKS, \ &_qzz_leaked, &_qzz_dubious, \ &_qzz_reachable, &_qzz_suppressed, 0); \ leaked = _qzz_leaked; \ dubious = _qzz_dubious; \ reachable = _qzz_reachable; \ suppressed = _qzz_suppressed; \ } /* Get the validity data for addresses [zza..zza+zznbytes-1] and copy it into the provided zzvbits array. Return values: 0 if not running on valgrind 1 success 2 [previously indicated unaligned arrays; these are now allowed] 3 if any parts of zzsrc/zzvbits are not addressable. The metadata is not copied in cases 0, 2 or 3 so it should be impossible to segfault your system by using this call. */ #define VALGRIND_GET_VBITS(zza,zzvbits,zznbytes) \ (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__GET_VBITS, \ (const char*)(zza), \ (char*)(zzvbits), \ (zznbytes), 0, 0) /* Set the validity data for addresses [zza..zza+zznbytes-1], copying it from the provided zzvbits array. Return values: 0 if not running on valgrind 1 success 2 [previously indicated unaligned arrays; these are now allowed] 3 if any parts of zza/zzvbits are not addressable. The metadata is not copied in cases 0, 2 or 3 so it should be impossible to segfault your system by using this call. */ #define VALGRIND_SET_VBITS(zza,zzvbits,zznbytes) \ (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ VG_USERREQ__SET_VBITS, \ (const char*)(zza), \ (const char*)(zzvbits), \ (zznbytes), 0, 0 ) /* Disable and re-enable reporting of addressing errors in the specified address range. */ #define VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__DISABLE_ADDR_ERROR_REPORTING_IN_RANGE, \ (_qzz_addr), (_qzz_len), 0, 0, 0) #define VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__ENABLE_ADDR_ERROR_REPORTING_IN_RANGE, \ (_qzz_addr), (_qzz_len), 0, 0, 0) #endif
15,621
47.666667
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/common/valgrind/pmemcheck.h
/* * Copyright (c) 2014-2015, 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __PMEMCHECK_H #define __PMEMCHECK_H /* This file is for inclusion into client (your!) code. You can use these macros to manipulate and query memory permissions inside your own programs. See comment near the top of valgrind.h on how to use them. */ #include "valgrind.h" /* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! This enum comprises an ABI exported by Valgrind to programs which use client requests. DO NOT CHANGE THE ORDER OF THESE ENTRIES, NOR DELETE ANY -- add new ones at the end. */ typedef enum { VG_USERREQ__PMC_REGISTER_PMEM_MAPPING = VG_USERREQ_TOOL_BASE('P','C'), VG_USERREQ__PMC_REGISTER_PMEM_FILE, VG_USERREQ__PMC_REMOVE_PMEM_MAPPING, VG_USERREQ__PMC_CHECK_IS_PMEM_MAPPING, VG_USERREQ__PMC_PRINT_PMEM_MAPPINGS, VG_USERREQ__PMC_DO_FLUSH, VG_USERREQ__PMC_DO_FENCE, VG_USERREQ__PMC_DO_COMMIT, VG_USERREQ__PMC_WRITE_STATS, VG_USERREQ__PMC_LOG_STORES, VG_USERREQ__PMC_NO_LOG_STORES, VG_USERREQ__PMC_ADD_LOG_REGION, VG_USERREQ__PMC_REMOVE_LOG_REGION, VG_USERREQ__PMC_FULL_REORDED, VG_USERREQ__PMC_PARTIAL_REORDER, VG_USERREQ__PMC_ONLY_FAULT, VG_USERREQ__PMC_STOP_REORDER_FAULT, VG_USERREQ__PMC_SET_CLEAN, /* transaction support */ VG_USERREQ__PMC_START_TX, VG_USERREQ__PMC_START_TX_N, VG_USERREQ__PMC_END_TX, VG_USERREQ__PMC_END_TX_N, VG_USERREQ__PMC_ADD_TO_TX, VG_USERREQ__PMC_ADD_TO_TX_N, VG_USERREQ__PMC_REMOVE_FROM_TX, VG_USERREQ__PMC_REMOVE_FROM_TX_N, VG_USERREQ__PMC_ADD_THREAD_TO_TX_N, VG_USERREQ__PMC_REMOVE_THREAD_FROM_TX_N, VG_USERREQ__PMC_ADD_TO_GLOBAL_TX_IGNORE, VG_USERREQ__PMC_DEFAULT_REORDER, VG_USERREQ__PMC_EMIT_LOG, } Vg_PMemCheckClientRequest; /* Client-code macros to manipulate pmem mappings */ /** Register a persistent memory mapping region */ #define VALGRIND_PMC_REGISTER_PMEM_MAPPING(_qzz_addr, _qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REGISTER_PMEM_MAPPING, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Register a persistent memory file */ #define VALGRIND_PMC_REGISTER_PMEM_FILE(_qzz_desc, _qzz_addr_base, \ _qzz_size, _qzz_offset) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REGISTER_PMEM_FILE, \ (_qzz_desc), (_qzz_addr_base), (_qzz_size), \ (_qzz_offset), 0) /** Remove a persistent memory mapping region */ #define VALGRIND_PMC_REMOVE_PMEM_MAPPING(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REMOVE_PMEM_MAPPING, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Check if the given range is a registered persistent memory mapping */ #define VALGRIND_PMC_CHECK_IS_PMEM_MAPPING(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_CHECK_IS_PMEM_MAPPING, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Register an SFENCE */ #define VALGRIND_PMC_PRINT_PMEM_MAPPINGS \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_PRINT_PMEM_MAPPINGS, \ 0, 0, 0, 0, 0) /** Register a CLFLUSH-like operation */ #define VALGRIND_PMC_DO_FLUSH(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_DO_FLUSH, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Register an SFENCE */ #define VALGRIND_PMC_DO_FENCE \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_DO_FENCE, \ 0, 0, 0, 0, 0) /** Register a PCOMMIT (DEPRECATED, DO NOT USE) */ #define VALGRIND_PMC_DO_COMMIT \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_DO_COMMIT, \ 0, 0, 0, 0, 0) /** Write tool stats */ #define VALGRIND_PMC_WRITE_STATS \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_WRITE_STATS, \ 0, 0, 0, 0, 0) /** Start logging memory operations */ #define VALGRIND_PMC_LOG_STORES \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_LOG_STORES, \ 0, 0, 0, 0, 0) /** Stop logging memory operations */ #define VALGRIND_PMC_NO_LOG_STORES \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_NO_LOG_STORES, \ 0, 0, 0, 0, 0) /** Add a region of persistent memory, for which all operations will be * logged */ #define VALGRIND_PMC_ADD_LOG_REGION(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_ADD_LOG_REGION, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Remove the loggable persistent memory region */ #define VALGRIND_PMC_REMOVE_LOG_REGION(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REMOVE_LOG_REGION, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Issue a full reorder log */ #define VALGRIND_PMC_FULL_REORDER \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_FULL_REORDED, \ 0, 0, 0, 0, 0) /** Issue a partial reorder log */ #define VALGRIND_PMC_PARTIAL_REORDER \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_PARTIAL_REORDER, \ 0, 0, 0, 0, 0) /** Issue a log to disable reordering */ #define VALGRIND_PMC_ONLY_FAULT \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_ONLY_FAULT, \ 0, 0, 0, 0, 0) /** Issue a log to disable reordering and faults */ #define VALGRIND_PMC_STOP_REORDER_FAULT \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_STOP_REORDER_FAULT, \ 0, 0, 0, 0, 0) /** Issue a log to set the default reorder engine */ #define VALGRIND_PMC_DEFAULT_REORDER \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_DEFAULT_REORDER, \ 0, 0, 0, 0, 0) /** Set a region of persistent memory as clean */ #define VALGRIND_PMC_SET_CLEAN(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_SET_CLEAN, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Emit user log */ #define VALGRIND_PMC_EMIT_LOG(_qzz_emit_log) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_EMIT_LOG, \ (_qzz_emit_log), 0, 0, 0, 0) /** Support for transactions */ /** Start an implicit persistent memory transaction */ #define VALGRIND_PMC_START_TX \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_START_TX, \ 0, 0, 0, 0, 0) /** Start an explicit persistent memory transaction */ #define VALGRIND_PMC_START_TX_N(_qzz_txn) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_START_TX_N, \ (_qzz_txn), 0, 0, 0, 0) /** End an implicit persistent memory transaction */ #define VALGRIND_PMC_END_TX \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_END_TX, \ 0, 0, 0, 0, 0) /** End an explicit persistent memory transaction */ #define VALGRIND_PMC_END_TX_N(_qzz_txn) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_END_TX_N, \ (_qzz_txn), 0, 0, 0, 0) /** Add a persistent memory region to the implicit transaction */ #define VALGRIND_PMC_ADD_TO_TX(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_ADD_TO_TX, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Add a persistent memory region to an explicit transaction */ #define VALGRIND_PMC_ADD_TO_TX_N(_qzz_txn,_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_ADD_TO_TX_N, \ (_qzz_txn), (_qzz_addr), (_qzz_len), 0, 0) /** Remove a persistent memory region from the implicit transaction */ #define VALGRIND_PMC_REMOVE_FROM_TX(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REMOVE_FROM_TX, \ (_qzz_addr), (_qzz_len), 0, 0, 0) /** Remove a persistent memory region from an explicit transaction */ #define VALGRIND_PMC_REMOVE_FROM_TX_N(_qzz_txn,_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REMOVE_FROM_TX_N, \ (_qzz_txn), (_qzz_addr), (_qzz_len), 0, 0) /** End an explicit persistent memory transaction */ #define VALGRIND_PMC_ADD_THREAD_TX_N(_qzz_txn) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_ADD_THREAD_TO_TX_N, \ (_qzz_txn), 0, 0, 0, 0) /** End an explicit persistent memory transaction */ #define VALGRIND_PMC_REMOVE_THREAD_FROM_TX_N(_qzz_txn) \ VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ VG_USERREQ__PMC_REMOVE_THREAD_FROM_TX_N, \ (_qzz_txn), 0, 0, 0, 0) /** Remove a persistent memory region from the implicit transaction */ #define VALGRIND_PMC_ADD_TO_GLOBAL_TX_IGNORE(_qzz_addr,_qzz_len) \ VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PMC_ADD_TO_GLOBAL_TX_IGNORE,\ (_qzz_addr), (_qzz_len), 0, 0, 0) #endif
13,180
48.367041
77
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/ex_common.h
/* * Copyright 2016-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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 */
2,714
24.613208
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemlog/manpage.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
2,960
28.316832
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemlog/logfile/addlog.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
4,015
27.48227
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemlog/logfile/logentry.h
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * info 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 };
1,795
38.043478
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemlog/logfile/printlog.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
3,118
27.099099
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/librpmem/basic.c
/* * Copyright 2016-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * basic.c -- basic example for the librpmem */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <librpmem.h> #define POOL_SIZE (32 * 1024 * 1024) #define OFFSET 4096 /* pool header size */ #define SIZE (POOL_SIZE - OFFSET) #define NLANES 64 #define SET_POOLSET_UUID 1 #define SET_UUID 2 #define SET_NEXT 3 #define SET_PREV 4 /* * default_attr -- fill pool attributes to default values */ 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); } int main(int argc, char *argv[]) { int ret = 0; if (argc < 4) { fprintf(stderr, "usage: %s [create|open|remove]" " <target> <pool_set> [options]\n", argv[0]); return 1; } char *op = argv[1]; char *target = argv[2]; char *pool_set = argv[3]; unsigned nlanes = NLANES; void *pool; long align = sysconf(_SC_PAGESIZE); if (align < 0) { perror("sysconf"); return -1; } errno = posix_memalign(&pool, (size_t)align, POOL_SIZE); if (errno) { perror("posix_memalign"); return -1; } if (strcmp(op, "create") == 0) { struct rpmem_pool_attr pool_attr; default_attr(&pool_attr); RPMEMpool *rpp = rpmem_create(target, pool_set, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_create: %s\n", rpmem_errormsg()); ret = 1; goto end; } ret = rpmem_persist(rpp, OFFSET, SIZE, 0, 0); if (ret) fprintf(stderr, "rpmem_persist: %s\n", rpmem_errormsg()); ret = rpmem_close(rpp); if (ret) fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); } else if (strcmp(op, "open") == 0) { struct rpmem_pool_attr def_attr; default_attr(&def_attr); struct rpmem_pool_attr pool_attr; RPMEMpool *rpp = rpmem_open(target, pool_set, pool, POOL_SIZE, &nlanes, &pool_attr); if (!rpp) { fprintf(stderr, "rpmem_open: %s\n", rpmem_errormsg()); ret = 1; goto end; } if (memcmp(&def_attr, &pool_attr, sizeof(def_attr))) { fprintf(stderr, "remote pool not consistent\n"); } ret = rpmem_persist(rpp, OFFSET, SIZE, 0, 0); if (ret) fprintf(stderr, "rpmem_persist: %s\n", rpmem_errormsg()); ret = rpmem_close(rpp); if (ret) fprintf(stderr, "rpmem_close: %s\n", rpmem_errormsg()); } else if (strcmp(op, "remove") == 0) { ret = rpmem_remove(target, pool_set, 0); if (ret) fprintf(stderr, "removing pool failed: %s\n", rpmem_errormsg()); } else { fprintf(stderr, "unsupported operation -- '%s'\n", op); ret = 1; } end: free(pool); return ret; }
4,476
26.98125
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/librpmem/manpage.c
/* * Copyright 2016-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * manpage.c -- example for librpmem manpage */ #include <stdio.h> #include <string.h> #include <librpmem.h> #define POOL_SIZE (32 * 1024 * 1024) #define NLANES 4 static unsigned char pool[POOL_SIZE]; int main(int argc, char *argv[]) { int ret; unsigned nlanes = NLANES; /* fill pool_attributes */ struct rpmem_pool_attr pool_attr; memset(&pool_attr, 0, sizeof(pool_attr)); /* create a remote pool */ RPMEMpool *rpp = rpmem_create("localhost", "pool.set", 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, 0, POOL_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; } return 0; }
2,603
30.756098
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/manpage.c
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * manpage.c -- simple example for the libpmemcto man page */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #endif #include <string.h> #include <libpmemcto.h> /* size of the pmemcto pool -- 1 GB */ #define POOL_SIZE ((size_t)(1 << 30)) /* name of our layout in the pool */ #define LAYOUT_NAME "example_layout" struct root { char *str; char *data; }; int main(int argc, char *argv[]) { const char path[] = "/pmem-fs/myfile"; PMEMctopool *pcp; /* create the pmemcto pool or open it if already exists */ pcp = pmemcto_create(path, LAYOUT_NAME, POOL_SIZE, 0666); if (pcp == NULL) pcp = pmemcto_open(path, LAYOUT_NAME); if (pcp == NULL) { perror(path); exit(1); } /* get the root object pointer */ struct root *rootp = pmemcto_get_root_pointer(pcp); if (rootp == NULL) { /* allocate root object */ rootp = pmemcto_malloc(pcp, sizeof(*rootp)); if (rootp == NULL) { perror(pmemcto_errormsg()); exit(1); } /* save the root object pointer */ pmemcto_set_root_pointer(pcp, rootp); rootp->str = pmemcto_strdup(pcp, "Hello World!"); rootp->data = NULL; } /* ... */ pmemcto_close(pcp); }
2,800
27.581633
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/lifesaver/resource.h
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * resource.h -- resource file for Life screen saver */ #define VS_VERSION_INFO 1 #define IDC_PATH 1000 #define IDC_OK 1002 #define IDC_CANCEL 1003 #define DLG_SCRNSAVECONFIGURE 2003
1,790
41.642857
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/lifesaver/lifesaver.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * lifesaver.c -- a simple screen saver which implements Conway's Game of Life */ #include <windows.h> #include <scrnsave.h> #include <time.h> #include <stdlib.h> #include <libpmemcto.h> #include "life.h" #include "resource.h" #define DEFAULT_PATH "c:\\temp\\life.cto" #define TIMER_ID 1 CHAR Path[MAX_PATH]; CHAR szAppName[] = "Life's Screen-Saver"; CHAR szIniFile[] = "lifesaver.ini"; CHAR szParamPath[] = "Data file path"; static int Width; static int Height; /* * game_draw -- displays game board */ void game_draw(HWND hWnd, struct game *gp) { RECT rect; PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); HBITMAP bmp = CreateBitmap(gp->width, gp->height, 1, 8, gp->board); HBRUSH brush = CreatePatternBrush(bmp); GetWindowRect(hWnd, &rect); FillRect(hdc, &rect, brush); DeleteObject(brush); DeleteObject(bmp); EndPaint(hWnd, &ps); } /* * load_config -- loads screen saver config */ static void load_config(void) { DWORD res = GetPrivateProfileString(szAppName, szParamPath, DEFAULT_PATH, Path, sizeof(Path), szIniFile); } /* * ScreenSaverConfigureDialog -- handles configuration dialog window * * XXX: fix saving configuration */ BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { static HWND hOK; static HWND hPath; BOOL res; switch (message) { case WM_INITDIALOG: load_config(); hPath = GetDlgItem(hDlg, IDC_PATH); hOK = GetDlgItem(hDlg, IDC_OK); return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_OK: /* write current file path to the .ini file */ res = WritePrivateProfileString(szAppName, szParamPath, Path, szIniFile); /* fall-thru to EndDialog() */ case IDC_CANCEL: EndDialog(hDlg, LOWORD(wParam) == IDC_OK); return TRUE; } } return FALSE; } BOOL RegisterDialogClasses(HANDLE hInst) { return TRUE; } /* * ScreenSaverProc -- screen saver window proc */ LRESULT CALLBACK ScreenSaverProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { static HANDLE hTimer; static struct game *gp; HDC hdc; static RECT rc; switch (iMessage) { case WM_CREATE: Width = GetSystemMetrics(SM_CXSCREEN); Height = GetSystemMetrics(SM_CYSCREEN); load_config(); gp = game_init(Path, Width, Height, 10); hTimer = (HANDLE)SetTimer(hWnd, TIMER_ID, 10, NULL); /* 10ms */ return 0; case WM_ERASEBKGND: hdc = GetDC(hWnd); GetClientRect(hWnd, &rc); FillRect(hdc, &rc, GetStockObject(BLACK_BRUSH)); ReleaseDC(hWnd, hdc); return 0; case WM_TIMER: game_next(gp); InvalidateRect(hWnd, NULL, FALSE); return 0; case WM_PAINT: game_draw(hWnd, gp); return 0; case WM_DESTROY: if (hTimer) KillTimer(hWnd, TIMER_ID); pmemcto_close(gp->pcp); PostQuitMessage(0); return 0; } return (DefScreenSaverProc(hWnd, iMessage, wParam, lParam)); }
4,428
23.469613
78
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/libart/art.h
/* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * Copyright 2012, Armon Dadgar. All rights reserved. * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ========================================================================== * * Filename: art.h * * Description: implement ART tree using libpmemcto 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.h */ #include <stdint.h> #ifndef ART_H #define ART_H #ifdef __cplusplus extern "C" { #endif #define NODE4 1 #define NODE16 2 #define NODE48 3 #define NODE256 4 #define MAX_PREFIX_LEN 10 #if defined(__GNUC__) && !defined(__clang__) #if __STDC_VERSION__ >= 199901L && 402 == (__GNUC__ * 100 + __GNUC_MINOR__) /* * GCC 4.2.2's C99 inline keyword support is pretty broken; avoid. Introduced in * GCC 4.2.something, fixed in 4.3.0. So checking for specific major.minor of * 4.2 is fine. */ #define BROKEN_GCC_C99_INLINE #endif #endif typedef int(*art_callback)(void *data, const unsigned char *key, uint32_t key_len, const unsigned char *value, uint32_t val_len); /* * This struct is included as part * of all the various node sizes */ typedef struct { uint8_t type; uint8_t num_children; uint32_t partial_len; unsigned char partial[MAX_PREFIX_LEN]; } art_node; /* * Small node with only 4 children */ typedef struct { art_node n; unsigned char keys[4]; art_node *children[4]; } art_node4; /* * Node with 16 children */ typedef struct { art_node n; unsigned char keys[16]; art_node *children[16]; } art_node16; /* * Node with 48 children, but * a full 256 byte field. */ typedef struct { art_node n; unsigned char keys[256]; art_node *children[48]; } art_node48; /* * Full node with 256 children */ typedef struct { art_node n; art_node *children[256]; } art_node256; /* * Represents a leaf. These are * of arbitrary size, as they include the key. */ typedef struct { uint32_t key_len; uint32_t val_len; unsigned char *key; unsigned char *value; unsigned char data[]; } art_leaf; /* * Main struct, points to root. */ typedef struct { art_node *root; uint64_t size; } art_tree; /* * Initializes an ART tree * @return 0 on success. */ int art_tree_init(art_tree *t); /* * DEPRECATED * Initializes an ART tree * @return 0 on success. */ #define init_art_tree(...) art_tree_init(__VA_ARGS__) /* * Destroys an ART tree * @return 0 on success. */ int art_tree_destroy(PMEMctopool *pcp, art_tree *t); /* * Returns the size of the ART tree. */ #ifdef BROKEN_GCC_C99_INLINE #define art_size(t) ((t)->size) #else static inline uint64_t art_size(art_tree *t) { return t->size; } #endif /* * 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. */ void *art_insert(PMEMctopool *pcp, art_tree *t, const unsigned char *key, int key_len, void *value, int val_len); /* * 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. */ void *art_delete(PMEMctopool *pcp, art_tree *t, const unsigned char *key, int 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. */ void *art_search(const art_tree *t, const unsigned char *key, int key_len); /* * Returns the minimum valued leaf * @return The minimum leaf or NULL */ art_leaf *art_minimum(art_tree *t); /* * Returns the maximum valued leaf * @return The maximum leaf or NULL */ art_leaf *art_maximum(art_tree *t); /* * 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(art_tree *t, art_callback cb, void *data); typedef struct _cb_data { int node_type; int child_idx; int first_child; void *node; } cb_data; int art_iter2(art_tree *t, art_callback cb, void *data); /* * 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 *prefix, int prefix_len, art_callback cb, void *data); #ifdef __cplusplus } #endif #endif
6,987
25.369811
80
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/libart/arttree.h
/* * Copyright 2016, FUJITSU TECHNOLOGY SOLUTIONS GMBH * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ========================================================================== * * Filename: arttree.h * * Description: implement ART tree using libpmemcto based on libart * * 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 __FreeBSD__ #define RESET_GETOPT optreset = 1; optind = 1 #else #define RESET_GETOPT optind = 0 #endif #ifdef __cplusplus } #endif #endif /* _ARTTREE_H */
2,390
34.161765
77
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/life/life.h
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * life.h -- internal definitions for pmemcto life example */ #define LAYOUT_NAME "LIFE" #define POOL_SIZE (2 * PMEMCTO_MIN_POOL) struct game { PMEMctopool *pcp; int width; int height; char *board1; char *board2; char *board; /* points to board1 or board2 */ }; #define X(x, w) (((x) + (w)) % (w)) #define Y(y, h) (((y) + (h)) % (h)) #define CELL(g, b, x, y) (b[Y(y, (g)->height) * (g)->width + X(x, (g)->width)]) struct game *game_init(const char *path, int width, int height, int percent); void game_next(struct game *gp);
2,137
37.178571
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/life/life.c
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * life.c -- a simple example which implements Conway's Game of Life */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ncurses.h> #include <libpmemcto.h> #include "life.h" #define WIDTH 64 #define HEIGHT 64 /* * game_draw -- displays game board */ static void game_draw(WINDOW *win, struct game *gp) { for (int x = 0; x < gp->width; x++) { for (int y = 0; y < gp->height; y++) { if (CELL(gp, gp->board, x, y)) mvaddch(x + 1, y + 1, 'O'); else mvaddch(x + 1, y + 1, ' '); } } wborder(win, '|', '|', '-', '-', '+', '+', '+', '+'); wrefresh(win); } int main(int argc, const char *argv[]) { if (argc < 2) { fprintf(stderr, "life path [iterations]\n"); exit(1); } unsigned iterations = ~0; /* ~inifinity */ if (argc == 3) iterations = atoi(argv[2]); struct game *gp = game_init(argv[1], WIDTH, HEIGHT, 10); if (gp == NULL) exit(1); initscr(); noecho(); WINDOW *win = newwin(HEIGHT + 2, WIDTH + 2, 0, 0); while (iterations > 0) { game_draw(win, gp); game_next(gp); timeout(500); if (getch() != -1) break; iterations--; } endwin(); pmemcto_close(gp->pcp); return 0; }
2,758
25.528846
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemcto/life/life_common.c
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * life_common.c -- shared code for pmemcto life examples */ #include <stdio.h> #include <stdlib.h> #include <time.h> #ifndef _WIN32 #include <unistd.h> #endif #include <libpmemcto.h> #include "life.h" /* * game_init -- creates/opens the pool and initializes game state */ struct game * game_init(const char *path, int width, int height, int percent) { /* create the pmemcto pool or open it if already exists */ PMEMctopool *pcp = pmemcto_create(path, LAYOUT_NAME, POOL_SIZE, 0666); if (pcp == NULL) pcp = pmemcto_open(path, LAYOUT_NAME); if (pcp == NULL) { fprintf(stderr, "%s", pmemcto_errormsg()); return NULL; } /* get the root object pointer */ struct game *gp = pmemcto_get_root_pointer(pcp); /* check if width/height is the same */ if (gp != NULL) { if (gp->width == width && gp->height == height) { return gp; } else { fprintf(stderr, "board dimensions changed"); pmemcto_free(pcp, gp->board1); pmemcto_free(pcp, gp->board2); pmemcto_free(pcp, gp); } } /* allocate root object */ gp = pmemcto_calloc(pcp, 1, sizeof(*gp)); if (gp == NULL) { fprintf(stderr, "%s", pmemcto_errormsg()); return NULL; } /* save the root object pointer */ pmemcto_set_root_pointer(pcp, gp); gp->pcp = pcp; gp->width = width; gp->height = height; gp->board1 = (char *)pmemcto_malloc(pcp, width * height); if (gp->board1 == NULL) { fprintf(stderr, "%s", pmemcto_errormsg()); return NULL; } gp->board2 = (char *)pmemcto_malloc(pcp, width * height); if (gp->board2 == NULL) { fprintf(stderr, "%s", pmemcto_errormsg()); return NULL; } gp->board = gp->board2; srand((unsigned)time(NULL)); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) CELL(gp, gp->board, x, y) = (rand() % 100 < percent); return gp; } /* * cell_next -- calculates next state of given cell */ static int cell_next(struct game *gp, char *b, int x, int y) { int alive = CELL(gp, b, x, y); int neighbors = CELL(gp, b, x - 1, y - 1) + CELL(gp, b, x - 1, y) + CELL(gp, b, x - 1, y + 1) + CELL(gp, b, x, y - 1) + CELL(gp, b, x, y + 1) + CELL(gp, b, x + 1, y - 1) + CELL(gp, b, x + 1, y) + CELL(gp, b, x + 1, y + 1); int next = (alive && (neighbors == 2 || neighbors == 3)) || (!alive && (neighbors == 3)); return next; } /* * game_next -- calculates next iteration of the game */ void game_next(struct game *gp) { char *prev = gp->board; char *next = (gp->board == gp->board2) ? gp->board1 : gp->board2; for (int x = 0; x < gp->width; x++) for (int y = 0; y < gp->height; y++) CELL(gp, next, x, y) = cell_next(gp, prev, x, y); gp->board = next; }
4,236
26.69281
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/manpage.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
2,926
28.565657
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/assetdb/asset_checkout.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
3,138
28.895238
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/assetdb/asset_list.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; int assetid; 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 (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: %d\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); }
2,923
28.535354
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/assetdb/asset_checkin.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
2,879
28.387755
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/assetdb/asset_load.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; int 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 %d 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); }
3,465
26.507937
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemblk/assetdb/asset.h
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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; };
1,815
40.272727
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/manpage.c
/* * Copyright 2014-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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); }
2,373
30.653333
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/btree.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
5,294
23.288991
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/pi.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
7,136
23.78125
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/lists.c
/* * Copyright 2016-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
5,258
23.347222
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/setjmp.c
/* * Copyright 2016, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * setjmp.c -- example illustrating an issue with indeterminate value * of non-volatile automatic variables after transaction abort. * See libpmemobj(3) 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); }
3,222
32.226804
77
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/pminvaders/pminvaders.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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 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; }
9,279
20.531323
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/pmemblk/obj_pmemblk.c
/* * Copyright 2015-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
10,963
24.497674
76
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/slab_allocator/main.c
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
3,581
28.360656
77
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/slab_allocator/slab_allocator.c
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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)); }
3,117
28.140187
76
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/slab_allocator/slab_allocator.h
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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 */
2,057
38.576923
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/array/array.c
/* * Copyright 2016-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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)); for (size_t i = prev_size; i < size; i++) D_RW(array)[i] = (int)i; 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); 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"}; int 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; }
13,222
24.138783
77
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/string_store_tx_type/writer.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
2,322
29.168831
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/string_store_tx_type/reader.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
2,130
31.287879
74
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/string_store_tx_type/layout.h
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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]; };
1,839
39
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/list_map/skiplist_map.c
/* * Copyright 2016, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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) 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 */ int skiplist_map_insert(PMEMobjpool *pop, TOID(struct skiplist_map_node) map, uint64_t key, PMEMoid value) { int ret = 0; TOID(struct skiplist_map_node) new_node; TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]; 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 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; TOID(struct skiplist_map_node) path[SKIPLIST_LEVELS_NUM]; TOID(struct skiplist_map_node) to_remove; 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 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,490
25.287926
78
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/list_map/skiplist_map.h
/* * Copyright 2016, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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 */
3,203
42.297297
80
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap.h
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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 */
1,860
36.22
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_tx.h
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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 */
2,785
41.861538
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_rp.h
/* * Copyright 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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 */
3,295
41.805195
76
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_internal.h
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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
2,036
40.571429
74
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_tx.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* 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; } }
11,208
23.908889
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_rp.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. */ /* * 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 int 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(hashmap)); 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; } int 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. */ int 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:%u \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; } }
18,372
24.412172
79
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_atomic.h
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #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 */
2,899
42.939394
79
h
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/hashmap/hashmap_atomic.c
/* * Copyright 2015-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* 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; } }
14,340
25.45941
80
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/pmemlog/obj_pmemlog_simple.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
11,235
22.906383
76
c
null
NearPMSW-main/nearpm/checkpointing/redis-NDP-chekpoint/deps/pmdk/src/examples/libpmemobj/pmemlog/obj_pmemlog.c
/* * Copyright 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * 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; }
11,002
22.816017
80
c